Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
项目实战DeFi 投资组合追踪器
中级DeFi5-6周

DeFi 投资组合追踪器

多协议 DeFi 资产聚合追踪,支持 LP 仓位、借贷头寸、质押收益的实时计算与风险评估

技术栈

GoGraphQLRedisPostgreSQLThe Graph

核心功能

多协议资产聚合(Uniswap、Aave、Compound、Curve)
LP 无常损失实时计算
借贷健康度监控与清算预警
质押收益 APY 追踪
历史收益曲线与 PnL 报表
Gas 成本追踪与优化建议

系统架构

┌─────────────────────────────────────────────────────────────┐
│                    API Gateway (GraphQL)                     │
├─────────────────────────────────────────────────────────────┤
│  Portfolio   │  Position    │   Yield      │   Risk        │
│  Service     │  Calculator  │   Tracker    │   Analyzer    │
├─────────────────────────────────────────────────────────────┤
│              Protocol Adapters Layer                         │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐           │
│  │ Uniswap │ │  Aave   │ │Compound │ │  Curve  │           │
│  └─────────┘ └─────────┘ └─────────┘ └─────────┘           │
├─────────────────────────────────────────────────────────────┤
│  The Graph Indexer  │  Price Oracle  │  PostgreSQL         │
└─────────────────────────────────────────────────────────────┘

课程章节

第一章:GraphQL API 设计

Schema 设计与类型定义2小时
Resolver 实现与 DataLoader3小时
订阅与实时推送2小时

第二章:协议适配器开发

Uniswap V3 仓位解析4小时
Aave 借贷头寸追踪3小时
Curve LP 收益计算3小时

第三章:收益与风险计算

无常损失算法实现3小时
APY/APR 计算引擎2小时
清算风险评估模型3小时

第四章:数据聚合与缓存

The Graph 集成3小时
Redis 缓存策略2小时
历史数据归档2小时

核心代码实现

Uniswap V3 仓位计算

go
1// Position 表示 Uniswap V3 LP 仓位
2type Position struct {
3 TokenID *big.Int
4 Token0 common.Address
5 Token1 common.Address
6 Fee *big.Int
7 TickLower int32
8 TickUpper int32
9 Liquidity *big.Int
10 Amount0 *big.Int
11 Amount1 *big.Int
12}
13
14// CalculatePositionValue 计算仓位当前价值
15func (s *UniswapV3Service) CalculatePositionValue(
16 ctx context.Context,
17 position *Position,
18) (*PositionValue, error) {
19 // 获取当前池子状态
20 pool, err := s.getPoolState(ctx, position.Token0, position.Token1, position.Fee)
21 if err != nil {
22 return nil, fmt.Errorf("get pool state: %w", err)
23 }
24
25 // 计算当前 tick 下的代币数量
26 amount0, amount1 := s.calculateAmounts(
27 position.Liquidity,
28 pool.CurrentTick,
29 position.TickLower,
30 position.TickUpper,
31 pool.SqrtPriceX96,
32 )
33
34 // 获取代币价格
35 price0, _ := s.priceOracle.GetPrice(ctx, position.Token0)
36 price1, _ := s.priceOracle.GetPrice(ctx, position.Token1)
37
38 // 计算总价值 (USD)
39 value0 := new(big.Float).Mul(toFloat(amount0), price0)
40 value1 := new(big.Float).Mul(toFloat(amount1), price1)
41 totalValue := new(big.Float).Add(value0, value1)
42
43 // 计算无常损失
44 il := s.calculateImpermanentLoss(position, pool)
45
46 return &PositionValue{
47 Amount0: amount0,
48 Amount1: amount1,
49 TotalValueUSD: totalValue,
50 ImpermanentLoss: il,
51 FeesEarned: s.calculateFeesEarned(position),
52 }, nil
53}

清算风险监控

go
1// HealthFactor 计算 Aave 借贷健康度
2type HealthFactor struct {
3 Value float64
4 CollateralUSD float64
5 DebtUSD float64
6 LiquidationRisk string // "safe", "warning", "danger"
7}
8
9// MonitorLendingPosition 监控借贷仓位健康度
10func (s *RiskService) MonitorLendingPosition(
11 ctx context.Context,
12 wallet common.Address,
13) (*HealthFactor, error) {
14 // 获取用户账户数据
15 accountData, err := s.aavePool.GetUserAccountData(
16 &bind.CallOpts{Context: ctx},
17 wallet,
18 )
19 if err != nil {
20 return nil, err
21 }
22
23 // 计算健康度 = 总抵押物 * 清算阈值 / 总债务
24 healthFactor := new(big.Float).Quo(
25 toFloat(accountData.HealthFactor),
26 big.NewFloat(1e18),
27 )
28 hf, _ := healthFactor.Float64()
29
30 // 评估风险等级
31 var risk string
32 switch {
33 case hf >= 1.5:
34 risk = "safe"
35 case hf >= 1.1:
36 risk = "warning"
37 default:
38 risk = "danger"
39 }
40
41 // 危险时发送告警
42 if risk == "danger" {
43 s.alertService.SendLiquidationWarning(ctx, wallet, hf)
44 }
45
46 return &HealthFactor{
47 Value: hf,
48 CollateralUSD: toUSD(accountData.TotalCollateralBase),
49 DebtUSD: toUSD(accountData.TotalDebtBase),
50 LiquidationRisk: risk,
51 }, nil
52}
NFT 交易市场后端区块链事件索引器
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao