DeFi协议开发实战:从AMM到借贷平台的完整指南

引言 DeFi(去中心化金融)是WEB3最重要的应用场景之一。从AMM到借贷协议,DeFi正在重塑传统金融。本文将深入探讨DeFi协议的核心机制和开发实践。 AMM(自动做市商) 恒定乘积AMM(Uniswap V2) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract UniswapV2Pair is ReentrancyGuard { string public constant name = "Uniswap V2 Pair"; string public constant symbol = "UNI-V2"; uint256 public constant MINIMUM_LIQUIDITY = 1000; address public token0; address public token1; uint256 public reserve0; uint256 public reserve1; uint256 public totalSupply; mapping(address => uint256) public balanceOf; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint256 reserve0, uint256 reserve1); constructor() { factory = msg.sender; } function initialize(address _token0, address _token1) external { require(msg.sender == factory, "Forbidden"); require(_token0 < _token1, "Invalid tokens"); token0 = _token0; token1 = _token1; } // 添加流动性 function mint(address to) external nonReentrant returns (uint256 liquidity) { (uint256 reserve0_, uint256 reserve1_) = getReserves(); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0 - reserve0_; uint256 amount1 = balance1 - reserve1_; uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { // 首次添加流动性 liquidity = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY; _mint(address(0), MINIMUM_LIQUIDITY); // 永久锁定最小流动性 } else { liquidity = Math.min( (amount0 * _totalSupply) / reserve0_, (amount1 * _totalSupply) / reserve1_ ); } require(liquidity > 0, "Insufficient liquidity minted"); _mint(to, liquidity); _update(balance0, balance1); emit Mint(to, amount0, amount1); } // 移除流动性 function burn(address to) external nonReentrant returns (uint256 amount0, uint256 amount1) { uint256 liquidity = balanceOf[address(this)]; require(liquidity > 0, "No liquidity"); (uint256 reserve0_, uint256 reserve1_) = getReserves(); uint256 _totalSupply = totalSupply; amount0 = (liquidity * reserve0_) / _totalSupply; amount1 = (liquidity * reserve1_) / _totalSupply; _burn(address(this), liquidity); _transfer( token0, address(this), to, amount0 ); _transfer( token1, address(this), to, amount1 ); (uint256 balance0, uint256 balance1) = getBalances(); _update(balance0, balance1); emit Burn(to, amount0, amount1); } // 交换(核心功能) function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external nonReentrant { require( amount0Out > 0 || amount1Out > 0, "Insufficient output amount" ); (uint256 reserve0_, uint256 reserve1_) = getReserves(); if (amount0Out > 0) { uint256 amount0In = getInputAmount( amount0Out, reserve0_, reserve1_ ); require( amount0In <= reserve0_ - amount0Out, "Insufficient liquidity" ); uint256 balance0Before = IERC20(token0).balanceOf(address(this)); _transfer(token0, msg.sender, address(this), amount0In); uint256 balance0After = IERC20(token0).balanceOf(address(this)); amount0In = balance0After - balance0Before; _transfer(token1, address(this), to, amount0Out); } if (amount1Out > 0) { uint256 amount1In = getInputAmount( amount1Out, reserve1_, reserve0_ ); require( amount1In <= reserve1_ - amount1Out, "Insufficient liquidity" ); uint256 balance1Before = IERC20(token1).balanceOf(address(this)); _transfer(token1, msg.sender, address(this), amount1In); uint256 balance1After = IERC20(token1).balanceOf(address(this)); amount1In = balance1After - balance1Before; _transfer(token0, address(this), to, amount1Out); } (uint256 balance0, uint256 balance1) = getBalances(); _update(balance0, balance1); emit Swap( msg.sender, amount0In, amount1In, amount0Out, amount1Out, to ); } // 计算输入量(恒定乘积公式) function getInputAmount( uint256 outputAmount, uint256 inputReserve, uint256 outputReserve ) public pure returns (uint256 inputAmount) { require(inputReserve > 0 && outputReserve > 0, "Invalid reserves"); require(outputAmount < outputReserve, "Output amount too high"); uint256 numerator = inputReserve * outputAmount * 1000; uint256 denominator = (outputReserve - outputAmount) * 997; return (numerator / denominator) + 1; } // 滑点计算 function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure returns (uint256 amountOut) { require(amountIn > 0, "Insufficient input amount"); require(reserveIn > 0 && reserveOut > 0, "Invalid reserves"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1000 + amountInWithFee; return numerator / denominator; } function getReserves() public view returns (uint256, uint256) { return (reserve0, reserve1); } function _update(uint256 balance0, uint256 balance1) private { reserve0 = balance0; reserve1 = balance1; emit Sync(balance0, balance1); } function _mint(address to, uint256 amount) private { totalSupply += amount; balanceOf[to] += amount; } function _burn(address from, uint256 amount) private { require(balanceOf[from] >= amount, "Insufficient balance"); balanceOf[from] -= amount; totalSupply -= amount; } function _transfer( address token, address from, address to, uint256 amount ) private { IERC20(token).transferFrom(from, to, amount); } function getBalances() public view returns (uint256, uint256) { return ( IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)) ); } } 集中流动性(Uniswap V3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 // Uniswap V3核心概念 contract UniswapV3Pool { struct Position { uint96 nonce; address operator; address token0; address token1; int24 tickLower; int24 tickUpper; uint128 liquidity; uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; uint128 tokensOwed0; uint128 tokensOwed1; } // Tick(价格)概念 // 价格 = 1.0001^tick // 例如:tick = 1000 => price = 1.0001^1000 ≈ 1.105 int24 internal constant MIN_TICK = -887272; int24 internal constant MAX_TICK = 887272; function getRatioFromTick(int24 tick) public pure returns (uint256) { uint256 ratio = 1.0001e18; int24 absTick = tick < 0 ? -tick : tick; for (int i = 0; i < absTick; i++) { if (tick < 0) { ratio = (ratio * 1e18) / 1000100000000000000; // /1.0001 } else { ratio = (ratio * 1000100000000000000) / 1e18; // *1.0001 } } return ratio; } function getTickFromRatio(uint256 ratio) public pure returns (int24 tick) { // 二分查找 int24 low = MIN_TICK; int24 high = MAX_TICK; while (low < high) { int24 mid = (low + high + 1) / 2; uint256 midRatio = getRatioFromTick(mid); if (ratio < midRatio) { high = mid - 1; } else { low = mid; } } return low; } // 流动性计算 function getLiquidityForAmounts( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) public pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = sqrtRatioAX96 * sqrtRatioBX96 / 96; uint256 amount0Intermediate = (amount0 * intermediate) / sqrtRatioBX96; if (amount0Intermediate <= amount1) { liquidity = uint128(amount0Intermediate); } else { liquidity = uint128((amount1 * sqrtRatioAX96 * sqrtRatioBX96) / 96); } } function getPositionAmounts( uint160 sqrtPriceX96, int24 tickLower, int24 tickUpper, uint128 liquidity ) public pure returns (uint256 amount0, uint256 amount1) { uint160 sqrtRatioAX96 = getSqrtRatioAtTick(tickLower); uint160 sqrtRatioBX96 = getSqrtRatioAtTick(tickUpper); if (sqrtPriceX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity( sqrtRatioAX96, sqrtRatioBX96, liquidity ); } else if (sqrtPriceX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity( sqrtPriceX96, sqrtRatioBX96, liquidity ); amount1 = getAmount1ForLiquidity( sqrtRatioAX96, sqrtPriceX96, liquidity ); } else { amount1 = getAmount1ForLiquidity( sqrtRatioAX96, sqrtRatioBX96, liquidity ); } } } 借贷协议 Compound风格借贷 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract LendingPool is ReentrancyGuard { struct Reserve { uint256 totalSupply; uint256 totalBorrowed; uint256 borrowRate; uint256 supplyRate; uint256 lastUpdate; uint256 index; } struct UserState { uint256 supplied; uint256 borrowed; uint256 borrowIndex; uint256 supplyIndex; uint256 collateralFactor; } mapping(address => Reserve) public reserves; mapping(address => UserState) public users; mapping(address => address[]) public userAssets; address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public constant COLLATERAL_FACTOR = 750; // 75% event Supply(address indexed user, address indexed asset, uint256 amount); event Borrow(address indexed user, address indexed asset, uint256 amount); event Repay(address indexed user, address indexed asset, uint256 amount); event Withdraw(address indexed user, address indexed asset, uint256 amount); event Liquidate(address indexed user, address indexed borrower, address indexed asset, uint256 amount); // 供应资产 function supply(address asset, uint256 amount) external nonReentrant { require(amount > 0, "Amount must be greater than 0"); IERC20(asset).transferFrom(msg.sender, address(this), amount); // 更新累计指数 _accrueInterest(asset); // 更新用户状态 UserState storage user = users[msg.sender]; Reserve storage reserve = reserves[asset]; uint256 userSupply = (amount * reserve.index) / 1e18; user.supplied += userSupply; user.supplyIndex = reserve.index; reserve.totalSupply += userSupply; // 记录用户资产 if (!_hasAsset(msg.sender, asset)) { userAssets[msg.sender].push(asset); } emit Supply(msg.sender, asset, amount); } // 借款 function borrow( address asset, uint256 amount ) external nonReentrant { require(amount > 0, "Amount must be greater than 0"); // 更新累计指数 _accrueInterest(asset); UserState storage user = users[msg.sender]; Reserve storage reserve = reserves[asset]; // 检查抵押品 uint256 maxBorrow = _getMaxBorrow(msg.sender); uint256 currentBorrow = _getUserBorrow(msg.sender); require( currentBorrow + amount <= maxBorrow, "Insufficient collateral" ); // 更新借款 uint256 borrowAmount = (amount * 1e18) / reserve.index; user.borrowed += borrowAmount; user.borrowIndex = reserve.index; reserve.totalBorrowed += borrowAmount; // 转出资产 IERC20(asset).transfer(msg.sender, amount); emit Borrow(msg.sender, asset, amount); } // 还款 function repay(address asset, uint256 amount) external nonReentrant { require(amount > 0, "Amount must be greater than 0"); // 更新累计指数 _accrueInterest(asset); UserState storage user = users[msg.sender]; Reserve storage reserve = reserves[asset]; // 计算实际债务 uint256 debt = _getUserBorrow(msg.sender); if (amount >= debt) { amount = debt; // 如果还清,可以提取抵押品 } IERC20(asset).transferFrom(msg.sender, address(this), amount); uint256 repayAmount = (amount * 1e18) / reserve.index; user.borrowed -= repayAmount; reserve.totalBorrowed -= (amount * 1e18) / reserve.index; emit Repay(msg.sender, asset, amount); } // 提取供应的资产 function withdraw(address asset, uint256 amount) external nonReentrant { require(amount > 0, "Amount must be greater than 0"); // 更新累计指数 _accrueInterest(asset); UserState storage user = users[msg.sender]; Reserve storage reserve = reserves[asset]; // 检查是否有未还贷款 uint256 currentBorrow = _getUserBorrow(msg.sender); uint256 maxBorrow = _getMaxBorrow(msg.sender); require( currentBorrow <= maxBorrow, "Cannot withdraw: insufficient collateral" ); // 计算可提取金额 uint256 userSupply = _getUserSupply(msg.sender, asset); require(userSupply >= amount, "Insufficient balance"); uint256 withdrawAmount = (amount * reserve.index) / 1e18; user.supplied -= withdrawAmount; reserve.totalSupply -= withdrawAmount; IERC20(asset).transfer(msg.sender, amount); emit Withdraw(msg.sender, asset, amount); } // 清算 function liquidate( address borrower, address asset, uint256 amount ) external nonReentrant { // 更新累计指数 _accrueInterest(asset); UserState storage user = users[borrower]; // 检查是否需要清算 uint256 currentBorrow = _getUserBorrow(borrower); uint256 maxBorrow = _getMaxBorrow(borrower); require( currentBorrow > maxBorrow, "Not eligible for liquidation" ); // 扣除抵押品 // 这里简化处理,实际需要拍卖机制 emit Liquidate(msg.sender, borrower, asset, amount); } // 计算累计利息 function _accrueInterest(address asset) internal { Reserve storage reserve = reserves[asset]; uint256 timeElapsed = block.timestamp - reserve.lastUpdate; if (timeElapsed == 0) return; // 简化的利息计算 uint256 interest = (reserve.totalBorrowed * reserve.borrowRate * timeElapsed) / (365 days * 1e18); uint256 supplyInterest = (reserve.totalSupply * reserve.supplyRate * timeElapsed) / (365 days * 1e18); reserve.totalBorrowed += interest; reserve.totalSupply += supplyInterest; reserve.lastUpdate = block.timestamp; } function _getUserSupply( address user, address asset ) internal view returns (uint256) { Reserve storage reserve = reserves[asset]; UserState storage userState = users[user]; if (userState.supplyIndex == 0) { return 0; } return (userState.supplied * reserve.index) / userState.supplyIndex; } function _getUserBorrow(address user) internal view returns (uint256) { uint256 totalBorrow = 0; for (uint256 i = 0; i < userAssets[user].length; i++) { address asset = userAssets[user][i]; UserState storage userState = users[user]; Reserve storage reserve = reserves[asset]; if (userState.borrowed > 0) { uint256 borrow = (userState.borrowed * reserve.index) / userState.borrowIndex; totalBorrow += borrow; } } return totalBorrow; } function _getMaxBorrow(address user) internal view returns (uint256) { uint256 totalCollateral = 0; for (uint256 i = 0; i < userAssets[user].length; i++) { address asset = userAssets[user][i]; uint256 supply = _getUserSupply(user, asset); // 假设所有资产都有同样的抵押因子 totalCollateral += (supply * COLLATERAL_FACTOR) / 1000; } return totalCollateral; } function _hasAsset(address user, address asset) internal view returns (bool) { for (uint256 i = 0; i < userAssets[user].length; i++) { if (userAssets[user][i] == asset) { return true; } } return false; } } 收益聚合器(Yearn风格) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract YieldAggregator is Ownable, ReentrancyGuard { struct Strategy { address strategy; uint256 allocation; // 分配比例(基点) uint256 performanceFee; bool active; } mapping(address => Strategy) public strategies; address[] public strategyList; uint256 public constant MAX_ALLOCATION = 10000; // 100% uint256 public constant PERFORMANCE_FEE = 1000; // 10% uint256 public totalShares; mapping(address => uint256) public shares; mapping(address => uint256) public userPrincipal; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed strategy, uint256 amount); event Rebalance(address[] strategies, uint256[] allocations); // 存款 function deposit(uint256 amount) external payable nonReentrant { require(amount > 0, "Amount must be greater than 0"); // 转入资产 if (msg.value > 0) { require(amount == msg.value, "ETH amount mismatch"); } else { IERC20(WETH).transferFrom(msg.sender, address(this), amount); IWETH(WETH).deposit{value: amount}(); } // 计算份额 uint256 shares; if (totalShares == 0) { shares = amount; } else { shares = (amount * totalShares) / totalAssets(); } shares[msg.sender] += shares; totalShares += shares; userPrincipal[msg.sender] += amount; // 分配到各个策略 _rebalance(); emit Deposit(msg.sender, amount); } // 提款 function withdraw(uint256 shares) external nonReentrant { require(shares > 0, "Shares must be greater than 0"); require(shares[msg.sender] >= shares, "Insufficient shares"); // 计算可提取金额 uint256 assets = (totalAssets() * shares) / totalShares; // 从策略中提取 _withdrawFromStrategies(assets); // 转出资产 if (address(this).balance >= assets) { payable(msg.sender).transfer(assets); } else { IWETH(WETH).withdraw(assets); payable(msg.sender).transfer(assets); } // 更新份额 shares[msg.sender] -= shares; totalShares -= shares; uint256 principal = (userPrincipal[msg.sender] * shares) / (shares + shares[msg.sender]); userPrincipal[msg.sender] -= principal; emit Withdraw(msg.sender, assets); } // 收获收益 function harvest(address strategy) external onlyOwner { Strategy storage s = strategies[strategy]; require(s.active, "Strategy not active"); // 调用策略的harvest函数 uint256 beforeBalance = address(this).balance; IStrategy(strategy).harvest(); uint256 afterBalance = address(this).balance; uint256 profit = afterBalance - beforeBalance; if (profit > 0) { // 提取性能费 uint256 fee = (profit * PERFORMANCE_FEE) / 10000; uint256 performanceFee = (fee * s.performanceFee) / 10000; payable(owner()).transfer(performanceFee); emit Harvest(strategy, profit); } } // 重新平衡 function _rebalance() internal { uint256 totalAssets = address(this).balance; for (uint256 i = 0; i < strategyList.length; i++) { Strategy storage s = strategies[strategyList[i]]; if (s.active && s.allocation > 0) { uint256 amount = (totalAssets * s.allocation) / MAX_ALLOCATION; IStrategy(s.strategy).invest{value: amount}(); } } } function _withdrawFromStrategies(uint256 amount) internal { uint256 withdrawn; for (uint256 i = 0; i < strategyList.length; i++) { Strategy storage s = strategies[strategyList[i]]; if (s.active && withdrawn < amount) { uint256 toWithdraw = amount - withdrawn; uint256 available = IStrategy(s.strategy).withdraw(toWithdraw); withdrawn += available; if (withdrawn >= amount) { break; } } } } function totalAssets() public view returns (uint256) { uint256 total = address(this).balance; for (uint256 i = 0; i < strategyList.length; i++) { Strategy storage s = strategies[strategyList[i]]; if (s.active) { total += IStrategy(s.strategy).estimatedTotalAssets(); } } return total; } // 添加策略 function addStrategy( address _strategy, uint256 _allocation ) external onlyOwner { require(_strategy != address(0), "Invalid strategy"); strategies[_strategy] = Strategy({ strategy: _strategy, allocation: _allocation, performanceFee: 5000, // 50% active: true }); strategyList.push(_strategy); _validateAllocations(); } // 更新分配比例 function updateAllocation( address _strategy, uint256 _allocation ) external onlyOwner { strategies[_strategy].allocation = _allocation; _validateAllocations(); _rebalance(); } function _validateAllocations() internal view { uint256 total; for (uint256 i = 0; i < strategyList.length; i++) { Strategy storage s = strategies[strategyList[i]]; if (s.active) { total += s.allocation; } } require(total <= MAX_ALLOCATION, "Total allocation exceeds 100%"); } } interface IStrategy { function invest(uint256 amount) external; function withdraw(uint256 amount) external returns (uint256); function harvest() external; function estimatedTotalAssets() external view returns (uint256); } interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; } 总结 DeFi协议开发需要深入理解: ...

