Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8357546f3c | |||
| a62141ea5e | |||
| 9157203653 | |||
| 23fc20763a | |||
| e96a0b6279 | |||
| 85d8619fe7 | |||
| 89fb980da7 | |||
| 9f0b22fab5 |
@@ -1,133 +0,0 @@
|
||||
# 🎉 v1.0.1 版本发布公告
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
2025年12月(具体日期待定)
|
||||
|
||||
## 🚀 主要更新
|
||||
|
||||
### 性能优化
|
||||
|
||||
#### 📊 订单簿请求优化
|
||||
- 优化订单簿获取逻辑,仅在需要时请求,避免不必要的 API 调用
|
||||
- 当未配置需要订单簿的过滤条件(价差、订单深度)时,跳过订单簿获取
|
||||
- 订单簿只请求一次,在过滤检查中复用,提高性能
|
||||
|
||||
#### 💰 卖出价格计算优化
|
||||
- 卖出改为市价卖出:优先使用订单簿的 bestBid(最高买入价)
|
||||
- 如果 bestBid 获取失败,自动降级使用 Leader 的交易价格
|
||||
- 卖出价格固定按 90% 计算,不再使用价格容忍度配置
|
||||
- 提高卖出订单的成交率
|
||||
|
||||
#### ⚙️ 价格容忍度默认值
|
||||
- 如果价格容忍度配置为 0,自动使用默认值 5%
|
||||
- 确保买入订单能够正常应用价格调整,提高成交率
|
||||
|
||||
### 代码优化
|
||||
|
||||
#### 🎯 使用枚举优化过滤逻辑
|
||||
- 新增 `FilterResult` 数据类和 `FilterStatus` 枚举
|
||||
- 使用类型安全的枚举替代字符串判断,提高代码可维护性
|
||||
- 移除无用字段 `isBuyOrder` 参数
|
||||
- 优化 `checkFilters` 方法返回值,使用数据类封装结果
|
||||
|
||||
#### 📝 代码结构优化
|
||||
- 减少 if-else 嵌套,使用 Kotlin 链式调用和空安全操作符
|
||||
- 优化卖出价格计算逻辑,使用 `runCatching` 和 `?.let` 简化代码
|
||||
- 提取公共方法 `calculateFallbackSellPrice`,提高代码复用性
|
||||
|
||||
### 功能改进
|
||||
|
||||
#### 🗑️ 移除最小订单簿深度功能
|
||||
- 移除 `minOrderbookDepth`(最小订单簿深度)配置项
|
||||
- 简化过滤逻辑,只保留 `minOrderDepth`(最小订单深度)
|
||||
- 更新前端界面,移除相关配置项和提示文案
|
||||
|
||||
#### 📈 优化最小订单深度逻辑
|
||||
- 修改 `minOrderDepth` 检查逻辑,检查所有方向(买盘+卖盘)的总深度
|
||||
- 不再区分买卖方向,提供更全面的市场流动性评估
|
||||
|
||||
#### 🎯 市场结算判断优化
|
||||
- 添加市场已关闭时的结算判断逻辑
|
||||
- 如果市场已关闭且该 outcome 赢了(价格 >= 0.99),返回价格为 1
|
||||
- 如果市场已关闭且该 outcome 输了(价格 <= 0.01),返回价格为 0
|
||||
- 当没有仓位但有未完成订单时,正确判断市场结算状态并设置价格
|
||||
|
||||
### Bug 修复
|
||||
|
||||
- ✅ 修复盈亏和持仓价值计算逻辑未实现的问题
|
||||
- ✅ 修复过滤检查中订单簿可能重复请求的问题
|
||||
- ✅ 修复健康检查路径不一致问题(从 `/api/health` 改为 `/api/system/health`)
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### Docker 部署
|
||||
|
||||
```bash
|
||||
# 拉取最新镜像
|
||||
docker pull wrbug/polyhermes:v1.0.1
|
||||
|
||||
# 或使用 latest 标签
|
||||
docker pull wrbug/polyhermes:latest
|
||||
|
||||
# 重启容器
|
||||
docker-compose down
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### 源码部署
|
||||
|
||||
```bash
|
||||
# 拉取最新代码
|
||||
git fetch origin
|
||||
git checkout v1.0.1
|
||||
|
||||
# 重新构建
|
||||
cd backend
|
||||
./gradlew bootJar
|
||||
|
||||
# 重启服务
|
||||
# 根据您的部署方式重启服务
|
||||
```
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 更新前端多语言文案,优化提示信息
|
||||
- 移除最小订单簿深度相关的文档说明
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.0.1
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.0.0...v1.0.1
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.0.1
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
**💬 如有问题或建议,欢迎在 GitHub Issues 中反馈。**
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
# 🎉 v1.1.0 版本更新指南
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
2025年12月26日
|
||||
|
||||
## 🎯 这次更新对您意味着什么?
|
||||
|
||||
### ⚡ 更快的跟单响应速度
|
||||
- **实时链上监听**:通过 WebSocket 实时监听链上交易,跟单响应速度提升 50% 以上
|
||||
- **双重保障**:链上监听和轮询同时运行,确保不错过任何交易机会
|
||||
- **自动去重**:系统自动处理重复数据,确保每笔交易只执行一次
|
||||
|
||||
### 💰 更准确的盈亏统计
|
||||
- **实际成交价追踪**:系统会自动更新卖出订单的实际成交价,而不是下单时的价格
|
||||
- **自动价格更新**:每 5 秒自动查询并更新订单的实际成交价
|
||||
- **精确盈亏计算**:基于实际成交价计算盈亏,统计数据更准确
|
||||
|
||||
### 🔧 更灵活的系统配置
|
||||
- **RPC 节点管理**:可以添加、编辑、删除自定义 RPC 节点
|
||||
- **节点启用/禁用**:可以随时启用或禁用节点,无需删除配置
|
||||
- **智能节点选择**:系统自动选择可用的节点,禁用的节点会被忽略
|
||||
|
||||
### 🐛 问题修复
|
||||
- **修复卖出订单失败问题**:修复了部分情况下卖出订单因 API 凭证问题导致的失败
|
||||
- **修复订单精度错误**:修复了卖出订单因精度问题导致的 API 错误
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### 方式一:使用 Docker(推荐)
|
||||
|
||||
#### 步骤 1:备份数据(强烈推荐)
|
||||
|
||||
**备份不是必须的,但强烈推荐!**
|
||||
|
||||
**为什么需要备份?**
|
||||
- Docker 更新不会删除数据(数据存储在独立的数据卷中)
|
||||
- 但数据库结构可能会变更(本次更新会添加 `price_updated` 字段)
|
||||
- 如果迁移失败或出现问题,备份可以帮助恢复数据
|
||||
- 生产环境建议必须备份,开发环境可以跳过
|
||||
|
||||
**如何备份?**
|
||||
|
||||
```bash
|
||||
# 方式 1:使用 mysqldump 备份数据库(推荐)
|
||||
docker exec polyhermes-mysql mysqldump -u root -p polyhermes > backup_$(date +%Y%m%d_%H%M%S).sql
|
||||
|
||||
# 方式 2:备份整个 MySQL 数据卷
|
||||
docker run --rm -v polyhermes_mysql-data:/data -v $(pwd):/backup alpine tar czf /backup/mysql_backup_$(date +%Y%m%d_%H%M%S).tar.gz /data
|
||||
|
||||
# 方式 3:如果已有定期备份,可以跳过此步骤
|
||||
```
|
||||
|
||||
**什么情况下可以跳过备份?**
|
||||
- ✅ 开发环境或测试环境
|
||||
- ✅ 数据不重要或可以重新生成
|
||||
- ✅ 已经有定期自动备份
|
||||
- ✅ 确定迁移不会失败(查看更新日志确认)
|
||||
|
||||
**什么情况下必须备份?**
|
||||
- ⚠️ 生产环境
|
||||
- ⚠️ 包含重要交易数据
|
||||
- ⚠️ 不确定迁移是否安全
|
||||
|
||||
#### 步骤 2:停止当前服务
|
||||
|
||||
```bash
|
||||
# 进入部署目录
|
||||
cd /path/to/polyhermes
|
||||
|
||||
# 停止服务
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
```
|
||||
|
||||
#### 步骤 3:拉取新版本
|
||||
|
||||
```bash
|
||||
# 拉取 v1.1.0 版本
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
# 或者拉取最新版本(推荐)
|
||||
docker pull wrbug/polyhermes:latest
|
||||
```
|
||||
|
||||
#### 步骤 4:更新配置(如果需要)
|
||||
|
||||
如果您想固定使用 v1.1.0 版本,可以编辑 `docker-compose.prod.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: wrbug/polyhermes:v1.1.0 # 修改这里
|
||||
```
|
||||
|
||||
#### 步骤 5:启动服务
|
||||
|
||||
```bash
|
||||
# 启动服务
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# 查看日志,确认服务正常启动
|
||||
docker-compose -f docker-compose.prod.yml logs -f
|
||||
```
|
||||
|
||||
#### 步骤 6:验证更新
|
||||
|
||||
1. 访问系统首页,查看页面标题是否显示 `v1.1.0`
|
||||
2. 检查系统功能是否正常
|
||||
3. 查看日志是否有错误信息
|
||||
|
||||
### 方式二:一键更新脚本
|
||||
|
||||
如果您使用 `latest` 标签,可以使用以下命令一键更新:
|
||||
|
||||
```bash
|
||||
# 进入部署目录
|
||||
cd /path/to/polyhermes
|
||||
|
||||
# 拉取最新镜像并重启
|
||||
docker-compose -f docker-compose.prod.yml pull
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# 查看日志
|
||||
docker-compose -f docker-compose.prod.yml logs -f
|
||||
```
|
||||
|
||||
## ⚠️ 更新注意事项
|
||||
|
||||
### 1. 数据库迁移
|
||||
- 本次更新会自动执行数据库迁移(添加 `price_updated` 字段)
|
||||
- 迁移过程不会影响现有数据,只是添加新字段
|
||||
- 迁移是安全的,但如果迁移失败,请检查数据库权限和连接
|
||||
- **如果迁移失败,可以使用备份恢复数据**
|
||||
|
||||
### 2. 服务中断时间
|
||||
- 更新过程中服务会短暂中断(通常 1-2 分钟)
|
||||
- 建议在低峰期进行更新
|
||||
- 更新期间正在进行的跟单操作可能会受影响
|
||||
|
||||
### 3. 配置检查
|
||||
- 更新后请检查 RPC 节点配置是否正确
|
||||
- 如果使用自定义 RPC 节点,请确认节点状态正常
|
||||
|
||||
### 4. 功能验证
|
||||
更新后建议验证以下功能:
|
||||
- ✅ 跟单功能是否正常
|
||||
- ✅ 订单价格更新是否正常
|
||||
- ✅ RPC 节点管理是否正常
|
||||
- ✅ 盈亏统计是否准确
|
||||
|
||||
## 🆕 新功能使用指南
|
||||
|
||||
### 1. RPC 节点管理
|
||||
|
||||
#### 如何添加自定义 RPC 节点?
|
||||
|
||||
1. 登录系统,进入 **系统设置** → **RPC 节点设置**
|
||||
2. 点击 **添加节点** 按钮
|
||||
3. 填写节点信息:
|
||||
- **节点名称**:给节点起个名字(如:Alchemy Polygon)
|
||||
- **RPC URL**:节点的 HTTP/HTTPS 地址
|
||||
- **启用状态**:默认启用,可以稍后禁用
|
||||
4. 点击 **保存**
|
||||
|
||||
#### 如何启用/禁用节点?
|
||||
|
||||
1. 在 RPC 节点列表中,找到要操作的节点
|
||||
2. 点击 **启用/禁用** 开关
|
||||
3. 系统会自动更新节点状态
|
||||
|
||||
**提示**:
|
||||
- 禁用的节点不会被使用,但配置会保留
|
||||
- 可以随时重新启用禁用的节点
|
||||
- 建议至少保留一个启用的节点
|
||||
|
||||
### 2. 实际成交价追踪
|
||||
|
||||
#### 这个功能做什么?
|
||||
|
||||
系统会自动追踪卖出订单的实际成交价,而不是使用下单时的价格。这样可以:
|
||||
- 更准确地计算盈亏
|
||||
- 了解订单的实际执行情况
|
||||
- 优化卖出策略
|
||||
|
||||
#### 如何查看实际成交价?
|
||||
|
||||
1. 进入 **跟单统计** → **卖出订单**
|
||||
2. 查看订单列表,**卖出价格** 列显示的是实际成交价
|
||||
3. 如果价格旁边有更新标记,说明价格已从订单详情中获取
|
||||
|
||||
**注意**:
|
||||
- 价格更新是自动的,每 5 秒检查一次
|
||||
- 如果订单还未成交,价格可能还是下单时的价格
|
||||
- 部分成交的订单会使用加权平均价格
|
||||
|
||||
## 🔍 常见问题
|
||||
|
||||
### Q1: 更新后无法启动怎么办?
|
||||
|
||||
**A:** 请按以下步骤排查:
|
||||
|
||||
1. 检查日志:`docker-compose -f docker-compose.prod.yml logs`
|
||||
2. 检查数据库连接是否正常
|
||||
3. 检查端口是否被占用
|
||||
4. 如果问题持续,可以回退到之前的版本:
|
||||
```bash
|
||||
# 修改 docker-compose.prod.yml 中的镜像标签为之前的版本
|
||||
# 例如:image: wrbug/polyhermes:v1.0.3
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
### Q2: 更新后跟单不工作怎么办?
|
||||
|
||||
**A:** 请检查:
|
||||
|
||||
1. RPC 节点是否正常(进入 RPC 节点设置查看)
|
||||
2. 跟单配置是否启用
|
||||
3. 账户 API 凭证是否有效
|
||||
4. 查看系统日志是否有错误信息
|
||||
|
||||
### Q3: 如何回退到之前的版本?
|
||||
|
||||
**A:** 按以下步骤操作:
|
||||
|
||||
1. 停止当前服务:`docker-compose -f docker-compose.prod.yml down`
|
||||
2. 修改 `docker-compose.prod.yml` 中的镜像标签为之前的版本
|
||||
3. 启动服务:`docker-compose -f docker-compose.prod.yml up -d`
|
||||
|
||||
**注意**:回退版本时,数据库结构可能不兼容,建议先备份数据库。
|
||||
|
||||
### Q4: 更新后数据会丢失吗?
|
||||
|
||||
**A:** 不会。更新过程不会删除任何数据。但为了安全起见,建议更新前备份数据库。
|
||||
|
||||
### Q5: 如何查看当前版本?
|
||||
|
||||
**A:** 有两种方式:
|
||||
|
||||
1. **页面查看**:登录系统后,页面标题会显示版本号(如:PolyHermes v1.1.0)
|
||||
2. **命令行查看**:
|
||||
```bash
|
||||
docker inspect polyhermes | grep -i version
|
||||
```
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [完整更新日志](https://github.com/WrBug/PolyHermes/compare/v1.0.3...v1.1.0)
|
||||
- [部署文档](docs/zh/DEPLOYMENT.md)
|
||||
- [版本管理文档](docs/zh/VERSION_MANAGEMENT.md)
|
||||
|
||||
## 🔗 获取帮助
|
||||
|
||||
如果更新过程中遇到问题:
|
||||
|
||||
1. 查看 [GitHub Issues](https://github.com/WrBug/PolyHermes/issues)
|
||||
2. 查看系统日志:`docker-compose -f docker-compose.prod.yml logs -f`
|
||||
3. 在 GitHub 上提交 Issue,描述您的问题
|
||||
|
||||
## ⚠️ 安全提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
**💬 如有问题或建议,欢迎在 GitHub Issues 中反馈。**
|
||||
|
||||
@@ -270,7 +270,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -337,7 +336,6 @@ cd frontend
|
||||
| `DB_USERNAME` | 数据库用户名 | `root` |
|
||||
| `DB_PASSWORD` | 数据库密码 | - |
|
||||
| `SERVER_PORT` | 后端服务端口 | `8000` |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC 地址 | `https://polygon-rpc.com` |
|
||||
| `JWT_SECRET` | JWT 密钥 | - |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | 管理员密码重置密钥 | - |
|
||||
| `CRYPTO_SECRET_KEY` | 加密密钥(用于加密存储私钥和 API Key) | - |
|
||||
|
||||
@@ -270,7 +270,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -337,7 +336,6 @@ cd frontend
|
||||
| `DB_USERNAME` | Database username | `root` |
|
||||
| `DB_PASSWORD` | Database password | - |
|
||||
| `SERVER_PORT` | Backend service port | `8000` |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC address | `https://polygon-rpc.com` |
|
||||
| `JWT_SECRET` | JWT secret key | - |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | Admin password reset key | - |
|
||||
| `CRYPTO_SECRET_KEY` | Encryption key (for encrypting stored private keys and API Keys) | - |
|
||||
|
||||
@@ -1,3 +1,67 @@
|
||||
# v1.1.1
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 监听优化
|
||||
- 创建 `UnifiedOnChainWsService` 统一管理 WebSocket 连接,所有服务共享同一个连接
|
||||
- 创建 `OnChainWsUtils` 工具类,提取公共的链上 WebSocket 相关功能
|
||||
- 创建 `AccountOnChainMonitorService` 监听账户链上卖出和赎回事件
|
||||
- 优化 `OnChainWsService`,复用公共代码,减少代码重复
|
||||
- 支持通过链上 WebSocket 实时监听账户的卖出和赎回交易,自动更新订单状态
|
||||
|
||||
### 📊 市场状态查询优化
|
||||
- 优化市场结算状态查询,优先使用链上查询 `ConditionalTokens.getCondition`
|
||||
- 如果链上查询失败,自动降级到 Gamma API 查询
|
||||
- 提供更实时和准确的市场结算结果
|
||||
|
||||
### 🔕 自动订单通知优化
|
||||
- 自动生成的订单(AUTO_、AUTO_FIFO_、AUTO_WS_ 前缀)不再发送 Telegram 通知
|
||||
- 优化 `OrderStatusUpdateService`,跳过自动生成订单的通知处理
|
||||
- 减少不必要的通知,提升用户体验
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复移动端 API 健康页面缺少数据显示
|
||||
- 移动端添加 URL 地址显示
|
||||
- 移动端添加状态文本显示(正常/异常/未配置)
|
||||
- 移动端添加消息/状态信息显示
|
||||
- 移动端和桌面端显示信息保持一致
|
||||
|
||||
## 🔧 功能优化
|
||||
|
||||
### 优化 Telegram 推送消息格式
|
||||
- 添加价格和数量截位处理:
|
||||
* 价格保留最多4位小数(截断,不四舍五入)
|
||||
* 数量保留最多2位小数(截断,不四舍五入)
|
||||
- 优化账户信息显示格式:
|
||||
* 有账户名和钱包地址时显示:账户名(0x123...123)
|
||||
* 只有账户名时显示账户名
|
||||
* 只有钱包地址时显示脱敏后的地址
|
||||
* 都没有时显示未知账户
|
||||
|
||||
### 配置优化
|
||||
- 移除 `polygon.rpc.url` 配置,使用 RpcNodeService 统一管理 RPC 节点
|
||||
- 删除无用的 `position.push.polling-interval` 和 `position.push.heartbeat-timeout` 配置项
|
||||
- 修正日志配置中的包名(polyhermes -> polymarketbot)
|
||||
- 更新 `ApiHealthCheckService` 直接使用 `RpcNodeService.getHttpUrl()`
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 统一发布说明文件,使用 RELEASE.md 替代版本化文件(RELEASE_v1.0.1.md、RELEASE_v1.1.0.md)
|
||||
- 更新所有部署文档,移除 POLYGON_RPC_URL 相关说明
|
||||
- 更新所有 Docker Compose 配置文件,移除 POLYGON_RPC_URL 环境变量
|
||||
- 更新所有部署脚本,移除 POLYGON_RPC_URL 环境变量定义
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 重构链上 WebSocket 服务,提取公共代码到 `OnChainWsUtils`
|
||||
- 创建统一的 WebSocket 连接管理服务 `UnifiedOnChainWsService`
|
||||
- 添加链上查询市场结算结果的功能(`BlockchainService.getCondition`)
|
||||
- 添加 ABI 编码/解码工具方法(`EthereumUtils.decodeConditionResult`)
|
||||
- 优化代码结构,减少代码重复,提高可维护性
|
||||
|
||||
---
|
||||
|
||||
# v1.1.0
|
||||
|
||||
## 🚀 主要功能
|
||||
@@ -61,10 +125,16 @@
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.0
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.0.3...v1.1.0
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.1
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.1.0...v1.1.1
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## 📊 统计信息
|
||||
|
||||
- **文件变更**: 32 个文件
|
||||
- **代码变更**: +1872 行 / -1503 行
|
||||
- **主要提交**: 7 个提交
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
@@ -75,7 +145,7 @@
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
docker pull wrbug/polyhermes:v1.1.1
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
@@ -93,3 +163,4 @@ docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# v1.0.1
|
||||
|
||||
## 🚀 性能优化
|
||||
|
||||
### 📊 订单簿请求优化
|
||||
* 优化订单簿获取逻辑,仅在需要时请求,避免不必要的 API 调用
|
||||
* 当未配置需要订单簿的过滤条件(价差、订单深度)时,跳过订单簿获取
|
||||
* 订单簿只请求一次,在过滤检查中复用,提高性能
|
||||
|
||||
### 💰 卖出价格计算优化
|
||||
* 卖出改为市价卖出:优先使用订单簿的 bestBid(最高买入价)
|
||||
* 如果 bestBid 获取失败,自动降级使用 Leader 的交易价格
|
||||
* 卖出价格固定按 90% 计算,不再使用价格容忍度配置
|
||||
* 提高卖出订单的成交率
|
||||
|
||||
### ⚙️ 价格容忍度默认值
|
||||
* 如果价格容忍度配置为 0,自动使用默认值 5%
|
||||
* 确保买入订单能够正常应用价格调整,提高成交率
|
||||
|
||||
## 🔧 代码优化
|
||||
|
||||
### 🎯 使用枚举优化过滤逻辑
|
||||
* 新增 `FilterResult` 数据类和 `FilterStatus` 枚举
|
||||
* 使用类型安全的枚举替代字符串判断,提高代码可维护性
|
||||
* 移除无用字段 `isBuyOrder` 参数
|
||||
* 优化 `checkFilters` 方法返回值,使用数据类封装结果
|
||||
|
||||
### 📝 代码结构优化
|
||||
* 减少 if-else 嵌套,使用 Kotlin 链式调用和空安全操作符
|
||||
* 优化卖出价格计算逻辑,使用 `runCatching` 和 `?.let` 简化代码
|
||||
* 提取公共方法 `calculateFallbackSellPrice`,提高代码复用性
|
||||
|
||||
## 🗑️ 功能移除
|
||||
|
||||
### 移除最小订单簿深度功能
|
||||
* 移除 `minOrderbookDepth`(最小订单簿深度)配置项
|
||||
* 简化过滤逻辑,只保留 `minOrderDepth`(最小订单深度)
|
||||
* 更新前端界面,移除相关配置项和提示文案
|
||||
|
||||
### 优化最小订单深度逻辑
|
||||
* 修改 `minOrderDepth` 检查逻辑,检查所有方向(买盘+卖盘)的总深度
|
||||
* 不再区分买卖方向,提供更全面的市场流动性评估
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
* 修复盈亏和持仓价值计算逻辑未实现的问题
|
||||
* 修复过滤检查中订单簿可能重复请求的问题
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
* 更新前端多语言文案,优化提示信息
|
||||
* 移除最小订单簿深度相关的文档说明
|
||||
|
||||
**Full Changelog**: https://github.com/WrBug/polymarket-bot/compare/v1.0.0...v1.0.1
|
||||
|
||||
@@ -154,9 +154,6 @@ SPRING_PROFILES_ACTIVE=prod
|
||||
# 服务器端口
|
||||
SERVER_PORT=8000
|
||||
|
||||
# Polygon RPC
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# JWT 密钥(已自动生成随机值,生产环境建议修改)
|
||||
JWT_SECRET=${JWT_SECRET}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
- JWT_SECRET=${JWT_SECRET:-change-me-in-production}
|
||||
- ADMIN_RESET_PASSWORD_KEY=${ADMIN_RESET_PASSWORD_KEY:-change-me-in-production}
|
||||
depends_on:
|
||||
|
||||
@@ -16,12 +16,14 @@ interface PolymarketGammaApi {
|
||||
* 根据 condition ID 列表获取市场信息
|
||||
* 文档: https://docs.polymarket.com/api-reference/markets/list-markets
|
||||
* @param conditionIds condition ID 数组(16 进制字符串,如 "0x...")
|
||||
* @param clobTokenIds CLOB token ID 数组(用于通过 tokenId 查询市场)
|
||||
* @param includeTag 是否包含标签信息
|
||||
* @return 市场信息数组
|
||||
*/
|
||||
@GET("/markets")
|
||||
suspend fun listMarkets(
|
||||
@Query("condition_ids") conditionIds: List<String>? = null,
|
||||
@Query("clob_token_ids") clobTokenIds: List<String>? = null,
|
||||
@Query("include_tag") includeTag: Boolean? = null
|
||||
): Response<List<MarketResponse>>
|
||||
}
|
||||
@@ -51,6 +53,9 @@ data class MarketResponse(
|
||||
val liquidityNum: Double? = null,
|
||||
val lastTradePrice: Double? = null,
|
||||
val bestBid: Double? = null,
|
||||
val bestAsk: Double? = null
|
||||
val bestAsk: Double? = null,
|
||||
// 以下字段可能存在于响应中,但不在标准文档中
|
||||
val clobTokenIds: String? = null, // CLOB token IDs(可能是 JSON 字符串或数组)
|
||||
val clob_token_ids: String? = null // 下划线格式(兼容不同 API 版本)
|
||||
)
|
||||
|
||||
|
||||
+97
-10
@@ -23,8 +23,10 @@ import com.wrbug.polymarketbot.service.system.RelayClientService
|
||||
import com.wrbug.polymarketbot.service.system.TelegramNotificationService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.JsonUtils
|
||||
import com.wrbug.polymarketbot.service.common.BlockchainService
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
import java.math.BigInteger
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
@@ -45,7 +47,8 @@ class PositionCheckService(
|
||||
private val telegramNotificationService: TelegramNotificationService?,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val messageSource: MessageSource,
|
||||
private val retrofitFactory: RetrofitFactory
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val blockchainService: BlockchainService
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(PositionCheckService::class.java)
|
||||
@@ -427,14 +430,45 @@ class PositionCheckService(
|
||||
|
||||
/**
|
||||
* 获取当前市场最新价(用于更新订单卖出价)
|
||||
* 优先使用 bestBid(最优买价),如果没有则使用 midpoint(中间价)
|
||||
* 优先使用链上查询获取市场结算结果,如果未结算则使用 API 查询
|
||||
* 如果市场已关闭:
|
||||
* - 该 outcome 赢了,返回 1
|
||||
* - 该 outcome 输了,返回 0
|
||||
*/
|
||||
private suspend fun getCurrentMarketPrice(marketId: String, outcomeIndex: Int): BigDecimal {
|
||||
return try {
|
||||
// 先获取市场信息,检查市场是否已关闭
|
||||
// 优先从链上查询市场结算结果(实时性高)
|
||||
val chainResult = blockchainService.getCondition(marketId)
|
||||
chainResult.fold(
|
||||
onSuccess = { (payoutDenominator, payouts) ->
|
||||
// 如果 payouts 不为空,说明市场已结算
|
||||
if (payouts.isNotEmpty() && outcomeIndex < payouts.size) {
|
||||
val payout = payouts[outcomeIndex]
|
||||
when {
|
||||
payout > BigInteger.ZERO -> {
|
||||
// payout > 0 表示赢了
|
||||
logger.info("从链上查询到市场已结算,该 outcome 赢了: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
return BigDecimal.ONE
|
||||
}
|
||||
payout == BigInteger.ZERO -> {
|
||||
// payout == 0 表示输了
|
||||
logger.info("从链上查询到市场已结算,该 outcome 输了: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
return BigDecimal.ZERO
|
||||
}
|
||||
else -> {
|
||||
logger.warn("从链上查询到异常的 payout 值: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.debug("从链上查询到市场尚未结算: marketId=$marketId, payouts=${payouts.size}")
|
||||
}
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.debug("链上查询市场条件失败,降级到 API 查询: marketId=$marketId, error=${e.message}")
|
||||
}
|
||||
)
|
||||
|
||||
// 链上查询失败或市场未结算,降级到 API 查询
|
||||
val gammaApi = retrofitFactory.createGammaApi()
|
||||
val marketResponse = gammaApi.listMarkets(conditionIds = listOf(marketId))
|
||||
|
||||
@@ -442,20 +476,27 @@ class PositionCheckService(
|
||||
val markets = marketResponse.body()!!
|
||||
val market = markets.firstOrNull()
|
||||
|
||||
if (market != null && market.closed == true) {
|
||||
// 市场已关闭,检查该 outcome 是赢了还是输了
|
||||
if (market != null) {
|
||||
// 检查市场是否已结束:1) closed == true 或 2) endDate 已过
|
||||
val isMarketEnded = checkIfMarketEnded(market)
|
||||
|
||||
if (isMarketEnded) {
|
||||
logger.debug("市场已结束: marketId=$marketId, closed=${market.closed}, endDate=${market.endDate}")
|
||||
// 市场已结束,检查该 outcome 是赢了还是输了
|
||||
val outcomeResult = checkOutcomeResult(market, outcomeIndex)
|
||||
when (outcomeResult) {
|
||||
OutcomeResult.WON -> {
|
||||
logger.info("市场已关闭且该 outcome 赢了,返回价格为 1: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
logger.info("市场已结束且该 outcome 赢了,返回价格为 1: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
return BigDecimal.ONE
|
||||
}
|
||||
OutcomeResult.LOST -> {
|
||||
logger.info("市场已关闭且该 outcome 输了,返回价格为 0: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
logger.info("市场已结束且该 outcome 输了,返回价格为 0: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
return BigDecimal.ZERO
|
||||
}
|
||||
OutcomeResult.UNKNOWN -> {
|
||||
// 无法判断,继续使用正常价格逻辑
|
||||
// 无法判断,记录警告并继续使用正常价格逻辑
|
||||
logger.warn("市场已结束但无法判断 outcome 结果,使用正常价格: marketId=$marketId, outcomeIndex=$outcomeIndex, closed=${market.closed}, endDate=${market.endDate}, outcomePrices=${market.outcomePrices}, bestBid=${market.bestBid}, bestAsk=${market.bestAsk}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -477,6 +518,50 @@ class PositionCheckService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查市场是否已结束
|
||||
* 判断条件:
|
||||
* 1. closed == true
|
||||
* 2. 或 endDate 已过(如果 endDate 不为空)
|
||||
*/
|
||||
private fun checkIfMarketEnded(market: com.wrbug.polymarketbot.api.MarketResponse): Boolean {
|
||||
// 1. 检查 closed 字段
|
||||
if (market.closed == true) {
|
||||
return true
|
||||
}
|
||||
|
||||
// 2. 检查 endDate 是否已过
|
||||
val endDateStr = market.endDate
|
||||
if (endDateStr != null && endDateStr.isNotBlank()) {
|
||||
try {
|
||||
// endDate 可能是 ISO 8601 格式字符串或时间戳
|
||||
val endDate = if (endDateStr.matches(Regex("^\\d+$"))) {
|
||||
// 时间戳(秒或毫秒)
|
||||
val timestamp = endDateStr.toLong()
|
||||
// 判断是秒还是毫秒(如果小于 10^10,认为是秒)
|
||||
if (timestamp < 10000000000L) {
|
||||
timestamp * 1000 // 转换为毫秒
|
||||
} else {
|
||||
timestamp
|
||||
}
|
||||
} else {
|
||||
// ISO 8601 格式,尝试解析
|
||||
java.time.Instant.parse(endDateStr).toEpochMilli()
|
||||
}
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
if (now >= endDate) {
|
||||
logger.debug("市场 endDate 已过: marketId=${market.conditionId}, endDate=$endDateStr, now=$now")
|
||||
return true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.warn("解析 endDate 失败: marketId=${market.conditionId}, endDate=$endDateStr, error=${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Outcome 结果枚举
|
||||
*/
|
||||
@@ -628,7 +713,8 @@ class PositionCheckService(
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // 自动生成的订单,直接标记为已处理,不发送通知
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
@@ -742,7 +828,8 @@ class PositionCheckService(
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // 自动生成的订单,直接标记为已处理,不发送通知
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
|
||||
@@ -602,6 +602,73 @@ class BlockchainService(
|
||||
return Result.success(txHash)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从链上查询市场条件(Condition)的结算结果
|
||||
* 通过调用 ConditionalTokens 合约的 getCondition 函数获取 payouts
|
||||
*
|
||||
* @param conditionId 市场条件ID(bytes32,必须是 0x 开头的 66 位十六进制字符串)
|
||||
* @return Result<Pair<payoutDenominator, payouts>>
|
||||
* - payoutDenominator: 支付分母(通常为 1)
|
||||
* - payouts: 每个 outcome 的支付金额数组(0 或 1)
|
||||
* - 如果 payouts[outcomeIndex] == 1,表示该 outcome 赢了
|
||||
* - 如果 payouts[outcomeIndex] == 0,表示该 outcome 输了
|
||||
* - 如果 payouts 为空,表示市场尚未结算
|
||||
*/
|
||||
suspend fun getCondition(conditionId: String): Result<Pair<BigInteger, List<BigInteger>>> {
|
||||
return try {
|
||||
// 验证 conditionId 格式
|
||||
if (conditionId.isBlank() || !conditionId.startsWith("0x") || conditionId.length != 66) {
|
||||
return Result.failure(IllegalArgumentException("conditionId 格式错误,必须是 0x 开头的 66 位十六进制字符串"))
|
||||
}
|
||||
|
||||
val rpcApi = polygonRpcApi
|
||||
|
||||
// 构建 getCondition(bytes32) 函数调用
|
||||
// 函数签名: getCondition(bytes32)
|
||||
val functionSelector = EthereumUtils.getFunctionSelector("getCondition(bytes32)")
|
||||
val encodedConditionId = EthereumUtils.encodeBytes32(conditionId)
|
||||
val data = functionSelector + encodedConditionId
|
||||
|
||||
// 构建 JSON-RPC 请求
|
||||
val rpcRequest = JsonRpcRequest(
|
||||
method = "eth_call",
|
||||
params = listOf(
|
||||
mapOf(
|
||||
"to" to conditionalTokensAddress,
|
||||
"data" to data
|
||||
),
|
||||
"latest"
|
||||
)
|
||||
)
|
||||
|
||||
// 发送 RPC 请求
|
||||
val response = rpcApi.call(rpcRequest)
|
||||
|
||||
if (!response.isSuccessful || response.body() == null) {
|
||||
return Result.failure(Exception("RPC 请求失败: ${response.code()} ${response.message()}"))
|
||||
}
|
||||
|
||||
val rpcResponse = response.body()!!
|
||||
|
||||
// 检查错误
|
||||
if (rpcResponse.error != null) {
|
||||
return Result.failure(Exception("RPC 错误: ${rpcResponse.error.message}"))
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 result(JsonElement)
|
||||
val hexResult = rpcResponse.result?.asString
|
||||
?: return Result.failure(Exception("RPC 响应格式错误: result 为空"))
|
||||
|
||||
// 解析 ABI 编码的返回结果
|
||||
val (payoutDenominator, payouts) = EthereumUtils.decodeConditionResult(hexResult)
|
||||
|
||||
Result.success(Pair(payoutDenominator, payouts))
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询市场条件失败: conditionId=$conditionId, ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询交易详情(用于调试和分析)
|
||||
* @param txHash 交易哈希
|
||||
|
||||
+10
-6
@@ -151,13 +151,14 @@ class CopyTradingService(
|
||||
|
||||
val saved = copyTradingRepository.save(copyTrading)
|
||||
|
||||
// 如果跟单已启用,更新 Leader 监听(增量更新,不重启所有监听)
|
||||
// 如果跟单已启用,更新 Leader 监听和账户监听(增量更新,不重启所有监听)
|
||||
if (saved.enabled) {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.updateLeaderMonitoring(saved.leaderId)
|
||||
monitorService.updateAccountMonitoring(saved.accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,12 +220,13 @@ class CopyTradingService(
|
||||
|
||||
val saved = copyTradingRepository.save(updated)
|
||||
|
||||
// 更新 Leader 监听(增量更新,根据 enabled 状态决定添加或移除)
|
||||
// 更新 Leader 监听和账户监听(增量更新,根据 enabled 状态决定添加或移除)
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.updateLeaderMonitoring(saved.leaderId)
|
||||
monitorService.updateAccountMonitoring(saved.accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,14 +325,16 @@ class CopyTradingService(
|
||||
?: return Result.failure(IllegalArgumentException("跟单配置不存在"))
|
||||
|
||||
val leaderId = copyTrading.leaderId
|
||||
val accountId = copyTrading.accountId
|
||||
copyTradingRepository.delete(copyTrading)
|
||||
|
||||
// 更新 Leader 监听(检查该 Leader 是否还有其他启用的跟单配置)
|
||||
// 更新 Leader 监听和账户监听(检查是否还有其他启用的跟单配置)
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.removeLeaderMonitoring(leaderId)
|
||||
monitorService.updateAccountMonitoring(accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.entity.Account
|
||||
import com.wrbug.polymarketbot.entity.CopyOrderTracking
|
||||
import com.wrbug.polymarketbot.entity.SellMatchDetail
|
||||
import com.wrbug.polymarketbot.entity.SellMatchRecord
|
||||
import com.wrbug.polymarketbot.repository.AccountRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyOrderTrackingRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyTradingRepository
|
||||
import com.wrbug.polymarketbot.repository.SellMatchDetailRepository
|
||||
import com.wrbug.polymarketbot.repository.SellMatchRecordRepository
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.multi
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 跟单账户链上 WebSocket 监听服务
|
||||
* 通过统一服务订阅跟单账户的卖出和赎回事件
|
||||
* 用于更新订单状态,不再依赖轮询
|
||||
*/
|
||||
@Service
|
||||
class AccountOnChainMonitorService(
|
||||
private val unifiedOnChainWsService: UnifiedOnChainWsService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val copyTradingRepository: CopyTradingRepository,
|
||||
private val copyOrderTrackingRepository: CopyOrderTrackingRepository,
|
||||
private val sellMatchRecordRepository: SellMatchRecordRepository,
|
||||
private val sellMatchDetailRepository: SellMatchDetailRepository
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AccountOnChainMonitorService::class.java)
|
||||
|
||||
// 存储需要监听的账户:accountId -> Account
|
||||
private val monitoredAccounts = ConcurrentHashMap<Long, Account>()
|
||||
|
||||
/**
|
||||
* 启动链上 WebSocket 监听
|
||||
* 通过统一服务订阅所有跟单账户
|
||||
*/
|
||||
fun start(accounts: List<Account>) {
|
||||
// 如果没有账户,取消所有订阅
|
||||
if (accounts.isEmpty()) {
|
||||
logger.info("没有需要监听的跟单账户,取消所有订阅")
|
||||
stop()
|
||||
return
|
||||
}
|
||||
|
||||
// 更新账户列表
|
||||
monitoredAccounts.clear()
|
||||
accounts.forEach { account ->
|
||||
addAccount(account)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加账户监听
|
||||
* 通过统一服务订阅该账户的地址
|
||||
*/
|
||||
fun addAccount(account: Account) {
|
||||
if (account.id == null) {
|
||||
logger.warn("账户 ID 为空,跳过: ${account.proxyAddress}")
|
||||
return
|
||||
}
|
||||
|
||||
val accountId = account.id!!
|
||||
|
||||
// 如果已经在监听列表中,不重复添加
|
||||
if (monitoredAccounts.containsKey(accountId)) {
|
||||
return
|
||||
}
|
||||
|
||||
monitoredAccounts[accountId] = account
|
||||
|
||||
// 通过统一服务订阅
|
||||
val subscriptionId = "ACCOUNT_$accountId"
|
||||
unifiedOnChainWsService.subscribe(
|
||||
subscriptionId = subscriptionId,
|
||||
address = account.proxyAddress,
|
||||
entityType = "ACCOUNT",
|
||||
entityId = accountId,
|
||||
callback = { txHash, httpClient, rpcApi ->
|
||||
handleAccountTransaction(accountId, txHash, httpClient, rpcApi)
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("已添加跟单账户进行链上监听: accountId=${accountId}, address=${account.proxyAddress}")
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理账户的交易
|
||||
*/
|
||||
private suspend fun handleAccountTransaction(accountId: Long, txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
val account = monitoredAccounts[accountId] ?: return
|
||||
|
||||
try {
|
||||
// 获取交易 receipt
|
||||
val receiptRequest = JsonRpcRequest(
|
||||
method = "eth_getTransactionReceipt",
|
||||
params = listOf(txHash)
|
||||
)
|
||||
|
||||
val receiptResponse = rpcApi.call(receiptRequest)
|
||||
if (!receiptResponse.isSuccessful || receiptResponse.body() == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val receiptRpcResponse = receiptResponse.body()!!
|
||||
if (receiptRpcResponse.error != null || receiptRpcResponse.result == null) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 receipt JSON
|
||||
val receiptJson = receiptRpcResponse.result.asJsonObject
|
||||
|
||||
// 获取区块号和时间戳
|
||||
val blockNumber = receiptJson.get("blockNumber")?.asString
|
||||
val blockTimestamp = if (blockNumber != null) {
|
||||
OnChainWsUtils.getBlockTimestamp(blockNumber, rpcApi)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 解析 receipt 中的 Transfer 日志
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: return
|
||||
val (erc20Transfers, erc1155Transfers) = OnChainWsUtils.parseReceiptTransfers(logs)
|
||||
|
||||
// 解析交易信息
|
||||
val trade = OnChainWsUtils.parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = account.proxyAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers,
|
||||
retrofitFactory = retrofitFactory
|
||||
)
|
||||
|
||||
if (trade != null && trade.side == "SELL") {
|
||||
// 检测到卖出或赎回事件,更新订单状态
|
||||
handleAccountSellOrRedeem(account, trade)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理账户交易失败: accountId=$accountId, txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理账户的卖出或赎回事件
|
||||
* 更新对应的订单状态
|
||||
*/
|
||||
private suspend fun handleAccountSellOrRedeem(account: Account, trade: TradeResponse) {
|
||||
try {
|
||||
// 获取该账户的所有启用的跟单配置
|
||||
val copyTradings = copyTradingRepository.findByAccountId(account.id!!)
|
||||
.filter { it.enabled }
|
||||
|
||||
if (copyTradings.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 trade 中已有的市场信息
|
||||
val marketId = trade.market // conditionId
|
||||
val outcomeIndex = trade.outcomeIndex ?: 0
|
||||
|
||||
// 计算卖出价格
|
||||
val sellPrice = trade.price.toSafeBigDecimal()
|
||||
|
||||
// 为每个跟单配置更新订单状态
|
||||
for (copyTrading in copyTradings) {
|
||||
// 查找该跟单配置下所有未卖出的订单(remaining_quantity > 0)
|
||||
val unmatchedOrders = copyOrderTrackingRepository.findByCopyTradingId(copyTrading.id!!)
|
||||
.filter {
|
||||
it.remainingQuantity > BigDecimal.ZERO &&
|
||||
it.marketId == marketId &&
|
||||
it.outcomeIndex == outcomeIndex
|
||||
}
|
||||
.sortedBy { it.createdAt } // 按创建时间排序(FIFO)
|
||||
|
||||
if (unmatchedOrders.isEmpty()) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 卖出数量就是交易的 size
|
||||
val soldQuantity = trade.size.toSafeBigDecimal()
|
||||
|
||||
// 更新订单状态为已卖出
|
||||
updateOrdersAsSoldByFIFO(
|
||||
unmatchedOrders,
|
||||
soldQuantity,
|
||||
sellPrice,
|
||||
copyTrading.id!!,
|
||||
marketId,
|
||||
outcomeIndex
|
||||
)
|
||||
|
||||
logger.info("跟单账户卖出/赎回事件处理完成: accountId=${account.id}, copyTradingId=${copyTrading.id}, txHash=${trade.id}, soldQuantity=$soldQuantity, sellPrice=$sellPrice")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理账户卖出/赎回事件失败: accountId=${account.id}, txHash=${trade.id}, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 FIFO 顺序更新订单为已卖出
|
||||
*/
|
||||
private suspend fun updateOrdersAsSoldByFIFO(
|
||||
orders: List<CopyOrderTracking>,
|
||||
soldQuantity: BigDecimal,
|
||||
sellPrice: BigDecimal,
|
||||
copyTradingId: Long,
|
||||
marketId: String,
|
||||
outcomeIndex: Int
|
||||
) {
|
||||
var remainingSoldQuantity = soldQuantity
|
||||
val matchDetails = mutableListOf<SellMatchDetail>()
|
||||
var totalMatchedQuantity = BigDecimal.ZERO
|
||||
var totalRealizedPnl = BigDecimal.ZERO
|
||||
|
||||
for (order in orders) {
|
||||
if (remainingSoldQuantity <= BigDecimal.ZERO) {
|
||||
break
|
||||
}
|
||||
|
||||
val currentOrderRemaining = order.remainingQuantity.toSafeBigDecimal()
|
||||
val matchedQty = minOf(currentOrderRemaining, remainingSoldQuantity)
|
||||
|
||||
if (matchedQty <= BigDecimal.ZERO) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算盈亏
|
||||
val buyPrice = order.price.toSafeBigDecimal()
|
||||
val realizedPnl = sellPrice.subtract(buyPrice).multi(matchedQty)
|
||||
|
||||
// 创建匹配明细
|
||||
val detail = SellMatchDetail(
|
||||
matchRecordId = 0, // 稍后设置
|
||||
trackingId = order.id!!,
|
||||
buyOrderId = order.buyOrderId,
|
||||
matchedQuantity = matchedQty,
|
||||
buyPrice = buyPrice,
|
||||
sellPrice = sellPrice,
|
||||
realizedPnl = realizedPnl
|
||||
)
|
||||
matchDetails.add(detail)
|
||||
|
||||
totalMatchedQuantity = totalMatchedQuantity.add(matchedQty)
|
||||
totalRealizedPnl = totalRealizedPnl.add(realizedPnl)
|
||||
|
||||
// 更新订单状态
|
||||
order.matchedQuantity = order.matchedQuantity.add(matchedQty)
|
||||
order.remainingQuantity = currentOrderRemaining.subtract(matchedQty)
|
||||
order.status = if (order.remainingQuantity <= BigDecimal.ZERO) "fully_matched" else "partially_matched"
|
||||
order.updatedAt = System.currentTimeMillis()
|
||||
copyOrderTrackingRepository.save(order)
|
||||
|
||||
remainingSoldQuantity = remainingSoldQuantity.subtract(matchedQty)
|
||||
}
|
||||
|
||||
// 如果有匹配的订单,创建卖出记录
|
||||
if (totalMatchedQuantity > BigDecimal.ZERO && matchDetails.isNotEmpty()) {
|
||||
val timestamp = System.currentTimeMillis()
|
||||
val sellOrderId = "AUTO_WS_${timestamp}_${copyTradingId}" // 区分 WS 自动卖出
|
||||
val leaderSellTradeId = "AUTO_WS_${timestamp}"
|
||||
|
||||
val matchRecord = SellMatchRecord(
|
||||
copyTradingId = copyTradingId,
|
||||
sellOrderId = sellOrderId,
|
||||
leaderSellTradeId = leaderSellTradeId,
|
||||
marketId = marketId,
|
||||
side = outcomeIndex.toString(),
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // WS 实时获取,直接标记为已更新
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
|
||||
// 保存匹配明细
|
||||
for (detail in matchDetails) {
|
||||
val savedDetail = detail.copy(matchRecordId = savedRecord.id!!)
|
||||
sellMatchDetailRepository.save(savedDetail)
|
||||
}
|
||||
|
||||
logger.info("创建跟单账户链上自动卖出记录: copyTradingId=$copyTradingId, marketId=$marketId, totalMatched=$totalMatchedQuantity, totalPnl=$totalRealizedPnl")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除账户监听
|
||||
* 取消该账户的订阅
|
||||
*/
|
||||
fun removeAccount(accountId: Long) {
|
||||
monitoredAccounts.remove(accountId)
|
||||
|
||||
// 通过统一服务取消订阅
|
||||
val subscriptionId = "ACCOUNT_$accountId"
|
||||
unifiedOnChainWsService.unsubscribe(subscriptionId)
|
||||
|
||||
logger.info("已移除跟单账户的链上监听: accountId=$accountId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新账户监听状态
|
||||
*/
|
||||
fun updateAccountMonitoring(accountId: Long) {
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
if (account != null && account.isEnabled) {
|
||||
addAccount(account)
|
||||
} else {
|
||||
removeAccount(accountId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止监听
|
||||
*/
|
||||
fun stop() {
|
||||
// 取消所有账户的订阅
|
||||
val accountIds = monitoredAccounts.keys.toList()
|
||||
for (accountId in accountIds) {
|
||||
removeAccount(accountId)
|
||||
}
|
||||
monitoredAccounts.clear()
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
+47
-4
@@ -2,6 +2,7 @@ package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.wrbug.polymarketbot.entity.CopyTrading
|
||||
import com.wrbug.polymarketbot.entity.Leader
|
||||
import com.wrbug.polymarketbot.repository.AccountRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyTradingRepository
|
||||
import com.wrbug.polymarketbot.repository.LeaderRepository
|
||||
import jakarta.annotation.PostConstruct
|
||||
@@ -14,13 +15,16 @@ import org.springframework.stereotype.Service
|
||||
* 跟单监听服务(主服务)
|
||||
* 管理所有Leader的交易监听
|
||||
* 同时运行链上 WebSocket 监听和轮询监听(并行处理)
|
||||
* 同时监听跟单账户的卖出/赎回事件(通过链上 WebSocket)
|
||||
*/
|
||||
@Service
|
||||
class CopyTradingMonitorService(
|
||||
private val copyTradingRepository: CopyTradingRepository,
|
||||
private val leaderRepository: LeaderRepository,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val pollingService: CopyTradingPollingService,
|
||||
private val onChainWsService: OnChainWsService
|
||||
private val onChainWsService: OnChainWsService,
|
||||
private val accountOnChainMonitorService: AccountOnChainMonitorService
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingMonitorService::class.java)
|
||||
@@ -50,11 +54,13 @@ class CopyTradingMonitorService(
|
||||
// 停止轮询和链上 WS 监听
|
||||
pollingService.stop()
|
||||
onChainWsService.stop()
|
||||
accountOnChainMonitorService.stop()
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动监听
|
||||
* 同时启动链上 WebSocket 监听和轮询监听(并行运行)
|
||||
* 同时启动跟单账户的链上 WebSocket 监听(用于检测卖出/赎回事件)
|
||||
*/
|
||||
suspend fun startMonitoring() {
|
||||
// 1. 获取所有启用的跟单关系
|
||||
@@ -70,12 +76,21 @@ class CopyTradingMonitorService(
|
||||
leaderRepository.findById(leaderId).orElse(null)
|
||||
}
|
||||
|
||||
// 3. 同时启动链上 WebSocket 监听和轮询监听(并行运行)
|
||||
// 链上 WS 监听(实时,秒级延迟)
|
||||
// 3. 获取所有需要监听的跟单账户(去重)
|
||||
val accountIds = enabledCopyTradings.map { it.accountId }.distinct()
|
||||
val accounts = accountIds.mapNotNull { accountId ->
|
||||
accountRepository.findById(accountId).orElse(null)
|
||||
}
|
||||
|
||||
// 4. 同时启动链上 WebSocket 监听和轮询监听(并行运行)
|
||||
// 链上 WS 监听 Leader 的交易(实时,秒级延迟)
|
||||
onChainWsService.start(leaders)
|
||||
|
||||
// 轮询监听(延迟,2秒间隔,作为备份)
|
||||
// 轮询监听 Leader 的交易(延迟,2秒间隔,作为备份)
|
||||
pollingService.start(leaders)
|
||||
|
||||
// 5. 启动跟单账户的链上 WebSocket 监听(用于检测卖出/赎回事件)
|
||||
accountOnChainMonitorService.start(accounts)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,6 +140,15 @@ class CopyTradingMonitorService(
|
||||
// 有启用的跟单配置,确保在监听列表中
|
||||
onChainWsService.addLeader(leader)
|
||||
pollingService.addLeader(leader)
|
||||
|
||||
// 更新账户监听(添加该配置关联的账户)
|
||||
val accountIds = copyTradings.map { it.accountId }.distinct()
|
||||
accountIds.forEach { accountId ->
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
if (account != null) {
|
||||
accountOnChainMonitorService.addAccount(account)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有启用的跟单配置,移除监听
|
||||
onChainWsService.removeLeader(leaderId)
|
||||
@@ -132,6 +156,25 @@ class CopyTradingMonitorService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新账户监听(当跟单配置状态改变时调用)
|
||||
* 根据当前状态决定添加或移除账户监听
|
||||
*/
|
||||
suspend fun updateAccountMonitoring(accountId: Long) {
|
||||
val copyTradings = copyTradingRepository.findByAccountId(accountId)
|
||||
.filter { it.enabled }
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
?: return
|
||||
|
||||
if (copyTradings.isNotEmpty()) {
|
||||
// 有启用的跟单配置,确保账户在监听列表中
|
||||
accountOnChainMonitorService.addAccount(account)
|
||||
} else {
|
||||
// 没有启用的跟单配置,移除账户监听
|
||||
accountOnChainMonitorService.removeAccount(accountId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新启动监听(当跟单关系状态改变时调用)
|
||||
* 注意:这个方法会停止所有监听并重新启动,建议使用 updateLeaderMonitoring 进行增量更新
|
||||
|
||||
+57
-805
@@ -1,37 +1,24 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.entity.Leader
|
||||
import com.wrbug.polymarketbot.repository.LeaderRepository
|
||||
import com.wrbug.polymarketbot.service.copytrading.statistics.CopyOrderTrackingService
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import com.wrbug.polymarketbot.util.getProxyConfig
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigInteger
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 链上 WebSocket 监听服务
|
||||
* 通过 Polygon RPC 的 eth_subscribe 实时监听链上交易
|
||||
* 通过统一服务订阅 Leader 的链上交易
|
||||
*/
|
||||
@Service
|
||||
class OnChainWsService(
|
||||
private val rpcNodeService: RpcNodeService,
|
||||
private val unifiedOnChainWsService: UnifiedOnChainWsService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val copyOrderTrackingService: CopyOrderTrackingService,
|
||||
private val leaderRepository: LeaderRepository
|
||||
@@ -39,84 +26,31 @@ class OnChainWsService(
|
||||
|
||||
private val logger = LoggerFactory.getLogger(OnChainWsService::class.java)
|
||||
|
||||
// Gson 实例,用于解析 JSON
|
||||
private val gson = Gson()
|
||||
|
||||
@Value("\${copy.trading.onchain.ws.reconnect.delay:3000}")
|
||||
private var reconnectDelay: Long = 3000 // 重连延迟(毫秒),默认3秒
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// 存储需要监听的Leader:leaderId -> Leader
|
||||
private val monitoredLeaders = ConcurrentHashMap<Long, Leader>()
|
||||
|
||||
// 存储每个 Leader 的订阅 ID:leaderId -> List<subscriptionId>
|
||||
// 每个 Leader 有 6 个订阅:USDC from/to, ERC1155 TransferSingle from/to, ERC1155 TransferBatch from/to
|
||||
private val leaderSubscriptions = ConcurrentHashMap<Long, MutableList<String>>()
|
||||
|
||||
// 存储请求 ID 到 Leader ID 的映射:requestId -> leaderId
|
||||
// 用于在收到订阅响应时,将 subscription ID 关联到对应的 Leader
|
||||
private val requestIdToLeaderId = ConcurrentHashMap<Int, Long>()
|
||||
|
||||
// WebSocket 连接
|
||||
private var webSocket: WebSocket? = null
|
||||
@Volatile
|
||||
private var isConnected = false
|
||||
|
||||
// 订阅ID计数器(用于请求 ID)
|
||||
private var requestIdCounter = 0
|
||||
|
||||
// 合约地址
|
||||
companion object {
|
||||
private const val USDC_CONTRACT = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
|
||||
private const val ERC1155_CONTRACT = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
|
||||
private const val ERC20_TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||
private const val ERC1155_TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
|
||||
private const val ERC1155_TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
|
||||
}
|
||||
|
||||
// 连接任务(确保只有一个连接任务在运行)
|
||||
private var connectionJob: Job? = null
|
||||
|
||||
/**
|
||||
* 启动链上 WebSocket 监听
|
||||
* 只创建一个 WebSocket 连接,为所有 Leader 订阅
|
||||
* 通过统一服务订阅所有 Leader
|
||||
*/
|
||||
fun start(leaders: List<Leader>) {
|
||||
// 如果没有 Leader,不启动连接
|
||||
// 如果没有 Leader,取消所有订阅
|
||||
if (leaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,不启动链上 WebSocket 连接")
|
||||
logger.info("没有需要监听的 Leader,取消所有订阅")
|
||||
stop()
|
||||
return
|
||||
}
|
||||
|
||||
// 如果连接任务已经在运行,先停止旧任务
|
||||
if (connectionJob != null && connectionJob!!.isActive) {
|
||||
logger.info("停止旧的连接任务,准备重新启动")
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
// 关闭旧连接
|
||||
webSocket?.close(1000, "重新启动")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
}
|
||||
|
||||
// 更新 Leader 列表
|
||||
monitoredLeaders.clear()
|
||||
leaders.forEach { leader ->
|
||||
addLeader(leader)
|
||||
}
|
||||
|
||||
// 启动连接任务(只创建一个)
|
||||
connectionJob = scope.launch {
|
||||
startConnection()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加Leader监听
|
||||
* 如果 Leader 已经在监听列表中,不重复添加
|
||||
* 如果已连接,立即订阅
|
||||
* 通过统一服务订阅该 Leader 的地址
|
||||
*/
|
||||
fun addLeader(leader: Leader) {
|
||||
if (leader.id == null) {
|
||||
@@ -133,406 +67,28 @@ class OnChainWsService(
|
||||
}
|
||||
|
||||
monitoredLeaders[leaderId] = leader
|
||||
|
||||
// 通过统一服务订阅
|
||||
val subscriptionId = "LEADER_$leaderId"
|
||||
unifiedOnChainWsService.subscribe(
|
||||
subscriptionId = subscriptionId,
|
||||
address = leader.leaderAddress,
|
||||
entityType = "LEADER",
|
||||
entityId = leaderId,
|
||||
callback = { txHash, httpClient, rpcApi ->
|
||||
handleLeaderTransaction(leaderId, txHash, httpClient, rpcApi)
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("添加 Leader 监听: ${leader.leaderName} (${leader.leaderAddress})")
|
||||
|
||||
// 如果已连接,立即订阅
|
||||
if (isConnected && webSocket != null) {
|
||||
scope.launch {
|
||||
subscribeLeader(leader)
|
||||
}
|
||||
} else {
|
||||
// 如果未连接,启动连接(如果连接任务未运行)
|
||||
if (connectionJob == null || !connectionJob!!.isActive) {
|
||||
connectionJob = scope.launch {
|
||||
startConnection()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除Leader监听
|
||||
* 通过 eth_unsubscribe 取消该 Leader 的所有订阅
|
||||
* 如果没有 Leader 了,关闭 WebSocket 连接
|
||||
* 处理 Leader 的交易
|
||||
*/
|
||||
fun removeLeader(leaderId: Long) {
|
||||
val leader = monitoredLeaders.remove(leaderId)
|
||||
if (leader != null) {
|
||||
logger.info("移除 Leader 监听: ${leader.leaderName} (${leader.leaderAddress})")
|
||||
}
|
||||
private suspend fun handleLeaderTransaction(leaderId: Long, txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
val leader = monitoredLeaders[leaderId] ?: return
|
||||
|
||||
// 取消该 Leader 的所有订阅
|
||||
val subscriptions = leaderSubscriptions.remove(leaderId)
|
||||
if (subscriptions != null && subscriptions.isNotEmpty() && isConnected && webSocket != null) {
|
||||
logger.info("取消 Leader ${leader?.leaderName} 的 ${subscriptions.size} 个订阅")
|
||||
subscriptions.forEach { subscriptionId ->
|
||||
unsubscribe(subscriptionId)
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有 Leader 了,关闭连接
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,关闭链上 WebSocket 连接")
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止所有监听
|
||||
*/
|
||||
fun stop() {
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
|
||||
// 取消所有订阅
|
||||
if (isConnected && webSocket != null) {
|
||||
leaderSubscriptions.values.flatten().forEach { subscriptionId ->
|
||||
unsubscribe(subscriptionId)
|
||||
}
|
||||
}
|
||||
|
||||
webSocket?.close(1000, "正常关闭")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
monitoredLeaders.clear()
|
||||
leaderSubscriptions.clear()
|
||||
requestIdToLeaderId.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动连接(带重连机制)
|
||||
* 只创建一个 WebSocket 连接
|
||||
*/
|
||||
private suspend fun startConnection() {
|
||||
while (scope.isActive) {
|
||||
try {
|
||||
// 检查是否有需要监听的 Leader
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止连接")
|
||||
// 确保关闭连接
|
||||
webSocket?.close(1000, "没有 Leader")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
break
|
||||
}
|
||||
|
||||
// 如果已经连接,不需要重新连接
|
||||
if (isConnected && webSocket != null) {
|
||||
// 等待连接断开
|
||||
waitForDisconnect()
|
||||
// 连接断开后继续重连循环
|
||||
continue
|
||||
}
|
||||
|
||||
// 从后台配置获取 WS RPC URL
|
||||
val wsUrl = rpcNodeService.getWsUrl()
|
||||
val httpUrl = rpcNodeService.getHttpUrl()
|
||||
|
||||
logger.info("连接链上 WebSocket: $wsUrl (监听 ${monitoredLeaders.size} 个 Leader)")
|
||||
|
||||
// 创建 HTTP 客户端(用于 RPC 调用)
|
||||
val httpClient = createHttpClient()
|
||||
|
||||
// 创建 RPC API 客户端
|
||||
val rpcApi = retrofitFactory.createEthereumRpcApi(httpUrl)
|
||||
|
||||
// 连接 WebSocket(只创建一个连接,会先关闭旧连接)
|
||||
connectWebSocket(wsUrl, httpClient, rpcApi)
|
||||
|
||||
// 等待连接建立(最多等待 15 秒)
|
||||
// 注意:onOpen 回调是异步的,需要等待一段时间
|
||||
var waitCount = 0
|
||||
val maxWait = 15 // 最多等待 15 秒
|
||||
while (!isConnected && waitCount < maxWait && scope.isActive) {
|
||||
delay(1000)
|
||||
waitCount++
|
||||
// 每 3 秒打印一次日志,方便调试
|
||||
if (waitCount % 3 == 0) {
|
||||
logger.debug("等待 WebSocket 连接建立... (${waitCount}/${maxWait}秒)")
|
||||
}
|
||||
}
|
||||
|
||||
// 检查连接状态(同时检查 isConnected 和 webSocket 状态)
|
||||
val actuallyConnected = isConnected && webSocket != null
|
||||
|
||||
// 如果连接失败,等待重连延迟后继续
|
||||
if (!actuallyConnected) {
|
||||
logger.warn("WebSocket 连接超时或失败: isConnected=$isConnected, webSocket=${webSocket != null}, 等待重连")
|
||||
delay(reconnectDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.info("WebSocket 连接已建立,开始监听")
|
||||
|
||||
// 连接成功后持续监听
|
||||
waitForDisconnect()
|
||||
|
||||
// 连接断开后,如果没有 Leader 了,不再重连
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止重连")
|
||||
break
|
||||
}
|
||||
|
||||
// 连接断开后,等待一下再重连(避免立即重连)
|
||||
logger.info("WebSocket 连接断开,等待 ${reconnectDelay}ms 后重连")
|
||||
delay(reconnectDelay)
|
||||
} catch (e: Exception) {
|
||||
// 如果没有 Leader 了,不再重连
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止重连")
|
||||
// 确保关闭连接
|
||||
webSocket?.close(1000, "没有 Leader")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
break
|
||||
}
|
||||
logger.warn("链上 WebSocket 连接失败,等待重连: ${e.message}")
|
||||
// 确保关闭旧连接
|
||||
webSocket?.close(1000, "重连前关闭")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
delay(reconnectDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 HTTP 客户端
|
||||
*/
|
||||
private fun createHttpClient(): OkHttpClient {
|
||||
val proxy = getProxyConfig()
|
||||
val builder = createClient()
|
||||
|
||||
if (proxy != null) {
|
||||
builder.proxy(proxy)
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接 WebSocket
|
||||
* 确保只创建一个连接,创建新连接前先关闭旧连接
|
||||
*/
|
||||
private fun connectWebSocket(wsUrl: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
// 先关闭旧连接(如果存在)
|
||||
val oldWebSocket = webSocket
|
||||
if (oldWebSocket != null) {
|
||||
try {
|
||||
oldWebSocket.close(1000, "重新连接")
|
||||
} catch (e: Exception) {
|
||||
logger.debug("关闭旧 WebSocket 连接时出错: ${e.message}")
|
||||
}
|
||||
}
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(wsUrl)
|
||||
.build()
|
||||
|
||||
// 创建新连接(只创建一个)
|
||||
webSocket = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
isConnected = true
|
||||
logger.info("链上 WebSocket 连接成功")
|
||||
|
||||
// 订阅所有 Leader
|
||||
scope.launch {
|
||||
monitoredLeaders.values.forEach { leader ->
|
||||
subscribeLeader(leader)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
scope.launch {
|
||||
handleMessage(text, httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
scope.launch {
|
||||
handleMessage(bytes.utf8(), httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接已关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
logger.error("链上 WebSocket 连接失败: ${t.message}", t)
|
||||
isConnected = false
|
||||
// 注意:这里不直接重连,由 startConnection 循环处理重连逻辑
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待连接断开
|
||||
*/
|
||||
private suspend fun waitForDisconnect() {
|
||||
while (isConnected && scope.isActive) {
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅 Leader 钱包地址
|
||||
* 每个 Leader 有 6 个订阅,保存订阅 ID 以便后续取消
|
||||
*/
|
||||
private suspend fun subscribeLeader(leader: Leader) {
|
||||
if (webSocket == null || !isConnected || leader.id == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val walletAddress = leader.leaderAddress.lowercase()
|
||||
val walletTopic = addressToTopic32(walletAddress)
|
||||
val leaderId = leader.id!!
|
||||
|
||||
// 初始化该 Leader 的订阅列表
|
||||
if (!leaderSubscriptions.containsKey(leaderId)) {
|
||||
leaderSubscriptions[leaderId] = mutableListOf()
|
||||
}
|
||||
|
||||
try {
|
||||
// 订阅 USDC Transfer (from wallet)
|
||||
subscribeLogs(USDC_CONTRACT, listOf(ERC20_TRANSFER_TOPIC, walletTopic), leaderId)
|
||||
|
||||
// 订阅 USDC Transfer (to wallet)
|
||||
subscribeLogs(USDC_CONTRACT, listOf(ERC20_TRANSFER_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (from wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_SINGLE_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (to wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_SINGLE_TOPIC, null, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (from wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_BATCH_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (to wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_BATCH_TOPIC, null, null, walletTopic), leaderId)
|
||||
|
||||
logger.debug("已订阅 Leader 钱包地址: ${leader.leaderName} (${walletAddress})")
|
||||
} catch (e: Exception) {
|
||||
logger.error("订阅 Leader 失败: leaderId=$leaderId, address=$walletAddress", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅日志
|
||||
* @param address 合约地址
|
||||
* @param topics 主题列表
|
||||
* @param leaderId Leader ID,用于关联订阅响应
|
||||
*/
|
||||
private fun subscribeLogs(address: String, topics: List<String?>, leaderId: Long) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val params = mapOf(
|
||||
"address" to address.lowercase(),
|
||||
"topics" to topics
|
||||
)
|
||||
|
||||
val subscribeParams = listOf("logs", params)
|
||||
|
||||
val requestId = ++requestIdCounter
|
||||
|
||||
// 保存请求 ID 到 Leader ID 的映射
|
||||
requestIdToLeaderId[requestId] = leaderId
|
||||
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to requestId,
|
||||
"method" to "eth_subscribe",
|
||||
"params" to subscribeParams
|
||||
)
|
||||
|
||||
val json = gson.toJson(request)
|
||||
ws.send(json)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
* @param subscriptionId 订阅 ID
|
||||
*/
|
||||
private fun unsubscribe(subscriptionId: String) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to (++requestIdCounter),
|
||||
"method" to "eth_unsubscribe",
|
||||
"params" to listOf(subscriptionId)
|
||||
)
|
||||
|
||||
val json = gson.toJson(request)
|
||||
ws.send(json)
|
||||
logger.debug("已发送取消订阅请求: subscriptionId=$subscriptionId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 WebSocket 消息
|
||||
*/
|
||||
private suspend fun handleMessage(message: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
// 使用 Gson 解析消息
|
||||
val messageJson = gson.fromJson(message, JsonObject::class.java)
|
||||
|
||||
// 处理订阅响应(包含 subscription ID)
|
||||
val id = messageJson.get("id")
|
||||
if (id != null && !id.isJsonNull) {
|
||||
val result = messageJson.get("result")
|
||||
if (result != null && result.isJsonPrimitive && result.asJsonPrimitive.isString) {
|
||||
// 这是订阅响应,result 是 subscription ID(字符串)
|
||||
val requestId = id.asInt
|
||||
val subscriptionId = result.asString
|
||||
val leaderId = requestIdToLeaderId.remove(requestId)
|
||||
if (leaderId != null) {
|
||||
// 保存订阅 ID 到 Leader
|
||||
leaderSubscriptions.getOrPut(leaderId) { mutableListOf() }.add(subscriptionId)
|
||||
logger.debug("收到订阅响应: leaderId=$leaderId, subscriptionId=$subscriptionId")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 处理订阅通知(交易日志)
|
||||
val method = messageJson.get("method")?.asString
|
||||
if (method != "eth_subscription") {
|
||||
return
|
||||
}
|
||||
|
||||
val params = messageJson.getAsJsonObject("params") ?: return
|
||||
// result 是一个对象,包含日志信息
|
||||
val result = params.getAsJsonObject("result") ?: return
|
||||
|
||||
// 从 result 对象中获取 transactionHash(关键数据)
|
||||
val txHash = result.get("transactionHash")?.asString
|
||||
if (txHash.isNullOrEmpty()) {
|
||||
logger.debug("订阅通知中缺少 transactionHash,跳过处理")
|
||||
return
|
||||
}
|
||||
|
||||
// 处理交易
|
||||
processTransaction(txHash, httpClient, rpcApi)
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理 WebSocket 消息失败: ${e.message}", e)
|
||||
logger.debug("消息内容: $message", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理交易
|
||||
*/
|
||||
private suspend fun processTransaction(txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
// 获取交易 receipt
|
||||
val receiptRequest = JsonRpcRequest(
|
||||
@@ -550,376 +106,72 @@ class OnChainWsService(
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 receipt JSON(result 是 JsonElement)
|
||||
// 使用 Gson 解析 receipt JSON
|
||||
val receiptJson = receiptRpcResponse.result.asJsonObject
|
||||
|
||||
// 获取区块号和时间戳
|
||||
val blockNumber = receiptJson.get("blockNumber")?.asString
|
||||
val blockTimestamp = if (blockNumber != null) {
|
||||
getBlockTimestamp(blockNumber, rpcApi)
|
||||
OnChainWsUtils.getBlockTimestamp(blockNumber, rpcApi)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 解析 receipt 中的 Transfer 日志
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: return
|
||||
val (erc20Transfers, erc1155Transfers) = parseReceiptTransfers(logs)
|
||||
val (erc20Transfers, erc1155Transfers) = OnChainWsUtils.parseReceiptTransfers(logs)
|
||||
|
||||
// 为每个 Leader 处理交易
|
||||
for (leader in monitoredLeaders.values) {
|
||||
val trade = parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = leader.leaderAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers
|
||||
// 解析交易信息
|
||||
val trade = OnChainWsUtils.parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = leader.leaderAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers,
|
||||
retrofitFactory = retrofitFactory
|
||||
)
|
||||
|
||||
if (trade != null) {
|
||||
// 调用 processTrade 处理交易
|
||||
copyOrderTrackingService.processTrade(
|
||||
leaderId = leaderId,
|
||||
trade = trade,
|
||||
source = "onchain-ws"
|
||||
)
|
||||
|
||||
if (trade != null) {
|
||||
// 调用 processTrade 处理交易(元数据已在 parseTradeFromTransfers 中补齐)
|
||||
copyOrderTrackingService.processTrade(
|
||||
leaderId = leader.id!!,
|
||||
trade = trade,
|
||||
source = "onchain-ws"
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易失败: txHash=$txHash, ${e.message}", e)
|
||||
logger.error("处理 Leader 交易失败: leaderId=$leaderId, txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 receipt 中的 Transfer 日志
|
||||
* 移除Leader监听
|
||||
* 取消该 Leader 的订阅
|
||||
*/
|
||||
private fun parseReceiptTransfers(logs: com.google.gson.JsonArray): Pair<List<Erc20Transfer>, List<Erc1155Transfer>> {
|
||||
val erc20 = mutableListOf<Erc20Transfer>()
|
||||
val erc1155 = mutableListOf<Erc1155Transfer>()
|
||||
fun removeLeader(leaderId: Long) {
|
||||
monitoredLeaders.remove(leaderId)
|
||||
|
||||
for (logElement in logs) {
|
||||
val log = logElement.asJsonObject
|
||||
val address = log.get("address")?.asString?.lowercase() ?: continue
|
||||
val topicsArray = log.getAsJsonArray("topics") ?: continue
|
||||
val topics = topicsArray.mapNotNull { it.asString }
|
||||
if (topics.isEmpty()) continue
|
||||
|
||||
val t0 = topics[0].lowercase()
|
||||
val data = log.get("data")?.asString ?: "0x"
|
||||
|
||||
// USDC ERC20 Transfer
|
||||
if (address == USDC_CONTRACT.lowercase() && t0 == ERC20_TRANSFER_TOPIC && topics.size >= 3) {
|
||||
val from = topicToAddress(topics[1])
|
||||
val to = topicToAddress(topics[2])
|
||||
val value = hexToBigInt(data)
|
||||
erc20.add(Erc20Transfer(from, to, value))
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferSingle
|
||||
if (t0 == ERC1155_TRANSFER_SINGLE_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size >= 64) {
|
||||
val tokenId = sliceBigInt32(bytes, 0)
|
||||
val value = sliceBigInt32(bytes, 32)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferBatch
|
||||
if (t0 == ERC1155_TRANSFER_BATCH_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size < 64) continue
|
||||
|
||||
val offIds = sliceBigInt32(bytes, 0).toInt()
|
||||
val offVals = sliceBigInt32(bytes, 32).toInt()
|
||||
if (offIds + 32 > bytes.size || offVals + 32 > bytes.size) continue
|
||||
|
||||
val nIds = sliceBigInt32(bytes, offIds).toInt()
|
||||
val nVals = sliceBigInt32(bytes, offVals).toInt()
|
||||
if (nIds != nVals) continue
|
||||
|
||||
val idsStart = offIds + 32
|
||||
val valsStart = offVals + 32
|
||||
for (i in 0 until nIds) {
|
||||
val ib = idsStart + i * 32
|
||||
val vb = valsStart + i * 32
|
||||
if (ib + 32 > bytes.size || vb + 32 > bytes.size) break
|
||||
val tokenId = sliceBigInt32(bytes, ib)
|
||||
val value = sliceBigInt32(bytes, vb)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
// 通过统一服务取消订阅
|
||||
val subscriptionId = "LEADER_$leaderId"
|
||||
unifiedOnChainWsService.unsubscribe(subscriptionId)
|
||||
|
||||
return Pair(erc20, erc1155)
|
||||
logger.info("移除 Leader 监听: leaderId=$leaderId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Transfer 日志解析交易信息
|
||||
* 停止监听
|
||||
*/
|
||||
private suspend fun parseTradeFromTransfers(
|
||||
txHash: String,
|
||||
timestamp: Long?,
|
||||
walletAddress: String,
|
||||
erc20Transfers: List<Erc20Transfer>,
|
||||
erc1155Transfers: List<Erc1155Transfer>
|
||||
): TradeResponse? {
|
||||
val wallet = walletAddress.lowercase()
|
||||
|
||||
// 计算 USDC 流入和流出
|
||||
val usdcOut = erc20Transfers.filter { it.from.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
val usdcIn = erc20Transfers.filter { it.to.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
|
||||
// 计算 ERC1155 流入和流出(按 tokenId 聚合)
|
||||
val inById = mutableMapOf<BigInteger, BigInteger>()
|
||||
val outById = mutableMapOf<BigInteger, BigInteger>()
|
||||
for (t in erc1155Transfers) {
|
||||
if (t.to.lowercase() == wallet) {
|
||||
inById[t.tokenId] = (inById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
if (t.from.lowercase() == wallet) {
|
||||
outById[t.tokenId] = (outById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
fun stop() {
|
||||
// 取消所有 Leader 的订阅
|
||||
val leaderIds = monitoredLeaders.keys.toList()
|
||||
for (leaderId in leaderIds) {
|
||||
removeLeader(leaderId)
|
||||
}
|
||||
|
||||
// 找到最大的流入和流出 tokenId
|
||||
fun best(map: Map<BigInteger, BigInteger>): Pair<BigInteger?, BigInteger> =
|
||||
map.entries.maxByOrNull { it.value }?.let { it.key to it.value } ?: (null to BigInteger.ZERO)
|
||||
|
||||
val (bestInId, bestInVal) = best(inById)
|
||||
val (bestOutId, bestOutVal) = best(outById)
|
||||
|
||||
// 判断交易方向
|
||||
var side: String? = null
|
||||
var asset: BigInteger? = null
|
||||
var sizeRaw = BigInteger.ZERO
|
||||
var usdcRaw = BigInteger.ZERO
|
||||
|
||||
if (bestInId != null && bestInVal > BigInteger.ZERO && usdcOut > BigInteger.ZERO) {
|
||||
// BUY: 收到 token,支付 USDC
|
||||
side = "BUY"
|
||||
asset = bestInId
|
||||
sizeRaw = bestInVal
|
||||
usdcRaw = usdcOut
|
||||
} else if (bestOutId != null && bestOutVal > BigInteger.ZERO && usdcIn > BigInteger.ZERO) {
|
||||
// SELL: 卖出 token,收到 USDC
|
||||
side = "SELL"
|
||||
asset = bestOutId
|
||||
sizeRaw = bestOutVal
|
||||
usdcRaw = usdcIn
|
||||
} else {
|
||||
// 无法判断交易方向
|
||||
return null
|
||||
}
|
||||
|
||||
// 计算价格和数量(USDC 有 6 位小数,shares 也有 6 位小数)
|
||||
val usdcSize = usdcRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val size = sizeRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val price = if (size.signum() > 0) {
|
||||
usdcSize.divide(size, 8, java.math.RoundingMode.DOWN)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
// 尝试通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
val marketInfo = fetchMarketByTokenId(asset.toString())
|
||||
|
||||
// 创建 TradeResponse
|
||||
return TradeResponse(
|
||||
id = txHash,
|
||||
market = marketInfo?.conditionId ?: "",
|
||||
side = side,
|
||||
price = price.toPlainString(),
|
||||
size = size.toPlainString(),
|
||||
timestamp = (timestamp ?: System.currentTimeMillis() / 1000).toString(),
|
||||
user = walletAddress,
|
||||
outcomeIndex = marketInfo?.outcomeIndex,
|
||||
outcome = marketInfo?.outcome
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
*/
|
||||
private suspend fun fetchMarketByTokenId(tokenId: String): MarketInfo? {
|
||||
return try {
|
||||
// 使用 HTTP 请求直接调用 Gamma API(因为 Retrofit 接口可能不支持 clob_token_ids 参数)
|
||||
val httpClient = createHttpClient()
|
||||
val url = "https://gamma-api.polymarket.com/markets?clob_token_ids=$tokenId"
|
||||
|
||||
val request = okhttp3.Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.build()
|
||||
|
||||
val response = httpClient.newCall(request).execute()
|
||||
if (!response.isSuccessful || response.body == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val responseBody = response.body!!.string()
|
||||
// 使用 Gson 解析市场列表
|
||||
val marketsType = object : TypeToken<List<JsonObject>>() {}.type
|
||||
val markets = gson.fromJson<List<JsonObject>>(responseBody, marketsType)
|
||||
|
||||
if (markets.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
val market = markets.first()
|
||||
|
||||
// 解析 clob_token_ids(可能是 JSON 字符串或数组)
|
||||
val clobTokenIdsRaw = market.get("clobTokenIds") ?: market.get("clob_token_ids")
|
||||
val clobTokenIds = when {
|
||||
clobTokenIdsRaw == null || clobTokenIdsRaw.isJsonNull -> null
|
||||
clobTokenIdsRaw.isJsonPrimitive && clobTokenIdsRaw.asJsonPrimitive.isString -> {
|
||||
// 尝试解析 JSON 字符串
|
||||
try {
|
||||
val listType = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(clobTokenIdsRaw.asString, listType)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
clobTokenIdsRaw.isJsonArray -> {
|
||||
clobTokenIdsRaw.asJsonArray.mapNotNull { it.asString }
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
// 解析 outcomes(可能是 JSON 字符串或数组)
|
||||
val outcomesRaw = market.get("outcomes")
|
||||
val outcomes = when {
|
||||
outcomesRaw == null || outcomesRaw.isJsonNull -> null
|
||||
outcomesRaw.isJsonPrimitive && outcomesRaw.asJsonPrimitive.isString -> {
|
||||
try {
|
||||
val listType = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(outcomesRaw.asString, listType)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
outcomesRaw.isJsonArray -> {
|
||||
outcomesRaw.asJsonArray.mapNotNull { it.asString }
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
// 查找 tokenId 在 clobTokenIds 中的索引
|
||||
val outcomeIndex = clobTokenIds?.indexOfFirst {
|
||||
it.equals(tokenId, ignoreCase = true)
|
||||
}?.takeIf { it >= 0 }
|
||||
|
||||
// 获取 outcome 名称
|
||||
val outcome = if (outcomeIndex != null && outcomes != null && outcomeIndex < outcomes.size) {
|
||||
outcomes[outcomeIndex]
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val conditionId = market.get("conditionId")?.asString ?: return null
|
||||
|
||||
MarketInfo(
|
||||
conditionId = conditionId,
|
||||
outcomeIndex = outcomeIndex,
|
||||
outcome = outcome
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("通过 Gamma API 查询市场信息失败: tokenId=$tokenId, ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 市场信息(从 Gamma API 获取)
|
||||
*/
|
||||
private data class MarketInfo(
|
||||
val conditionId: String,
|
||||
val outcomeIndex: Int?,
|
||||
val outcome: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* 获取区块时间戳
|
||||
*/
|
||||
private suspend fun getBlockTimestamp(blockNumber: String, rpcApi: EthereumRpcApi): Long? {
|
||||
return try {
|
||||
val blockRequest = JsonRpcRequest(
|
||||
method = "eth_getBlockByNumber",
|
||||
params = listOf(blockNumber, false)
|
||||
)
|
||||
|
||||
val blockResponse = rpcApi.call(blockRequest)
|
||||
if (!blockResponse.isSuccessful || blockResponse.body() == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val blockRpcResponse = blockResponse.body()!!
|
||||
if (blockRpcResponse.error != null || blockRpcResponse.result == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 block JSON(result 是 JsonElement)
|
||||
val blockJson = blockRpcResponse.result.asJsonObject
|
||||
val timestampHex = blockJson.get("timestamp")?.asString ?: return null
|
||||
hexToBigInt(timestampHex).toLong()
|
||||
} catch (e: Exception) {
|
||||
logger.warn("获取区块时间戳失败: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数
|
||||
private data class Erc20Transfer(val from: String, val to: String, val value: BigInteger)
|
||||
private data class Erc1155Transfer(val from: String, val to: String, val tokenId: BigInteger, val value: BigInteger)
|
||||
|
||||
private fun topicToAddress(topic: String): String {
|
||||
val t = topic.removePrefix("0x").lowercase()
|
||||
return "0x" + t.takeLast(40)
|
||||
}
|
||||
|
||||
private fun hexToBigInt(hex: String): BigInteger {
|
||||
val h = hex.removePrefix("0x")
|
||||
if (h.isEmpty()) return BigInteger.ZERO
|
||||
return BigInteger(h, 16)
|
||||
}
|
||||
|
||||
private fun bytesFromHex(hex: String): ByteArray {
|
||||
val s = hex.removePrefix("0x")
|
||||
if (s.isEmpty()) return ByteArray(0)
|
||||
val out = ByteArray(s.length / 2)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
out[i / 2] = s.substring(i, i + 2).toInt(16).toByte()
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun sliceBigInt32(b: ByteArray, offset: Int): BigInteger {
|
||||
val sub = b.copyOfRange(offset, offset + 32)
|
||||
return BigInteger(1, sub)
|
||||
}
|
||||
|
||||
/**
|
||||
* 地址转换为 32 字节 topic(前 24 字节为 0,后 8 字节为地址)
|
||||
*/
|
||||
private fun addressToTopic32(address: String): String {
|
||||
val addr = address.removePrefix("0x").lowercase()
|
||||
return "0x" + "0".repeat(24) + addr
|
||||
monitoredLeaders.clear()
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.math.BigInteger
|
||||
|
||||
/**
|
||||
* 链上 WebSocket 工具类
|
||||
* 提取公共的交易解析、工具函数等逻辑
|
||||
*/
|
||||
object OnChainWsUtils {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(OnChainWsUtils::class.java)
|
||||
|
||||
// 合约地址
|
||||
const val USDC_CONTRACT = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
|
||||
const val ERC1155_CONTRACT = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
|
||||
const val ERC20_TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||
const val ERC1155_TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
|
||||
const val ERC1155_TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
|
||||
|
||||
/**
|
||||
* ERC20 Transfer 数据类
|
||||
*/
|
||||
data class Erc20Transfer(
|
||||
val from: String,
|
||||
val to: String,
|
||||
val value: BigInteger
|
||||
)
|
||||
|
||||
/**
|
||||
* ERC1155 Transfer 数据类
|
||||
*/
|
||||
data class Erc1155Transfer(
|
||||
val from: String,
|
||||
val to: String,
|
||||
val tokenId: BigInteger,
|
||||
val value: BigInteger
|
||||
)
|
||||
|
||||
/**
|
||||
* 市场信息数据类
|
||||
*/
|
||||
data class MarketInfo(
|
||||
val conditionId: String,
|
||||
val outcomeIndex: Int?, // 可空,因为可能找不到对应的 tokenId
|
||||
val outcome: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* 解析 receipt 中的 Transfer 日志
|
||||
*/
|
||||
fun parseReceiptTransfers(logs: JsonArray): Pair<List<Erc20Transfer>, List<Erc1155Transfer>> {
|
||||
val erc20 = mutableListOf<Erc20Transfer>()
|
||||
val erc1155 = mutableListOf<Erc1155Transfer>()
|
||||
|
||||
for (logElement in logs) {
|
||||
val log = logElement.asJsonObject
|
||||
val address = log.get("address")?.asString?.lowercase() ?: continue
|
||||
val topicsArray = log.getAsJsonArray("topics") ?: continue
|
||||
val topics = topicsArray.mapNotNull { it.asString }
|
||||
if (topics.isEmpty()) continue
|
||||
|
||||
val t0 = topics[0].lowercase()
|
||||
val data = log.get("data")?.asString ?: "0x"
|
||||
|
||||
// USDC ERC20 Transfer
|
||||
if (address == USDC_CONTRACT.lowercase() && t0 == ERC20_TRANSFER_TOPIC && topics.size >= 3) {
|
||||
val from = topicToAddress(topics[1])
|
||||
val to = topicToAddress(topics[2])
|
||||
val value = hexToBigInt(data)
|
||||
erc20.add(Erc20Transfer(from, to, value))
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferSingle
|
||||
if (t0 == ERC1155_TRANSFER_SINGLE_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size >= 64) {
|
||||
val tokenId = sliceBigInt32(bytes, 0)
|
||||
val value = sliceBigInt32(bytes, 32)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferBatch
|
||||
if (t0 == ERC1155_TRANSFER_BATCH_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size < 64) continue
|
||||
|
||||
val offIds = sliceBigInt32(bytes, 0).toInt()
|
||||
val offVals = sliceBigInt32(bytes, 32).toInt()
|
||||
if (offIds + 32 > bytes.size || offVals + 32 > bytes.size) continue
|
||||
|
||||
val nIds = sliceBigInt32(bytes, offIds).toInt()
|
||||
val nVals = sliceBigInt32(bytes, offVals).toInt()
|
||||
if (nIds != nVals) continue
|
||||
|
||||
val idsStart = offIds + 32
|
||||
val valsStart = offVals + 32
|
||||
for (i in 0 until nIds) {
|
||||
val ib = idsStart + i * 32
|
||||
val vb = valsStart + i * 32
|
||||
if (ib + 32 > bytes.size || vb + 32 > bytes.size) break
|
||||
val tokenId = sliceBigInt32(bytes, ib)
|
||||
val value = sliceBigInt32(bytes, vb)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Pair(erc20, erc1155)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Transfer 日志解析交易信息
|
||||
*/
|
||||
suspend fun parseTradeFromTransfers(
|
||||
txHash: String,
|
||||
timestamp: Long?,
|
||||
walletAddress: String,
|
||||
erc20Transfers: List<Erc20Transfer>,
|
||||
erc1155Transfers: List<Erc1155Transfer>,
|
||||
retrofitFactory: RetrofitFactory
|
||||
): TradeResponse? {
|
||||
val wallet = walletAddress.lowercase()
|
||||
|
||||
// 计算 USDC 流入和流出
|
||||
val usdcOut = erc20Transfers.filter { it.from.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
val usdcIn = erc20Transfers.filter { it.to.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
|
||||
// 计算 ERC1155 流入和流出(按 tokenId 聚合)
|
||||
val inById = mutableMapOf<BigInteger, BigInteger>()
|
||||
val outById = mutableMapOf<BigInteger, BigInteger>()
|
||||
for (t in erc1155Transfers) {
|
||||
if (t.to.lowercase() == wallet) {
|
||||
inById[t.tokenId] = (inById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
if (t.from.lowercase() == wallet) {
|
||||
outById[t.tokenId] = (outById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
}
|
||||
|
||||
// 找到最大的流入和流出 tokenId
|
||||
fun best(map: Map<BigInteger, BigInteger>): Pair<BigInteger?, BigInteger> =
|
||||
map.entries.maxByOrNull { it.value }?.let { it.key to it.value } ?: (null to BigInteger.ZERO)
|
||||
|
||||
val (bestInId, bestInVal) = best(inById)
|
||||
val (bestOutId, bestOutVal) = best(outById)
|
||||
|
||||
// 判断交易方向
|
||||
var side: String? = null
|
||||
var asset: BigInteger? = null
|
||||
var sizeRaw = BigInteger.ZERO
|
||||
var usdcRaw = BigInteger.ZERO
|
||||
|
||||
if (bestInId != null && bestInVal > BigInteger.ZERO && usdcOut > BigInteger.ZERO) {
|
||||
// BUY: 收到 token,支付 USDC
|
||||
side = "BUY"
|
||||
asset = bestInId
|
||||
sizeRaw = bestInVal
|
||||
usdcRaw = usdcOut
|
||||
} else if (bestOutId != null && bestOutVal > BigInteger.ZERO && usdcIn > BigInteger.ZERO) {
|
||||
// SELL: 卖出 token,收到 USDC
|
||||
side = "SELL"
|
||||
asset = bestOutId
|
||||
sizeRaw = bestOutVal
|
||||
usdcRaw = usdcIn
|
||||
} else {
|
||||
// 无法判断交易方向
|
||||
return null
|
||||
}
|
||||
|
||||
// 计算价格和数量(USDC 有 6 位小数,shares 也有 6 位小数)
|
||||
val usdcSize = usdcRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val size = sizeRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val price = if (size.signum() > 0) {
|
||||
usdcSize.divide(size, 8, java.math.RoundingMode.DOWN)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
// 尝试通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
val marketInfo = fetchMarketByTokenId(asset.toString(), retrofitFactory)
|
||||
|
||||
// 创建 TradeResponse
|
||||
return TradeResponse(
|
||||
id = txHash,
|
||||
market = marketInfo?.conditionId ?: "",
|
||||
side = side,
|
||||
price = price.toPlainString(),
|
||||
size = size.toPlainString(),
|
||||
timestamp = (timestamp ?: System.currentTimeMillis() / 1000).toString(),
|
||||
user = walletAddress,
|
||||
outcomeIndex = marketInfo?.outcomeIndex,
|
||||
outcome = marketInfo?.outcome
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
* 使用 Retrofit 接口,支持 clob_token_ids 参数
|
||||
*/
|
||||
suspend fun fetchMarketByTokenId(tokenId: String, retrofitFactory: RetrofitFactory): MarketInfo? {
|
||||
return try {
|
||||
val gammaApi = retrofitFactory.createGammaApi()
|
||||
val marketsResponse = gammaApi.listMarkets(
|
||||
conditionIds = null,
|
||||
clobTokenIds = listOf(tokenId),
|
||||
includeTag = null
|
||||
)
|
||||
|
||||
if (!marketsResponse.isSuccessful || marketsResponse.body() == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val markets = marketsResponse.body()!!
|
||||
val market = markets.firstOrNull()
|
||||
|
||||
if (market == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 解析 clobTokenIds(可能是 JSON 字符串或数组)
|
||||
val clobTokenIdsRaw = market.clobTokenIds ?: market.clob_token_ids
|
||||
val clobTokenIds = when {
|
||||
clobTokenIdsRaw == null -> null
|
||||
else -> {
|
||||
try {
|
||||
// 尝试解析 JSON 字符串
|
||||
val gson = com.google.gson.Gson()
|
||||
val listType = object : com.google.gson.reflect.TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(clobTokenIdsRaw, listType)
|
||||
} catch (e: Exception) {
|
||||
// 如果不是 JSON 字符串,可能是其他格式,返回 null
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 outcomes(可能是 JSON 字符串或数组)
|
||||
val outcomes = com.wrbug.polymarketbot.util.JsonUtils.parseStringArray(market.outcomes)
|
||||
|
||||
// 查找 tokenId 在 clobTokenIds 中的索引
|
||||
val outcomeIndex = clobTokenIds?.indexOfFirst {
|
||||
it.equals(tokenId, ignoreCase = true)
|
||||
}?.takeIf { it >= 0 }
|
||||
|
||||
// 获取 outcome 名称
|
||||
val outcome = if (outcomeIndex != null && outcomes.isNotEmpty() && outcomeIndex < outcomes.size) {
|
||||
outcomes[outcomeIndex]
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val conditionId = market.conditionId ?: return null
|
||||
|
||||
MarketInfo(
|
||||
conditionId = conditionId,
|
||||
outcomeIndex = outcomeIndex,
|
||||
outcome = outcome
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("查询市场信息失败: tokenId=$tokenId, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取区块时间戳
|
||||
*/
|
||||
suspend fun getBlockTimestamp(blockNumber: String, rpcApi: EthereumRpcApi): Long? {
|
||||
return try {
|
||||
val blockRequest = JsonRpcRequest(
|
||||
method = "eth_getBlockByNumber",
|
||||
params = listOf(blockNumber, false)
|
||||
)
|
||||
|
||||
val blockResponse = rpcApi.call(blockRequest)
|
||||
if (blockResponse.isSuccessful && blockResponse.body() != null) {
|
||||
val blockRpcResponse = blockResponse.body()!!
|
||||
if (blockRpcResponse.error == null && blockRpcResponse.result != null) {
|
||||
val blockJson = blockRpcResponse.result.asJsonObject
|
||||
val timestampHex = blockJson.get("timestamp")?.asString
|
||||
if (timestampHex != null) {
|
||||
BigInteger(timestampHex.removePrefix("0x"), 16).toLong() * 1000 // 转换为毫秒
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.warn("获取区块时间戳失败: blockNumber=$blockNumber, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:地址转 topic(32字节,左对齐)
|
||||
*/
|
||||
fun addressToTopic32(address: String): String {
|
||||
val clean = address.removePrefix("0x").lowercase()
|
||||
return "0x" + clean.padStart(64, '0')
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:topic 转地址
|
||||
*/
|
||||
fun topicToAddress(topic: String): String {
|
||||
val clean = topic.removePrefix("0x").lowercase()
|
||||
return "0x" + clean.takeLast(40)
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:十六进制转 BigInteger
|
||||
*/
|
||||
fun hexToBigInt(hex: String): BigInteger {
|
||||
val clean = hex.removePrefix("0x")
|
||||
return if (clean.isBlank()) BigInteger.ZERO else BigInteger(clean, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:十六进制转字节数组
|
||||
*/
|
||||
fun bytesFromHex(hex: String): ByteArray {
|
||||
val clean = hex.removePrefix("0x")
|
||||
return ByteArray(clean.length / 2) { i ->
|
||||
clean.substring(i * 2, i * 2 + 2).toInt(16).toByte()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:从字节数组切片 BigInteger(32字节)
|
||||
*/
|
||||
fun sliceBigInt32(bytes: ByteArray, offset: Int): BigInteger {
|
||||
if (offset + 32 > bytes.size) return BigInteger.ZERO
|
||||
val slice = bytes.sliceArray(offset until offset + 32)
|
||||
return BigInteger(1, slice)
|
||||
}
|
||||
}
|
||||
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import com.wrbug.polymarketbot.util.getProxyConfig
|
||||
import jakarta.annotation.PostConstruct
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 统一的链上 WebSocket 服务
|
||||
* 管理唯一的 WebSocket 连接,其他服务通过订阅的方式接收链上事件
|
||||
*/
|
||||
@Service
|
||||
class UnifiedOnChainWsService(
|
||||
private val rpcNodeService: RpcNodeService,
|
||||
private val retrofitFactory: RetrofitFactory
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(UnifiedOnChainWsService::class.java)
|
||||
|
||||
// Gson 实例,用于解析 JSON
|
||||
private val gson = Gson()
|
||||
|
||||
@Value("\${copy.trading.onchain.ws.reconnect.delay:3000}")
|
||||
private var reconnectDelay: Long = 3000 // 重连延迟(毫秒),默认3秒
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// WebSocket 连接(唯一)
|
||||
private var webSocket: WebSocket? = null
|
||||
@Volatile
|
||||
private var isConnected = false
|
||||
|
||||
// 订阅ID计数器(用于请求 ID)
|
||||
private var requestIdCounter = 0
|
||||
|
||||
// 连接任务(确保只有一个连接任务在运行)
|
||||
private var connectionJob: Job? = null
|
||||
|
||||
// 存储所有订阅:subscriptionId -> 订阅信息
|
||||
private val subscriptions = ConcurrentHashMap<String, SubscriptionInfo>()
|
||||
|
||||
// 存储请求 ID 到订阅 ID 的映射:requestId -> subscriptionId
|
||||
// 用于在收到订阅响应时,将 subscription ID 关联到对应的订阅
|
||||
private val requestIdToSubscriptionId = ConcurrentHashMap<Int, String>()
|
||||
|
||||
// 存储 RPC subscriptionId 到订阅 ID 的映射:rpcSubscriptionId -> subscriptionId
|
||||
// 用于在收到日志通知时,知道是哪个订阅
|
||||
private val rpcSubscriptionIdToSubscriptionId = ConcurrentHashMap<String, String>()
|
||||
|
||||
/**
|
||||
* 订阅信息
|
||||
*/
|
||||
data class SubscriptionInfo(
|
||||
val subscriptionId: String, // 订阅的唯一标识
|
||||
val address: String, // 要监听的地址(Leader 地址或账户代理地址)
|
||||
val entityType: String, // 实体类型:LEADER 或 ACCOUNT
|
||||
val entityId: Long, // 实体 ID(Leader ID 或 Account ID)
|
||||
val callback: suspend (String, OkHttpClient, EthereumRpcApi) -> Unit // 回调函数
|
||||
)
|
||||
|
||||
/**
|
||||
* 订阅地址监听
|
||||
* @param subscriptionId 订阅的唯一标识(建议格式:"{entityType}_{entityId}")
|
||||
* @param address 要监听的地址(Leader 地址或账户代理地址)
|
||||
* @param entityType 实体类型:LEADER 或 ACCOUNT
|
||||
* @param entityId 实体 ID(Leader ID 或 Account ID)
|
||||
* @param callback 回调函数,当检测到该地址的交易时调用
|
||||
* @return 是否订阅成功
|
||||
*/
|
||||
fun subscribe(
|
||||
subscriptionId: String,
|
||||
address: String,
|
||||
entityType: String,
|
||||
entityId: Long,
|
||||
callback: suspend (String, OkHttpClient, EthereumRpcApi) -> Unit
|
||||
): Boolean {
|
||||
try {
|
||||
// 如果已经订阅,先取消
|
||||
if (subscriptions.containsKey(subscriptionId)) {
|
||||
unsubscribe(subscriptionId)
|
||||
}
|
||||
|
||||
// 创建订阅信息
|
||||
val subscription = SubscriptionInfo(
|
||||
subscriptionId = subscriptionId,
|
||||
address = address.lowercase(),
|
||||
entityType = entityType,
|
||||
entityId = entityId,
|
||||
callback = callback
|
||||
)
|
||||
|
||||
subscriptions[subscriptionId] = subscription
|
||||
|
||||
// 如果已连接,立即订阅
|
||||
if (isConnected) {
|
||||
scope.launch {
|
||||
subscribeAddress(subscription)
|
||||
}
|
||||
} else {
|
||||
// 如果未连接,启动连接
|
||||
startConnection()
|
||||
}
|
||||
|
||||
logger.info("订阅地址监听: subscriptionId=$subscriptionId, address=$address, entityType=$entityType, entityId=$entityId")
|
||||
return true
|
||||
} catch (e: Exception) {
|
||||
logger.error("订阅地址监听失败: subscriptionId=$subscriptionId, address=$address, error=${e.message}", e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
*/
|
||||
fun unsubscribe(subscriptionId: String) {
|
||||
val subscription = subscriptions.remove(subscriptionId)
|
||||
|
||||
if (subscription != null && isConnected) {
|
||||
// 取消该订阅的所有 RPC 订阅
|
||||
scope.launch {
|
||||
// 查找该订阅的所有 RPC subscriptionId
|
||||
val rpcSubscriptionIds = rpcSubscriptionIdToSubscriptionId.entries
|
||||
.filter { it.value == subscriptionId }
|
||||
.map { it.key }
|
||||
|
||||
for (rpcSubId in rpcSubscriptionIds) {
|
||||
unsubscribeRpc(rpcSubId)
|
||||
rpcSubscriptionIdToSubscriptionId.remove(rpcSubId)
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("取消订阅: subscriptionId=$subscriptionId")
|
||||
}
|
||||
|
||||
// 如果没有订阅了,停止连接
|
||||
if (subscriptions.isEmpty()) {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动连接(如果还没有连接)
|
||||
*/
|
||||
private fun startConnection() {
|
||||
// 如果没有订阅,不启动连接
|
||||
if (subscriptions.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
// 如果连接任务已经在运行,不重复启动
|
||||
if (connectionJob != null && connectionJob!!.isActive) {
|
||||
return
|
||||
}
|
||||
|
||||
// 启动连接任务
|
||||
connectionJob = scope.launch {
|
||||
startConnectionLoop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动连接循环
|
||||
*/
|
||||
private suspend fun startConnectionLoop() {
|
||||
while (scope.isActive) {
|
||||
try {
|
||||
// 如果没有订阅,停止连接
|
||||
if (subscriptions.isEmpty()) {
|
||||
logger.info("没有订阅,停止连接")
|
||||
stop()
|
||||
break
|
||||
}
|
||||
|
||||
// 如果已经连接,等待断开
|
||||
if (isConnected && webSocket != null) {
|
||||
waitForDisconnect()
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取可用的 RPC 节点
|
||||
val wsUrl = rpcNodeService.getWsUrl()
|
||||
val httpUrl = rpcNodeService.getHttpUrl()
|
||||
|
||||
if (wsUrl.isBlank() || httpUrl.isBlank()) {
|
||||
logger.warn("没有可用的 RPC 节点,等待重试...")
|
||||
delay(reconnectDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.info("连接链上 WebSocket: $wsUrl (${subscriptions.size} 个订阅)")
|
||||
|
||||
// 创建 HTTP 客户端(用于 RPC 调用)
|
||||
val httpClient = createHttpClient()
|
||||
|
||||
// 创建 RPC API 客户端
|
||||
val rpcApi = retrofitFactory.createEthereumRpcApi(httpUrl)
|
||||
|
||||
// 连接 WebSocket
|
||||
connectWebSocket(wsUrl, httpClient, rpcApi)
|
||||
|
||||
// 等待连接建立
|
||||
waitForConnect()
|
||||
|
||||
// 如果连接成功,订阅所有地址
|
||||
if (isConnected) {
|
||||
logger.info("WebSocket 连接已建立,开始订阅")
|
||||
for (subscription in subscriptions.values) {
|
||||
subscribeAddress(subscription)
|
||||
}
|
||||
|
||||
// 等待连接断开
|
||||
waitForDisconnect()
|
||||
}
|
||||
|
||||
// 连接断开后,如果没有订阅了,不再重连
|
||||
if (subscriptions.isEmpty()) {
|
||||
logger.info("没有订阅,停止重连")
|
||||
break
|
||||
}
|
||||
|
||||
// 等待后重连
|
||||
logger.info("WebSocket 连接断开,等待 ${reconnectDelay}ms 后重连")
|
||||
delay(reconnectDelay)
|
||||
|
||||
} catch (e: Exception) {
|
||||
logger.error("连接异常: ${e.message}", e)
|
||||
delay(reconnectDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 HTTP 客户端
|
||||
*/
|
||||
private fun createHttpClient(): OkHttpClient {
|
||||
val proxy = getProxyConfig()
|
||||
val builder = createClient()
|
||||
|
||||
if (proxy != null) {
|
||||
builder.proxy(proxy)
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接 WebSocket
|
||||
*/
|
||||
private fun connectWebSocket(wsUrl: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
// 先关闭旧连接
|
||||
webSocket?.close(1000, "重新连接")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(wsUrl)
|
||||
.build()
|
||||
|
||||
webSocket = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
isConnected = true
|
||||
logger.info("链上 WebSocket 连接成功")
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
scope.launch {
|
||||
handleMessage(text, httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
scope.launch {
|
||||
handleMessage(bytes.utf8(), httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接已关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
logger.error("链上 WebSocket 连接失败: ${t.message}", t)
|
||||
isConnected = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待连接建立
|
||||
*/
|
||||
private suspend fun waitForConnect() {
|
||||
var waited = 0L
|
||||
val timeout = 15000L // 15秒超时
|
||||
|
||||
while (!isConnected && waited < timeout) {
|
||||
delay(100)
|
||||
waited += 100
|
||||
}
|
||||
|
||||
if (!isConnected) {
|
||||
logger.warn("WebSocket 连接超时,等待重连")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待连接断开
|
||||
*/
|
||||
private suspend fun waitForDisconnect() {
|
||||
while (isConnected && scope.isActive) {
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅地址(为每个地址订阅 6 个事件)
|
||||
*/
|
||||
private suspend fun subscribeAddress(subscription: SubscriptionInfo) {
|
||||
if (webSocket == null || !isConnected) {
|
||||
return
|
||||
}
|
||||
|
||||
val address = subscription.address
|
||||
val walletTopic = OnChainWsUtils.addressToTopic32(address)
|
||||
val subscriptionId = subscription.subscriptionId
|
||||
|
||||
try {
|
||||
// 订阅 USDC Transfer (from wallet)
|
||||
subscribeLogs(OnChainWsUtils.USDC_CONTRACT, listOf(OnChainWsUtils.ERC20_TRANSFER_TOPIC, walletTopic), subscriptionId)
|
||||
|
||||
// 订阅 USDC Transfer (to wallet)
|
||||
subscribeLogs(OnChainWsUtils.USDC_CONTRACT, listOf(OnChainWsUtils.ERC20_TRANSFER_TOPIC, null, walletTopic), subscriptionId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (from wallet)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_SINGLE_TOPIC, null, walletTopic), subscriptionId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (to wallet)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_SINGLE_TOPIC, null, null, walletTopic), subscriptionId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (from wallet)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_BATCH_TOPIC, null, walletTopic), subscriptionId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (to wallet)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_BATCH_TOPIC, null, null, walletTopic), subscriptionId)
|
||||
|
||||
logger.debug("已订阅地址: subscriptionId=$subscriptionId, address=$address")
|
||||
} catch (e: Exception) {
|
||||
logger.error("订阅地址失败: subscriptionId=$subscriptionId, address=$address, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅日志
|
||||
*/
|
||||
private fun subscribeLogs(address: String, topics: List<String?>, subscriptionId: String) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val params = mapOf(
|
||||
"address" to address.lowercase(),
|
||||
"topics" to topics.filterNotNull()
|
||||
)
|
||||
|
||||
val requestId = ++requestIdCounter
|
||||
requestIdToSubscriptionId[requestId] = subscriptionId
|
||||
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to requestId,
|
||||
"method" to "eth_subscribe",
|
||||
"params" to listOf("logs", params)
|
||||
)
|
||||
|
||||
val message = gson.toJson(request)
|
||||
ws.send(message)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消 RPC 订阅
|
||||
*/
|
||||
private fun unsubscribeRpc(rpcSubscriptionId: String) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val requestId = ++requestIdCounter
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to requestId,
|
||||
"method" to "eth_unsubscribe",
|
||||
"params" to listOf(rpcSubscriptionId)
|
||||
)
|
||||
|
||||
val message = gson.toJson(request)
|
||||
ws.send(message)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 WebSocket 消息
|
||||
*/
|
||||
private suspend fun handleMessage(text: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
val message = gson.fromJson(text, JsonObject::class.java)
|
||||
|
||||
// 处理订阅响应
|
||||
if (message.has("result") && message.has("id")) {
|
||||
val requestId = message.get("id")?.asInt
|
||||
val rpcSubscriptionId = message.get("result")?.asString
|
||||
|
||||
if (requestId != null && rpcSubscriptionId != null) {
|
||||
val subscriptionId = requestIdToSubscriptionId.remove(requestId)
|
||||
if (subscriptionId != null) {
|
||||
// 保存 RPC subscriptionId 到订阅的映射
|
||||
rpcSubscriptionIdToSubscriptionId[rpcSubscriptionId] = subscriptionId
|
||||
logger.debug("订阅成功: subscriptionId=$subscriptionId, rpcSubscriptionId=$rpcSubscriptionId")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 处理日志通知
|
||||
if (message.has("params")) {
|
||||
val params = message.getAsJsonObject("params")
|
||||
val subscriptionIdParam = params.get("subscription")?.asString
|
||||
val result = params.getAsJsonObject("result")
|
||||
|
||||
if (result != null) {
|
||||
val txHash = result.get("transactionHash")?.asString
|
||||
if (txHash != null && subscriptionIdParam != null) {
|
||||
// 根据 RPC subscriptionId 找到对应的订阅
|
||||
val subscriptionId = rpcSubscriptionIdToSubscriptionId[subscriptionIdParam]
|
||||
if (subscriptionId != null) {
|
||||
// 处理交易,分发给对应的订阅者
|
||||
processTransactionForSubscription(txHash, subscriptionId, httpClient, rpcApi)
|
||||
} else {
|
||||
// 如果没有找到订阅,可能是新订阅还未建立映射,尝试处理所有订阅
|
||||
processTransaction(txHash, httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理 WebSocket 消息失败: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理交易(为特定订阅)
|
||||
* 直接调用订阅的回调
|
||||
*/
|
||||
private suspend fun processTransactionForSubscription(
|
||||
txHash: String,
|
||||
subscriptionId: String,
|
||||
httpClient: OkHttpClient,
|
||||
rpcApi: EthereumRpcApi
|
||||
) {
|
||||
val subscription = subscriptions[subscriptionId] ?: return
|
||||
|
||||
try {
|
||||
subscription.callback(txHash, httpClient, rpcApi)
|
||||
} catch (e: Exception) {
|
||||
logger.error("调用订阅回调失败: subscriptionId=$subscriptionId, txHash=$txHash, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理交易(为所有订阅,用于兼容)
|
||||
* 解析交易中的 Transfer 事件,分发给所有订阅者
|
||||
*/
|
||||
private suspend fun processTransaction(txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
// 获取交易 receipt
|
||||
val receiptRequest = JsonRpcRequest(
|
||||
method = "eth_getTransactionReceipt",
|
||||
params = listOf(txHash)
|
||||
)
|
||||
|
||||
val receiptResponse = rpcApi.call(receiptRequest)
|
||||
if (!receiptResponse.isSuccessful || receiptResponse.body() == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val receiptRpcResponse = receiptResponse.body()!!
|
||||
if (receiptRpcResponse.error != null || receiptRpcResponse.result == null) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 receipt JSON
|
||||
val receiptJson = receiptRpcResponse.result.asJsonObject
|
||||
|
||||
// 解析 receipt 中的 Transfer 日志
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: return
|
||||
val (erc20Transfers, erc1155Transfers) = OnChainWsUtils.parseReceiptTransfers(logs)
|
||||
|
||||
// 为每个订阅检查是否匹配,如果匹配则调用回调
|
||||
for (subscription in subscriptions.values) {
|
||||
val address = subscription.address
|
||||
|
||||
// 检查该地址是否参与了交易(通过检查 Transfer 日志)
|
||||
val isInvolved = erc20Transfers.any {
|
||||
it.from.lowercase() == address || it.to.lowercase() == address
|
||||
} || erc1155Transfers.any {
|
||||
it.from.lowercase() == address || it.to.lowercase() == address
|
||||
}
|
||||
|
||||
if (isInvolved) {
|
||||
// 该地址参与了交易,调用回调
|
||||
try {
|
||||
subscription.callback(txHash, httpClient, rpcApi)
|
||||
} catch (e: Exception) {
|
||||
logger.error("调用订阅回调失败: subscriptionId=${subscription.subscriptionId}, txHash=$txHash, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易失败: txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止连接
|
||||
*/
|
||||
fun stop() {
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
|
||||
// 关闭 WebSocket 连接
|
||||
webSocket?.close(1000, "停止监听")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
|
||||
// 清空订阅信息
|
||||
subscriptions.clear()
|
||||
requestIdToSubscriptionId.clear()
|
||||
rpcSubscriptionIdToSubscriptionId.clear()
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
fun init() {
|
||||
// 服务启动时不自动连接,等待有订阅时再连接
|
||||
logger.info("统一链上 WebSocket 服务已初始化")
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
+72
-72
@@ -125,88 +125,88 @@ open class CopyOrderTrackingService(
|
||||
|
||||
return mutex.withLock {
|
||||
try {
|
||||
// 1. 检查是否已处理(去重,包括失败状态)
|
||||
val existingProcessed = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
// 1. 检查是否已处理(去重,包括失败状态)
|
||||
val existingProcessed = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
|
||||
if (existingProcessed != null) {
|
||||
if (existingProcessed.status == "FAILED") {
|
||||
if (existingProcessed != null) {
|
||||
if (existingProcessed.status == "FAILED") {
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
}
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否已记录为失败交易
|
||||
val failedTrade = failedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (failedTrade != null) {
|
||||
// 检查是否已记录为失败交易
|
||||
val failedTrade = failedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (failedTrade != null) {
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 处理交易逻辑
|
||||
val result = when (trade.side.uppercase()) {
|
||||
"BUY" -> processBuyTrade(leaderId, trade)
|
||||
"SELL" -> processSellTrade(leaderId, trade)
|
||||
else -> {
|
||||
logger.warn("未知的交易方向: ${trade.side}")
|
||||
Result.failure(IllegalArgumentException("未知的交易方向: ${trade.side}"))
|
||||
}
|
||||
// 2. 处理交易逻辑
|
||||
val result = when (trade.side.uppercase()) {
|
||||
"BUY" -> processBuyTrade(leaderId, trade)
|
||||
"SELL" -> processSellTrade(leaderId, trade)
|
||||
else -> {
|
||||
logger.warn("未知的交易方向: ${trade.side}")
|
||||
Result.failure(IllegalArgumentException("未知的交易方向: ${trade.side}"))
|
||||
}
|
||||
}
|
||||
|
||||
if (result.isFailure) {
|
||||
logger.error(
|
||||
"处理交易失败: leaderId=$leaderId, tradeId=${trade.id}, side=${trade.side}",
|
||||
result.exceptionOrNull()
|
||||
)
|
||||
if (result.isFailure) {
|
||||
logger.error(
|
||||
"处理交易失败: leaderId=$leaderId, tradeId=${trade.id}, side=${trade.side}",
|
||||
result.exceptionOrNull()
|
||||
)
|
||||
return@withLock result
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 标记为已处理(成功状态)
|
||||
// 3. 标记为已处理(成功状态)
|
||||
// 由于使用了 Mutex,这里理论上不会出现并发冲突,但保留异常处理作为兜底
|
||||
try {
|
||||
val processed = ProcessedTrade(
|
||||
leaderId = leaderId,
|
||||
leaderTradeId = trade.id,
|
||||
tradeType = trade.side.uppercase(),
|
||||
source = source,
|
||||
status = "SUCCESS",
|
||||
processedAt = System.currentTimeMillis()
|
||||
)
|
||||
processedTradeRepository.save(processed)
|
||||
} catch (e: Exception) {
|
||||
// 检查是否是唯一键冲突异常(理论上不会发生,但保留作为兜底)
|
||||
if (isUniqueConstraintViolation(e)) {
|
||||
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existing != null) {
|
||||
if (existing.status == "FAILED") {
|
||||
logger.debug("交易已标记为失败,跳过处理: leaderId=$leaderId, tradeId=${trade.id}")
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
logger.debug("交易已处理(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existing.status}")
|
||||
return@withLock Result.success(Unit)
|
||||
} else {
|
||||
// 如果检查不到,可能是事务隔离级别问题,等待一下再查询
|
||||
delay(100)
|
||||
val existingAfterDelay =
|
||||
processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existingAfterDelay != null) {
|
||||
logger.debug("延迟查询到记录(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existingAfterDelay.status}")
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
logger.warn(
|
||||
"保存ProcessedTrade时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
||||
e
|
||||
)
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
} else {
|
||||
// 其他类型的异常,重新抛出
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
try {
|
||||
val processed = ProcessedTrade(
|
||||
leaderId = leaderId,
|
||||
leaderTradeId = trade.id,
|
||||
tradeType = trade.side.uppercase(),
|
||||
source = source,
|
||||
status = "SUCCESS",
|
||||
processedAt = System.currentTimeMillis()
|
||||
)
|
||||
processedTradeRepository.save(processed)
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易异常: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||
Result.failure(e)
|
||||
// 检查是否是唯一键冲突异常(理论上不会发生,但保留作为兜底)
|
||||
if (isUniqueConstraintViolation(e)) {
|
||||
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existing != null) {
|
||||
if (existing.status == "FAILED") {
|
||||
logger.debug("交易已标记为失败,跳过处理: leaderId=$leaderId, tradeId=${trade.id}")
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
logger.debug("交易已处理(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existing.status}")
|
||||
return@withLock Result.success(Unit)
|
||||
} else {
|
||||
// 如果检查不到,可能是事务隔离级别问题,等待一下再查询
|
||||
delay(100)
|
||||
val existingAfterDelay =
|
||||
processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existingAfterDelay != null) {
|
||||
logger.debug("延迟查询到记录(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existingAfterDelay.status}")
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
logger.warn(
|
||||
"保存ProcessedTrade时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
||||
e
|
||||
)
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
} else {
|
||||
// 其他类型的异常,重新抛出
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易异常: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -594,7 +594,7 @@ open class CopyOrderTrackingService(
|
||||
)
|
||||
|
||||
copyOrderTrackingRepository.save(tracking)
|
||||
|
||||
|
||||
logger.info("买入订单已保存,等待轮询任务获取实际数据后发送通知: orderId=$realOrderId, copyTradingId=${copyTrading.id}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理买入交易失败: copyTradingId=${copyTrading.id}, tradeId=${trade.id}", e)
|
||||
@@ -995,7 +995,7 @@ open class CopyOrderTrackingService(
|
||||
}
|
||||
|
||||
val realSellOrderId = createOrderResult.getOrNull() ?: return
|
||||
|
||||
|
||||
// 12. 下单时直接使用下单价格保存,等待定时任务更新实际成交价
|
||||
// priceUpdated 统一由定时任务更新,下单时统一设置为 false(非0x开头的除外)
|
||||
val priceUpdated = !realSellOrderId.startsWith("0x", ignoreCase = true)
|
||||
|
||||
+47
-10
@@ -194,16 +194,27 @@ class OrderStatusUpdateService(
|
||||
// 如果 orderId 不是 0x 开头,直接标记为已处理(priceUpdated = true 表示已处理,包括价格更新和通知发送)
|
||||
if (!record.sellOrderId.startsWith("0x", ignoreCase = true)) {
|
||||
logger.debug("卖出订单ID非0x开头,直接标记为已处理: orderId=${record.sellOrderId}")
|
||||
// 发送通知(使用临时数据)
|
||||
sendSellOrderNotification(
|
||||
record = record,
|
||||
useTemporaryData = true,
|
||||
account = account,
|
||||
copyTrading = copyTrading,
|
||||
clobApi = clobApi,
|
||||
apiSecret = apiSecret,
|
||||
apiPassphrase = apiPassphrase
|
||||
)
|
||||
|
||||
// 检查是否为自动生成的订单(AUTO_ 或 AUTO_FIFO_ 开头),如果是则不发送通知
|
||||
val isAutoOrder = record.sellOrderId.startsWith("AUTO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_FIFO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_WS_", ignoreCase = true)
|
||||
|
||||
if (!isAutoOrder) {
|
||||
// 非自动订单,发送通知(使用临时数据)
|
||||
sendSellOrderNotification(
|
||||
record = record,
|
||||
useTemporaryData = true,
|
||||
account = account,
|
||||
copyTrading = copyTrading,
|
||||
clobApi = clobApi,
|
||||
apiSecret = apiSecret,
|
||||
apiPassphrase = apiPassphrase
|
||||
)
|
||||
} else {
|
||||
logger.debug("自动生成的订单,跳过发送通知: orderId=${record.sellOrderId}")
|
||||
}
|
||||
|
||||
// 标记为已处理(priceUpdated = true 同时表示价格已更新和通知已发送)
|
||||
val updatedRecord = SellMatchRecord(
|
||||
id = record.id,
|
||||
@@ -223,6 +234,32 @@ class OrderStatusUpdateService(
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查是否为自动生成的订单(AUTO_ 或 AUTO_FIFO_ 开头),如果是则跳过发送通知
|
||||
val isAutoOrder = record.sellOrderId.startsWith("AUTO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_FIFO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_WS_", ignoreCase = true)
|
||||
|
||||
if (isAutoOrder) {
|
||||
logger.debug("自动生成的订单,跳过发送通知并直接标记为已处理: orderId=${record.sellOrderId}")
|
||||
// 直接标记为已处理,不发送通知
|
||||
val updatedRecord = SellMatchRecord(
|
||||
id = record.id,
|
||||
copyTradingId = record.copyTradingId,
|
||||
sellOrderId = record.sellOrderId,
|
||||
leaderSellTradeId = record.leaderSellTradeId,
|
||||
marketId = record.marketId,
|
||||
side = record.side,
|
||||
outcomeIndex = record.outcomeIndex,
|
||||
totalMatchedQuantity = record.totalMatchedQuantity,
|
||||
sellPrice = record.sellPrice,
|
||||
totalRealizedPnl = record.totalRealizedPnl,
|
||||
priceUpdated = true, // 标记为已处理
|
||||
createdAt = record.createdAt
|
||||
)
|
||||
sellMatchRecordRepository.save(updatedRecord)
|
||||
continue
|
||||
}
|
||||
|
||||
// 查询订单详情,获取实际成交价
|
||||
val actualSellPrice = trackingService.getActualExecutionPrice(
|
||||
orderId = record.sellOrderId,
|
||||
|
||||
+3
-21
@@ -28,8 +28,6 @@ class ApiHealthCheckService(
|
||||
private val dataApiBaseUrl: String,
|
||||
@Value("\${polymarket.gamma.base-url}")
|
||||
private val gammaBaseUrl: String,
|
||||
@Value("\${polygon.rpc.url:}")
|
||||
private val polygonRpcUrl: String,
|
||||
@Value("\${polymarket.rtds.ws-url}")
|
||||
private val polymarketWsUrl: String,
|
||||
@Value("\${polymarket.builder.relayer-url:}")
|
||||
@@ -187,27 +185,11 @@ class ApiHealthCheckService(
|
||||
|
||||
/**
|
||||
* 检查 Polygon RPC
|
||||
* 使用动态获取的可用节点,而不是固定的配置
|
||||
* 使用动态获取的可用节点(RpcNodeService 总是返回一个有效的 URL,包括默认节点)
|
||||
*/
|
||||
private suspend fun checkPolygonRpc(): ApiHealthCheckDto = withContext(Dispatchers.IO) {
|
||||
// 优先使用动态获取的可用节点
|
||||
val rpcUrl = try {
|
||||
rpcNodeService.getHttpUrl()
|
||||
} catch (e: Exception) {
|
||||
logger.debug("获取可用 RPC 节点失败,使用配置的默认值: ${e.message}")
|
||||
// 如果获取失败,使用配置的默认值作为兜底
|
||||
if (polygonRpcUrl.isNotBlank()) {
|
||||
polygonRpcUrl
|
||||
} else {
|
||||
return@withContext ApiHealthCheckDto(
|
||||
name = "Polygon RPC",
|
||||
url = "未配置",
|
||||
status = "skipped",
|
||||
message = "未配置 Polygon RPC URL 且没有可用的节点"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 RpcNodeService 获取可用节点(总是返回有效值,包括默认节点)
|
||||
val rpcUrl = rpcNodeService.getHttpUrl()
|
||||
checkJsonRpcApi("Polygon RPC", rpcUrl)
|
||||
}
|
||||
|
||||
|
||||
+92
-63
@@ -100,14 +100,14 @@ class TelegramNotificationService(
|
||||
if (orderResponse.isSuccessful && orderResponse.body() != null) {
|
||||
val order = orderResponse.body()!!
|
||||
if (actualPrice == null) {
|
||||
actualPrice = order.price
|
||||
actualPrice = order.price
|
||||
}
|
||||
if (actualSize == null) {
|
||||
actualSize = order.originalSize // 使用 originalSize 作为订单数量
|
||||
actualSize = order.originalSize // 使用 originalSize 作为订单数量
|
||||
}
|
||||
actualSide = order.side // 使用订单详情中的 side
|
||||
if (actualOutcome == null) {
|
||||
actualOutcome = order.outcome // 使用订单详情中的 outcome(市场方向)
|
||||
actualOutcome = order.outcome // 使用订单详情中的 outcome(市场方向)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -306,18 +306,8 @@ class TelegramNotificationService(
|
||||
else -> filterType
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -369,13 +359,17 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """🚫 <b>$orderFiltered</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo
|
||||
|
||||
@@ -580,6 +574,68 @@ class TelegramNotificationService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化价格显示(保留最多4位小数,截断不四舍五入)
|
||||
*/
|
||||
private fun formatPrice(price: String): String {
|
||||
return try {
|
||||
val priceDecimal = price.toSafeBigDecimal()
|
||||
val formatted = if (priceDecimal.scale() > 4) {
|
||||
priceDecimal.setScale(4, java.math.RoundingMode.DOWN).stripTrailingZeros()
|
||||
} else {
|
||||
priceDecimal.stripTrailingZeros()
|
||||
}
|
||||
formatted.toPlainString()
|
||||
} catch (e: Exception) {
|
||||
price
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化数量显示(保留最多2位小数,截断不四舍五入)
|
||||
*/
|
||||
private fun formatQuantity(quantity: String): String {
|
||||
return try {
|
||||
val quantityDecimal = quantity.toSafeBigDecimal()
|
||||
val formatted = if (quantityDecimal.scale() > 2) {
|
||||
quantityDecimal.setScale(2, java.math.RoundingMode.DOWN).stripTrailingZeros()
|
||||
} else {
|
||||
quantityDecimal.stripTrailingZeros()
|
||||
}
|
||||
formatted.toPlainString()
|
||||
} catch (e: Exception) {
|
||||
quantity
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建账户信息显示(格式:账户名(钱包地址))
|
||||
*/
|
||||
private fun buildAccountInfo(
|
||||
accountName: String?,
|
||||
walletAddress: String?,
|
||||
unknownAccount: String
|
||||
): String {
|
||||
return when {
|
||||
!accountName.isNullOrBlank() && !walletAddress.isNullOrBlank() -> {
|
||||
// 有账户名和钱包地址:账户名(钱包地址)
|
||||
"${accountName}(${maskAddress(walletAddress)})"
|
||||
}
|
||||
!accountName.isNullOrBlank() -> {
|
||||
// 只有账户名
|
||||
accountName
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
// 只有钱包地址
|
||||
maskAddress(walletAddress)
|
||||
}
|
||||
else -> {
|
||||
// 都没有
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建订单成功消息
|
||||
*/
|
||||
@@ -623,18 +679,8 @@ class TelegramNotificationService(
|
||||
else -> side
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
// 构建跟单信息(如果有)
|
||||
val copyTradingInfo = mutableListOf<String>()
|
||||
@@ -704,14 +750,18 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """✅ <b>$orderCreatedSuccess</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $orderIdLabel: <code>${orderId ?: unknown}</code>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo$escapedCopyTradingInfo
|
||||
|
||||
@@ -758,18 +808,8 @@ class TelegramNotificationService(
|
||||
else -> side
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -828,13 +868,17 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """❌ <b>$orderCreatedFailed</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo
|
||||
|
||||
@@ -899,18 +943,8 @@ class TelegramNotificationService(
|
||||
val timeLabel = messageSource.getMessage("notification.order.time", null, "时间", locale)
|
||||
val unknownAccount: String = messageSource.getMessage("notification.order.unknown_account", null, "未知账户", locale) ?: "未知账户"
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -933,12 +967,7 @@ class TelegramNotificationService(
|
||||
|
||||
// 构建仓位列表
|
||||
val positionsText = positions.joinToString("\n") { position ->
|
||||
val quantityDisplay = try {
|
||||
val quantityDecimal = position.quantity.toSafeBigDecimal()
|
||||
quantityDecimal.stripTrailingZeros().toPlainString()
|
||||
} catch (e: Exception) {
|
||||
position.quantity
|
||||
}
|
||||
val quantityDisplay = formatQuantity(position.quantity)
|
||||
val valueDisplay = try {
|
||||
val valueDecimal = position.value.toSafeBigDecimal()
|
||||
val formatted = if (valueDecimal.scale() > 4) {
|
||||
|
||||
@@ -77,6 +77,67 @@ object EthereumUtils {
|
||||
return BigInteger(cleanHex, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ABI 编码的响应中解析 uint256 数组
|
||||
* ABI 编码格式:
|
||||
* - offset (32 bytes): 数组数据的位置偏移量
|
||||
* - length (32 bytes): 数组长度
|
||||
* - data: 每个元素 32 字节
|
||||
* @param hexResult 十六进制结果(完整的 ABI 编码响应)
|
||||
* @param offset 数组数据的偏移位置(字节数,从 offset 位置开始读取)
|
||||
* @return BigInteger 数组
|
||||
*/
|
||||
fun decodeUint256Array(hexResult: String, offset: Int = 0): List<BigInteger> {
|
||||
val cleanHex = hexResult.removePrefix("0x")
|
||||
if (cleanHex.length < (offset + 1) * 64) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// 从 offset 位置开始读取
|
||||
val startPos = offset * 64 // 每个 uint256 是 64 个十六进制字符
|
||||
val lengthHex = cleanHex.substring(startPos, startPos + 64)
|
||||
val length = BigInteger(lengthHex, 16).toInt()
|
||||
|
||||
if (length <= 0 || length > 100) { // 防止异常数据
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val result = mutableListOf<BigInteger>()
|
||||
for (i in 0 until length) {
|
||||
val elementStart = startPos + 64 + (i * 64) // 跳过长度字段
|
||||
if (elementStart + 64 > cleanHex.length) {
|
||||
break
|
||||
}
|
||||
val elementHex = cleanHex.substring(elementStart, elementStart + 64)
|
||||
result.add(BigInteger(elementHex, 16))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ABI 编码的元组响应中解析数据
|
||||
* 用于解析 getCondition 返回的 (uint256 payoutDenominator, uint256[] payouts)
|
||||
* @param hexResult 十六进制结果
|
||||
* @return Pair<payoutDenominator, payouts>
|
||||
*/
|
||||
fun decodeConditionResult(hexResult: String): Pair<BigInteger, List<BigInteger>> {
|
||||
val cleanHex = hexResult.removePrefix("0x")
|
||||
|
||||
// 第一个 32 字节:payoutDenominator
|
||||
val payoutDenominatorHex = cleanHex.substring(0, 64)
|
||||
val payoutDenominator = BigInteger(payoutDenominatorHex, 16)
|
||||
|
||||
// 第二个 32 字节:payouts 数组的偏移量(通常是 0x40 = 64 字节)
|
||||
val offsetHex = cleanHex.substring(64, 128)
|
||||
val offset = BigInteger(offsetHex, 16).toInt() / 32 // 转换为 32 字节单位
|
||||
|
||||
// 从 offset 位置解析数组
|
||||
val payouts = decodeUint256Array(hexResult, offset)
|
||||
|
||||
return Pair(payoutDenominator, payouts)
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 Keccak-256 哈希(Ethereum 标准)
|
||||
* 使用 BouncyCastle 库实现真正的 Keccak-256
|
||||
|
||||
@@ -40,23 +40,12 @@ polymarket.rtds.ws-url=wss://ws-subscriptions-clob.polymarket.com
|
||||
polymarket.data-api.base-url=https://data-api.polymarket.com
|
||||
polymarket.gamma.base-url=https://gamma-api.polymarket.com
|
||||
|
||||
# Polygon RPC 配置(用于查询链上余额)
|
||||
# 可选:如果未配置,将无acc法查询 USDC 余额,但仍可通过 Subgraph API 查询持仓
|
||||
# 示例:https://polygon-rpc.com 或 https://polygon-mainnet.infura.io/v3/YOUR_PROJECT_ID
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# Builder Relayer 配置(用于 Gasless 交易)
|
||||
# 从 polymarket.com/settings?tab=builder 获取 Builder API 凭证
|
||||
# Builder API Key、Secret、Passphrase 现在通过系统设置页面配置,存储在数据库中
|
||||
# 如果未配置,将使用手动发送交易的方式(需要用户支付 gas)
|
||||
polymarket.builder.relayer-url=${POLYMARKET_BUILDER_RELAYER_URL:https://relayer-v2.polymarket.com/}
|
||||
|
||||
# 仓位推送配置
|
||||
# 轮询间隔(毫秒),默认3秒
|
||||
position.push.polling-interval=${POSITION_PUSH_POLLING_INTERVAL:3000}
|
||||
# 心跳超时时间(毫秒),默认60秒,超过此时间未收到心跳则清理连接
|
||||
position.push.heartbeat-timeout=${POSITION_PUSH_HEARTBEAT_TIMEOUT:60000}
|
||||
|
||||
# 跟单轮询配置
|
||||
# 轮询间隔(毫秒),默认2秒
|
||||
copy.trading.polling.interval=${COPY_TRADING_POLLING_INTERVAL:2000}
|
||||
|
||||
@@ -71,9 +71,6 @@ SERVER_PORT=80
|
||||
# MySQL 端口(可选,用于外部连接,默认 3307 避免与本地 MySQL 冲突)
|
||||
MYSQL_PORT=3307
|
||||
|
||||
# Polygon RPC
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# JWT 密钥(已自动生成随机值,生产环境建议修改)
|
||||
JWT_SECRET=${JWT_SECRET}
|
||||
|
||||
|
||||
@@ -38,12 +38,6 @@ SERVER_PORT=80
|
||||
# Optional, for external connections, default 3307 to avoid conflicts with local MySQL
|
||||
MYSQL_PORT=3307
|
||||
|
||||
# ============================================
|
||||
# Polygon RPC
|
||||
# ============================================
|
||||
# Polygon 网络 RPC 地址 / Polygon network RPC address
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# ============================================
|
||||
# 安全配置 / Security Configuration
|
||||
# ============================================
|
||||
|
||||
@@ -24,7 +24,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
# ⚠️ 安全警告:以下两个环境变量不能使用默认值,否则容器启动会失败
|
||||
# 请在 .env 文件中设置,或通过环境变量传入
|
||||
# 生成随机密钥:openssl rand -hex 32 (ADMIN_RESET_PASSWORD_KEY) 或 openssl rand -hex 64 (JWT_SECRET)
|
||||
|
||||
@@ -22,7 +22,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
# ⚠️ 安全警告:以下两个环境变量不能使用默认值,否则容器启动会失败
|
||||
# 请在 .env 文件中设置,或通过环境变量传入
|
||||
# 生成随机密钥:openssl rand -hex 32 (ADMIN_RESET_PASSWORD_KEY) 或 openssl rand -hex 64 (JWT_SECRET)
|
||||
|
||||
@@ -163,7 +163,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -393,7 +392,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=8000
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -554,7 +552,6 @@ serve -s dist -l 3000
|
||||
| `DB_USERNAME` | Database username | `root` | Yes (Production) |
|
||||
| `DB_PASSWORD` | Database password | - | Yes (Production) |
|
||||
| `SERVER_PORT` | Server port | `8000` | No |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC address | `https://polygon-rpc.com` | No |
|
||||
| `JWT_SECRET` | JWT secret key | - | Yes (Production) |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | Admin password reset key | - | Yes (Production) |
|
||||
|
||||
|
||||
@@ -100,9 +100,6 @@ spring.datasource.password=${DB_PASSWORD:password}
|
||||
# Server port
|
||||
server.port=${SERVER_PORT:8000}
|
||||
|
||||
# Polygon RPC
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# JWT secret
|
||||
jwt.secret=${JWT_SECRET:change-me-in-production}
|
||||
|
||||
|
||||
@@ -165,7 +165,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -397,7 +396,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=8000
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -558,7 +556,6 @@ serve -s dist -l 3000
|
||||
| `DB_USERNAME` | 数据库用户名 | `root` | 是(生产) |
|
||||
| `DB_PASSWORD` | 数据库密码 | - | 是(生产) |
|
||||
| `SERVER_PORT` | 服务器端口 | `8000` | 否 |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC 地址 | `https://polygon-rpc.com` | 否 |
|
||||
| `JWT_SECRET` | JWT 密钥 | - | 是(生产) |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | 管理员密码重置密钥 | - | 是(生产) |
|
||||
|
||||
|
||||
@@ -93,9 +93,6 @@ spring.datasource.password=${DB_PASSWORD:password}
|
||||
# 服务器端口
|
||||
server.port=${SERVER_PORT:8000}
|
||||
|
||||
# Polygon RPC
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# JWT 密钥
|
||||
jwt.secret=${JWT_SECRET:change-me-in-production}
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ const ApiHealthStatus: React.FC = () => {
|
||||
}}
|
||||
bodyStyle={{ padding: '12px' }}
|
||||
>
|
||||
<Space direction="vertical" size="small" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '8px' }}>
|
||||
<Text strong style={{ fontSize: '14px' }}>
|
||||
{item.name}
|
||||
@@ -110,9 +111,28 @@ const ApiHealthStatus: React.FC = () => {
|
||||
)}
|
||||
<Badge
|
||||
status={item.status === 'success' ? 'success' : item.status === 'skipped' ? 'default' : 'error'}
|
||||
text={getStatusText(item.status)}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Text type="secondary" style={{ fontSize: '12px', wordBreak: 'break-all' }}>
|
||||
{item.url}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{item.message && item.message !== '连接成功' && (
|
||||
<div>
|
||||
<Text
|
||||
type={item.status === 'success' ? 'success' : item.status === 'skipped' ? 'secondary' : 'danger'}
|
||||
style={{ fontSize: '12px' }}
|
||||
>
|
||||
{item.message}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
) : (
|
||||
<Card
|
||||
|
||||
Reference in New Issue
Block a user