Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
项目实战Gas 价格追踪器
初级区块链开发1周

Gas 价格追踪器

多链 Gas 价格监控,历史趋势分析,最佳交易时机推荐

技术栈

GoEchogo-ethereumInfluxDBGrafana

核心功能

实时 Gas 价格获取
EIP-1559 费用估算
历史价格趋势图表
最佳交易时机推荐
Gas 价格告警
多链对比分析

系统架构


┌──────────────┐     ┌─────────────┐     ┌──────────────┐
│   Clients    │────▶│  Echo API   │────▶│  Blockchain  │
│  (REST/HTTP) │     │   Service   │     │ (go-ethereum)│
└──────────────┘     └─────────────┘     └──────────────┘
                            │
               ┌────────────┼────────────┐
               ▼            ▼            ▼
         ┌──────────┐ ┌──────────┐ ┌──────────┐
         │ InfluxDB │ │  Grafana │ │  Alerts  │
         │(TimeSeries)│ │(Dashboard)│ │ (Notify) │
         └──────────┘ └──────────┘ └──────────┘
  

课程章节

第一章:Gas 价格获取与解析

EIP-1559 费用机制1小时
实时 Gas 数据获取1小时
费用等级估算45分钟

第二章:时序数据存储

InfluxDB 配置45分钟
数据写入与查询1小时
聚合与窗口函数1小时

第三章:最佳时机推荐算法

历史数据分析1小时
时段统计算法1小时
推荐排序逻辑45分钟

第四章:Gas 告警系统

告警规则设计45分钟
多渠道通知1小时
防抖与静默期30分钟

核心代码实现

Gas 价格数据结构

go
1type GasPrice struct {
2 Chain string `json:"chain"`
3 Timestamp time.Time `json:"timestamp"`
4 BaseFee *big.Int `json:"base_fee"`
5 MaxPriority *big.Int `json:"max_priority"`
6 GasPrice *big.Int `json:"gas_price"` // Legacy
7
8 // 预估费用等级
9 Slow *GasEstimate `json:"slow"`
10 Standard *GasEstimate `json:"standard"`
11 Fast *GasEstimate `json:"fast"`
12 Instant *GasEstimate `json:"instant"`
13}
14
15func (s *GasService) GetGasPrice(ctx context.Context, chain string) (*GasPrice, error) {
16 client := s.clients[chain]
17 block, err := client.BlockByNumber(ctx, nil)
18 if err != nil {
19 return nil, err
20 }
21
22 baseFee := block.BaseFee()
23 priorityFee, _ := client.SuggestGasTipCap(ctx)
24
25 return &GasPrice{
26 Chain: chain,
27 Timestamp: time.Now(),
28 BaseFee: baseFee,
29 MaxPriority: priorityFee,
30 Slow: s.estimateGas(baseFee, 0.8),
31 Standard: s.estimateGas(baseFee, 1.0),
32 Fast: s.estimateGas(baseFee, 1.25),
33 Instant: s.estimateGas(baseFee, 1.5),
34 }, nil
35}

InfluxDB 存储

go
1func (s *GasStorage) SaveGasPrice(ctx context.Context, gas *GasPrice) error {
2 writeAPI := s.client.WriteAPIBlocking(s.org, s.bucket)
3
4 p := influxdb2.NewPoint(
5 "gas_price",
6 map[string]string{"chain": gas.Chain},
7 map[string]interface{}{
8 "base_fee": gas.BaseFee.Int64(),
9 "priority_fee": gas.MaxPriority.Int64(),
10 "slow_gwei": weiToGwei(gas.Slow.MaxFeePerGas),
11 "standard_gwei": weiToGwei(gas.Standard.MaxFeePerGas),
12 "fast_gwei": weiToGwei(gas.Fast.MaxFeePerGas),
13 },
14 gas.Timestamp,
15 )
16
17 return writeAPI.WritePoint(ctx, p)
18}

最佳交易时机推荐

go
1func (a *GasAnalyzer) GetBestTradingTimes(ctx context.Context, chain string) ([]*TimeRecommendation, error) {
2 history, err := a.storage.GetHistory(ctx, chain, 7*24*time.Hour)
3 if err != nil {
4 return nil, err
5 }
6
7 // 按小时和星期几分组统计
8 hourlyStats := make(map[int]map[int][]float64)
9
10 for _, gas := range history {
11 dow := int(gas.Timestamp.Weekday())
12 hour := gas.Timestamp.Hour()
13
14 if hourlyStats[dow] == nil {
15 hourlyStats[dow] = make(map[int][]float64)
16 }
17 hourlyStats[dow][hour] = append(hourlyStats[dow][hour], weiToGwei(gas.Standard.MaxFeePerGas))
18 }
19
20 var recommendations []*TimeRecommendation
21 overallAvg := a.calculateOverallAverage(history)
22
23 for dow, hours := range hourlyStats {
24 for hour, prices := range hours {
25 avg := average(prices)
26 savings := (overallAvg - avg) / overallAvg * 100
27 recommendations = append(recommendations, &TimeRecommendation{
28 Hour: hour, DayOfWeek: dow, AvgGas: avg, Savings: savings,
29 })
30 }
31 }
32
33 sort.Slice(recommendations, func(i, j int) bool {
34 return recommendations[i].Savings > recommendations[j].Savings
35 })
36 return recommendations[:10], nil
37}
NFT 元数据服务代币转账历史查询
Easy-Go-Web3

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

学习路径

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

资源中心

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

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

Created withbyhardybao