智能合约安全审计:从漏洞分析到最佳实践

引言 智能合约安全是WEB3生态的生命线。一次漏洞可能导致数千万甚至数亿美元的损失。本文将系统性地探讨智能合约安全审计的完整方法论,从常见漏洞到审计工具,再到最佳实践。 常见漏洞类型 重入攻击(Reentrancy) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 // ❌ 有重入漏洞的合约 contract VulnerableBank { mapping(address => uint256) public balances; function deposit() public payable { balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount, "Insufficient balance"); // 滑洞:在更新状态前进行外部调用 (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); balances[msg.sender] -= amount; } } // ✅ 修复后的合约(使用Checks-Effects-Interactions模式) contract SecureBank { mapping(address => uint256) public balances; function deposit() public payable { balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount, "Insufficient balance"); // 先更新状态 balances[msg.sender] -= amount; // 再进行外部调用 (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); } } // ✅ 使用ReentrancyGuard import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract GuardedBank is ReentrancyGuard { mapping(address => uint256) public balances; function withdraw(uint256 amount) external nonReentrant { require(balances[msg.sender] >= amount, "Insufficient balance"); balances[msg.sender] -= amount; (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); } } 整数溢出/下溢 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // ❌ Solidity 0.8.0之前的溢出漏洞 contract OldVulnerable { uint256 public value; function unsafeAdd(uint256 a, uint256 b) public { // 可能溢出 value = a + b; } function unsafeSubtract(uint256 a, uint256 b) public { // 可能下溢 value = a - b; } } // ✅ Solidity 0.8.0+自动检查溢出 contract ModernSafe { uint256 public value; function safeAdd(uint256 a, uint256 b) public { // Solidity 0.8.0+自动检查溢出 value = a + b; } function safeSubtract(uint256 a, uint256 b) public { // 自动检查下溢 value = a - b; } // 使用SafeMath库(0.8.0之前) // using SafeMath for uint256; } // ✅ 使用OpenZeppelin的SafeMath(旧版Solidity) import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract SafeMathContract { using SafeMath for uint256; function add(uint256 a, uint256 b) public pure returns (uint256) { return a.add(b); // 自动检查溢出 } function sub(uint256 a, uint256 b) public pure returns (uint256) { return a.sub(b); // 自动检查下溢 } } 访问控制漏洞 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 // ❌ 缺少访问控制 contract NoAccessControl { uint256 public importantValue; function setImportantValue(uint256 _value) public { // 任何人都可以调用 importantValue = _value; } function destroy() public { // 任何人都可以销毁合约 selfdestruct(payable(msg.sender)); } } // ✅ 正确的访问控制 import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract ProperAccessControl is Ownable, AccessControl { uint256 public importantValue; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); constructor() Ownable(msg.sender) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } // 只有所有者可以调用 function setImportantValue(uint256 _value) external onlyOwner { importantValue = _value; } // 只有管理员可以调用 function adminFunction() external onlyRole(ADMIN_ROLE) { // 管理员专属功能 } // 管理员或经理可以调用 function managerFunction() external onlyRole(ADMIN_ROLE) onlyRole(MANAGER_ROLE) { // 功能实现 } // 基于时间的访问控制 modifier onlyBefore(uint256 deadline) { require(block.timestamp < deadline, "Deadline passed"); _; } function timedFunction() external onlyBefore(1735689600) { // 只能在指定时间前调用 } // 多重签名 mapping(bytes32 => bool) public signatures; uint256 public requiredSignatures = 2; function multiSigFunction(bytes32 data) external { bytes32 signature = keccak256(abi.encodePacked(data, msg.sender)); signatures[signature] = true; uint256 count; bytes32 hash; for (uint256 i = 0; i < 255; i++) { hash = keccak256(abi.encodePacked(data, i)); if (signatures[hash]) { count++; } } require(count >= requiredSignatures, "Not enough signatures"); } } 前端运行(Front-Running) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 // ❌ 容易被抢跑的合约 contract FrontRunnable { mapping(uint256 => uint256) public bids; uint256 public auctionEnd; function bid(uint256 amount) external payable { require(block.timestamp < auctionEnd, "Auction ended"); // 滑洞:未隐藏出价,容易被抢跑 bids[msg.sender] = msg.value; if (msg.value > bids[highestBidder]) { highestBidder = msg.sender; } } } // ✅ 使用commit-reveal方案 import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; class CommitRevealAuction is ReentrancyGuard { struct Commitment { bytes32 hash; uint256 amount; bool revealed; } mapping(address => Commitment) public commitments; uint256 public commitDeadline; uint256 public revealDeadline; uint256 public highestBid; address public highestBidder; function commit(bytes32 hash) external payable { require(block.timestamp < commitDeadline, "Commit period ended"); require(msg.value > 0, "Must commit with ETH"); commitments[msg.sender] = Commitment({ hash: hash, amount: msg.value, revealed: false }); } function reveal(uint256 value, bytes32 salt) external nonReentrant { require( block.timestamp >= commitDeadline && block.timestamp < revealDeadline, "Not in reveal period" ); bytes32 hash = keccak256(abi.encodePacked(value, salt)); require(commitments[msg.sender].hash == hash, "Invalid reveal"); commitments[msg.sender].revealed = true; if (value > highestBid) { // 退还之前的最高出价 if (highestBidder != address(0)) { payable(highestBidder).transfer(highestBid); } highestBid = value; highestBidder = msg.sender; } } } // ✅ 使用暗池(暗拍卖) import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract SealedBidAuction { struct Bid { bytes32 blindedBid; uint256 deposit; } mapping(address => Bid) public bids; mapping(address => uint256) public refunds; uint256 public auctionEnd; address public highestBidder; uint256 public highestBid; bool public ended; function bid(bytes32 blindedBid) external payable { require(block.timestamp < auctionEnd, "Auction ended"); require(msg.value >= highestBid / 10, "Deposit too low"); bids[msg.sender] = Bid({ blindedBid: blindedBid, deposit: msg.value }); } function reveal( uint256[] calldata values, bytes32[] calldata secrets ) external { require( block.timestamp >= auctionEnd && !ended, "Cannot reveal" ); for (uint256 i = 0; i < values.length; i++) { address bidder = msg.sender; Bid storage bid = bids[bidder]; bytes32 hash = keccak256(abi.encodePacked(values[i], secrets[i])); if (hash != bid.blindedBid) { refunds[bidder] += bid.deposit; continue; } if (bid.deposit < values[i]) { refunds[bidder] += bid.deposit; continue; } if (values[i] > highestBid) { if (highestBidder != address(0)) { refunds[highestBidder] += highestBid; } highestBidder = bidder; highestBid = values[i]; } refunds[bidder] += bid.deposit - values[i]; } } function withdrawRefund() external { uint256 refund = refunds[msg.sender]; refunds[msg.sender] = 0; payable(msg.sender).transfer(refund); } } 静态分析工具 Slither 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 # Slither安装 # pip install slither-analyzer # 基础扫描 slither contract.sol # 生成报告 slither contract.sol --json output.json slither contract.sol --markdown output.md # 自定义打印机 from slither import Slither from slither.detectors import ReentrancyDetector from slither.printers import CustomPrinter slither = Slither('contract.sol') # 检测重入漏洞 for detector in slither.detectors: if isinstance(detector, ReentrancyDetector): for finding in detector.detect(): print(f"Reentrancy found: {finding}") # 自定义检测器 from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification class MyCustomDetector(AbstractDetector): ARGUMENT = 'my-custom-detector' HELP = 'Custom detector description' IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = 'https://github.com/my-detector/wiki' def detect(self): results = [] for contract in self.contracts: for function in contract.functions: # 自定义检测逻辑 if self.has_vulnerability(function): results.append({ 'contract': contract.name, 'function': function.name, 'line': function.source_mapping['start']['line'] }) return results Mythril 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 # Mythril安装 # pip install mythril # 命令行使用 myth analyze contract.sol # Python API from mythril.platform import mythril_platform from mythril.analysis import symbolic_executor def analyze_contract(contract_path: str): platform = mythril_platform.get_platform() # 加载合约 platform.set_execution_timeout(30) platform.load_bytecode(contract_path) # 执行符号执行 executor = symbolic_executor.SymbolicExecutor() issues = executor.execute(platform.bytecode) # 分析结果 for issue in issues: print(f"[{issue.severity}] {issue.title}") print(f" Description: {issue.description}") print(f" SWC ID: {issue.swc_id}") print() # 自定义分析规则 from mythril.analysis.issue import Severity from mythril.analysis.reporter import Issue class MyCustomAnalyzer: def __init__(self): self.issues = [] def check_access_control(self, bytecode): # 检查访问控制问题 if not self.has_access_control(bytecode): self.issues.append(Issue( severity=Severity.HIGH, title="Missing Access Control", description="Critical functions lack access control", swc_id="SWC-105" )) def has_access_control(self, bytecode): # 实现检查逻辑 return True Echidna 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 # Echidna安装 # git clone https://github.com/crytic/echidna.git # cd echidna # cabal install # Echidna配置文件 """ echidna-test: # 测试用例 testMode: assertion # 最大时间(秒) testLimit: 50000 # 最大序列长度 seqLen: 20 # 合约覆盖率 coverage: true # 指定部署账户 deployer: "0x00a329c0648769a73afac7f9381e08fb43dbea70" """ # Solidity测试合约 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "echidna-test.sol"; contract VulnerableContract { uint256 public publicVar = 100; // 不变式:publicVar应该始终 <= 100 function invariant_publicVar_not_greater_than_100() public view { assert(publicVar <= 100); } // 有漏洞的函数 function setPublicVar(uint256 _value) public { publicVar = _value; // Echidna会发现这里违反了不变式 } // 正确的函数 function safeSetPublicVar(uint256 _value) public { require(_value <= 100, "Value too large"); publicVar = _value; } } // 运行Echidna // echidna-test contract.sol --test-mode assertion 形式化验证 SMT求解器验证 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 from z3 import * def verify_swap_function(): """使用Z3验证swap函数的正确性""" # 定义变量 x = Real('x') # 用户输入的token A数量 y = Real('y') # 用户输入的token B数量 reserve_x = Real('reserve_x') # 池中token A储备 reserve_y = Real('reserve_y') # 池中token B储备 # 不变量 k = Real('k') invariant = (reserve_x * reserve_y == k) # 前置条件 preconditions = And( x > 0, y > 0, reserve_x > 0, reserve_y > 0, # 满足恒定乘积公式 (reserve_x + x) * (reserve_y - y) == reserve_x * reserve_y, # y不能超过储备量 y < reserve_y ) # Swap后的状态 new_reserve_x = reserve_x + x new_reserve_y = reserve_y - y # 后置条件 postconditions = And( # 储备量应该增加/减少 new_reserve_x == reserve_x + x, new_reserve_y == reserve_y - y, # 仍然满足恒定乘积 new_reserve_x * new_reserve_y == reserve_x * reserve_y, # 储备量非负 new_reserve_y >= 0 ) # 求解器验证 s = Solver() s.add(invariant) s.add(preconditions) s.add(Not(postconditions)) # 如果无解,说明后置条件总是满足 if s.check() == unsat: print("✓ Swap函数是正确的") return True else: print("✗ 发现反例:") model = s.model() print(f" x = {model[x]}") print(f" y = {model[y]}") print(f" reserve_x = {model[reserve_x]}") print(f" reserve_y = {model[reserve_y]}") return False # 验证AMM池 def verify_amm_invariant(): """验证AMM恒定乘积不变式""" # 初始状态 x0 = Real('x0') y0 = Real('y0') k = x0 * y0 # 交易后状态 dx = Real('dx') dy = Real('dy') x1 = x0 + dx y1 = y0 + dy # 验证恒定乘积 s = Solver() # 约束条件 s.add(x0 > 0, y0 > 0) s.add(k == x0 * y0) s.add(x0 * y0 == x1 * y1) # 检查是否可满足 if s.check() == sat: model = s.model() print(f"有效交易: dx = {model[dx]}, dy = {model[dy]}") return True else: print("违反恒定乘积") return False Certora规范 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 // Certora规范语言 // 使用SMT求解器验证智能合约 methods { function swap(uint256 amount0In, uint256 amount1In, address to, bytes calldata data) external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1); } // 确保swap遵循恒定乘积公式 RULE invariant CONSTANT_PRODUCT calldataarg uint256 amount0In; calldataarg uint256 amount1In; address to; bytes data; { env e; require e.msg.value == 0; uint256 reserve0Before; uint256 reserve1Before; reserve0Before, reserve1Before = getReserves(); swap(e, amount0In, amount1In, to, data); uint256 reserve0After; uint256 reserve1After; reserve0After, reserve1After = getReserves(); // 恒定乘积公式:reserve0 * reserve1 应该保持不变 assert(reserve0Before * reserve1Before == reserve0After * reserve1After, "Invariant violated: constant product formula"); } // 确保swap不会导致储备量变为0 RULE invariant NO_ZERO_RESERVES calldataarg uint256 amount0In; calldataarg uint256 amount1In; address to; bytes data; { env e; swap(e, amount0In, amount1In, to, data); uint256 reserve0; uint256 reserve1; reserve0, reserve1 = getReserves(); assert(reserve0 > 0 && reserve1 > 0, "Reserves cannot be zero"); } // 验证转账函数 FUNCTION transfer(address to, uint256 amount) creates evm(uint256 balance) = balanceOf(to), evm(uint256 balance) = balanceOf(msg.sender) updates balanceOf(to) = toBalance => toBalance >= balance, balanceOf(msg.sender) = fromBalance => fromBalance <= balance; // 确保总供应量不变 RULE invariant TOTAL_SUPPLY { env e; uint256 totalBefore = totalSupply(); // 执行任意操作 havoc(e); uint256 totalAfter = totalSupply(); assert(totalBefore == totalAfter, "Total supply changed"); } 审计流程 完整审计清单 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 # 智能合约审计清单 ## 1. 代码质量检查 - [ ] 遵循Solidity最佳实践 - [ ] 使用最新编译器版本 - [ ] 启用优化器 - [ ] 遵循Checks-Effects-Interactions模式 - [ ] 避免使用tx.origin进行身份验证 - [ ] 使用SafeMath(旧版本) - [ ] 正确处理浮点数(使用定点数) ## 2. 访问控制审查 - [ ] 关键函数有适当的访问控制 - [ ] onlyOwner修饰符正确使用 - [ ] 角色权限合理配置 - [ ] 多重签名机制 - [ ] 时间锁机制 ## 3. 状态管理 - [ ] 外部调用在状态更新之后 - [ ] 重入保护 - [ ] 正确的事件记录 - [ ] 临界区管理 ## 4. 数值处理 - [ ] 整数溢出保护 - [ ] 除法检查(除数不为0) - [ ] 舍入误差处理 - [ ] 浮点数使用正确 ## 5. 逻辑漏洞 - [ ] 业务逻辑完整性 - [ ] 边界条件处理 - [ ] 异常情况处理 - [ ] 竞态条件检查 ## 6. DeFi特定检查 - [ ] 滑点保护 - [ ] MEV防护 - [ ] 抢跑保护 - [ ] 清算机制 - [ ] 价格操纵防护 - [ ] oracle使用正确 ## 7. Gas优化 - [ ] 循环优化 - [ ] 存储优化 - [ ] 批量操作 - [ ] 事件记录优化 ## 8. 升级机制 - [ ] 代理模式正确实现 - [ ] 存储布局兼容性 - [ ] 升级流程安全 - [ ] 紧急暂停机制 ## 9. 测试覆盖 - [ ] 单元测试覆盖率 > 90% - [ ] 集成测试完整 - [ ] 模糊测试 - [ ] 形式化验证 ## 10. 文档 - [ ] NatSpec注释完整 - [ ] 架构文档 - [ ] 用户文档 - [ ] API文档 分阶段审计 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 interface AuditPhases { phase1: { name: "初步扫描", duration: "2-3天", tools: ["Slither", "Mythril", "MythX"], output: "漏洞清单" }, phase2: { name: "人工代码审查", duration: "1-2周", methods: ["行内审查", "架构分析", "威胁建模"], output: "审计报告初稿" }, phase3: { name: "测试和验证", duration: "1周", methods: ["单元测试", "集成测试", "形式化验证"], output: "测试报告" }, phase4: { name: "修复验证", duration: "3-5天", process: "修复后重新测试", output: "最终审计报告" } } DeFi安全最佳实践 Oracle使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 // ✅ 使用Chainlink Price Feed import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract OracleExample { AggregatorV3Interface internal priceFeed; constructor() { // ETH/USD Price Feed priceFeed = AggregatorV3Interface( 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 ); } function getLatestPrice() public view returns (int256) { ( uint80 roundId, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // 检查价格是否新鲜 require( timeStamp + 3 hours > block.timestamp, "Price too stale" ); // 检查数据是否为空 require(price > 0, "Invalid price"); return price; } function getPrice(uint256 amount) external view returns (uint256) { int256 price = getLatestPrice(); // price有8位小数 return (amount * uint256(price)) / 1e8; } } // ✅ TWAP(时间加权平均价格) import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; contract TWAPExample { struct Observation { uint256 timestamp; uint256 price0Cumulative; uint256 price1Cumulative; } function getTWAP( address pool, uint32 secondsAgo ) external view returns (uint256 price) { // 获取当前观察值 ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = IUniswapV3Pool(pool).observe(secondsAgo); // 计算TWAP uint256 timeElapsed = blockTimestamp - (blockTimestamp - secondsAgo); require(timeElapsed > 0, "Not enough data"); price = (price0Cumulative - price1Cumulative) / timeElapsed; return price; } } 滑点保护 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 // ✅ 滑点保护实现 import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; contract SlippageProtection { IUniswapV2Router02 public router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); function swapWithSlippage( address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut ) external returns (uint256 amountOut) { // 授权 IERC20(tokenIn).approve(address(router), amountIn); // 定义路径 address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; // 执行交换 uint256[] memory amounts = router.swapExactTokensForTokens( amountIn, minAmountOut, // 最小输出量(滑点保护) path, block.timestamp ); amountOut = amounts[1]; require( amountOut >= minAmountOut, "Slippage exceeded" ); } function calculateMinAmountOut( uint256 amountIn, uint256 slippageBps ) external pure returns (uint256) { // slippageBps: 基点,100 = 1% uint256 slippage = (amountIn * slippageBps) / 10000; return amountIn - slippage; } } // ✅ 动态滑点 contract DynamicSlippage { uint256 public baseSlippage = 30; // 0.3% uint256 public maxSlippage = 300; // 3% function getDynamicSlippage(uint256 volatility) public view returns (uint256) { // 根据波动率调整滑点 uint256 slippage = baseSlippage + (volatility * 10); // 不超过最大滑点 if (slippage > maxSlippage) { slippage = maxSlippage; } return slippage; } function swapWithDynamicSlippage( uint256 amountIn, uint256 volatility ) external returns (uint256) { uint256 slippageBps = getDynamicSlippage(volatility); uint256 minAmountOut = calculateMinAmountOut(amountIn, slippageBps); // 执行交换... } } 总结 智能合约安全审计是WEB3开发不可或缺的环节。系统性的审计流程、专业的分析工具和严格的安全实践是保护资产安全的关键。 ...

Web3与区块链开发完全指南:从智能合约到DApp

引言 Web3和区块链技术正在重塑互联网的形态。本文将深入探讨智能合约开发、DeFi协议、NFT等核心主题,帮助开发者进入Web3世界。 一、Solidity智能合约 1.1 基础合约结构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MyToken is ERC20, Ownable { uint256 public constant MAX_SUPPLY = 1_000_000_000 * 10**18; constructor() ERC20("MyToken", "MTK") { _mint(msg.sender, MAX_SUPPLY); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function burn(uint256 amount) public { _burn(msg.sender, amount); } } 1.2 安全最佳实践 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // ========== 重入攻击防护 ========== contract ReentrancyGuard { bool private locked; modifier noReentrant() { require(!locked, "Reentrant call"); locked = true; _; locked = false; } function withdraw() external noReentrant { // ... } } // ========== 访问控制 ========== contract AccessControl { mapping(address => bool) public admins; modifier onlyAdmin() { require(admins[msg.sender], "Not admin"); _; } function addAdmin(address admin) external onlyAdmin { admins[admin] = true; } } // ========== 安全数学运算 ========== library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { require(a + b >= a, "Overflow"); return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "Underflow"); return a - b; } } 二、DeFi协议开发 2.1 AMM交换池 1 2 3 4 5 6 7 8 9 10 11 12 contract AMMPool { uint256 public reserve0; uint256 public reserve1; function addLiquidity(uint256 amount0, uint256 amount1) external { // ... } function swap(uint256 amount0In, uint256 amount1In) external { // ... } } 三、NFT开发 1 2 3 4 5 6 7 8 9 10 11 12 import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; contract MyNFT is ERC721URIStorage { uint256 private _tokenIdCounter; function mint(address to, string memory uri) public returns (uint256) { uint256 tokenId = _tokenIdCounter++; _safeMint(to, tokenId); _setTokenURI(tokenId, uri); return tokenId; } } 四、前端集成 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import { ethers } from 'ethers'; // 连接钱包 async function connectWallet() { const provider = new ethers.BrowserProvider(window.ethereum); await provider.send("eth_requestAccounts", []); const signer = await provider.getSigner(); return signer; } // 调用合约 async function mintNFT(signer, contractAddress, uri) { const contract = new ethers.Contract( contractAddress, ['function mint(address to, string memory uri) returns (uint256)'], signer ); const tx = await contract.mint(await signer.getAddress(), uri); await tx.wait(); } 总结 Web3开发需要掌握智能合约、区块链原理和前端集成。持续关注安全最佳实践至关重要。 ...