Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07164853c3 | ||
|
|
3a1201e485 | ||
|
|
a88d36918a | ||
|
|
46665ce060 | ||
|
|
a4ed778a94 | ||
|
|
03980768c7 | ||
|
|
79a67fa942 | ||
|
|
6f1b1ef6f6 | ||
|
|
08bb49ea78 | ||
|
|
014bb8e12b | ||
|
|
efe4a3873e | ||
|
|
f46b4b7f74 | ||
|
|
e7f857d21e | ||
|
|
b0292c87dc | ||
|
|
0354e07232 | ||
|
|
1f127e237b | ||
|
|
6dcbc2ad00 | ||
|
|
d36d34fe04 | ||
|
|
e769e32b1c | ||
|
|
16a46716c0 | ||
|
|
f2516d3212 | ||
|
|
3dafd2e7e1 | ||
|
|
aa3bd5097f | ||
|
|
50f7f16c28 | ||
|
|
9be43676aa | ||
|
|
4d88040fd4 | ||
|
|
82f7bcfbed | ||
|
|
fdbecadfb7 | ||
|
|
4d6afb48e7 | ||
|
|
7eb0263193 | ||
|
|
bf068e1775 | ||
|
|
8c95b5b5b8 | ||
|
|
b321da7bba | ||
|
|
fc86061ecc | ||
|
|
62fc6947b8 | ||
|
|
efd1ce348a | ||
|
|
43c579198a | ||
|
|
e180b52c9a | ||
|
|
3ca46e7fb9 | ||
|
|
8076cd4b75 | ||
|
|
e5e847f18f | ||
|
|
54e73e48e4 | ||
|
|
451da12e09 | ||
|
|
06694a92e8 | ||
|
|
6bf42ddc1b | ||
|
|
1f92306b03 | ||
|
|
096cb9523a | ||
|
|
79982c935f | ||
|
|
d1beeafbe8 | ||
|
|
3ebfdb424c | ||
|
|
95503b75fd | ||
|
|
7ef226b722 | ||
|
|
3639dad003 | ||
|
|
bd50f293b4 | ||
|
|
482bbf92e2 | ||
|
|
275a2a3d22 | ||
|
|
cec21fa0a7 | ||
|
|
4ce3c9b2f6 | ||
|
|
a6381c4aac | ||
|
|
1e5896ac96 | ||
|
|
6ac02a9214 | ||
|
|
827bc48c1d | ||
|
|
36907635b6 | ||
|
|
aafbac7b7b | ||
|
|
5120f193cb | ||
|
|
befc24487d | ||
|
|
3203c5d9e5 | ||
|
|
7eddf82957 | ||
|
|
af023b085f | ||
|
|
11ceb32773 | ||
|
|
f6e6d485dd | ||
|
|
74ed3fdc91 | ||
|
|
2edf26857e | ||
|
|
ff2989bc18 | ||
|
|
13d3fad174 | ||
|
|
5e598cd2f3 | ||
|
|
c350868195 | ||
|
|
d458ef7ca3 | ||
|
|
8033ccfe93 | ||
|
|
10257024ca | ||
|
|
96d0b5f6c1 | ||
|
|
9ac18ade71 | ||
|
|
f4bdee12e1 | ||
|
|
1e52f40a6c | ||
|
|
24372a9639 | ||
|
|
f28ae2aa8d | ||
|
|
54eb29756a | ||
|
|
2bf1406566 | ||
|
|
46af120fd7 | ||
|
|
11592ded0b | ||
|
|
94440de2d3 | ||
|
|
68b42a098d | ||
|
|
ea113e6e90 | ||
|
|
9981df3839 | ||
|
|
68f59eba48 | ||
|
|
c659103e02 | ||
|
|
db2b5e32b6 | ||
|
|
041f7e9cef | ||
|
|
1e52ee2d44 | ||
|
|
97565fb490 | ||
|
|
1e68d067af | ||
|
|
82caa97e3b | ||
|
|
eeb7ac1f79 | ||
|
|
468fe8b0c2 | ||
|
|
48b7c0b414 | ||
|
|
c8304a05cd | ||
|
|
34127df014 | ||
|
|
f4a225baea | ||
|
|
126905400d | ||
|
|
89bd4caba4 | ||
|
|
c84ca4ab30 | ||
|
|
3be13ebb6f | ||
|
|
584998bf02 | ||
|
|
f14a7680af | ||
|
|
cd6994d611 | ||
|
|
64ab143e0e | ||
|
|
8525dd4722 | ||
|
|
90e672f7f8 | ||
|
|
cb5aed93c6 | ||
|
|
e46706370c | ||
|
|
34e7dc6b81 | ||
|
|
5a0d333f71 | ||
|
|
9f89015722 | ||
|
|
609a850e61 | ||
|
|
43614ee3c5 | ||
|
|
a603e201c1 | ||
|
|
4081e7e5ab | ||
|
|
17b0d1cad1 | ||
|
|
742d05d253 | ||
|
|
1b0df627a5 | ||
|
|
94ba4b7c5b | ||
|
|
14644e00a5 | ||
|
|
be2ef02923 | ||
|
|
6ccd93a161 | ||
|
|
2edf71dee1 | ||
|
|
86251ac054 | ||
|
|
2f4915a808 | ||
|
|
a596ebc875 | ||
|
|
5e7f9ca701 | ||
|
|
0f4346cd5f | ||
|
|
c4d5e20c7a | ||
|
|
56bf320588 | ||
|
|
e6f8112df2 | ||
|
|
30eb6659d8 | ||
|
|
240da52d11 | ||
|
|
a45003ce3d | ||
|
|
f9bdf1f18a | ||
|
|
a5467d3fbb | ||
|
|
f866db9f1b | ||
|
|
b8df9d1d72 | ||
|
|
0e1e22cebb | ||
|
|
9cfd4b6e1c | ||
|
|
8c4ead0169 | ||
|
|
2992a1f032 | ||
|
|
9e7707588f | ||
|
|
0db728dc52 | ||
|
|
6a2f3b6d6e | ||
|
|
e906090ba6 | ||
|
|
077070b2cb |
+5
-3
@@ -1,9 +1,11 @@
|
||||
# 监听地址,格式为 ip:port,例如 :8080
|
||||
LISTEN=127.0.0.1:8080
|
||||
|
||||
# 日志文件保存路径
|
||||
LOG=/var/log/bepusdt/
|
||||
|
||||
# SQLite 数据库文件路径(如果使用 MySQL,此项可忽略)
|
||||
SQLITE=/var/lib/bepusdt/sqlite.db
|
||||
# MySQL 数据库连接字符串(留空则使用 SQLite)
|
||||
# 格式:user:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local
|
||||
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s
|
||||
|
||||
# PostgreSQL 数据库
|
||||
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
|
||||
@@ -19,6 +19,8 @@ body:
|
||||
required: true
|
||||
- label: 我明白任何人针对我提交的问题没有义务提供帮助,包括项目维护者。
|
||||
required: true
|
||||
- label: 我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue 。
|
||||
required: false
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: 问题类型
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 30
|
||||
days-before-issue-stale: 3
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "此议题由于30天内没有任何活动,现在标记为过时。"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
name: pr-check
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
concurrency:
|
||||
group: pr-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
jobs:
|
||||
docker-build:
|
||||
name: Docker Build
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Generate App Version
|
||||
run: |
|
||||
echo "APP_VERSION=$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
echo "VERSION_TAG=pr-${{ github.event.pull_request.number }}-$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
|
||||
- name: Build Docker image (no push)
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./dockerfile
|
||||
platforms: linux/amd64
|
||||
push: false
|
||||
load: false
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VERSION=${{ env.VERSION_TAG }}
|
||||
tags: |
|
||||
${{ env.APP_NAME }}:pr-${{ github.event.pull_request.number }}
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
with:
|
||||
node-version: '25'
|
||||
- name: Install pnpm
|
||||
run: npm install -g pnpm
|
||||
run: npm install -g pnpm@10
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./web
|
||||
run: pnpm install --frozen-lockfile --shamefully-hoist
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.25.4'
|
||||
go-version: '1.26.2'
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
|
||||
+3
-1
@@ -7,4 +7,6 @@ conf.toml
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
static/web
|
||||
*.log
|
||||
static/secure
|
||||
*.log
|
||||
AGENTS.md
|
||||
@@ -1,4 +1,4 @@
|
||||
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务(谨防诈骗)
|
||||
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务 (谨防诈骗)
|
||||
,不鼓励任何衍生金融属性的交易行为,不负责任何使用本项目进行的三方行为;使用过程中遇见问题请提`issue`
|
||||
或群里交流,开源项目请自重!**
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# BEpusdt (Better Easy Payment USDT)
|
||||
|
||||
<p align="center">
|
||||
<img src="./static/payment/assets/img/tether.svg" width="15%" alt="tether">
|
||||
<img src="./static/checkout/official/assets/img/bepusdt.svg" width="15%" alt="tether">
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.html">
|
||||
@@ -31,6 +31,8 @@
|
||||
|
||||
缘起于`Epusdt`,但不仅限于此,加入了一些新特性,致力于成为一款更好用的个人`加密货币`收款网关。
|
||||
|
||||
> 原始 EPusdt 项目已被转手,现与本项目再没任何联系、两个项目完全独立运营,[具体说明](./docs/faq/epusdt.md)。
|
||||
|
||||
## 🎉 新特性
|
||||
|
||||
### 🌟 目前支持收款网络
|
||||
@@ -42,13 +44,10 @@
|
||||
- ️✅ 支持主流区块网络 不仅限于`USDT`
|
||||
- ✅ 支持主流法定货币 汇率自动更新
|
||||
- ✅ 轻依赖 单体二进制文件 部署便捷
|
||||
- ✅ 支持非订单交易监控 余额变动通知
|
||||
- ✅ 支持自定义支付精度与递增颗粒度
|
||||
- ✅ 底层区块扫描 安全确认 速度稳定
|
||||
- ✅ 支持波场能量代理 回收实时监控
|
||||
- ✅ 原生兼容`易支付`收单 接入便捷
|
||||
- ✅ 完整独立WEB后台 方便配置管理
|
||||
- ✅ 收银台支持中英适配 助力出海需求
|
||||
- ✅ 地址独占模式 底层支持不定额收款
|
||||
- ✅ 支持MQTT消息发布 交易信息即时广播
|
||||
- ✅ 快速迭代期 超多实用特性功能等你发现
|
||||
|
||||
## 🚀 快捷启动
|
||||
@@ -62,14 +61,14 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
|
||||
- 安装:[Docker](docs/docker/docker.md) [Linux](docs/linux/install.md) [1Panel](./docs/1panel/README.md) [宝塔](./docs/bt_panel/README.md)
|
||||
- 开发:[API对接](docs/api/api.md) [订单回调](docs/notify/readme.md) [Python](https://github.com/luoyanglang/bepusdt-python-sdk) [PHP](https://github.com/v03413/bepusdt-php-sdk)
|
||||
- 对接:[独角数卡](docs/api/dujiaoka/dujiaoka.md) [彩虹易支付](https://github.com/v03413/Epay-BEpusdt) [whmcs](https://github.com/v03413/whmcs-gateway-epusdt) [其它](docs/api/other.md)
|
||||
- 其它:[https 配置](./docs/ssl.md) [时钟同步](docs/linux/systemd-timesyncd.md) [收银台修改](docs/payment-template/README.md)
|
||||
- 对接:[独角Next](docs/api/dujiao-next/dujiao-next.md) [彩虹易支付](https://github.com/v03413/Epay-BEpusdt) [whmcs](https://github.com/v03413/whmcs-gateway-epusdt) [其它](docs/api/other.md)
|
||||
- 其它:[https 配置](./docs/ssl.md) [时钟同步](docs/linux/systemd-timesyncd.md) [收银台修改](docs/checkout/README.md)
|
||||
|
||||
## 🖼 功能截图
|
||||
|
||||
| 前台收银 | 后台订单 | Telegram 通知 |
|
||||
|-------------------------------------------------|--------------------------------------------------|--------------------------------------------------------|
|
||||
| <img src=./docs/images/1.png alt=收银台 width=300> | <img src=./docs/images/2.png alt=后台订单 width=300> | <img src=./docs/images/3.png alt=Telegram通知 width=300> |
|
||||
| 前台收银 | 后台订单 | 订单通知 |
|
||||
|-----------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------|
|
||||
| <img src=./docs/images/checkout.png alt=收银台 width=300> | <img src=./docs/images/admin.png alt=后台订单 width=300> | <img src=./docs/images/telegram.png alt=Telegram通知 width=300> |
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
@@ -77,12 +76,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
- [服务器流量消耗说明解释](./docs/faq/bandwidth.md)
|
||||
- [后台入口账密忘记重置教程](./docs/faq/login-reset.md)
|
||||
- [Telegram 通知 Chat ID 获取教程](docs/faq/telegram-chat-id.md)
|
||||
- [推荐配置提高 Tron 扫块稳定性‼️](./docs/tron-grid/readme.md)
|
||||
|
||||
## ⚠️ 重要提示
|
||||
|
||||
- **订单交易强依赖时间**:请确保服务器时间准确,否则可能导致订单异常
|
||||
- **网络环境要求**:请确保服务器网络环境稳定,否则可能影响功能正常运行
|
||||
- [区块 RPC 节点稳定性说明指南‼️](./docs/faq/rpc-endpoint.md)
|
||||
|
||||
## 🏝️ 社区交流
|
||||
|
||||
@@ -91,8 +85,16 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
- [Epusdt](https://github.com/assimon/epusdt)
|
||||
感谢原项目提供的灵感和参考:
|
||||
|
||||
- [EPusdt](./docs/faq/epusdt.md)
|
||||
|
||||
感谢为本项目作出贡献的开发者:
|
||||
|
||||
<a href="https://github.com/v03413/BEpusdt/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=v03413/BEpusdt" alt="BEpusdt 贡献者清单">
|
||||
</a>
|
||||
|
||||
## 🌟 Star 历史
|
||||
|
||||
[](https://starchart.cc/v03413/bepusdt)
|
||||
[](https://www.star-history.com/?repos=v03413%2Fbepusdt&type=date&legend=top-left)
|
||||
+4
-4
@@ -9,11 +9,11 @@ var SQLiteFlag = &cli.StringFlag{
|
||||
Sources: cli.EnvVars("SQLITE"),
|
||||
}
|
||||
|
||||
var MySQLDSNFlag = &cli.StringFlag{
|
||||
Name: "mysql",
|
||||
var PostgresDSNFlag = &cli.StringFlag{
|
||||
Name: "postgres",
|
||||
Value: "",
|
||||
Usage: "MySQL 数据库连接字符串 (DSN),例如: user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s",
|
||||
Sources: cli.EnvVars("MYSQL_DSN"),
|
||||
Usage: "PostgreSQL 数据库连接字符串 (DSN),例如: postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3",
|
||||
Sources: cli.EnvVars("POSTGRESQL_DSN"),
|
||||
}
|
||||
|
||||
var LogFlag = &cli.StringFlag{
|
||||
|
||||
+3
-3
@@ -15,11 +15,11 @@ import (
|
||||
var Reset = &cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "忘记密码时,此命令可重置账号密码登录入口",
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
dsn := c.String("mysql")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, dsn); err != nil {
|
||||
postgres := c.String("postgres")
|
||||
if err := model.Init(sqlite, postgres); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -27,11 +27,11 @@ import (
|
||||
var Start = &cli.Command{
|
||||
Name: "start",
|
||||
Usage: "启动收款网关",
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, LogFlag, ListenFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, LogFlag, ListenFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
dsn := c.String("mysql")
|
||||
postgres := c.String("postgres")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, dsn); err != nil {
|
||||
if err := model.Init(sqlite, postgres); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ func start(ctx context.Context, cmd *cli.Command) error {
|
||||
|
||||
notifier.Welcome()
|
||||
|
||||
fmt.Println(fmt.Sprintf("日志保存路径:%s", log.GetPath()))
|
||||
fmt.Println(fmt.Sprintf("BEpusdt 启动成功(%s),当前版本:%s", listen, app.Version))
|
||||
|
||||
// 等待中断信号
|
||||
|
||||
@@ -8,6 +8,12 @@ const (
|
||||
const Debug = false
|
||||
|
||||
const (
|
||||
Pid = "1000" // 暂时固定易支付商户ID
|
||||
Api = "https://api.bepusdt.online"
|
||||
)
|
||||
|
||||
const (
|
||||
Ton = "ton" // The Open Network
|
||||
Bsc = "bsc" // Binance Smart Chain
|
||||
Tron = "tron"
|
||||
Aptos = "aptos"
|
||||
@@ -21,6 +27,7 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
UsdtTon = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs"
|
||||
UsdtErc20 = "0xdac17f958d2ee523a2206206994597c13d831ec7"
|
||||
UsdtBep20 = "0x55d398326f99059ff775485246999027b3197955"
|
||||
UsdtXlayer = "0x779ded0c9e1022225f8e0630b35a9b54be713736"
|
||||
@@ -50,6 +57,7 @@ const (
|
||||
UsdtArbitrumDecimals = -6 // USDT Arbitrum小数位数
|
||||
UsdtAptosDecimals = -6 // USDT Aptos小数位数
|
||||
UsdtSolanaDecimals = -6 // USDT Solana小数位数
|
||||
UsdtTonDecimals = -6 // USDT Ton小数位数
|
||||
|
||||
UsdcEthDecimals = -6 // USDC ERC20小数位数
|
||||
UsdcPolygonDecimals = -6 // USDC Polygon小数位数
|
||||
@@ -61,6 +69,7 @@ const (
|
||||
UsdcAptosDecimals = -6 // USDC Aptos小数位数
|
||||
UsdcSolanaDecimals = -6 // USDC Solana小数位数
|
||||
|
||||
TonTonDecimals = -9 // TON Ton小数位数
|
||||
BscBnbDecimals = -18 // BSC BNB 小数位数
|
||||
EthereumEthDecimals = -18 // Ethereum ETH 小数位数
|
||||
)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
Secret = "BEpusdt, a more user-friendly personal cryptocurrency payment gateway!"
|
||||
AdminTokenK = "admin_token"
|
||||
AdminSecureK = "admin_secure"
|
||||
)
|
||||
|
||||
+21
-1
@@ -3,6 +3,7 @@ package conf
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxRecords = 1000
|
||||
@@ -15,8 +16,15 @@ type stat struct {
|
||||
succ int // 成功记录数
|
||||
}
|
||||
|
||||
type info struct {
|
||||
Block string `json:"block"`
|
||||
Succ string `json:"succ"`
|
||||
Time int64 `json:"time"`
|
||||
}
|
||||
|
||||
var (
|
||||
data sync.Map // map[string]*stat
|
||||
last sync.Map
|
||||
)
|
||||
|
||||
func getStat(net string) *stat {
|
||||
@@ -26,7 +34,8 @@ func getStat(net string) *stat {
|
||||
return val.(*stat)
|
||||
}
|
||||
|
||||
func RecordSuccess(net string) {
|
||||
func RecordSuccess(net, block string) {
|
||||
last.Store(net, info{Block: block, Succ: GetSuccessRate(net), Time: time.Now().Unix()})
|
||||
s := getStat(net)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -60,6 +69,17 @@ func RecordFailure(net string) {
|
||||
}
|
||||
}
|
||||
|
||||
func GetStats() map[string]info {
|
||||
var m = make(map[string]info)
|
||||
last.Range(func(k, v interface{}) bool {
|
||||
m[k.(string)] = v.(info)
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func GetSuccessRate(net string) string {
|
||||
s := getStat(net)
|
||||
s.mu.RLock()
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
api string
|
||||
}
|
||||
|
||||
func New() Api {
|
||||
return Api{
|
||||
api: conf.Api,
|
||||
}
|
||||
}
|
||||
|
||||
func (Api) get(url string) ([]byte, error) {
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建请求失败: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("BEpusdt/%s", app.Version))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(gjson.GetBytes(body, "error").String())
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (Api) error(err error) {
|
||||
log.Warn("Api Error:", err.Error())
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type BoundaryResp struct {
|
||||
Start int64 `json:"start"`
|
||||
End int64 `json:"end"`
|
||||
}
|
||||
|
||||
func (a Api) GetBoundaryHeights(start, end int64, network string) (int64, int64) {
|
||||
url := fmt.Sprintf("%s/api/block/get_boundary_heights?network=%s&start=%d&end=%d",
|
||||
a.api, network, start, end)
|
||||
|
||||
body, err := a.get(url)
|
||||
if err != nil {
|
||||
a.error(err)
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
var response BoundaryResp
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
a.error(err)
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
return response.Start, response.End
|
||||
}
|
||||
+38
-17
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/handler/base"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notifier"
|
||||
@@ -65,7 +66,7 @@ func (Conf) Del(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
model.Db.Where("`k` = ?", req.Key).Delete(&model.Conf{})
|
||||
model.Db.Where("k = ?", req.Key).Delete(&model.Conf{})
|
||||
|
||||
base.Ok(ctx, "删除成功")
|
||||
}
|
||||
@@ -79,7 +80,7 @@ func (Conf) Gets(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
var items = make([]model.Conf, 0)
|
||||
model.Db.Where("`k` IN ?", req.Keys).Find(&items)
|
||||
model.Db.Where("k IN ?", req.Keys).Find(&items)
|
||||
|
||||
var data = gin.H{}
|
||||
for _, item := range items {
|
||||
@@ -106,20 +107,7 @@ func (Conf) Sets(ctx *gin.Context) {
|
||||
data = append(data, model.Conf{K: model.ConfKey(k), V: v})
|
||||
}
|
||||
|
||||
for _, v := range data {
|
||||
if v.K == model.PaymentStaticPath && v.V != "" && !utils.IsExist(v.V) {
|
||||
base.BadRequest(ctx, "静态资源路径不存在,请确认后重新配置:"+v.V)
|
||||
|
||||
return
|
||||
}
|
||||
if v.K == model.ApiAuthToken {
|
||||
base.BadRequest(ctx, "安全考虑,不允许自定义修改 API 对接令牌")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
model.Db.Where("`k` IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&data)
|
||||
|
||||
defer model.RefreshC()
|
||||
@@ -127,6 +115,35 @@ func (Conf) Sets(ctx *gin.Context) {
|
||||
base.Ok(ctx, "配置成功")
|
||||
}
|
||||
|
||||
func (Conf) Rpc(ctx *gin.Context) {
|
||||
var keys = []model.ConfKey{
|
||||
model.RpcEndpointPlasma,
|
||||
model.RpcEndpointBsc,
|
||||
model.RpcEndpointSolana,
|
||||
model.RpcEndpointXlayer,
|
||||
model.RpcEndpointPolygon,
|
||||
model.RpcEndpointArbitrum,
|
||||
model.RpcEndpointEthereum,
|
||||
model.RpcEndpointBase,
|
||||
model.RpcEndpointAptos,
|
||||
model.RpcEndpointTron,
|
||||
model.RpcEndpointTronGridApiKey,
|
||||
model.RpcGlobalConfigUrlTon,
|
||||
}
|
||||
|
||||
var rpc = make(map[model.ConfKey]string)
|
||||
var items = make([]model.Conf, 0)
|
||||
model.Db.Where("k IN ?", keys).Find(&items)
|
||||
for _, item := range items {
|
||||
rpc[item.K] = item.V
|
||||
}
|
||||
|
||||
base.Ok(ctx, gin.H{
|
||||
"rpc": rpc,
|
||||
"stats": conf.GetStats(),
|
||||
})
|
||||
}
|
||||
|
||||
func (Conf) Notifier(ctx *gin.Context) {
|
||||
var req notifierConf
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
@@ -136,7 +153,7 @@ func (Conf) Notifier(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
var keys = []string{string(model.NotifierChannel), string(model.NotifierParams)}
|
||||
model.Db.Where("`k` IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&[]model.Conf{
|
||||
{K: model.NotifierChannel, V: req.Channel},
|
||||
{K: model.NotifierParams, V: string(req.Params)},
|
||||
@@ -156,6 +173,10 @@ func (Conf) NotifierTest(ctx *gin.Context) {
|
||||
base.Ok(ctx, "发送测试成功")
|
||||
}
|
||||
|
||||
func (Conf) CheckoutList(ctx *gin.Context) {
|
||||
base.Ok(ctx, model.CheckoutList())
|
||||
}
|
||||
|
||||
func (Conf) ResetApiAuthToken(ctx *gin.Context) {
|
||||
model.SetK(model.ApiAuthToken, strings.ToUpper(utils.Md5String(utils.StrSha256(time.Now().String()))))
|
||||
|
||||
|
||||
+227
-29
@@ -1,19 +1,37 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/handler/base"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
type Dashboard struct {
|
||||
}
|
||||
|
||||
type homeReq struct {
|
||||
Fiat string `json:"fiat" binding:"required"`
|
||||
Fiat string `json:"fiat" binding:"required"`
|
||||
Range string `json:"range"`
|
||||
TZ string `json:"tz"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Force bool `json:"force"`
|
||||
}
|
||||
|
||||
type dashboardPoint struct {
|
||||
Date string `json:"date"`
|
||||
OrdersTotal int64 `json:"orders_total"`
|
||||
OrdersPaid int64 `json:"orders_paid"`
|
||||
OrdersSuccess int64 `json:"orders_success"`
|
||||
OrdersFailed int64 `json:"orders_failed"`
|
||||
GMVPaid string `json:"gmv_paid"`
|
||||
}
|
||||
|
||||
func (Dashboard) Home(ctx *gin.Context) {
|
||||
@@ -24,13 +42,33 @@ func (Dashboard) Home(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var rows = make([]model.Order, 0)
|
||||
model.Db.Where("fiat = ? and status = ?", req.Fiat, model.OrderStatusSuccess).Find(&rows)
|
||||
rangeKey, from, to, loc, err := resolveDashboardRange(req)
|
||||
if err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
var today = time.Now().Format("2006-01-02")
|
||||
var totalMoney, todayMoney float64
|
||||
var totalCount, todayCount int64
|
||||
var monthly = make(map[string]float64)
|
||||
return
|
||||
}
|
||||
|
||||
cacheKey := dashboardCacheKey(req.Fiat, rangeKey, loc.String(), from, to)
|
||||
if !req.Force {
|
||||
if data, ok := cache.Get(cacheKey); ok {
|
||||
base.Ok(ctx, data)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
data := buildDashboardHome(req, rangeKey, from, to, loc)
|
||||
cache.Set(cacheKey, data, dashboardCacheTTL(rangeKey, to, loc))
|
||||
base.Ok(ctx, data)
|
||||
}
|
||||
|
||||
func buildDashboardHome(req homeReq, rangeKey string, from, to time.Time, loc *time.Location) gin.H {
|
||||
var rows = make([]model.Order, 0)
|
||||
model.Db.Where("fiat = ? and created_at >= ? and created_at <= ?", req.Fiat, from, to).Find(&rows)
|
||||
|
||||
var totalCount, pendingCount, confirmingCount, successCount, expiredCount, failedCount, notifyFailedCount int64
|
||||
gmvPaid := decimal.Zero
|
||||
var tokenMap = map[model.Crypto]float64{
|
||||
model.USDT: 0,
|
||||
model.USDC: 0,
|
||||
@@ -38,38 +76,198 @@ func (Dashboard) Home(ctx *gin.Context) {
|
||||
model.BNB: 0,
|
||||
model.ETH: 0,
|
||||
}
|
||||
points := make([]dashboardPoint, 0)
|
||||
pointMap := make(map[string]int)
|
||||
for day := dayStart(from, loc); !day.After(dayStart(to, loc)); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
point := dashboardPoint{
|
||||
Date: date,
|
||||
GMVPaid: "0.00",
|
||||
}
|
||||
points = append(points, point)
|
||||
pointMap[date] = len(points) - 1
|
||||
}
|
||||
|
||||
for _, itm := range rows {
|
||||
money := cast.ToFloat64(itm.Money)
|
||||
|
||||
totalMoney += money
|
||||
totalCount++
|
||||
if itm.CreatedAt.Format("2006-01-02") == today {
|
||||
todayMoney += money
|
||||
todayCount++
|
||||
createdAt := time.Now().In(loc)
|
||||
if itm.CreatedAt != nil {
|
||||
createdAt = time.Time(*itm.CreatedAt).In(loc)
|
||||
}
|
||||
date := createdAt.Format("2006-01-02")
|
||||
pointIndex, ok := pointMap[date]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
point := &points[pointIndex]
|
||||
|
||||
if crypto, err := model.GetCrypto(itm.TradeType); err == nil {
|
||||
point.OrdersTotal++
|
||||
|
||||
switch itm.Status {
|
||||
case model.OrderStatusWaiting:
|
||||
pendingCount++
|
||||
case model.OrderStatusConfirming:
|
||||
confirmingCount++
|
||||
case model.OrderStatusExpired:
|
||||
expiredCount++
|
||||
case model.OrderStatusSuccess:
|
||||
successCount++
|
||||
point.OrdersSuccess++
|
||||
point.OrdersPaid++
|
||||
|
||||
money, _ := decimal.NewFromString(itm.Money)
|
||||
gmvPaid = gmvPaid.Add(money)
|
||||
pointMoney, _ := decimal.NewFromString(point.GMVPaid)
|
||||
point.GMVPaid = pointMoney.Add(money).Round(2).StringFixed(2)
|
||||
|
||||
crypto := itm.Crypto
|
||||
if crypto == "" {
|
||||
if tradeCrypto, err := model.GetCrypto(itm.TradeType); err == nil {
|
||||
crypto = tradeCrypto
|
||||
}
|
||||
}
|
||||
if _, ok := tokenMap[crypto]; !ok {
|
||||
tokenMap[crypto] = 0
|
||||
}
|
||||
tokenAmount := cast.ToFloat64(itm.Amount)
|
||||
if tokenAmount == 0 {
|
||||
tokenAmount = cast.ToFloat64(itm.Money)
|
||||
}
|
||||
tokenMap[crypto] += tokenAmount
|
||||
|
||||
tokenMap[crypto] += money
|
||||
if itm.NotifyState == model.OrderNotifyStateFail {
|
||||
notifyFailedCount++
|
||||
}
|
||||
case model.OrderStatusFailed:
|
||||
failedCount++
|
||||
point.OrdersFailed++
|
||||
}
|
||||
|
||||
var month = itm.CreatedAt.Time().Format("2006/01")
|
||||
if _, ok := monthly[month]; !ok {
|
||||
monthly[month] = 0
|
||||
}
|
||||
monthly[month] += money
|
||||
}
|
||||
|
||||
base.Ok(ctx, gin.H{
|
||||
"total_money": totalMoney,
|
||||
"total_count": totalCount,
|
||||
"today_money": todayMoney,
|
||||
"today_count": todayCount,
|
||||
"token_map": tokenMap,
|
||||
"monthly": monthly,
|
||||
})
|
||||
successRate := "0.00"
|
||||
finishedCount := successCount + expiredCount + failedCount
|
||||
if finishedCount > 0 {
|
||||
rate := decimal.NewFromInt(successCount).Div(decimal.NewFromInt(finishedCount)).Mul(decimal.NewFromInt(100))
|
||||
successRate = rate.Round(2).StringFixed(2)
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"range": rangeKey,
|
||||
"from": from.In(loc).Format(time.RFC3339),
|
||||
"to": to.In(loc).Format(time.RFC3339),
|
||||
"timezone": loc.String(),
|
||||
"currency": req.Fiat,
|
||||
"kpi": gin.H{
|
||||
"orders_total": totalCount,
|
||||
"orders_pending": pendingCount,
|
||||
"orders_confirming": confirmingCount,
|
||||
"gmv_paid": gmvPaid.Round(2).StringFixed(2),
|
||||
"orders_success": successCount,
|
||||
"orders_failed": failedCount,
|
||||
"notify_failed": notifyFailedCount,
|
||||
"order_success_rate": successRate,
|
||||
},
|
||||
"token_map": tokenMap,
|
||||
"points": points,
|
||||
}
|
||||
}
|
||||
|
||||
func dashboardCacheKey(fiat, rangeKey, timezone string, from, to time.Time) string {
|
||||
return fmt.Sprintf("dashboard:home:v1:%s:%s:%s:%d:%d", fiat, rangeKey, timezone, from.Unix(), to.Unix())
|
||||
}
|
||||
|
||||
func dashboardCacheTTL(rangeKey string, to time.Time, loc *time.Location) time.Duration {
|
||||
switch rangeKey {
|
||||
case "today":
|
||||
return 10 * time.Second
|
||||
case "30d":
|
||||
return time.Minute
|
||||
case "custom":
|
||||
if to.Before(dayStart(time.Now().In(loc), loc)) {
|
||||
return 5 * time.Minute
|
||||
}
|
||||
|
||||
return 30 * time.Second
|
||||
default:
|
||||
return 30 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
func resolveDashboardRange(req homeReq) (string, time.Time, time.Time, *time.Location, error) {
|
||||
loc := time.Local
|
||||
if req.TZ != "" {
|
||||
if loadedLoc, err := time.LoadLocation(req.TZ); err == nil {
|
||||
loc = loadedLoc
|
||||
}
|
||||
}
|
||||
|
||||
rangeKey := req.Range
|
||||
if rangeKey == "" {
|
||||
rangeKey = "7d"
|
||||
}
|
||||
|
||||
now := time.Now().In(loc)
|
||||
switch rangeKey {
|
||||
case "today":
|
||||
start := dayStart(now, loc)
|
||||
return rangeKey, start, dayEnd(start), loc, nil
|
||||
case "30d":
|
||||
yesterday := dayStart(now, loc).AddDate(0, 0, -1)
|
||||
start := yesterday.AddDate(0, 0, -29)
|
||||
return rangeKey, start, dayEnd(yesterday), loc, nil
|
||||
case "custom":
|
||||
from, err := parseDashboardDate(req.From, loc, true)
|
||||
if err != nil {
|
||||
return "", time.Time{}, time.Time{}, nil, err
|
||||
}
|
||||
to, err := parseDashboardDate(req.To, loc, false)
|
||||
if err != nil {
|
||||
return "", time.Time{}, time.Time{}, nil, err
|
||||
}
|
||||
if to.Before(from) {
|
||||
return "", time.Time{}, time.Time{}, nil, errors.New("自定义统计周期结束时间不能早于开始时间")
|
||||
}
|
||||
|
||||
return rangeKey, from, to, loc, nil
|
||||
case "7d":
|
||||
fallthrough
|
||||
default:
|
||||
yesterday := dayStart(now, loc).AddDate(0, 0, -1)
|
||||
start := yesterday.AddDate(0, 0, -6)
|
||||
return "7d", start, dayEnd(yesterday), loc, nil
|
||||
}
|
||||
}
|
||||
|
||||
func parseDashboardDate(value string, loc *time.Location, start bool) (time.Time, error) {
|
||||
if value == "" {
|
||||
return time.Time{}, errors.New("请选择自定义统计周期")
|
||||
}
|
||||
|
||||
layouts := []string{time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
|
||||
for _, layout := range layouts {
|
||||
t, err := time.ParseInLocation(layout, value, loc)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if layout == "2006-01-02" {
|
||||
if start {
|
||||
return dayStart(t, loc), nil
|
||||
}
|
||||
return dayEnd(t), nil
|
||||
}
|
||||
|
||||
return t.In(loc), nil
|
||||
}
|
||||
|
||||
return time.Time{}, errors.New("自定义统计周期格式错误")
|
||||
}
|
||||
|
||||
func dayStart(t time.Time, loc *time.Location) time.Time {
|
||||
local := t.In(loc)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc)
|
||||
}
|
||||
|
||||
func dayEnd(t time.Time) time.Time {
|
||||
start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||
return start.Add(24*time.Hour - time.Nanosecond)
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ func (Order) Create(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// NotifyURL RedirectURL 同为付款链接
|
||||
url := model.CheckoutCashier(host, order.TradeId)
|
||||
url := model.CheckoutUrl(host, order.TradeId)
|
||||
|
||||
// Update order with generated URLs
|
||||
hostUri := model.GetK(model.ApiAppUri)
|
||||
@@ -201,10 +201,17 @@ func (Order) Paid(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status == model.OrderStatusCanceled {
|
||||
base.BadRequest(ctx, "交易已取消,无法补单")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
confirmedAt := time.Now()
|
||||
var update = map[string]interface{}{
|
||||
"ref_hash": req.RefHash,
|
||||
"status": model.OrderStatusSuccess,
|
||||
"confirmed_at": model.Datetime(time.Now()),
|
||||
"confirmed_at": model.Datetime(confirmedAt),
|
||||
}
|
||||
|
||||
err := model.Db.Model(&order).Updates(update).Error
|
||||
@@ -214,6 +221,10 @@ func (Order) Paid(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
order.RefHash = req.RefHash
|
||||
order.Status = model.OrderStatusSuccess
|
||||
order.ConfirmedAt = &confirmedAt
|
||||
|
||||
go notify.Handle(order)
|
||||
|
||||
base.Ok(ctx, "操作成功")
|
||||
@@ -250,6 +261,37 @@ func (Order) ManualNotify(ctx *gin.Context) {
|
||||
base.Ok(ctx, "订单回调成功!")
|
||||
}
|
||||
|
||||
func (Order) Cancel(ctx *gin.Context) {
|
||||
var req base.IDRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order model.Order
|
||||
model.Db.Where("id = ?", req.ID).Find(&order)
|
||||
if order.ID == 0 {
|
||||
base.BadRequest(ctx, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
base.BadRequest(ctx, "仅允许取消未支付订单")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := order.SetCanceled(); err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "订单取消成功")
|
||||
}
|
||||
|
||||
func (Order) Del(ctx *gin.Context) {
|
||||
var req base.IDListRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
|
||||
@@ -61,17 +61,12 @@ func (Wallet) Add(ctx *gin.Context) {
|
||||
OtherNotify: req.OtherNotify,
|
||||
}
|
||||
|
||||
if !wallet.IsValid() {
|
||||
base.BadRequest(ctx, "钱包地址格式不合法,请检查")
|
||||
if err := wallet.Validate(); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 非大小写敏感的地址,统一转为小写存储
|
||||
if !model.AddrCaseSens(model.TradeType(wallet.TradeType)) {
|
||||
wallet.MatchAddr = strings.ToLower(wallet.MatchAddr)
|
||||
}
|
||||
|
||||
if err := model.Db.Create(&wallet).Error; err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
@@ -158,17 +153,12 @@ func (Wallet) Mod(ctx *gin.Context) {
|
||||
w.OtherNotify = *req.OtherNotify
|
||||
}
|
||||
|
||||
if !w.IsValid() {
|
||||
base.BadRequest(ctx, "钱包地址格式不合法,请检查")
|
||||
if err := w.Validate(); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 非大小写敏感的地址,统一转为小写存储
|
||||
if !model.AddrCaseSens(model.TradeType(w.TradeType)) {
|
||||
w.MatchAddr = strings.ToLower(w.Address)
|
||||
}
|
||||
|
||||
if err := model.Db.Save(&w).Error; err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ func (Auth) Info(ctx *gin.Context) {
|
||||
"trade_type": model.GetAllAlias(),
|
||||
"trade_fiat": model.GetSupportFiat(),
|
||||
"trade_crypto": model.GetSupportCrypto(),
|
||||
"trade_network": model.GetAllNetwork(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -302,7 +303,7 @@ func (Auth) Menu(ctx *gin.Context) {
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "https://github.com/v03413/BEpusdt/blob/main/docs/api/api.md",
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
|
||||
+13
-12
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -69,6 +68,17 @@ func (e Epay) Submit(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(data.NotifyURL) {
|
||||
ctx.String(200, "notify_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(data.ReturnURL) {
|
||||
ctx.String(200, "return_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
money, err := decimal.NewFromString(data.Money)
|
||||
if err != nil {
|
||||
ctx.String(200, "参数 money 解析错误,"+err.Error())
|
||||
@@ -76,7 +86,7 @@ func (e Epay) Submit(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var order, err2 = model.BuildOrder(model.OrderParams{
|
||||
var order, err2 = model.StartBuildOrder(model.OrderParams{
|
||||
Money: money,
|
||||
ApiType: model.OrderApiTypeEpay,
|
||||
Address: data.Address,
|
||||
@@ -101,7 +111,7 @@ func (e Epay) Submit(ctx *gin.Context) {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
ctx.Redirect(http.StatusFound, model.CheckoutCounter(host, order.TradeId))
|
||||
ctx.Redirect(http.StatusFound, model.CheckoutUrl(host, order.TradeId))
|
||||
}
|
||||
|
||||
// verify 验证请求参数
|
||||
@@ -175,12 +185,3 @@ func (e Epay) sign(data map[string]string, token string) string {
|
||||
|
||||
return md5sum
|
||||
}
|
||||
|
||||
func BuildNotifyParams(order model.Order) string {
|
||||
var signStr = utils.Md5String(fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(order.Money), order.Name, order.OrderId, Pid, order.TradeId, order.TradeType) + model.AuthToken())
|
||||
var params = fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(order.Money), url.QueryEscape(order.Name), url.QueryEscape(order.OrderId), Pid, order.TradeId, order.TradeType)
|
||||
|
||||
return fmt.Sprintf("%s&sign=%s", params, signStr)
|
||||
}
|
||||
|
||||
+359
-441
@@ -5,14 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/handler/epay"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
@@ -21,11 +18,11 @@ import (
|
||||
type Epusdt struct{}
|
||||
|
||||
type createReq struct {
|
||||
Amount float64 `json:"amount" binding:"required"`
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
TradeType string `json:"trade_type"`
|
||||
@@ -35,11 +32,11 @@ type createReq struct {
|
||||
}
|
||||
|
||||
type createOrderReq struct {
|
||||
Amount float64 `json:"amount" binding:"required"`
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
Currencies string `json:"currencies"`
|
||||
@@ -57,21 +54,367 @@ type cancelReq struct {
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
}
|
||||
|
||||
type infoReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
}
|
||||
|
||||
type methodsReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
Currency string `json:"currency"`
|
||||
}
|
||||
|
||||
type methodItem struct {
|
||||
Amount string `json:"amount"`
|
||||
ActualAmount string `json:"actual_amount"`
|
||||
Fiat string `json:"fiat"`
|
||||
ExchangeRate string `json:"exchange_rate"`
|
||||
Currency string `json:"currency"`
|
||||
Network string `json:"network"`
|
||||
TokenNetName string `json:"token_net_name"`
|
||||
TokenCustomName string `json:"token_custom_name"`
|
||||
IsPopular bool `json:"is_popular"`
|
||||
func loadPayOrder(ctx *gin.Context, tradeID string) (model.Order, bool) {
|
||||
order, ok := model.GetTradeOrder(tradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("order not found"))
|
||||
return model.Order{}, false
|
||||
}
|
||||
|
||||
if order.FingerprintBound() && !order.MatchFingerprint(utils.ClientFingerprint(ctx)) {
|
||||
ctx.JSON(200, respFailJson("order not found"))
|
||||
return model.Order{}, false
|
||||
}
|
||||
|
||||
return order, true
|
||||
}
|
||||
|
||||
func (Epusdt) Notify(ctx *gin.Context) {
|
||||
rawData, err := ctx.GetRawData()
|
||||
if err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
sign, ok := m["signature"]
|
||||
if !ok {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
if utils.EpusdtSign(m, model.AuthToken()) != sign {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.String(200, "ok")
|
||||
}
|
||||
|
||||
func (Epusdt) CreateOrder(ctx *gin.Context) {
|
||||
var req createOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: request error: %s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
|
||||
// 创建待付款订单
|
||||
order, err := model.BuildPendingOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdtOrder,
|
||||
OrderId: req.OrderID,
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Fiat: req.Fiat,
|
||||
CurrencyLimit: req.Currencies,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: order create failed: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"name": order.Name,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(host, order.TradeId),
|
||||
"network": order.GetMethods(""),
|
||||
"reselect": order.CanReselectPayment(),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) UpdateOrder(ctx *gin.Context) {
|
||||
// 接收 trade_id, currency, network 三个参数
|
||||
var req updateOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 仅待付订单才可更新订单
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
|
||||
return
|
||||
}
|
||||
|
||||
if order.TradeType != "" && !order.CanReselectPayment() {
|
||||
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
|
||||
return
|
||||
}
|
||||
|
||||
fp := utils.ClientFingerprint(ctx)
|
||||
|
||||
// 拒绝过期订单
|
||||
remaining := time.Until(order.ExpiredAt)
|
||||
if remaining <= 0 {
|
||||
ctx.JSON(200, respFailJson("update order failed: order expired"))
|
||||
return
|
||||
}
|
||||
|
||||
// 根据 currency 和 network 解析出 TradeType
|
||||
tradeType, err := model.GetTradeTypeByCurrencyAndNetwork(req.Currency, req.Network)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: unsupported payment method: %s - %s", req.Currency, req.Network)))
|
||||
return
|
||||
}
|
||||
|
||||
// 重建订单(更新支付方式)
|
||||
// 注意:RebuildOrder 需要 OrderParams,我们需要从现有订单构造参数
|
||||
money, _ := decimal.NewFromString(order.Money)
|
||||
params := model.OrderParams{
|
||||
Money: money,
|
||||
OrderId: order.OrderId,
|
||||
TradeType: tradeType, // 新的交易类型
|
||||
RedirectUrl: order.ReturnUrl,
|
||||
NotifyUrl: order.NotifyUrl,
|
||||
Name: order.Name,
|
||||
Timeout: int64(math.Ceil(remaining.Seconds())),
|
||||
Fiat: order.Fiat,
|
||||
ClientFingerprint: fp,
|
||||
}
|
||||
|
||||
newOrder, err := model.RebuildOrder(order, params)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("update order failed: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": newOrder.Fiat,
|
||||
"trade_type": newOrder.TradeType,
|
||||
"trade_id": newOrder.TradeId,
|
||||
"order_id": newOrder.OrderId,
|
||||
"status": newOrder.Status,
|
||||
"amount": newOrder.Money,
|
||||
"actual_amount": newOrder.Amount,
|
||||
"token": newOrder.Address,
|
||||
"expiration_time": uint64(newOrder.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(host, newOrder.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) CreateTransaction(ctx *gin.Context) {
|
||||
var req createReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
if req.TradeType == "" {
|
||||
req.TradeType = string(model.UsdtTrc20)
|
||||
}
|
||||
|
||||
order, err := model.StartBuildOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
Address: req.Address,
|
||||
AddressLocked: req.Amount == 0,
|
||||
OrderId: req.OrderID,
|
||||
TradeType: model.TradeType(req.TradeType),
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Rate: req.Rate,
|
||||
Fiat: req.Fiat,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_type": order.TradeType,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"actual_amount": order.Amount,
|
||||
"token": order.Address,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(utils.GetRequestHost(ctx.Request), order.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) CancelTransaction(ctx *gin.Context) {
|
||||
var req cancelReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := model.GetTradeOrder(req.TradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("当前订单(%s)状态不允许取消", req.TradeID)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := order.SetCanceled(); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单取消失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{"trade_id": req.TradeID}))
|
||||
}
|
||||
|
||||
func (Epusdt) Checkout(ctx *gin.Context) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
if _, ok := model.GetTradeOrder(tradeId); !ok {
|
||||
ctx.String(200, "order not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 收银台模板
|
||||
tmpl := model.GetC(model.PaymentCheckout) + "/checkout.html"
|
||||
|
||||
ctx.HTML(200, tmpl, gin.H{"trade_id": tradeId})
|
||||
}
|
||||
|
||||
func (Epusdt) GetMethods(ctx *gin.Context) {
|
||||
var req methodsReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson("error: Invalid order status"))
|
||||
return
|
||||
}
|
||||
|
||||
if order.TradeType != "" && !order.CanReselectPayment() {
|
||||
ctx.JSON(200, respFailJson("error: The order status does not allow retrieving the payment method"))
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"methods": order.GetMethods(model.Crypto(req.Currency)),
|
||||
"network_sort": model.GetC(model.PaymentNetworkSort),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) Info(ctx *gin.Context) {
|
||||
var req infoReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("参数错误:%s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"network": order.Network(), // 网络信息
|
||||
"trade_id": order.TradeId, // 交易编号
|
||||
"order_id": order.OrderId, // 商户订单
|
||||
"trade_type": order.TradeType, // 交易类型
|
||||
"status": order.Status, // 订单状态
|
||||
"money": order.Money, // 订单金额
|
||||
"actual_amount": order.Amount, // 实付数额
|
||||
"token": order.Address, // 收款地址
|
||||
"fiat": order.Fiat, // 法币类型
|
||||
"name": order.Name, // 商品名称
|
||||
"expired_at": order.ExpiredAt.Unix(), // 截止时间
|
||||
"created_at": order.CreatedAt.Time().Unix(), // 创建时间
|
||||
"trade_url": order.GetTxUrl(), // 链上详情
|
||||
"support_url": model.GetC(model.PaymentSupportUrl), // 客服链接
|
||||
"redirect_url": order.RedirectUrl(), // 跳转地址
|
||||
"reselect": order.CanReselectPayment(), // 是否允许确认交易类型后重选
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) SignVerify(ctx *gin.Context) {
|
||||
@@ -110,436 +453,11 @@ func (Epusdt) SignVerify(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func (Epusdt) Notify(ctx *gin.Context) {
|
||||
rawData, err := ctx.GetRawData()
|
||||
if err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
sign, ok := m["signature"]
|
||||
if !ok {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
if utils.EpusdtSign(m, model.AuthToken()) != sign {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.String(200, "ok")
|
||||
}
|
||||
|
||||
// CreateOrder Order creation API
|
||||
func (Epusdt) CreateOrder(ctx *gin.Context) {
|
||||
var req createOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: request error: %s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
|
||||
// 创建待付款订单
|
||||
order, err := model.BuildPendingOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
OrderId: req.OrderID,
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Fiat: req.Fiat,
|
||||
CurrencyLimit: req.Currencies,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: order create failed: %s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"name": order.Name,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutCashier(host, order.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
// UpdateOrder 更新订单,返回付款链接。更新订单不需要签名,因为创建订单时已经验证,只需要提交参数更新订单即可。
|
||||
func (Epusdt) UpdateOrder(ctx *gin.Context) {
|
||||
// 接收 trade_id, currency, network 三个参数
|
||||
var req updateOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
// 获取订单
|
||||
order, ok := model.GetTradeOrder(req.TradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("order not found"))
|
||||
return
|
||||
}
|
||||
|
||||
// 根据 currency 和 network 解析出 TradeType
|
||||
tradeType, err := model.GetTradeTypeByCurrencyAndNetwork(req.Currency, req.Network)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: unsupported payment method: %s - %s", req.Currency, req.Network)))
|
||||
return
|
||||
}
|
||||
|
||||
// 重建订单(更新支付方式)
|
||||
// 注意:RebuildOrder 需要 OrderParams,我们需要从现有订单构造参数
|
||||
money, _ := decimal.NewFromString(order.Money)
|
||||
params := model.OrderParams{
|
||||
Money: money,
|
||||
OrderId: order.OrderId,
|
||||
TradeType: tradeType, // 新的交易类型
|
||||
RedirectUrl: order.ReturnUrl,
|
||||
NotifyUrl: order.NotifyUrl,
|
||||
Name: order.Name,
|
||||
Timeout: int64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
Fiat: order.Fiat,
|
||||
}
|
||||
|
||||
newOrder, err := model.RebuildOrder(order, params)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("update order failed: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": newOrder.Fiat,
|
||||
"trade_type": newOrder.TradeType,
|
||||
"trade_id": newOrder.TradeId,
|
||||
"order_id": newOrder.OrderId,
|
||||
"status": newOrder.Status,
|
||||
"amount": newOrder.Money,
|
||||
"actual_amount": newOrder.Amount,
|
||||
"token": newOrder.Address,
|
||||
"expiration_time": uint64(newOrder.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutCounter(host, newOrder.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) CreateTransaction(ctx *gin.Context) {
|
||||
var req createReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
if req.TradeType == "" {
|
||||
req.TradeType = string(model.UsdtTrc20)
|
||||
}
|
||||
|
||||
order, err := model.BuildOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
Address: req.Address,
|
||||
OrderId: req.OrderID,
|
||||
TradeType: model.TradeType(req.TradeType),
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Rate: req.Rate,
|
||||
Fiat: req.Fiat,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_type": order.TradeType,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"actual_amount": order.Amount,
|
||||
"token": order.Address,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutCounter(utils.GetRequestHost(ctx.Request), order.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Epusdt) CancelTransaction(ctx *gin.Context) {
|
||||
var req cancelReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := model.GetTradeOrder(req.TradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("当前订单(%s)状态不允许取消", req.TradeID)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := order.SetCanceled(); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单取消失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{"trade_id": req.TradeID}))
|
||||
}
|
||||
|
||||
func (Epusdt) CheckoutCounter(ctx *gin.Context) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.String(200, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
uri, err := url.ParseRequestURI(order.ReturnUrl)
|
||||
if err != nil {
|
||||
ctx.String(200, "同步地址错误")
|
||||
log.Error("同步地址解析错误", err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(200, string(order.TradeType+".html"), gin.H{
|
||||
"http_host": uri.Host,
|
||||
"amount": order.Amount,
|
||||
"address": order.Address,
|
||||
"expire": int64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"return_url": order.ReturnUrl,
|
||||
"usdt_rate": order.Rate,
|
||||
"trade_id": tradeId,
|
||||
"order_id": order.OrderId,
|
||||
"trade_type": order.TradeType,
|
||||
"money": order.Money,
|
||||
"fiat": order.Fiat,
|
||||
})
|
||||
}
|
||||
|
||||
func (Epusdt) CheckoutCashier(ctx *gin.Context) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.String(200, "order not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
uri, err := url.ParseRequestURI(order.ReturnUrl)
|
||||
if err != nil {
|
||||
ctx.String(200, "sync address error")
|
||||
log.Error("CheckoutCashier: sync address error: ", err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(200, "cashier.html", gin.H{
|
||||
"http_host": uri.Host,
|
||||
"amount": order.Amount,
|
||||
"expire": int64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"return_url": order.ReturnUrl,
|
||||
"trade_id": tradeId,
|
||||
"order_id": order.OrderId,
|
||||
"name": order.Name,
|
||||
"money": order.Money,
|
||||
"fiat": order.Fiat,
|
||||
})
|
||||
}
|
||||
|
||||
func (Epusdt) CheckStatus(ctx *gin.Context) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var returnUrl string
|
||||
if order.Status == model.OrderStatusSuccess {
|
||||
returnUrl = order.ReturnUrl
|
||||
if order.ApiType == model.OrderApiTypeEpay {
|
||||
// 易支付兼容
|
||||
returnUrl = fmt.Sprintf("%s?%s", returnUrl, epay.BuildNotifyParams(order))
|
||||
}
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, gin.H{
|
||||
"trade_id": tradeId,
|
||||
"trade_hash": order.RefHash,
|
||||
"status": order.Status,
|
||||
"return_url": returnUrl,
|
||||
})
|
||||
}
|
||||
|
||||
func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
var req methodsReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(500, respFailJson(fmt.Sprintf("request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := model.GetTradeOrder(req.TradeID)
|
||||
if !ok {
|
||||
ctx.JSON(400, respFailJson("order not found"))
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status == model.OrderStatusExpired {
|
||||
ctx.JSON(400, respFailJson("order expired"))
|
||||
return
|
||||
}
|
||||
|
||||
// 强制使用订单的法币类型
|
||||
fiat := order.Fiat
|
||||
|
||||
var methods []methodItem
|
||||
allTrades := model.GetAllTradeConfig()
|
||||
|
||||
// 解析限定币种
|
||||
var whitelist = make(map[string]bool)
|
||||
var blacklist = make(map[string]bool)
|
||||
if order.CurrencyLimit != "" {
|
||||
for _, c := range strings.Split(order.CurrencyLimit, ",") {
|
||||
c = strings.TrimSpace(c)
|
||||
if strings.HasPrefix(c, "-") {
|
||||
blacklist[strings.ToUpper(strings.TrimPrefix(c, "-"))] = true
|
||||
} else {
|
||||
whitelist[strings.ToUpper(c)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for tradeTypeStr, conf := range allTrades {
|
||||
// 如果指定了货币,则进行过滤
|
||||
if req.Currency != "" && string(conf.Crypto) != req.Currency {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check blacklist
|
||||
if len(blacklist) > 0 && blacklist[string(conf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check whitelist
|
||||
if len(whitelist) > 0 && !whitelist[string(conf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查是否有可用钱包
|
||||
var count int
|
||||
tradeType := model.TradeType(tradeTypeStr)
|
||||
count = len(model.GetAvailableAddress(tradeType))
|
||||
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取汇率配置的浮动语法
|
||||
syntax := model.GetK(model.ConfKey(fmt.Sprintf("rate_float_%s_%s", conf.Crypto, fiat)))
|
||||
|
||||
// 获取汇率
|
||||
rate, err := model.GetOrderRate(conf.Crypto, fiat, syntax)
|
||||
if err != nil {
|
||||
log.Error(fmt.Sprintf("GetPaymentMethods: get order rate error: %s", err.Error()))
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算实际支付金额 (加密货币)
|
||||
// Money 是法币金额
|
||||
moneyDecimal, _ := decimal.NewFromString(order.Money)
|
||||
|
||||
// 计算精度
|
||||
atom, precision := model.GetAtomicity(model.TradeType(tradeTypeStr))
|
||||
actualAmount := moneyDecimal.DivRound(rate, precision)
|
||||
if actualAmount.LessThan(atom) {
|
||||
actualAmount = atom
|
||||
}
|
||||
actualAmountStr := actualAmount.String()
|
||||
|
||||
methods = append(methods, methodItem{
|
||||
Amount: order.Money,
|
||||
ActualAmount: actualAmountStr,
|
||||
Fiat: string(fiat),
|
||||
ExchangeRate: rate.String(),
|
||||
Currency: string(conf.Crypto),
|
||||
Network: string(conf.Network),
|
||||
TokenNetName: string(conf.NetworkName),
|
||||
TokenCustomName: "", // 暂为空
|
||||
IsPopular: false, // 暂为 false
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by Currency A-Z
|
||||
sort.Slice(methods, func(i, j int) bool {
|
||||
if methods[i].Currency != methods[j].Currency {
|
||||
return methods[i].Currency < methods[j].Currency
|
||||
}
|
||||
return methods[i].Network < methods[j].Network
|
||||
})
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"methods": methods,
|
||||
}))
|
||||
}
|
||||
|
||||
func respFailJson(message string) gin.H {
|
||||
|
||||
return gin.H{"status_code": 400, "message": message}
|
||||
}
|
||||
|
||||
func respSuccJson(data interface{}) gin.H {
|
||||
|
||||
return gin.H{"status_code": 200, "message": "success", "data": data, "request_id": ""}
|
||||
}
|
||||
|
||||
+7
-1
@@ -14,6 +14,7 @@ var (
|
||||
Task *logrus.Logger
|
||||
be *logrus.Logger
|
||||
loggers []*lumberjack.Logger
|
||||
logPath string
|
||||
)
|
||||
|
||||
func newLogger(file string) (*logrus.Logger, error) {
|
||||
@@ -42,7 +43,6 @@ func newLogger(file string) (*logrus.Logger, error) {
|
||||
|
||||
func Init(dir string) error {
|
||||
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
||||
|
||||
return fmt.Errorf("创建日志目录失败:%w", err)
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ func Init(dir string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logPath = dir
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -82,6 +84,10 @@ func GetWriter() *io.PipeWriter {
|
||||
return be.Writer()
|
||||
}
|
||||
|
||||
func GetPath() string {
|
||||
return logPath
|
||||
}
|
||||
|
||||
func Close() {
|
||||
for _, f := range loggers {
|
||||
if f != nil {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
type Checkout struct {
|
||||
Name string `json:"name"`
|
||||
Author string `json:"author"`
|
||||
Desc string `json:"desc"`
|
||||
Link string `json:"link"`
|
||||
}
|
||||
|
||||
var checkoutMap = make(map[string]Checkout)
|
||||
|
||||
// RegisterCheckout 注册收银台模板
|
||||
func RegisterCheckout(name string, checkout Checkout) {
|
||||
checkoutMap[name] = checkout
|
||||
}
|
||||
|
||||
func CheckoutList() map[string]Checkout {
|
||||
return checkoutMap
|
||||
}
|
||||
+90
-47
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
"github.com/v03413/go-cache"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -15,10 +16,48 @@ import (
|
||||
)
|
||||
|
||||
var confCache sync.Map
|
||||
var defaultConf = map[ConfKey]string{
|
||||
ApiAppUri: "",
|
||||
RateSyncInterval: "3600",
|
||||
AtomUSDT: "0.01",
|
||||
AtomUSDC: "0.01",
|
||||
AtomTRX: "0.01",
|
||||
AtomBNB: "0.00001",
|
||||
AtomETH: "0.000001",
|
||||
AtomGRAM: "0.01",
|
||||
MonitorMinAmount: "0.01",
|
||||
PaymentMinAmount: "0.01",
|
||||
PaymentMaxAmount: "99999",
|
||||
RpcEndpointTron: "grpc.trongrid.io:50051",
|
||||
RpcEndpointBsc: "https://binance-smart-chain-public.nodies.app/",
|
||||
RpcEndpointSolana: "https://solana-rpc.publicnode.com/",
|
||||
RpcEndpointXlayer: "https://xlayerrpc.okx.com/",
|
||||
RpcEndpointPolygon: "https://polygon-public.nodies.app/",
|
||||
RpcEndpointArbitrum: "https://arb1.arbitrum.io/rpc",
|
||||
RpcEndpointEthereum: "https://ethereum-public.nodies.app/",
|
||||
RpcEndpointBase: "https://base-public.nodies.app/",
|
||||
RpcEndpointAptos: "https://aptos-rest.publicnode.com/",
|
||||
RpcEndpointPlasma: "https://rpc.plasma.to/",
|
||||
RpcGlobalConfigUrlTon: "https://ton.org/global-config.json",
|
||||
NotifyMaxRetry: "10",
|
||||
BlockHeightMaxDiff: "1000",
|
||||
BlockOffsetConfirm: "0",
|
||||
PaymentTimeout: "1200", // 20分钟
|
||||
PaymentCheckout: "official", // 官方模板
|
||||
PaymentMatchMode: string(Classic),
|
||||
PaymentSupportUrl: "",
|
||||
PaymentLookbackHour: "3",
|
||||
PaymentNetworkSort: "",
|
||||
SystemInstallLock: "0",
|
||||
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
|
||||
RateSyncHistoryDays: "30",
|
||||
MqttTopicPrefix: "bepusdt",
|
||||
HomeRedirectUrl: "",
|
||||
}
|
||||
|
||||
type Conf struct {
|
||||
K ConfKey `gorm:"column:k;type:varchar(32);not null;primaryKey" json:"key"`
|
||||
V string `gorm:"column:v;type:varchar(255);not null" json:"val"`
|
||||
V string `gorm:"column:v;type:varchar(512);not null" json:"val"`
|
||||
}
|
||||
|
||||
func (c Conf) TableName() string {
|
||||
@@ -28,7 +67,7 @@ func (c Conf) TableName() string {
|
||||
|
||||
func SetK(k ConfKey, v string) {
|
||||
if err = Db.Transaction(func(db *gorm.DB) error {
|
||||
if err2 := db.Where("`k` = ?", k).Delete(&Conf{}).Error; err2 != nil {
|
||||
if err2 := db.Where("k = ?", k).Delete(&Conf{}).Error; err2 != nil {
|
||||
|
||||
return err2
|
||||
}
|
||||
@@ -96,22 +135,13 @@ func RefreshC() {
|
||||
}
|
||||
}
|
||||
|
||||
func CheckoutCounter(host, id string) string {
|
||||
func CheckoutUrl(host, id string) string {
|
||||
uri := GetK(ApiAppUri)
|
||||
if uri == "" {
|
||||
uri = host
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/pay/checkout-counter/%s", uri, id)
|
||||
}
|
||||
|
||||
func CheckoutCashier(host, id string) string {
|
||||
uri := GetK(ApiAppUri)
|
||||
if uri == "" {
|
||||
uri = host
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/pay/cashier/%s", uri, id)
|
||||
return fmt.Sprintf("%s/pay/checkout/%s", uri, id)
|
||||
}
|
||||
|
||||
func ConfInit() {
|
||||
@@ -122,45 +152,19 @@ func ConfInit() {
|
||||
var password = hash[20:30]
|
||||
var encrypt, _ = bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
var data = map[ConfKey]string{
|
||||
ApiAppUri: "",
|
||||
ApiAuthToken: token,
|
||||
AdminSecure: secure,
|
||||
AdminUsername: username,
|
||||
AdminPassword: string(encrypt),
|
||||
RateSyncInterval: "3600",
|
||||
AtomUSDT: "0.01",
|
||||
AtomUSDC: "0.01",
|
||||
AtomTRX: "0.01",
|
||||
AtomBNB: "0.00001",
|
||||
AtomETH: "0.000001",
|
||||
MonitorMinAmount: "0.01",
|
||||
PaymentMinAmount: "0.01",
|
||||
PaymentMaxAmount: "99999",
|
||||
RpcEndpointTron: "grpc.trongrid.io:50051",
|
||||
RpcEndpointBsc: "https://binance-smart-chain-public.nodies.app/",
|
||||
RpcEndpointSolana: "https://solana-rpc.publicnode.com/",
|
||||
RpcEndpointXlayer: "https://xlayerrpc.okx.com/",
|
||||
RpcEndpointPolygon: "https://polygon-public.nodies.app/",
|
||||
RpcEndpointArbitrum: "https://arb1.arbitrum.io/rpc",
|
||||
RpcEndpointEthereum: "https://ethereum-public.nodies.app/",
|
||||
RpcEndpointBase: "https://base-public.nodies.app/",
|
||||
RpcEndpointAptos: "https://aptos-rest.publicnode.com/",
|
||||
RpcEndpointPlasma: "https://rpc.plasma.to/",
|
||||
NotifyMaxRetry: "10",
|
||||
BlockHeightMaxDiff: "1000",
|
||||
BlockOffsetConfirm: "0",
|
||||
PaymentTimeout: "1200", // 20分钟
|
||||
PaymentStaticPath: "",
|
||||
PaymentMatchMode: string(Classic),
|
||||
SystemInstallLock: "0",
|
||||
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
|
||||
RateSyncCoingeckoApiKey: "",
|
||||
ApiAuthToken: token,
|
||||
AdminSecret: utils.StrSha256(hash),
|
||||
AdminSecure: secure,
|
||||
AdminUsername: username,
|
||||
AdminPassword: string(encrypt),
|
||||
}
|
||||
|
||||
var rows = make([]Conf, 0)
|
||||
for k, v := range data {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
for k, v := range defaultConf {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("╔═══════════════════════════════════════════════════════════════════════")
|
||||
@@ -220,3 +224,42 @@ func GetInstallInfo() gin.H {
|
||||
|
||||
return gin.H{}
|
||||
}
|
||||
|
||||
func GetTronGridApiKeys() []string {
|
||||
arr := strings.Split(GetC(RpcEndpointTronGridApiKey), ",")
|
||||
keys := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
if v != "" {
|
||||
keys = append(keys, v)
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func FillDefaultConf() {
|
||||
var existKeys []string
|
||||
Db.Model(&Conf{}).Pluck("k", &existKeys)
|
||||
|
||||
existSet := make(map[ConfKey]struct{}, len(existKeys))
|
||||
for _, k := range existKeys {
|
||||
existSet[ConfKey(k)] = struct{}{}
|
||||
}
|
||||
|
||||
var rows []Conf
|
||||
for k, v := range defaultConf {
|
||||
if _, ok := existSet[k]; !ok {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
Db.Create(&rows)
|
||||
}
|
||||
}
|
||||
|
||||
func GetLookbackHour() time.Duration {
|
||||
var hour = time.Hour * -1
|
||||
var num = cast.ToInt(GetC(PaymentLookbackHour))
|
||||
|
||||
return time.Duration(num) * hour
|
||||
}
|
||||
|
||||
+27
-9
@@ -31,6 +31,7 @@ const (
|
||||
AdminUsername ConfKey = "admin_username"
|
||||
AdminPassword ConfKey = "admin_password"
|
||||
AdminSecure ConfKey = "admin_secure"
|
||||
AdminSecret ConfKey = "admin_secret"
|
||||
AdminLoginIP ConfKey = "admin_login_ip"
|
||||
AdminLoginAt ConfKey = "admin_login_at"
|
||||
|
||||
@@ -42,13 +43,17 @@ const (
|
||||
AtomTRX ConfKey = "atom_trx"
|
||||
AtomBNB ConfKey = "atom_bnb"
|
||||
AtomETH ConfKey = "atom_eth"
|
||||
AtomGRAM ConfKey = "atom_gram"
|
||||
|
||||
MonitorMinAmount ConfKey = "monitor_min_amount" // 监控最小金额,低于此金额的入账不进行通知
|
||||
PaymentMinAmount ConfKey = "payment_min_amount"
|
||||
PaymentMaxAmount ConfKey = "payment_max_amount"
|
||||
PaymentTimeout ConfKey = "payment_timeout" // 订单支付超时时间,单位秒
|
||||
PaymentStaticPath ConfKey = "payment_static_path" // 收银台静态资源路径
|
||||
PaymentMatchMode ConfKey = "payment_match_mode" // 订单金额匹配模式
|
||||
MonitorMinAmount ConfKey = "monitor_min_amount" // 监控最小金额,低于此金额的入账不进行通知
|
||||
PaymentMinAmount ConfKey = "payment_min_amount"
|
||||
PaymentMaxAmount ConfKey = "payment_max_amount"
|
||||
PaymentTimeout ConfKey = "payment_timeout" // 订单支付超时时间,单位秒
|
||||
PaymentCheckout ConfKey = "payment_checkout" // 收银台模板
|
||||
PaymentMatchMode ConfKey = "payment_match_mode" // 订单金额匹配模式
|
||||
PaymentSupportUrl ConfKey = "payment_support_url" // 订单支付客服链接
|
||||
PaymentLookbackHour ConfKey = "payment_lookback_hour" // 订单回溯时间
|
||||
PaymentNetworkSort ConfKey = "payment_network_sort" // 收银台网络顺序,逗号分隔
|
||||
|
||||
RpcEndpointPlasma ConfKey = "rpc_endpoint_plasma" // Plasma RPC节点
|
||||
RpcEndpointBsc ConfKey = "rpc_endpoint_bsc" // BSC RPC节点
|
||||
@@ -61,18 +66,30 @@ const (
|
||||
RpcEndpointAptos ConfKey = "rpc_endpoint_aptos" // APTOS RPC节点
|
||||
RpcEndpointTron ConfKey = "rpc_endpoint_tron" // TRON RPC节点
|
||||
RpcEndpointTronGridApiKey ConfKey = "rpc_endpoint_tron_grid_api_key" // TRON RPC节点 TronGrid Api Key
|
||||
RpcGlobalConfigUrlTon ConfKey = "rpc_global_config_url_ton" // Ton Global Config Url
|
||||
|
||||
RateSyncCoingeckoApiUrl ConfKey = "rate_sync_coingecko_api_url" // 汇率同步 Coingecko Api URL
|
||||
RateSyncCoingeckoApiKey ConfKey = "rate_sync_coingecko_api_key" // 汇率同步 Coingecko Api Key
|
||||
RateSyncInterval ConfKey = "rate_sync_interval" // 汇率同步间隔,单位秒
|
||||
NotifyMaxRetry ConfKey = "notify_max_retry" // 最大重试次数,订单回调失败
|
||||
BlockHeightMaxDiff ConfKey = "block_height_max_diff" // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
BlockOffsetConfirm ConfKey = "block_offset_confirm" // 区块偏移确认数,扫描时以当前区块高度减去此偏移量为准,避免重链导致的订单回调失败
|
||||
RateSyncHistoryDays ConfKey = "rate_sync_history_days" // 历史汇率保存天数
|
||||
|
||||
NotifyMaxRetry ConfKey = "notify_max_retry" // 最大重试次数,订单回调失败
|
||||
BlockHeightMaxDiff ConfKey = "block_height_max_diff" // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
BlockOffsetConfirm ConfKey = "block_offset_confirm" // 区块偏移确认数,扫描时以当前区块高度减去此偏移量为准,避免重链导致的订单回调失败
|
||||
|
||||
MqttHost ConfKey = "mqtt_host"
|
||||
MqttPort ConfKey = "mqtt_port"
|
||||
MqttUser ConfKey = "mqtt_user"
|
||||
MqttPass ConfKey = "mqtt_pass"
|
||||
MqttPublishQos ConfKey = "mqtt_publish_qos"
|
||||
MqttTopicPrefix ConfKey = "mqtt_topic_prefix" // 消息发布 Topic 路径前缀
|
||||
MqttNetworks ConfKey = "mqtt_networks" // 需要持续监控的区块网络
|
||||
|
||||
NotifierParams ConfKey = "notifier_params" // 通知参数 (token, chat_id, email
|
||||
NotifierChannel ConfKey = "notifier_channel" // 通知渠道 (telegram, wechat, email
|
||||
|
||||
SystemInstallLock ConfKey = "system_install_lock" // 系统安装锁
|
||||
HomeRedirectUrl ConfKey = "home_redirect_url"
|
||||
)
|
||||
const (
|
||||
CNY Fiat = "CNY"
|
||||
@@ -87,6 +104,7 @@ const (
|
||||
TRX Crypto = "TRX"
|
||||
BNB Crypto = "BNB"
|
||||
ETH Crypto = "ETH"
|
||||
GRAM Crypto = "GRAM" // 其实就是 Ton
|
||||
)
|
||||
const (
|
||||
Classic MatchMode = "classic" // 经典模式,精确匹配
|
||||
|
||||
+7
-13
@@ -6,17 +6,18 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var localLocation = time.Local
|
||||
|
||||
type Datetime time.Time
|
||||
|
||||
func (d *Datetime) MarshalJSON() ([]byte, error) {
|
||||
tTime := time.Time(*d)
|
||||
tTime := time.Time(*d).In(localLocation)
|
||||
return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
|
||||
}
|
||||
|
||||
func (d Datetime) Value() (driver.Value, error) {
|
||||
var zeroTime time.Time
|
||||
tlt := time.Time(d)
|
||||
// 判断给定时间是否和默认零时间的时间戳相同
|
||||
if tlt.UnixNano() == zeroTime.UnixNano() {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -26,34 +27,27 @@ func (d Datetime) Value() (driver.Value, error) {
|
||||
func (d *Datetime) Scan(v interface{}) error {
|
||||
if value, ok := v.(time.Time); ok {
|
||||
*d = Datetime(value)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("can not convert %v to timestamp", v)
|
||||
}
|
||||
|
||||
func (d *Datetime) String() string {
|
||||
|
||||
return time.Time(*d).Format(time.DateTime)
|
||||
return time.Time(*d).In(localLocation).Format(time.DateTime)
|
||||
}
|
||||
|
||||
func (d *Datetime) Year() string {
|
||||
|
||||
return time.Time(*d).Format("2006")
|
||||
return time.Time(*d).In(localLocation).Format("2006")
|
||||
}
|
||||
|
||||
func (d *Datetime) Before(u time.Time) bool {
|
||||
|
||||
return time.Time(*d).Before(u)
|
||||
}
|
||||
|
||||
func (d *Datetime) Time() time.Time {
|
||||
|
||||
return time.Time(*d)
|
||||
return time.Time(*d).In(localLocation)
|
||||
}
|
||||
|
||||
func (d *Datetime) Format(layout string) string {
|
||||
|
||||
return time.Time(*d).Format(layout)
|
||||
return time.Time(*d).In(localLocation).Format(layout)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 202607081430 - 删除 bep_order.trade_type_reselect 列
|
||||
func m202607081430DropOrderTradeTypeReselect() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202607081430_drop_order_trade_type_reselect",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasTable("bep_order") {
|
||||
return nil
|
||||
}
|
||||
if tx.Migrator().HasColumn("bep_order", "trade_type_reselect") {
|
||||
return tx.Exec("ALTER TABLE bep_order DROP COLUMN trade_type_reselect").Error
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasTable("bep_order") {
|
||||
return nil
|
||||
}
|
||||
if !tx.Migrator().HasColumn("bep_order", "trade_type_reselect") {
|
||||
return tx.Exec("ALTER TABLE bep_order ADD COLUMN trade_type_reselect INTEGER NOT NULL DEFAULT 0").Error
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const TableName = "bep_migration"
|
||||
|
||||
var migrations = []*gormigrate.Migration{
|
||||
m202607081430DropOrderTradeTypeReselect(),
|
||||
}
|
||||
|
||||
func Run(db *gorm.DB, initModels []any) error {
|
||||
if err := db.AutoMigrate(initModels...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := &gormigrate.Options{TableName: TableName}
|
||||
|
||||
// 旧版升级/全新安装,构建迁移表
|
||||
if !db.Migrator().HasTable(TableName) {
|
||||
if err := db.Exec("CREATE TABLE " + TableName + " (id VARCHAR(255) PRIMARY KEY)").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
m := gormigrate.New(db, options, migrations)
|
||||
|
||||
return m.Migrate()
|
||||
}
|
||||
+30
-25
@@ -7,7 +7,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/driver/mysql"
|
||||
"github.com/v03413/bepusdt/app/model/migration"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -19,21 +20,20 @@ type Id struct {
|
||||
}
|
||||
|
||||
type AutoTimeAt struct {
|
||||
CreatedAt *Datetime `gorm:"column:created_at;type:Datetime;not null;comment:记录创建时间;index" json:"created_at"`
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;type:Datetime;not null;comment:最后更新时间" json:"updated_at"`
|
||||
CreatedAt *Datetime `gorm:"column:created_at;not null;comment:记录创建时间;index" json:"created_at"`
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;not null;comment:最后更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
func Init(path, dsn string) error {
|
||||
func Init(db, dsn string) error {
|
||||
if dsn != "" {
|
||||
|
||||
return initMySQL(dsn)
|
||||
return initPostgres(dsn)
|
||||
}
|
||||
|
||||
return initSqlite(path)
|
||||
return initSqlite(db)
|
||||
}
|
||||
|
||||
func initSqlite(path string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||
func initSqlite(db string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(db), os.ModePerm); err != nil {
|
||||
|
||||
return fmt.Errorf("创建数据库目录失败:%w", err)
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func initSqlite(path string) error {
|
||||
"&_pragma=busy_timeout(8000)"+ // 8 秒超时,兼顾慢速磁盘
|
||||
"&_pragma=synchronous(NORMAL)"+ // NORMAL 模式,性能与安全平衡
|
||||
"&_pragma=wal_autocheckpoint(1500)", // 适中的 checkpoint 频率
|
||||
path)
|
||||
db)
|
||||
Db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
@@ -73,40 +73,38 @@ func initSqlite(path string) error {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func initMySQL(dsn string) error {
|
||||
func initPostgres(dsn string) error {
|
||||
// 首次启动可能出现 SLOW SQL 告警,这是由于连接池首次连接预热引起的,后续连接将正常
|
||||
|
||||
var err error
|
||||
Db, err = gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: dsn,
|
||||
DefaultStringSize: 256, // string 类型字段的默认长度
|
||||
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
|
||||
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
|
||||
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
|
||||
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
|
||||
}), &gorm.Config{})
|
||||
Db, err = gorm.Open(postgres.New(postgres.Config{DSN: dsn, PreferSimpleProtocol: true}), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("数据库初始化失败:%w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("获取数据库连接失败:%w", err)
|
||||
return err
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(30 * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
|
||||
return fmt.Errorf("数据库结构迁移失败:%w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
var count int64
|
||||
@@ -115,13 +113,20 @@ func initMySQL(dsn string) error {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func AutoMigrate() error {
|
||||
return Db.AutoMigrate(&Wallet{}, &Order{}, &NotifyRecord{}, &Conf{}, &Rate{})
|
||||
return migration.Run(Db, []any{
|
||||
&Wallet{},
|
||||
&Order{},
|
||||
&NotifyRecord{},
|
||||
&Conf{},
|
||||
&Rate{},
|
||||
})
|
||||
}
|
||||
|
||||
func Close() {
|
||||
|
||||
+249
-42
@@ -4,11 +4,17 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -25,6 +31,7 @@ const (
|
||||
BscBnb TradeType = "bsc.bnb"
|
||||
EthereumEth TradeType = "ethereum.eth"
|
||||
TronTrx TradeType = "tron.trx"
|
||||
TonGram TradeType = "ton.gram"
|
||||
|
||||
UsdtTrc20 TradeType = "usdt.trc20"
|
||||
UsdcTrc20 TradeType = "usdc.trc20"
|
||||
@@ -44,49 +51,86 @@ const (
|
||||
UsdtAptos TradeType = "usdt.aptos"
|
||||
UsdcAptos TradeType = "usdc.aptos"
|
||||
UsdtPlasma TradeType = "usdt.plasma"
|
||||
UsdtTon TradeType = "usdt.ton"
|
||||
)
|
||||
|
||||
const (
|
||||
OrderApiTypeEpusdt = "epusdt" // epusdt
|
||||
OrderApiTypeEpay = "epay" // 彩虹易支付
|
||||
OrderApiTypeAdmin = "admin" // 管理后台
|
||||
OrderApiTypeEpusdt = "epusdt" // epusdt
|
||||
OrderApiTypeEpusdtOrder = "epusdt_order" // epusdt create-order
|
||||
OrderApiTypeEpay = "epay" // 彩虹易支付
|
||||
OrderApiTypeAdmin = "admin" // 管理后台
|
||||
)
|
||||
|
||||
var calcMutex sync.Mutex
|
||||
|
||||
type Order struct {
|
||||
Id
|
||||
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
|
||||
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"`
|
||||
TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;comment:交易类型" json:"trade_type"`
|
||||
Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"`
|
||||
Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"`
|
||||
CurrencyLimit string `gorm:"column:currency_limit;type:varchar(255);not null;default:'';comment:限定币种" json:"currency_limit"`
|
||||
Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"`
|
||||
Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"`
|
||||
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
|
||||
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
|
||||
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
|
||||
Status int `gorm:"column:status;type:tinyint(1);not null;default:1;index;comment:交易状态" json:"status"`
|
||||
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
|
||||
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"`
|
||||
ReturnUrl string `gorm:"column:return_url;type:varchar(255);not null;default:'';comment:同步地址" json:"return_url"`
|
||||
NotifyUrl string `gorm:"column:notify_url;type:varchar(255);not null;default:'';comment:异步地址" json:"notify_url"`
|
||||
NotifyNum int `gorm:"column:notify_num;type:int(11);not null;default:0;comment:回调次数" json:"notify_num"`
|
||||
NotifyState int `gorm:"column:notify_state;type:tinyint(1);not null;default:0;comment:回调状态 1:成功 0:失败" json:"notify_state"`
|
||||
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
|
||||
RefBlockNum int64 `gorm:"column:ref_block_num;type:varchar(64);not null;default:0;comment:区块索引" json:"ref_block_num"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;type:datetime;not null;comment:失效时间" json:"expired_at"`
|
||||
ConfirmedAt *time.Time `gorm:"column:confirmed_at;type:datetime;not null;comment:交易确认时间" json:"confirmed_at"`
|
||||
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
|
||||
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"`
|
||||
TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;comment:交易类型" json:"trade_type"`
|
||||
Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"`
|
||||
Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"`
|
||||
CurrencyLimit string `gorm:"column:currency_limit;type:varchar(255);not null;default:'';comment:限定币种" json:"currency_limit"`
|
||||
Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"`
|
||||
Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"`
|
||||
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
|
||||
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
|
||||
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
|
||||
MatchAddress string `gorm:"column:match_address;type:varchar(128);not null;default:'';comment:校验地址" json:"match_address"`
|
||||
AddressLocked bool `gorm:"column:address_locked;not null;default:false;comment:地址锁定 1:独占 0:共享" json:"address_locked"`
|
||||
Status int `gorm:"column:status;not null;default:1;index;index:idx_order_notify_retry,priority:1;comment:交易状态" json:"status"`
|
||||
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
|
||||
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"`
|
||||
ReturnUrl string `gorm:"column:return_url;type:text;not null;default:'';comment:同步地址" json:"return_url"`
|
||||
NotifyUrl string `gorm:"column:notify_url;type:text;not null;default:'';comment:异步地址" json:"notify_url"`
|
||||
NotifyNum int `gorm:"column:notify_num;not null;default:0;index:idx_order_notify_retry,priority:3;comment:回调次数" json:"notify_num"`
|
||||
NotifyState int `gorm:"column:notify_state;not null;default:0;index:idx_order_notify_retry,priority:2;comment:回调状态 1:成功 0:失败" json:"notify_state"`
|
||||
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
|
||||
RefBlockNum int `gorm:"column:ref_block_num;not null;default:0;comment:区块索引" json:"ref_block_num"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;not null;comment:失效时间" json:"expired_at"`
|
||||
ConfirmedAt *time.Time `gorm:"column:confirmed_at;not null;comment:交易确认时间" json:"confirmed_at"`
|
||||
ClientFingerprint string `gorm:"column:client_fingerprint;type:varchar(64);not null;default:'';comment:'客户端指纹'" json:"-"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
type MethodItem struct {
|
||||
Amount string `json:"amount"`
|
||||
ActualAmount string `json:"actual_amount"`
|
||||
Fiat string `json:"fiat"`
|
||||
ExchangeRate string `json:"exchange_rate"`
|
||||
Currency string `json:"currency"`
|
||||
Network string `json:"network"`
|
||||
TokenNetName string `json:"token_net_name"`
|
||||
TokenCustomName string `json:"token_custom_name"`
|
||||
IsPopular bool `json:"is_popular"`
|
||||
}
|
||||
|
||||
func (o *Order) SetCanceled() error {
|
||||
core.New()
|
||||
o.Status = OrderStatusCanceled
|
||||
|
||||
return Db.Save(o).Error
|
||||
}
|
||||
|
||||
// CanReselectPayment 判断订单是否支持重选交易类型
|
||||
func (o *Order) CanReselectPayment() bool {
|
||||
if o.Status != OrderStatusWaiting {
|
||||
return false
|
||||
}
|
||||
|
||||
if o.ApiType != OrderApiTypeEpusdtOrder && o.ApiType != OrderApiTypeAdmin {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (o *Order) FingerprintBound() bool {
|
||||
return o.ClientFingerprint != ""
|
||||
}
|
||||
|
||||
func (o *Order) MatchFingerprint(fingerprint string) bool {
|
||||
return !o.FingerprintBound() || o.ClientFingerprint == fingerprint
|
||||
}
|
||||
|
||||
func (o *Order) SetExpired() {
|
||||
o.Status = OrderStatusExpired
|
||||
|
||||
@@ -105,14 +149,19 @@ func (o *Order) SetFailed() {
|
||||
Db.Save(o)
|
||||
}
|
||||
|
||||
func (o *Order) MarkConfirming(blockNum int64, from, hash string, at time.Time) {
|
||||
func (o *Order) MarkConfirming(blockNum int, from, hash string, at time.Time, amount decimal.Decimal) error {
|
||||
o.FromAddress = from
|
||||
o.ConfirmedAt = &at
|
||||
o.RefHash = hash
|
||||
o.RefBlockNum = blockNum
|
||||
o.Status = OrderStatusConfirming
|
||||
if o.AddressLocked {
|
||||
rate, _ := decimal.NewFromString(o.Rate)
|
||||
o.Amount = amount.String()
|
||||
o.Money = rate.Mul(amount).String()
|
||||
}
|
||||
|
||||
Db.Save(o)
|
||||
return Db.Save(o).Error
|
||||
}
|
||||
|
||||
func (o *Order) SetNotifyState(state int) error {
|
||||
@@ -156,6 +205,138 @@ func (o *Order) GetTxUrl() string {
|
||||
return GetTxUrl(o.TradeType, o.RefHash)
|
||||
}
|
||||
|
||||
func (o *Order) RedirectUrl() string {
|
||||
var redirect = o.ReturnUrl
|
||||
if o.Status == OrderStatusSuccess && o.ApiType == OrderApiTypeEpay {
|
||||
redirect = fmt.Sprintf("%s?%s", redirect, o.BuildNotifyParams())
|
||||
}
|
||||
|
||||
return redirect
|
||||
}
|
||||
|
||||
func (o *Order) BuildNotifyParams() string {
|
||||
var signStr = utils.Md5String(fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(o.Money), o.Name, o.OrderId, conf.Pid, o.TradeId, o.TradeType) + AuthToken())
|
||||
var params = fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(o.Money), url.QueryEscape(o.Name), url.QueryEscape(o.OrderId), conf.Pid, o.TradeId, o.TradeType)
|
||||
|
||||
return fmt.Sprintf("%s&sign=%s", params, signStr)
|
||||
}
|
||||
|
||||
func (o *Order) GetMethods(crypto Crypto) []MethodItem {
|
||||
var items = make([]MethodItem, 0)
|
||||
if o.Status != OrderStatusWaiting {
|
||||
return items
|
||||
}
|
||||
if o.TradeType != "" && !o.CanReselectPayment() {
|
||||
return items
|
||||
}
|
||||
|
||||
allTrades := GetAllTradeConfig()
|
||||
|
||||
// 解析限定币种
|
||||
var whitelist = make(map[string]bool)
|
||||
var blacklist = make(map[string]bool)
|
||||
if o.CurrencyLimit != "" {
|
||||
for _, c := range strings.Split(o.CurrencyLimit, ",") {
|
||||
c = strings.TrimSpace(c)
|
||||
if strings.HasPrefix(c, "-") {
|
||||
blacklist[strings.ToUpper(strings.TrimPrefix(c, "-"))] = true
|
||||
} else {
|
||||
whitelist[strings.ToUpper(c)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for tradeTypeStr, typeConf := range allTrades {
|
||||
// 如果指定了货币,则进行过滤
|
||||
if crypto != "" && typeConf.Crypto != crypto {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check blacklist
|
||||
if len(blacklist) > 0 && blacklist[string(typeConf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check whitelist
|
||||
if len(whitelist) > 0 && !whitelist[string(typeConf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查是否有可用钱包
|
||||
count := len(GetAvailableWallets(TradeType(tradeTypeStr)))
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取汇率配置的浮动语法
|
||||
syntax := GetK(ConfKey(fmt.Sprintf("rate_float_%s_%s", typeConf.Crypto, o.Fiat)))
|
||||
|
||||
// 获取汇率
|
||||
rate, err := GetOrderRate(typeConf.Crypto, o.Fiat, syntax)
|
||||
if err != nil {
|
||||
log.Error(fmt.Sprintf("GetPaymentMethods: get order rate error: %s", err.Error()))
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算实际支付金额 (加密货币)
|
||||
// Money 是法币金额
|
||||
moneyDecimal, _ := decimal.NewFromString(o.Money)
|
||||
|
||||
// 计算精度
|
||||
atom, precision := GetAtomicity(TradeType(tradeTypeStr))
|
||||
actualAmount := moneyDecimal.DivRound(rate, precision)
|
||||
if actualAmount.LessThan(atom) {
|
||||
actualAmount = atom
|
||||
}
|
||||
|
||||
items = append(items, MethodItem{
|
||||
Amount: o.Money,
|
||||
ActualAmount: actualAmount.String(),
|
||||
Fiat: string(o.Fiat),
|
||||
ExchangeRate: rate.String(),
|
||||
Currency: string(typeConf.Crypto),
|
||||
Network: string(typeConf.Network),
|
||||
TokenNetName: typeConf.NetworkName,
|
||||
TokenCustomName: "", // 暂为空
|
||||
IsPopular: false, // 暂为 false
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by Currency A-Z
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].Currency != items[j].Currency {
|
||||
return items[i].Currency < items[j].Currency
|
||||
}
|
||||
return items[i].Network < items[j].Network
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func (o *Order) Network() any {
|
||||
type network struct {
|
||||
Alias string `json:"alias"`
|
||||
Name string `json:"name"`
|
||||
Crypto Crypto `json:"crypto"`
|
||||
Network Network `json:"network"`
|
||||
}
|
||||
|
||||
var net = network{}
|
||||
info, ok := registry[o.TradeType]
|
||||
if !ok {
|
||||
return net
|
||||
}
|
||||
|
||||
net.Name = info.NetworkName
|
||||
net.Alias = info.Alias
|
||||
net.Crypto = info.Crypto
|
||||
net.Network = info.Network
|
||||
|
||||
return net
|
||||
}
|
||||
|
||||
func (o *Order) TableName() string {
|
||||
return "bep_order"
|
||||
}
|
||||
@@ -177,51 +358,77 @@ func GetOrderByStatus(Status int) []Order {
|
||||
|
||||
func GetNotifyFailedTradeOrders() ([]Order, error) {
|
||||
var orders []Order
|
||||
maxRetry := cast.ToInt(GetC(NotifyMaxRetry))
|
||||
if maxRetry <= 0 {
|
||||
maxRetry = cast.ToInt(defaultConf[NotifyMaxRetry])
|
||||
}
|
||||
|
||||
res := Db.Where("status = ?", OrderStatusSuccess).
|
||||
Where("notify_num <= ?", GetC(NotifyMaxRetry)).
|
||||
Where("notify_state = ?", OrderNotifyStateFail).Find(&orders)
|
||||
Where("notify_state = ?", OrderNotifyStateFail).
|
||||
Where("notify_num <= ?", maxRetry).Find(&orders)
|
||||
|
||||
return orders, res.Error
|
||||
}
|
||||
|
||||
// CalcTradeAmount 计算当前实际可用的交易金额
|
||||
func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType) (string, string, error) {
|
||||
calcMutex.Lock()
|
||||
defer calcMutex.Unlock()
|
||||
func CalcTradeAmount(wallets []Wallet, rate decimal.Decimal, p OrderParams) (Wallet, string, error) {
|
||||
if p.AddressLocked {
|
||||
return LockTradeAddress(wallets, p.TradeType)
|
||||
}
|
||||
|
||||
var orders []Order
|
||||
lock := make(map[string]bool)
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
Db.Where("status in (?) and trade_type = ?", status, t).Find(&orders)
|
||||
Db.Where("status in (?) and trade_type = ?", status, p.TradeType).Find(&orders)
|
||||
for _, order := range orders {
|
||||
lock[order.Address+order.Amount] = true
|
||||
}
|
||||
|
||||
atom, precision := GetAtomicity(t)
|
||||
atom, precision := GetAtomicity(p.TradeType)
|
||||
if rate.LessThanOrEqual(decimal.Zero) || precision <= 0 {
|
||||
return "", "", errors.New(fmt.Sprintf("[%v - %v]原子颗粒度计算异常,联系管理员处理!", atom, precision))
|
||||
return Wallet{}, "", errors.New(fmt.Sprintf("[%v - %v]原子颗粒度计算异常,联系管理员处理!", atom, precision))
|
||||
}
|
||||
|
||||
amount := money.DivRound(rate, precision)
|
||||
amount := p.Money.DivRound(rate, precision)
|
||||
if amount.LessThan(atom) { // 低于最小原子精度,从最小原子精度开始计算
|
||||
amount = atom
|
||||
}
|
||||
|
||||
var i = 0
|
||||
var m = 100
|
||||
for {
|
||||
for _, addr := range address {
|
||||
k := addr + amount.String()
|
||||
for _, w := range wallets {
|
||||
k := w.GetMatchAddr() + amount.String()
|
||||
if _, ok := lock[k]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
return addr, amount.String(), nil
|
||||
return w, amount.String(), nil
|
||||
}
|
||||
|
||||
// 已经被占用,每次递增一个原子精度
|
||||
amount = amount.Add(atom)
|
||||
if i++; i > m {
|
||||
return Wallet{}, "", errors.New("计算交易金额异常,联系管理员处理!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LockTradeAddress 检测交易地址,独占使用
|
||||
func LockTradeAddress(wallets []Wallet, t TradeType) (Wallet, string, error) {
|
||||
zero := decimal.Zero.String()
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
for _, w := range wallets {
|
||||
var o Order
|
||||
Db.Where("match_address = ? and status in (?) and trade_type = ? and address_locked = ?", w.GetMatchAddr(), status, t, true).Order("id desc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
return w, zero, nil
|
||||
}
|
||||
}
|
||||
|
||||
return Wallet{}, zero, errors.New("暂无可用钱包地址")
|
||||
}
|
||||
|
||||
// CalcTradeExpiredAt 计算订单过期时间 最小180,最大3600,默认1200
|
||||
func CalcTradeExpiredAt(sec int64) time.Time {
|
||||
if sec >= 180 && sec <= 3600 {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
"gorm.io/gorm"
|
||||
@@ -67,6 +68,7 @@ func CoingeckoRate() error {
|
||||
}
|
||||
|
||||
req.Header.Set("x-cg-demo-api-key", GetC(RateSyncCoingeckoApiKey))
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("BEpusdt/%s", app.Version))
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
+53
-6
@@ -24,10 +24,23 @@ var supportCrypto = map[Crypto]CoinId{
|
||||
TRX: "tron",
|
||||
BNB: "binancecoin",
|
||||
ETH: "ethereum",
|
||||
GRAM: "the-open-network",
|
||||
}
|
||||
|
||||
// TradeType 交易类型,当下类型开始增多,现在这里统一管理、尽量收缩配置项
|
||||
var registry = map[TradeType]TradeTypeConf{
|
||||
UsdtTon: {
|
||||
Alias: "USDT・Ton",
|
||||
NetworkName: "Ton",
|
||||
Network: conf.Ton,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtTon,
|
||||
Decimal: conf.UsdtTonDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://tonscan.org/tx/%s#overview",
|
||||
EndpointKey: RpcGlobalConfigUrlTon,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdtPlasma: {
|
||||
Alias: "USDT・Plasma",
|
||||
NetworkName: "Plasma",
|
||||
@@ -41,7 +54,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdtTrc20: {
|
||||
Alias: "USDT・TRC20",
|
||||
NetworkName: "TRC20",
|
||||
NetworkName: "Tron",
|
||||
Network: conf.Tron,
|
||||
Crypto: USDT,
|
||||
Contract: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 占位,目前实际没使用
|
||||
@@ -53,7 +66,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdtErc20: {
|
||||
Alias: "USDT・ERC20",
|
||||
NetworkName: "ERC20",
|
||||
NetworkName: "Ethereum",
|
||||
Network: conf.Ethereum,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtErc20,
|
||||
@@ -64,7 +77,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdtBep20: {
|
||||
Alias: "USDT・BEP20",
|
||||
NetworkName: "BEP20",
|
||||
NetworkName: "Bsc",
|
||||
Network: conf.Bsc,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtBep20,
|
||||
@@ -131,7 +144,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdcErc20: {
|
||||
Alias: "USDC・ERC20",
|
||||
NetworkName: "ERC20",
|
||||
NetworkName: "Ethereum",
|
||||
Network: conf.Ethereum,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcErc20,
|
||||
@@ -142,7 +155,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdcBep20: {
|
||||
Alias: "USDC・BEP20",
|
||||
NetworkName: "BEP20",
|
||||
NetworkName: "Bsc",
|
||||
Network: conf.Bsc,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcBep20,
|
||||
@@ -197,7 +210,7 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
},
|
||||
UsdcTrc20: {
|
||||
Alias: "USDC・TRC20",
|
||||
NetworkName: "TRC20",
|
||||
NetworkName: "Tron",
|
||||
Network: conf.Tron,
|
||||
Crypto: USDC,
|
||||
Contract: "TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8", // 占位,目前实际没使用
|
||||
@@ -273,6 +286,21 @@ var registry = map[TradeType]TradeTypeConf{
|
||||
ExplorerFmt: "https://bscscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointBsc,
|
||||
},
|
||||
TonGram: {
|
||||
Alias: "Ton・Gram",
|
||||
NetworkName: "Ton",
|
||||
Network: conf.Ton,
|
||||
Crypto: GRAM,
|
||||
Native: true,
|
||||
Decimal: conf.TonTonDecimals,
|
||||
AmountRange: Range{
|
||||
MinAmount: decimal.NewFromFloat(0.00001),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
},
|
||||
ExplorerFmt: "https://tonscan.org/tx/%s#overview",
|
||||
EndpointKey: RpcGlobalConfigUrlTon,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -314,6 +342,15 @@ func GetAllAlias() map[string]string {
|
||||
return alias
|
||||
}
|
||||
|
||||
func GetAllNetwork() map[string]string {
|
||||
var networks = make(map[string]string)
|
||||
for _, c := range registry {
|
||||
networks[string(c.Network)] = c.NetworkName
|
||||
}
|
||||
|
||||
return networks
|
||||
}
|
||||
|
||||
func GetAllTradeConfig() map[string]TradeTypeConf {
|
||||
var config = make(map[string]TradeTypeConf)
|
||||
|
||||
@@ -359,6 +396,16 @@ func GetTxUrl(t TradeType, hash string) string {
|
||||
return "https://tronscan.org/#/transaction/" + hash
|
||||
}
|
||||
|
||||
func GetTradeContract(t TradeType) string {
|
||||
c, ok := registry[t]
|
||||
if !ok {
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
return c.Contract
|
||||
}
|
||||
|
||||
func GetTradeDecimal(t TradeType) int32 {
|
||||
c, ok := registry[t]
|
||||
if !ok {
|
||||
|
||||
+115
-80
@@ -13,52 +13,58 @@ import (
|
||||
)
|
||||
|
||||
type OrderParams struct {
|
||||
Money decimal.Decimal `json:"money"` // 交易金额 (单位:法币)s
|
||||
ApiType string `json:"api_type"` // 支付 API 类型
|
||||
Address string `json:"address"` // 收款地址
|
||||
OrderId string `json:"order_id"` // 商户订单 ID
|
||||
TradeType TradeType `json:"trade_type"` // 交易类型
|
||||
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
|
||||
NotifyUrl string `json:"notify_url"` // 异步通知地址
|
||||
Name string `json:"name"` // 商品名称
|
||||
Timeout int64 `json:"timeout"` // 订单超时时间(秒)
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
Fiat Fiat `json:"fiat"` // 法币类型
|
||||
CurrencyLimit string `json:"currency_limit"` // 限定币种
|
||||
Money decimal.Decimal `json:"money"` // 交易金额 (单位:法币)s
|
||||
ApiType string `json:"api_type"` // 支付 API 类型
|
||||
Address string `json:"address"` // 收款地址
|
||||
OrderId string `json:"order_id"` // 商户订单 ID
|
||||
TradeType TradeType `json:"trade_type"` // 交易类型
|
||||
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
|
||||
NotifyUrl string `json:"notify_url"` // 异步通知地址
|
||||
Name string `json:"name"` // 商品名称
|
||||
Timeout int64 `json:"timeout"` // 订单超时时间(秒)
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
Fiat Fiat `json:"fiat"` // 法币类型
|
||||
CurrencyLimit string `json:"currency_limit"` // 限定币种
|
||||
AddressLocked bool `json:"address_locked"` // 地址独占锁定
|
||||
ClientFingerprint string `json:"client_fingerprint"` // 客户端指纹
|
||||
}
|
||||
|
||||
type Addr struct {
|
||||
Address string // 对外前端收款地址
|
||||
MatchAddr string // 对内订单校验地址
|
||||
}
|
||||
|
||||
type Trade struct {
|
||||
Crypto Crypto
|
||||
Rate decimal.Decimal
|
||||
Address string
|
||||
Amount string
|
||||
Wallet Wallet
|
||||
Crypto Crypto
|
||||
Rate decimal.Decimal
|
||||
Amount string
|
||||
}
|
||||
|
||||
func BuildOrder(p OrderParams) (Order, error) {
|
||||
var buildMutex sync.Mutex
|
||||
|
||||
func StartBuildOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
if p.Address != "" {
|
||||
if !utils.IsValidTronAddress(p.Address) &&
|
||||
!utils.IsValidEvmAddress(p.Address) &&
|
||||
!utils.IsValidSolanaAddress(p.Address) &&
|
||||
!utils.IsValidAptosAddress(p.Address) {
|
||||
!utils.IsValidAptosAddress(p.Address) &&
|
||||
!utils.IsValidTonAddress(p.Address) {
|
||||
|
||||
return order, fmt.Errorf("钱包地址格式错误:%s", p.Address)
|
||||
}
|
||||
}
|
||||
if _, ok := registry[p.TradeType]; !ok {
|
||||
|
||||
return order, fmt.Errorf("不支持的交易类型:%s", p.TradeType)
|
||||
}
|
||||
if _, ok := supportFiat[p.Fiat]; !ok {
|
||||
|
||||
return order, fmt.Errorf("不支持的法币类型:%s", p.Fiat)
|
||||
}
|
||||
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount) {
|
||||
|
||||
if !p.AddressLocked && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
@@ -67,50 +73,26 @@ func BuildOrder(p OrderParams) (Order, error) {
|
||||
return order, nil
|
||||
}
|
||||
|
||||
buildMutex.Lock()
|
||||
defer buildMutex.Unlock()
|
||||
|
||||
Db.Where("order_id = ?", p.OrderId).Order("id desc").Limit(1).Find(&order)
|
||||
if order.Status == OrderStatusSuccess || order.Status == OrderStatusConfirming {
|
||||
return order, nil
|
||||
}
|
||||
if order.Status == OrderStatusWaiting {
|
||||
return RebuildOrder(order, p)
|
||||
}
|
||||
|
||||
var lock sync.Mutex
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return order, err
|
||||
}
|
||||
|
||||
return NewOrder(p, data)
|
||||
return BuildOrder(p, data)
|
||||
}
|
||||
|
||||
func RebuildOrder(t Order, p OrderParams) (Order, error) {
|
||||
if p.OrderId == t.OrderId &&
|
||||
p.TradeType == t.TradeType &&
|
||||
p.Money.String() == t.Money &&
|
||||
p.Fiat == t.Fiat {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
var lock sync.Mutex
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
t.Amount = data.Amount
|
||||
t.TradeType = p.TradeType
|
||||
t.Address = data.Address
|
||||
t.Crypto = data.Crypto
|
||||
t.Rate = fmt.Sprintf("%v", data.Rate)
|
||||
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
|
||||
|
||||
return t, Db.Save(&t).Error
|
||||
}
|
||||
|
||||
func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
func BuildOrder(p OrderParams, trade Trade) (Order, error) {
|
||||
tradeId, err := utils.GenerateTradeId()
|
||||
if err != nil {
|
||||
return Order{}, err
|
||||
@@ -122,10 +104,12 @@ func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
TradeId: tradeId,
|
||||
RefHash: tradeId,
|
||||
TradeType: p.TradeType,
|
||||
Rate: fmt.Sprintf("%v", data.Rate),
|
||||
Amount: data.Amount,
|
||||
Rate: fmt.Sprintf("%v", trade.Rate),
|
||||
Amount: trade.Amount,
|
||||
Money: p.Money.String(),
|
||||
Address: data.Address,
|
||||
Address: trade.Wallet.GetPaymentAddr(),
|
||||
MatchAddress: trade.Wallet.GetMatchAddr(),
|
||||
AddressLocked: p.Money.IsZero(), // 零值订单,地址锁定 独占
|
||||
Status: OrderStatusWaiting,
|
||||
Name: p.Name,
|
||||
ApiType: p.ApiType,
|
||||
@@ -135,7 +119,7 @@ func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
NotifyState: OrderNotifyStateFail,
|
||||
ExpiredAt: CalcTradeExpiredAt(p.Timeout),
|
||||
Fiat: p.Fiat,
|
||||
Crypto: data.Crypto,
|
||||
Crypto: trade.Crypto,
|
||||
CurrencyLimit: p.CurrencyLimit,
|
||||
ConfirmedAt: &zero, // 默认填充一个0值时间,尽量避免数据库出现允许 NULL 值存在
|
||||
}
|
||||
@@ -143,7 +127,6 @@ func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
if tradeOrder.Name == "" {
|
||||
tradeOrder.Name = tradeOrder.OrderId
|
||||
}
|
||||
|
||||
if err = Db.Create(&tradeOrder).Error; err != nil {
|
||||
log.Error("订单创建失败:", err.Error())
|
||||
return Order{}, err
|
||||
@@ -168,40 +151,93 @@ func BuildTrade(p OrderParams) (Trade, error) {
|
||||
return Trade{}, fmt.Errorf("%s %s 汇率异常", crypto, p.Fiat)
|
||||
}
|
||||
|
||||
var wallet = GetAvailableAddress(p.TradeType)
|
||||
if p.Address != "" {
|
||||
wallet = []string{p.Address}
|
||||
if !AddrCaseSens(p.TradeType) { // 交易类型不区分大小写,统一转小写;这个地址最后的交易匹配要用到,千万不能错
|
||||
wallet = []string{strings.ToLower(p.Address)}
|
||||
var wallets = GetAvailableWallets(p.TradeType)
|
||||
if p.Address != "" { // 指定地址
|
||||
w, err := NewWallet(p.Address, p.TradeType)
|
||||
if err != nil {
|
||||
return Trade{}, err
|
||||
}
|
||||
|
||||
wallets = []Wallet{w}
|
||||
}
|
||||
|
||||
if len(wallet) == 0 {
|
||||
if len(wallets) == 0 {
|
||||
return Trade{}, fmt.Errorf("%s 未检测到可用钱包地址", p.TradeType)
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
address, amount, err := CalcTradeAmount(wallet, rate, p.Money, p.TradeType)
|
||||
wallet, amount, err := CalcTradeAmount(wallets, rate, p)
|
||||
if err != nil {
|
||||
|
||||
return Trade{}, err
|
||||
}
|
||||
|
||||
return Trade{
|
||||
Crypto: crypto,
|
||||
Rate: rate,
|
||||
Address: address,
|
||||
Amount: amount,
|
||||
Crypto: crypto,
|
||||
Rate: rate,
|
||||
Wallet: wallet,
|
||||
Amount: amount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func RebuildOrder(t Order, p OrderParams) (Order, error) {
|
||||
if p.OrderId == t.OrderId && p.TradeType == t.TradeType && p.Money.String() == t.Money && p.Fiat == t.Fiat {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
if t.TradeType == "" && p.ClientFingerprint != "" {
|
||||
t.ClientFingerprint = p.ClientFingerprint
|
||||
}
|
||||
|
||||
t.Fiat = p.Fiat
|
||||
t.Address = data.Wallet.GetPaymentAddr()
|
||||
t.MatchAddress = data.Wallet.GetMatchAddr()
|
||||
t.Crypto = data.Crypto
|
||||
t.Amount = data.Amount
|
||||
t.Money = p.Money.String()
|
||||
t.TradeType = p.TradeType
|
||||
t.Rate = fmt.Sprintf("%v", data.Rate)
|
||||
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
|
||||
|
||||
query := Db.Model(&Order{}).Where("id = ?", t.ID)
|
||||
if p.ClientFingerprint != "" {
|
||||
query = query.Where("(client_fingerprint = '' OR client_fingerprint = ?)", p.ClientFingerprint)
|
||||
}
|
||||
|
||||
res := query.Updates(map[string]any{
|
||||
"fiat": t.Fiat,
|
||||
"address": t.Address,
|
||||
"match_address": t.MatchAddress,
|
||||
"crypto": t.Crypto,
|
||||
"amount": t.Amount,
|
||||
"money": t.Money,
|
||||
"trade_type": t.TradeType,
|
||||
"rate": t.Rate,
|
||||
"expired_at": t.ExpiredAt,
|
||||
"client_fingerprint": t.ClientFingerprint,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return t, res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return t, fmt.Errorf("client fingerprint mismatch")
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// BuildPendingOrder 创建待支付订单(不锁定地址和汇率)
|
||||
func BuildPendingOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount) {
|
||||
if !p.Money.IsZero() && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
@@ -217,18 +253,17 @@ func BuildPendingOrder(p OrderParams) (Order, error) {
|
||||
if err == nil {
|
||||
crypto = c
|
||||
}
|
||||
} else if p.CurrencyLimit != "" {
|
||||
// 如果指定了唯一的币种限制,且不是黑名单模式,则使用该币种
|
||||
} else if p.CurrencyLimit != "" { // 如果指定了唯一的币种限制,且不是黑名单模式,则使用该币种
|
||||
cur := strings.ToUpper(p.CurrencyLimit)
|
||||
if !strings.Contains(cur, ",") && !strings.HasPrefix(cur, "-") {
|
||||
crypto = Crypto(cur)
|
||||
}
|
||||
}
|
||||
|
||||
return NewOrder(p, Trade{
|
||||
Crypto: crypto,
|
||||
Rate: decimal.Zero,
|
||||
Amount: "0",
|
||||
Address: "",
|
||||
return BuildOrder(p, Trade{
|
||||
Crypto: crypto,
|
||||
Rate: decimal.Zero,
|
||||
Amount: "0",
|
||||
Wallet: Wallet{},
|
||||
})
|
||||
}
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ type TronTransfer struct {
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType TradeType
|
||||
BlockNum int64
|
||||
BlockNum int
|
||||
}
|
||||
|
||||
type TronResource struct {
|
||||
|
||||
+77
-22
@@ -1,7 +1,12 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -14,11 +19,11 @@ const (
|
||||
type Wallet struct {
|
||||
Id
|
||||
Name string `gorm:"column:name;type:varchar(32);not null;default:-';comment:名称" json:"name"`
|
||||
Status uint8 `gorm:"column:status;type:tinyint(1);not null;default:1;comment:地址状态" json:"status"`
|
||||
Status uint8 `gorm:"column:status;not null;default:1;comment:地址状态" json:"status"`
|
||||
Address string `gorm:"column:address;type:varchar(128);not null;index;comment:钱包地址" json:"address"`
|
||||
MatchAddr string `gorm:"column:match_addr;type:varchar(128);not null;uniqueIndex:idx_address;comment:匹配地址" json:"match_addr"`
|
||||
TradeType string `gorm:"column:trade_type;type:varchar(20);not null;uniqueIndex:idx_address;comment:交易类型" json:"trade_type"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;type:tinyint(1);not null;default:0;comment:其它通知" json:"other_notify"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;not null;default:0;comment:其它通知" json:"other_notify"`
|
||||
Remark string `gorm:"column:remark;type:varchar(255);not null;default:'';comment:备注" json:"remark"`
|
||||
AutoTimeAt
|
||||
}
|
||||
@@ -33,26 +38,58 @@ func (wa *Wallet) SetStatus(status uint8) {
|
||||
Db.Save(wa)
|
||||
}
|
||||
|
||||
func (wa *Wallet) IsValid() bool {
|
||||
func (wa *Wallet) Validate() error {
|
||||
tradeType := TradeType(wa.TradeType)
|
||||
wa.MatchAddr = wa.Address
|
||||
|
||||
// Tron 地址验证
|
||||
if tradeType == TronTrx || tradeType == UsdtTrc20 || tradeType == UsdcTrc20 {
|
||||
return utils.IsValidTronAddress(wa.Address)
|
||||
switch tradeType {
|
||||
case TronTrx, UsdtTrc20, UsdcTrc20:
|
||||
if !utils.IsValidTronAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtSolana, UsdcSolana:
|
||||
if !utils.IsValidSolanaAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtAptos, UsdcAptos:
|
||||
if !utils.IsValidAptosAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtTon:
|
||||
if !utils.IsValidTonAddress(wa.Address) {
|
||||
return errors.New("TON 地址必须以 UQ 开头")
|
||||
}
|
||||
owner, err := address.ParseAddr(wa.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr, err := utils.GetJettonWalletAddr(utils.NewTonClient(GetC(RpcGlobalConfigUrlTon)), address.MustParseAddr(conf.UsdtTon), owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wa.MatchAddr = addr.Bounce(false).String()
|
||||
return nil
|
||||
case TonGram:
|
||||
if !utils.IsValidTonAddress(wa.Address) {
|
||||
return errors.New("TON 地址必须以 UQ 开头")
|
||||
}
|
||||
owner, err := address.ParseAddr(wa.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wa.MatchAddr = owner.Bounce(false).String()
|
||||
return nil
|
||||
default:
|
||||
if !utils.IsValidEvmAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
}
|
||||
|
||||
// Solana 地址验证
|
||||
if tradeType == UsdtSolana || tradeType == UsdcSolana {
|
||||
return utils.IsValidSolanaAddress(wa.Address)
|
||||
if !AddrCaseSens(tradeType) {
|
||||
wa.MatchAddr = strings.ToLower(wa.Address)
|
||||
}
|
||||
|
||||
// Aptos 地址验证
|
||||
if tradeType == UsdtAptos || tradeType == UsdcAptos {
|
||||
return utils.IsValidAptosAddress(wa.Address)
|
||||
}
|
||||
|
||||
// 默认使用 EVM 地址验证(Ethereum, BSC, Polygon, Arbitrum, Base, X Layer)
|
||||
return utils.IsValidEvmAddress(wa.Address)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wa *Wallet) SetOtherNotify(notify uint8) {
|
||||
@@ -92,14 +129,32 @@ func (wa *Wallet) GetNetwork() Network {
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetAvailableAddress(t TradeType) []string {
|
||||
var rows []Wallet
|
||||
Db.Where("trade_type = ? and status = ?", t, WaStatusEnable).Find(&rows)
|
||||
func (wa *Wallet) GetPaymentAddr() string {
|
||||
if wa.TradeType == string(UsdtTon) {
|
||||
|
||||
wallets := make([]string, 0, len(rows))
|
||||
for _, w := range rows {
|
||||
wallets = append(wallets, w.MatchAddr)
|
||||
return wa.Address
|
||||
}
|
||||
|
||||
return wa.MatchAddr
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetMatchAddr() string {
|
||||
return wa.MatchAddr
|
||||
}
|
||||
|
||||
func GetAvailableWallets(t TradeType) []Wallet {
|
||||
var wallets = make([]Wallet, 0)
|
||||
|
||||
Db.Where("trade_type = ? and status = ?", t, WaStatusEnable).Find(&wallets)
|
||||
|
||||
return wallets
|
||||
}
|
||||
|
||||
func NewWallet(address string, tradeType TradeType) (Wallet, error) {
|
||||
wa := Wallet{Address: address, TradeType: string(tradeType)}
|
||||
if err := wa.Validate(); err != nil {
|
||||
return Wallet{}, err
|
||||
}
|
||||
|
||||
return wa, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
type activeConf struct {
|
||||
host string
|
||||
port string
|
||||
user string
|
||||
pass string
|
||||
}
|
||||
|
||||
var (
|
||||
client mqtt.Client
|
||||
mu sync.RWMutex
|
||||
curConf activeConf
|
||||
)
|
||||
|
||||
// Reload 按最新配置连接MQTT服务器
|
||||
func Reload() error {
|
||||
host := model.GetC(model.MqttHost)
|
||||
port := model.GetC(model.MqttPort)
|
||||
if host == "" || port == "" {
|
||||
return nil // 未配置 MQTT,跳过
|
||||
}
|
||||
|
||||
newConf := activeConf{
|
||||
host: host,
|
||||
port: port,
|
||||
user: model.GetC(model.MqttUser),
|
||||
pass: model.GetC(model.MqttPass),
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if newConf == curConf { // 配置未变更,无需重连
|
||||
return nil
|
||||
}
|
||||
|
||||
// 断开旧连接(给 250ms 优雅退出)
|
||||
if client != nil {
|
||||
client.Disconnect(250)
|
||||
log.Info("🔄 MQTT 配置变动,正在连接...")
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
// 暂时只支持 tcp 模式
|
||||
opts.AddBroker(fmt.Sprintf("tcp://%s:%s", newConf.host, newConf.port))
|
||||
opts.SetUsername(newConf.user)
|
||||
opts.SetPassword(newConf.pass)
|
||||
opts.SetClientID(fmt.Sprintf("BEpusdt %d", os.Getpid()))
|
||||
opts.SetAutoReconnect(true)
|
||||
opts.SetOrderMatters(false)
|
||||
opts.SetOnConnectHandler(onConnectHandler)
|
||||
opts.SetConnectionLostHandler(onConnectionLost)
|
||||
|
||||
newClient := mqtt.NewClient(opts)
|
||||
if token := newClient.Connect(); token.Wait() && token.Error() != nil {
|
||||
return fmt.Errorf("MQTT 连接失败: %s", token.Error())
|
||||
}
|
||||
|
||||
client = newClient
|
||||
curConf = newConf
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func onConnectHandler(c mqtt.Client) {
|
||||
for topic, cb := range subscribeMap {
|
||||
c.Subscribe(topic, cb.Qos, cb.Handler).Wait()
|
||||
}
|
||||
|
||||
log.Info("✅ MQTT 连接成功")
|
||||
}
|
||||
|
||||
func onConnectionLost(_ mqtt.Client, err error) {
|
||||
log.Warn(fmt.Sprintf("❌ MQTT 连接断开: %s", err.Error()))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
)
|
||||
|
||||
// Publish 发布消息。若 MQTT 未连接则静默丢弃,返回 nil。
|
||||
func Publish(topic string, qos byte, retained bool, payload interface{}) mqtt.Token {
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
token := c.Publish(topic, qos, retained, payload)
|
||||
if qos > 0 {
|
||||
go func() {
|
||||
token.Wait()
|
||||
if err := token.Error(); err != nil {
|
||||
log.Warn("MQTT publish error: " + err.Error())
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return token
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
)
|
||||
|
||||
type callback struct {
|
||||
Qos byte
|
||||
Handler mqtt.MessageHandler
|
||||
}
|
||||
|
||||
var subscribeMap = make(map[string]callback)
|
||||
|
||||
// Subscribe 注册订阅。topic 会持久保存在 subscribeMap,
|
||||
// 重连后由 onConnectHandler 自动恢复所有订阅。
|
||||
func Subscribe(topic string, qos byte, handler mqtt.MessageHandler) {
|
||||
subscribeMap[topic] = callback{Qos: qos, Handler: handler}
|
||||
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if token := c.Subscribe(topic, qos, handler); token.Wait() && token.Error() == nil {
|
||||
log.Info(fmt.Sprintf("✅ 订阅主题: %s", topic))
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func (t *Telegram) Success(o model.Order) {
|
||||
\-\-\-
|
||||
` + "```" + `
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💰请求金额:%v ` + string(o.Fiat) + `(%v)
|
||||
💲支付数额:%v ` + tradeType + `
|
||||
💎交易哈希:%s
|
||||
✅收款地址:%s
|
||||
@@ -111,7 +111,7 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) {
|
||||
`+"```"+`
|
||||
🚦商户订单:%v
|
||||
💲支付数额:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💰请求金额:%v `+string(o.Fiat)+`(%v)
|
||||
💍交易类别:%s
|
||||
⚖️️确认时间:%s
|
||||
⏰下次回调:%s
|
||||
@@ -141,10 +141,7 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) {
|
||||
}
|
||||
|
||||
func (t *Telegram) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
title := "收入"
|
||||
if trans.RecvAddress != wa.Address {
|
||||
title = "支出"
|
||||
}
|
||||
title := nonOrderTransferTitle(trans, wa)
|
||||
|
||||
text := fmt.Sprintf(
|
||||
"\\#账户%s \\#非订单交易\n\\-\\-\\-\n```\n💲交易数额:%v \n💍交易类别:"+strings.ToUpper(string(trans.TradeType))+"\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
@@ -168,6 +165,14 @@ func (t *Telegram) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
})
|
||||
}
|
||||
|
||||
func nonOrderTransferTitle(trans model.TronTransfer, wa model.Wallet) string {
|
||||
if trans.RecvAddress == wa.MatchAddr {
|
||||
return "收入"
|
||||
}
|
||||
|
||||
return "支出"
|
||||
}
|
||||
|
||||
func (t *Telegram) TronResourceChange(res model.TronResource) {
|
||||
title := "代理"
|
||||
if res.Type == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func TestNonOrderTransferTitleUsesMatchAddress(t *testing.T) {
|
||||
trans := model.TronTransfer{
|
||||
RecvAddress: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
FromAddress: "0x6cba0ff7e76b225ee3b975c3096d828f012c8c72",
|
||||
}
|
||||
wallet := model.Wallet{
|
||||
Address: "0xF9DFF4E813644eDc7D9b1b535100b7e92333f743",
|
||||
MatchAddr: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
|
||||
if title := nonOrderTransferTitle(trans, wallet); title != "收入" {
|
||||
t.Fatalf("title = %q, want %q", title, "收入")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonOrderTransferTitleMarksOutgoingTransfer(t *testing.T) {
|
||||
trans := model.TronTransfer{
|
||||
RecvAddress: "0xrecipient",
|
||||
FromAddress: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
wallet := model.Wallet{
|
||||
Address: "0xF9DFF4E813644eDc7D9b1b535100b7e92333f743",
|
||||
MatchAddr: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
|
||||
if title := nonOrderTransferTitle(trans, wallet); title != "支出" {
|
||||
t.Fatalf("title = %q, want %q", title, "支出")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ func adminInit(e *gin.Engine) {
|
||||
var confRtr = e.Group("/api/conf")
|
||||
var confHdr = new(admin.Conf)
|
||||
{
|
||||
GetRegister(confRtr, "/rpc", true, confHdr.Rpc)
|
||||
PostRegister(confRtr, "/set", true, confHdr.Set)
|
||||
PostRegister(confRtr, "/get", true, confHdr.Get)
|
||||
PostRegister(confRtr, "/del", true, confHdr.Del)
|
||||
@@ -16,6 +17,7 @@ func adminInit(e *gin.Engine) {
|
||||
PostRegister(confRtr, "/sets", true, confHdr.Sets)
|
||||
PostRegister(confRtr, "/notifier", true, confHdr.Notifier)
|
||||
PostRegister(confRtr, "/notifier_test", true, confHdr.NotifierTest)
|
||||
PostRegister(confRtr, "/checkout_list", true, confHdr.CheckoutList)
|
||||
PostRegister(confRtr, "/reset_api_auth_token", true, confHdr.ResetApiAuthToken)
|
||||
}
|
||||
|
||||
@@ -36,6 +38,7 @@ func adminInit(e *gin.Engine) {
|
||||
PostRegister(orderRtr, "/detail", true, orderHdr.Detail)
|
||||
PostRegister(orderRtr, "/paid", true, orderHdr.Paid)
|
||||
PostRegister(orderRtr, "/manual_notify", true, orderHdr.ManualNotify)
|
||||
PostRegister(orderRtr, "/cancel", true, orderHdr.Cancel)
|
||||
PostRegister(orderRtr, "/del", true, orderHdr.Del)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/v03413/bepusdt/static"
|
||||
)
|
||||
|
||||
func TestLangGeCheckoutTemplateIsEmbedded(t *testing.T) {
|
||||
checkout, err := readCheckoutInfoFromFS(static.Checkout, "checkout/langge")
|
||||
if err != nil {
|
||||
t.Fatalf("read langge checkout info: %v", err)
|
||||
}
|
||||
|
||||
if checkout.Name != "LangGe design" {
|
||||
t.Fatalf("unexpected checkout name: %q", checkout.Name)
|
||||
}
|
||||
if checkout.Author == "" {
|
||||
t.Fatal("checkout author is required")
|
||||
}
|
||||
if checkout.Desc == "" {
|
||||
t.Fatal("checkout desc is required")
|
||||
}
|
||||
|
||||
view, err := fs.ReadFile(static.Checkout, "checkout/langge/views/checkout.html")
|
||||
if err != nil {
|
||||
t.Fatalf("read langge checkout template: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(view), "{{ .trade_id }}") {
|
||||
t.Fatal("langge checkout template must only depend on trade_id server injection")
|
||||
}
|
||||
|
||||
tmpl := template.New("default")
|
||||
if !registerTemplatesFromFS(tmpl, static.Checkout, "checkout/langge", "langge") {
|
||||
t.Fatal("langge checkout template was not registered")
|
||||
}
|
||||
if tmpl.Lookup("langge/checkout.html") == nil {
|
||||
t.Fatal("langge checkout template was not registered under expected name")
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,7 @@ func epusdtInit(engine *gin.Engine) {
|
||||
epGrp := engine.Group("/pay")
|
||||
epHdr := new(epusdt.Epusdt)
|
||||
{
|
||||
epGrp.GET("/checkout-counter/:trade_id", epHdr.CheckoutCounter)
|
||||
epGrp.GET("/cashier/:trade_id", epHdr.CheckoutCashier)
|
||||
epGrp.GET("/check-status/:trade_id", epHdr.CheckStatus)
|
||||
epGrp.GET("/checkout/:trade_id", epHdr.Checkout)
|
||||
}
|
||||
|
||||
orderGrp := engine.Group("/api/v1/order")
|
||||
@@ -22,10 +20,11 @@ func epusdtInit(engine *gin.Engine) {
|
||||
orderGrp.POST("/create-order", epHdr.CreateOrder)
|
||||
}
|
||||
|
||||
payApiGrp := engine.Group("/api/v1/pay")
|
||||
payGrp := engine.Group("/api/v1/pay")
|
||||
{
|
||||
payApiGrp.POST("/methods", epHdr.GetPaymentMethods)
|
||||
payApiGrp.POST("/update-order", epHdr.UpdateOrder)
|
||||
payApiGrp.POST("/notify", epHdr.Notify)
|
||||
payGrp.POST("/info", epHdr.Info)
|
||||
payGrp.POST("/notify", epHdr.Notify)
|
||||
payGrp.POST("/methods", epHdr.GetMethods)
|
||||
payGrp.POST("/update-order", epHdr.UpdateOrder)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,7 @@ func Handler() *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
engine = gin.New()
|
||||
|
||||
session := memstore.NewStore([]byte(conf.Secret))
|
||||
session := memstore.NewStore([]byte(model.GetK(model.AdminSecret)))
|
||||
session.Options(sessions.Options{
|
||||
MaxAge: 86400,
|
||||
HttpOnly: true,
|
||||
@@ -47,7 +46,11 @@ func Handler() *gin.Engine {
|
||||
sess := sessions.Default(ctx)
|
||||
if secure, ok := sess.Get(conf.AdminSecureK).(bool); ok && secure {
|
||||
ctx.HTML(200, "secure.html", gin.H{})
|
||||
return
|
||||
}
|
||||
|
||||
if url := model.GetC(model.HomeRedirectUrl); url != "" {
|
||||
ctx.Redirect(302, url)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+110
-27
@@ -1,53 +1,136 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
"github.com/v03413/bepusdt/static"
|
||||
)
|
||||
|
||||
func staticInit(e *gin.Engine) {
|
||||
customPath := model.GetK(model.PaymentStaticPath)
|
||||
if customPath != "" && utils.IsExist(customPath) {
|
||||
initCustomPayment(e, customPath)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
initDefaultPayment(e)
|
||||
}
|
||||
|
||||
func initCustomPayment(e *gin.Engine, path string) {
|
||||
tmpl := template.New("customer")
|
||||
|
||||
template.Must(tmpl.ParseGlob(filepath.Join(path, "views", "*.html")))
|
||||
template.Must(tmpl.ParseFS(static.Secure, "secure/secure.html"))
|
||||
e.SetHTMLTemplate(tmpl)
|
||||
|
||||
e.StaticFS("/payment/assets", http.Dir(filepath.Join(path, "assets")))
|
||||
e.StaticFS("/secure/assets", http.FS(subFS(static.Secure, "secure/assets")))
|
||||
|
||||
log.Info("成功注册自定义静态资源路径:", path)
|
||||
}
|
||||
|
||||
func initDefaultPayment(e *gin.Engine) {
|
||||
tmpl := template.New("default")
|
||||
|
||||
template.Must(tmpl.ParseFS(static.Secure, "secure/secure.html"))
|
||||
template.Must(tmpl.ParseFS(static.Payment, "payment/views/*.html"))
|
||||
e.SetHTMLTemplate(tmpl)
|
||||
|
||||
checkoutFS, checkoutRoot, checkoutSourceDesc := checkoutSource()
|
||||
log.Info("当前使用", checkoutSourceDesc)
|
||||
|
||||
// 注册收银台模板和静态资源
|
||||
entries, err := fs.ReadDir(checkoutFS, checkoutRoot)
|
||||
if err != nil {
|
||||
panic(errors.New(fmt.Sprintf("收银台模板读取异常:%v", err)))
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
name := entry.Name()
|
||||
dir := path.Join(checkoutRoot, name)
|
||||
checkout, err := readCheckoutInfoFromFS(checkoutFS, dir)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if registerTemplatesFromFS(tmpl, checkoutFS, dir, name) {
|
||||
model.RegisterCheckout(name, checkout)
|
||||
log.Info("前台收银模板注册成功:", name)
|
||||
}
|
||||
|
||||
registerAssetsFromFS(e, checkoutFS, dir, "/checkout/"+name+"/assets")
|
||||
}
|
||||
|
||||
e.SetHTMLTemplate(tmpl)
|
||||
e.StaticFS("/payment/assets", http.FS(subFS(static.Payment, "payment/assets")))
|
||||
e.StaticFS("/secure/assets", http.FS(subFS(static.Secure, "secure/assets")))
|
||||
}
|
||||
|
||||
func checkoutSource() (fs.FS, string, string) {
|
||||
const externalStaticDir = "static"
|
||||
const checkoutRoot = "checkout"
|
||||
const externalCheckoutDir = externalStaticDir + "/" + checkoutRoot
|
||||
|
||||
if info, err := os.Stat(externalCheckoutDir); err == nil && info.IsDir() {
|
||||
return os.DirFS(externalStaticDir), checkoutRoot, "外部收银台模板目录:" + externalCheckoutDir
|
||||
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return static.Checkout, checkoutRoot, "内嵌收银台模板(外部目录读取失败:" + err.Error() + ")"
|
||||
}
|
||||
|
||||
return static.Checkout, checkoutRoot, "内嵌收银台模板"
|
||||
}
|
||||
|
||||
func readCheckoutInfoFromFS(src fs.FS, baseDir string) (model.Checkout, error) {
|
||||
infoPath := path.Join(baseDir, "checkout.json")
|
||||
data, err := fs.ReadFile(src, infoPath)
|
||||
if err != nil {
|
||||
return model.Checkout{}, fmt.Errorf("checkout.json 不存在或读取失败: %w", err)
|
||||
}
|
||||
|
||||
var checkout model.Checkout
|
||||
if err := json.Unmarshal(data, &checkout); err != nil {
|
||||
return model.Checkout{}, fmt.Errorf("解析 checkout.json 失败: %w", err)
|
||||
}
|
||||
|
||||
return checkout, nil
|
||||
}
|
||||
|
||||
func registerTemplatesFromFS(tmpl *template.Template, src fs.FS, baseDir, namePrefix string) bool {
|
||||
viewsDir := path.Join(baseDir, "views")
|
||||
files, err := fs.ReadDir(src, viewsDir)
|
||||
if err != nil {
|
||||
log.Error("读取模板目录失败:", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
registered := false
|
||||
for _, f := range files {
|
||||
if f.IsDir() || !strings.HasSuffix(f.Name(), ".html") {
|
||||
continue
|
||||
}
|
||||
|
||||
content, rErr := fs.ReadFile(src, path.Join(viewsDir, f.Name()))
|
||||
if rErr != nil {
|
||||
log.Error("读取模板文件失败:", rErr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
name := f.Name()
|
||||
if namePrefix != "" {
|
||||
name = namePrefix + "/" + name
|
||||
}
|
||||
|
||||
if _, pErr := tmpl.New(name).Parse(string(content)); pErr != nil {
|
||||
log.Error("解析模板失败:", pErr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
registered = true
|
||||
}
|
||||
|
||||
return registered
|
||||
}
|
||||
|
||||
func registerAssetsFromFS(e *gin.Engine, src fs.FS, baseDir, routePath string) {
|
||||
assetsDir := path.Join(baseDir, "assets")
|
||||
if _, err := fs.Stat(src, assetsDir); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
e.StaticFS(routePath, http.FS(subFS(src, assetsDir)))
|
||||
}
|
||||
|
||||
func subFS(src fs.FS, dir string) fs.FS {
|
||||
sub, _ := fs.Sub(src, dir)
|
||||
|
||||
|
||||
+35
-62
@@ -8,31 +8,31 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
blockapi "github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
)
|
||||
|
||||
type aptos struct {
|
||||
versionChunkSize int64
|
||||
versionConfirmedOffset int64
|
||||
lastVersion int64
|
||||
versionChunkSize int
|
||||
versionConfirmedOffset int
|
||||
lastVersion int
|
||||
versionQueue *chanx.UnboundedChan[version]
|
||||
client *http.Client
|
||||
earliestBlockTs atomic.Int64
|
||||
}
|
||||
|
||||
type version struct {
|
||||
Start int64
|
||||
Limit int64
|
||||
Start int
|
||||
Limit int
|
||||
}
|
||||
|
||||
var apt aptos
|
||||
@@ -54,16 +54,16 @@ func init() {
|
||||
Register(Task{Callback: apt.versionDispatch})
|
||||
Register(Task{Callback: apt.syncVersionForward, Duration: time.Second * 3})
|
||||
Register(Task{Callback: apt.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: apt.lookbackVersion, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
func newAptos() aptos {
|
||||
return aptos{
|
||||
versionChunkSize: 100, // 目前好像最大就只能100
|
||||
versionChunkSize: 100,
|
||||
versionConfirmedOffset: 1000,
|
||||
lastVersion: 0,
|
||||
versionQueue: chanx.NewUnboundedChan[version](context.Background(), 30),
|
||||
client: utils.NewHttpClient(),
|
||||
earliestBlockTs: atomic.Int64{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,17 +96,13 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "ledger_version").Int()
|
||||
now := int(gjson.GetBytes(body, "ledger_version").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncVersionForward Error: invalid ledger_version:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if a.lastVersion == 0 {
|
||||
a.syncVersionBackward(ctx, now)
|
||||
}
|
||||
|
||||
if now-a.lastVersion > 10000 {
|
||||
a.lastVersion = now - a.versionChunkSize
|
||||
}
|
||||
@@ -116,7 +112,7 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
a.versionQueue.In <- version{Start: a.lastVersion, Limit: sub}
|
||||
} else {
|
||||
chunks := (sub + a.versionChunkSize - 1) / a.versionChunkSize
|
||||
for i := int64(0); i < chunks; i++ {
|
||||
for i := 0; i < chunks; i++ {
|
||||
limit := a.versionChunkSize
|
||||
start := a.lastVersion + a.versionChunkSize*i
|
||||
if i == chunks-1 {
|
||||
@@ -133,43 +129,33 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
a.lastVersion = now
|
||||
}
|
||||
|
||||
func (a *aptos) syncVersionBackward(ctx context.Context, now int64) {
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(conf.Aptos)
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)",
|
||||
model.OrderStatusWaiting, trade).Order("created_at asc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
func (a *aptos) lookbackVersion(ctx context.Context) {
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
start := o.CreatedAt.Time().Unix()
|
||||
startAt, endAt, ok := getLookbackUnix(conf.Aptos)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
if a.earliestBlockTs.Load() != 0 && a.earliestBlockTs.Load() < start {
|
||||
return
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{
|
||||
Start: now - a.versionChunkSize,
|
||||
Limit: a.versionChunkSize,
|
||||
}
|
||||
|
||||
now = now - a.versionChunkSize
|
||||
}
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Aptos)
|
||||
for i := int(start); i <= int(end); i += a.versionChunkSize {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
}()
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
return
|
||||
}
|
||||
limit := a.versionChunkSize
|
||||
if i+limit > int(end) {
|
||||
limit = int(end) - i + 1
|
||||
}
|
||||
a.versionQueue.In <- version{Start: i, Limit: limit}
|
||||
time.Sleep(time.Millisecond * 200) // 速率控制
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionDispatch(ctx context.Context) {
|
||||
@@ -207,7 +193,7 @@ func (a *aptos) versionParse(n any) {
|
||||
var net = conf.Aptos
|
||||
var url = fmt.Sprintf("%sv1/transactions?start=%d&limit=%d", model.Endpoint(conf.Aptos), p.Start, p.Limit)
|
||||
|
||||
conf.RecordSuccess(net)
|
||||
conf.RecordSuccess(net, cast.ToString(p.Start+p.Limit))
|
||||
resp, err := a.client.Get(url)
|
||||
if err != nil {
|
||||
conf.RecordFailure(net)
|
||||
@@ -245,9 +231,8 @@ func (a *aptos) versionParse(n any) {
|
||||
for _, trans := range gjson.ParseBytes(body).Array() {
|
||||
tsNano := trans.Get("timestamp").Int() * 1000
|
||||
timestamp := time.Unix(tsNano/1e9, tsNano%1e9)
|
||||
a.recordEarliestBlockTs(timestamp.Unix())
|
||||
|
||||
ver := trans.Get("version").Int()
|
||||
ver := int(trans.Get("version").Int())
|
||||
hash := trans.Get("hash").String()
|
||||
addrOwner := make(map[string]string) // [address] => owner address
|
||||
addrType := make(map[string]model.TradeType) // [address] => tradeType
|
||||
@@ -466,15 +451,3 @@ func (a *aptos) tradeConfirmHandle(ctx context.Context) {
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (a *aptos) recordEarliestBlockTs(unix int64) {
|
||||
for {
|
||||
current := a.earliestBlockTs.Load()
|
||||
if current != 0 && unix >= current {
|
||||
return
|
||||
}
|
||||
if a.earliestBlockTs.CompareAndSwap(current, unix) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,4 +23,5 @@ func arbitrumInit() {
|
||||
Register(Task{Callback: arb.blockDispatch})
|
||||
Register(Task{Callback: arb.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: arb.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: arb.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -23,4 +23,5 @@ func baseInit() {
|
||||
Register(Task{Callback: base.blockDispatch})
|
||||
Register(Task{Callback: base.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: base.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: base.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -29,4 +29,5 @@ func bscInit() {
|
||||
Register(Task{Callback: bsc.blockDispatch})
|
||||
Register(Task{Callback: bsc.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: bsc.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: bsc.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@ import (
|
||||
func ethInit() {
|
||||
ctx := context.Background()
|
||||
eth := evm{
|
||||
Network: conf.Ethereum,
|
||||
Network: conf.Ethereum,
|
||||
LookbackInterval: time.Second * 2,
|
||||
Block: block{
|
||||
ConfirmedOffset: 12,
|
||||
},
|
||||
@@ -29,4 +30,5 @@ func ethInit() {
|
||||
Register(Task{Callback: eth.blockDispatch})
|
||||
Register(Task{Callback: eth.syncBlocksForward, Duration: time.Second * 12})
|
||||
Register(Task{Callback: eth.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: eth.lookbackBlocks, Duration: time.Second * 20})
|
||||
}
|
||||
|
||||
+44
-58
@@ -8,7 +8,6 @@ import (
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -19,6 +18,7 @@ import (
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
blockapi "github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
@@ -33,7 +33,7 @@ var chainBlockNum sync.Map
|
||||
|
||||
type block struct {
|
||||
RollDelayOffset int64 // 延迟偏移量,某些RPC节点如果不延迟,会报错 block is out of range,目前发现 https://rpc.xlayer.tech/ 存在此问题
|
||||
ConfirmedOffset int64 // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
ConfirmedOffset int // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
}
|
||||
|
||||
type evmNative struct {
|
||||
@@ -43,12 +43,12 @@ type evmNative struct {
|
||||
}
|
||||
|
||||
type evm struct {
|
||||
Network string
|
||||
Block block
|
||||
Native evmNative
|
||||
Client *http.Client
|
||||
AvgBlockTime int64 // 平均出块时间,单位秒;一个大概值,用于计算首次启动时需要回溯的区块数量,尽量准确设置,默认1秒一个区块
|
||||
blockScanQueue *chanx.UnboundedChan[evmBlock]
|
||||
Network string
|
||||
Block block
|
||||
Native evmNative
|
||||
Client *http.Client
|
||||
blockScanQueue *chanx.UnboundedChan[evmBlock]
|
||||
LookbackInterval time.Duration // 回溯时每批入队的间隔,控制 RPC 调用速率;默认 500ms
|
||||
}
|
||||
|
||||
type evmBlock struct {
|
||||
@@ -102,10 +102,7 @@ func (e *evm) syncBlocksForward(ctx context.Context) {
|
||||
|
||||
var lastBlockNumber int64
|
||||
if v, ok := chainBlockNum.Load(e.Network); ok {
|
||||
|
||||
lastBlockNumber = v.(int64)
|
||||
} else {
|
||||
e.syncBlocksBackward(now) // 不存在,说明是第一次启动
|
||||
}
|
||||
|
||||
if now-lastBlockNumber > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
@@ -129,42 +126,38 @@ func (e *evm) syncBlocksForward(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *evm) syncBlocksBackward(now int64) {
|
||||
if e.AvgBlockTime <= 0 { // 未设置平均出块时间,默认1秒一个
|
||||
e.AvgBlockTime = 1
|
||||
}
|
||||
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(model.Network(e.Network))
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Order("created_at asc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
|
||||
func (e *evm) lookbackBlocks(ctx context.Context) {
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
sub := ((time.Now().Unix() - o.CreatedAt.Time().Unix()) / e.AvgBlockTime) + 30 //计算需要回溯的区块数量,同时冗余30个区块
|
||||
start := now - sub
|
||||
startAt, endAt, ok := getLookbackUnix(model.Network(e.Network))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
interval := e.LookbackInterval
|
||||
if interval <= 0 {
|
||||
interval = time.Millisecond * 300
|
||||
}
|
||||
|
||||
for from := start; from <= now; from += blockParseMaxNum {
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
to := from + blockParseMaxNum - 1
|
||||
if to > now {
|
||||
to = now
|
||||
}
|
||||
|
||||
e.blockScanQueue.In <- evmBlock{From: from, To: to}
|
||||
|
||||
<-ticker.C
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, e.Network)
|
||||
for i := start; i <= end; i += blockParseMaxNum {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
}()
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
return
|
||||
}
|
||||
to := i + blockParseMaxNum - 1
|
||||
if to > end {
|
||||
to = end
|
||||
}
|
||||
e.blockScanQueue.In <- evmBlock{From: i, To: to}
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *evm) blockDispatch(ctx context.Context) {
|
||||
@@ -235,7 +228,7 @@ func (e *evm) getBlockByNumber(a any) {
|
||||
return
|
||||
}
|
||||
|
||||
conf.RecordSuccess(e.Network)
|
||||
conf.RecordSuccess(e.Network, cast.ToString(b.To))
|
||||
|
||||
nativeTransfers := make([]transfer, 0)
|
||||
blockTimestamp := make(map[string]time.Time)
|
||||
@@ -256,7 +249,7 @@ func (e *evm) getBlockByNumber(a any) {
|
||||
var array = itm.Get("result.transactions").Array()
|
||||
if e.Native.Parse && len(array) != 0 {
|
||||
|
||||
nativeTransfers = append(nativeTransfers, e.parseNativeTransfer(array, utils.HexStr2Int(blockNumHex).Int64(), blockTime)...)
|
||||
nativeTransfers = append(nativeTransfers, e.parseNativeTransfer(array, int(utils.HexStr2Int(blockNumHex).Int64()), blockTime)...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +272,7 @@ func (e *evm) getBlockByNumber(a any) {
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(%s): %d → %d 成功率:%s", e.Network, b.From, b.To, conf.GetSuccessRate(e.Network)))
|
||||
}
|
||||
|
||||
func (e *evm) parseNativeTransfer(array []gjson.Result, num int64, timestamp time.Time) []transfer {
|
||||
func (e *evm) parseNativeTransfer(array []gjson.Result, num int, timestamp time.Time) []transfer {
|
||||
nativeTransfers := make([]transfer, 0)
|
||||
for _, tx := range array {
|
||||
if tx.Get("input").String() != "0x" {
|
||||
@@ -372,20 +365,13 @@ func (e *evm) parseEventTransfer(b evmBlock, timestamp map[string]time.Time) ([]
|
||||
continue
|
||||
}
|
||||
|
||||
blockNum, err := strconv.ParseInt(itm.Get("blockNumber").String(), 0, 64)
|
||||
if err != nil {
|
||||
log.Task.Warn("evmBlockParse Error parsing block number:", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: e.Network,
|
||||
FromAddress: from,
|
||||
RecvAddress: recv,
|
||||
Amount: decimal.NewFromBigInt(amount, model.GetContractDecimal(to)),
|
||||
TxHash: itm.Get("transactionHash").String(),
|
||||
BlockNum: blockNum,
|
||||
BlockNum: cast.ToInt(itm.Get("blockNumber").String()),
|
||||
Timestamp: timestamp[itm.Get("blockNumber").String()],
|
||||
TradeType: tradeType,
|
||||
})
|
||||
@@ -404,7 +390,7 @@ func (e *evm) tradeConfirmHandle(ctx context.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if last.(int64)-o.RefBlockNum < e.Block.ConfirmedOffset {
|
||||
if cast.ToInt(last)-o.RefBlockNum < e.Block.ConfirmedOffset {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -469,6 +455,10 @@ func syncBreak(network string, num int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
if mqttSubscribed(network) {
|
||||
return false
|
||||
}
|
||||
|
||||
trades := model.GetNetworkTrades(model.Network(network))
|
||||
if len(trades) == 0 {
|
||||
|
||||
@@ -484,9 +474,5 @@ func syncBreak(network string, num int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
model.Db.Model(&model.Order{}).
|
||||
Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trades).
|
||||
Count(&count)
|
||||
|
||||
return count == 0
|
||||
return !hasLookbackOrders(trades)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
appMqtt "github.com/v03413/bepusdt/app/mqtt"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
type mqttTransfer struct {
|
||||
Network string `json:"network"`
|
||||
TxHash string `json:"tx_hash"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
FromAddress string `json:"from_address"`
|
||||
RecvAddress string `json:"recv_address"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
TradeType model.TradeType `json:"trade_type"`
|
||||
BlockNum int `json:"block_num"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(Task{Duration: time.Second * 5, Callback: mqttWatcher})
|
||||
}
|
||||
|
||||
func mqttWatcher(_ context.Context) {
|
||||
if err := appMqtt.Reload(); err != nil {
|
||||
log.Printf("❌ MQTT 连接失败: %s\n", err.Error())
|
||||
}
|
||||
|
||||
networks := strings.Split(model.GetC(model.MqttNetworks), ",")
|
||||
for _, n := range networks {
|
||||
cache.Set("mqtt_subscribed_"+n, true, time.Second*8)
|
||||
}
|
||||
}
|
||||
|
||||
func mqttPublish(t transfer) {
|
||||
if !mqttSubscribed(t.Network) {
|
||||
return
|
||||
}
|
||||
|
||||
var qos = cast.ToUint8(model.GetC(model.MqttPublishQos))
|
||||
var topic = model.GetC(model.MqttTopicPrefix) + "/transfer/" + t.Network
|
||||
var data = mqttTransfer{
|
||||
Network: t.Network,
|
||||
TxHash: t.TxHash,
|
||||
Amount: t.Amount,
|
||||
FromAddress: t.FromAddress,
|
||||
RecvAddress: t.RecvAddress,
|
||||
Timestamp: t.Timestamp.Unix(),
|
||||
TradeType: t.TradeType,
|
||||
BlockNum: t.BlockNum,
|
||||
}
|
||||
go func() {
|
||||
payload, _ := json.Marshal(data)
|
||||
|
||||
appMqtt.Publish(topic, qos, false, payload)
|
||||
}()
|
||||
}
|
||||
|
||||
func mqttSubscribed(n string) bool {
|
||||
_, found := cache.Get("mqtt_subscribed_" + n)
|
||||
return found
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notifier"
|
||||
"github.com/v03413/bepusdt/app/task/notify"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
)
|
||||
@@ -37,3 +38,9 @@ func notifyRoll(context.Context) {
|
||||
notify.Bepusdt(o)
|
||||
}
|
||||
}
|
||||
|
||||
// notifyOrderSuccess 统一触发订单成功后的回调与订单通知。
|
||||
func notifyOrderSuccess(order model.Order) {
|
||||
go notify.Handle(order)
|
||||
go notifier.Success(order)
|
||||
}
|
||||
|
||||
+72
-81
@@ -12,13 +12,13 @@ import (
|
||||
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
epay2 "github.com/v03413/bepusdt/app/handler/epay"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notifier"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
|
||||
"github.com/v03413/go-cache"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type EpNotify struct {
|
||||
@@ -59,7 +59,7 @@ func Handle(order model.Order) error {
|
||||
|
||||
func epay(ctx context.Context, order model.Order) error {
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var notifyUrl = fmt.Sprintf("%s?%s", order.NotifyUrl, epay2.BuildNotifyParams(order))
|
||||
var notifyUrl = fmt.Sprintf("%s?%s", order.NotifyUrl, order.BuildNotifyParams())
|
||||
|
||||
postReq, err2 := http.NewRequestWithContext(ctx, "GET", notifyUrl, nil)
|
||||
if err2 != nil {
|
||||
@@ -161,95 +161,86 @@ func epusdt(ctx context.Context, order model.Order) error {
|
||||
}
|
||||
|
||||
func Bepusdt(o model.Order) {
|
||||
if o.ApiType != model.OrderApiTypeEpusdt {
|
||||
if o.ApiType != model.OrderApiTypeEpusdt && o.ApiType != model.OrderApiTypeEpusdtOrder {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var todo = func() error {
|
||||
var db = model.Db.Begin()
|
||||
if err := db.Where("trade_id = ? and status = ?", o.TradeId, o.Status).Limit(1).Find(&o).Error; err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var key = fmt.Sprintf("bepusdt_notify_%d_%s", o.Status, o.TradeId)
|
||||
if _, ok := cache.Get(key); ok {
|
||||
db.Rollback()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
cache.Set(key, true, time.Minute)
|
||||
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: o.TradeId,
|
||||
OrderId: o.OrderId,
|
||||
Amount: cast.ToFloat64(o.Money),
|
||||
ActualAmount: o.Amount,
|
||||
Token: o.Address,
|
||||
BlockTransactionId: o.RefHash,
|
||||
Status: o.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = utils.EpusdtSign(data, model.AuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, _ = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var req, err2 = http.NewRequest("POST", o.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err2
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://github.com/v03413/BEpusdt")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
db.Rollback()
|
||||
|
||||
return fmt.Errorf("resp.StatusCode != 200")
|
||||
}
|
||||
|
||||
all, _ := io.ReadAll(resp.Body)
|
||||
|
||||
log.Info(fmt.Sprintf("订单回调成功[%d]:%s %s", o.Status, o.TradeId, string(all)))
|
||||
|
||||
db.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
var authToken = model.AuthToken()
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
go func() {
|
||||
if err := todo(); err != nil {
|
||||
if err := deliverBepusdtStatusUpdate(model.Db, client, authToken, o); err != nil {
|
||||
log.Warn("notify BEpusdt Error:", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken string, o model.Order) error {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: time.Second * 5}
|
||||
}
|
||||
|
||||
var current model.Order
|
||||
tx := db.Where("trade_id = ? and status = ?", o.TradeId, o.Status).Limit(1).Find(¤t)
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var key = fmt.Sprintf("bepusdt_notify_%d_%s", current.Status, current.TradeId)
|
||||
if _, ok := cache.Get(key); ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
cache.Set(key, true, time.Minute)
|
||||
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: current.TradeId,
|
||||
OrderId: current.OrderId,
|
||||
Amount: cast.ToFloat64(current.Money),
|
||||
ActualAmount: current.Amount,
|
||||
Token: current.Address,
|
||||
BlockTransactionId: current.RefHash,
|
||||
Status: current.Status,
|
||||
}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body.Signature = utils.EpusdtSign(data, authToken)
|
||||
|
||||
jsonBody, _ = json.Marshal(body)
|
||||
req, err := http.NewRequest("POST", current.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://github.com/v03413/BEpusdt")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("resp.StatusCode != 200")
|
||||
}
|
||||
|
||||
all, _ := io.ReadAll(resp.Body)
|
||||
log.Info(fmt.Sprintf("订单回调成功[%d]:%s %s", current.Status, current.TradeId, string(all)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func markNotifyFail(o model.Order, reason string) {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):%s %v", o.TradeId, reason, o.SetNotifyState(model.OrderNotifyStateFail)))
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
applog "github.com/v03413/bepusdt/app/log"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newNotifyTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
dbPath := filepath.Join(t.TempDir(), "notify-test.db")
|
||||
db, err := gorm.Open(sqlite.Open(dbPath+"?cache=shared&mode=rwc&_pragma=journal_mode(WAL)&_pragma=busy_timeout(1000)"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open test db: %v", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get sql db: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
sqlDB.SetMaxIdleConns(1)
|
||||
|
||||
if err := db.AutoMigrate(&model.Order{}); err != nil {
|
||||
t.Fatalf("auto migrate order: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func initNotifyTestLog(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if err := applog.Init(filepath.Join(t.TempDir(), "logs")); err != nil {
|
||||
t.Fatalf("init log: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
applog.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func newWaitingOrder(notifyURL string) model.Order {
|
||||
now := time.Now()
|
||||
confirmedAt := now
|
||||
|
||||
return model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdtTrc20,
|
||||
Fiat: "CNY",
|
||||
Crypto: "USDT",
|
||||
Rate: "7.00",
|
||||
Amount: "1.00",
|
||||
Money: "7.00",
|
||||
Address: "TTestAddress1234567890",
|
||||
Status: model.OrderStatusWaiting,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
NotifyUrl: notifyURL,
|
||||
ExpiredAt: now.Add(10 * time.Minute),
|
||||
ConfirmedAt: &confirmedAt,
|
||||
AutoTimeAt: model.AutoTimeAt{CreatedAt: (*model.Datetime)(&now), UpdatedAt: (*model.Datetime)(&now)},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverBepusdtStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T) {
|
||||
db := newNotifyTestDB(t)
|
||||
initNotifyTestLog(t)
|
||||
|
||||
requestStarted := make(chan struct{}, 1)
|
||||
releaseResponse := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestStarted <- struct{}{}
|
||||
<-releaseResponse
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
order := newWaitingOrder(server.URL)
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatalf("seed order: %v", err)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- deliverBepusdtStatusUpdate(db, &http.Client{Timeout: 2 * time.Second}, "test-auth-token", order)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-requestStarted:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("notification request never reached test server")
|
||||
}
|
||||
|
||||
queryDone := make(chan error, 1)
|
||||
go func() {
|
||||
var count int64
|
||||
queryDone <- db.Model(&model.Order{}).Where("status = ?", model.OrderStatusWaiting).Count(&count).Error
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-queryDone:
|
||||
if err != nil {
|
||||
t.Fatalf("concurrent query failed: %v", err)
|
||||
}
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
close(releaseResponse)
|
||||
<-errCh
|
||||
t.Fatal("database query was blocked while notification HTTP request was in flight")
|
||||
}
|
||||
|
||||
close(releaseResponse)
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatalf("deliver notification: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -23,4 +23,5 @@ func plasmaInit() {
|
||||
Register(Task{Callback: xpl.blockDispatch})
|
||||
Register(Task{Callback: xpl.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: xpl.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: xpl.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -23,4 +23,5 @@ func polygonInit() {
|
||||
Register(Task{Callback: pol.blockDispatch})
|
||||
Register(Task{Callback: pol.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: pol.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: pol.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
func init() {
|
||||
var rate = Rate{}
|
||||
|
||||
Register(Task{Duration: time.Hour, Callback: rate.Clear})
|
||||
Register(Task{Duration: time.Second * 5, Callback: rate.Sync})
|
||||
}
|
||||
|
||||
@@ -34,3 +35,13 @@ func (Rate) Sync(ctx context.Context) {
|
||||
log.Warn(fmt.Sprintf("同步汇率失败: %s", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func (Rate) Clear(ctx context.Context) {
|
||||
days := cast.ToInt(model.GetC(model.RateSyncHistoryDays))
|
||||
if days <= 0 {
|
||||
days = 1
|
||||
}
|
||||
|
||||
createdAt := time.Now().AddDate(0, 0, -days)
|
||||
model.Db.Where("created_at < ?", createdAt).Delete(&model.Rate{})
|
||||
}
|
||||
|
||||
+319
-147
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
blockapi "github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
@@ -28,10 +29,18 @@ import (
|
||||
// - https://github.com/solana-program/token/blob/6d18ff73b1dd30703a30b1ca941cb0f1d18c2b2a/program/src/instruction.rs
|
||||
|
||||
type solana struct {
|
||||
slotConfirmedOffset int64
|
||||
lastSlotNum int64
|
||||
slotQueue *chanx.UnboundedChan[int64]
|
||||
slotConfirmedOffset int
|
||||
lastSlotNum int
|
||||
forwardIdle bool // 因没有待支付订单而暂停了向前扫描
|
||||
slotQueue *chanx.UnboundedChan[int]
|
||||
client *http.Client
|
||||
retryMu sync.Mutex
|
||||
retryAttempts map[int]int
|
||||
retryScheduled map[int]*time.Timer
|
||||
lookbackMu sync.Mutex
|
||||
lookbackNext int
|
||||
lookbackEnd int
|
||||
lookbackOrderIDs []int64
|
||||
}
|
||||
|
||||
type solanaTokenOwner struct {
|
||||
@@ -46,20 +55,34 @@ func init() {
|
||||
Register(Task{Callback: sol.slotDispatch})
|
||||
Register(Task{Callback: sol.syncSlotForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: sol.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: sol.lookbackSlots, Duration: time.Second * 15})
|
||||
Register(Task{Callback: sol.reconcileExpiredOrders, Duration: time.Minute})
|
||||
}
|
||||
|
||||
func newSolana() solana {
|
||||
return solana{
|
||||
slotConfirmedOffset: 60,
|
||||
lastSlotNum: 0,
|
||||
slotQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
slotQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
|
||||
client: utils.NewHttpClient(),
|
||||
retryAttempts: make(map[int]int),
|
||||
retryScheduled: make(map[int]*time.Timer),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
if syncBreak(conf.Solana, s.slotQueue.Len()) {
|
||||
func solanaGetBlockPayload(slot int) []byte {
|
||||
return []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":1,"transactionDetails":"full","rewards":false}]}`, slot))
|
||||
}
|
||||
|
||||
func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
if queued := s.slotQueue.Len(); syncBreak(conf.Solana, queued) {
|
||||
if queued < blockQueueLimit {
|
||||
s.forwardIdle = true
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if s.pendingSlotRetryCount() > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -88,67 +111,32 @@ func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "result").Int()
|
||||
now := int(gjson.GetBytes(body, "result").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncSlotForward Error: invalid slot number:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if s.lastSlotNum == 0 { // 首次启动,往后追溯
|
||||
s.syncSlotBackward(now)
|
||||
}
|
||||
|
||||
if now-s.lastSlotNum > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) { // 区块高度变化过大,强制丢块重扫
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
if now == s.lastSlotNum { // 区块高度没有变化
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for n := s.lastSlotNum + 1; n <= now; n++ {
|
||||
// 待扫描区块入列
|
||||
|
||||
s.slotQueue.In <- n
|
||||
}
|
||||
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
func (s *solana) syncSlotBackward(now int64) {
|
||||
if now == 0 || s.lastSlotNum != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(conf.Solana)
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Order("created_at asc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Solana 大概1秒3个区块(大概值,实际存在波动)
|
||||
num := (time.Now().Unix() - o.CreatedAt.Time().Unix() + 1) * 3 // 计算需要反向扫描的区块数量
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Millisecond * 125)
|
||||
defer ticker.Stop()
|
||||
|
||||
for i := int64(0); i < num; i++ {
|
||||
if syncBreak(conf.Solana, s.slotQueue.Len()) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
s.slotQueue.In <- now - i
|
||||
|
||||
<-ticker.C
|
||||
if lag := now - s.lastSlotNum; lag > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
if s.lastSlotNum == 0 || s.forwardIdle { // 启动或空闲后恢复扫描:直接从最新高度开始
|
||||
s.lastSlotNum = now
|
||||
} else { // 扫描期间落后:继续追赶,不能跳过,其中可能有付款
|
||||
log.Task.Warn(fmt.Sprintf("Solana 扫描落后 %d 个 slot,继续追赶", lag))
|
||||
}
|
||||
}()
|
||||
}
|
||||
s.forwardIdle = false
|
||||
|
||||
if now <= s.lastSlotNum { // 区块高度没有变化或节点返回旧高度
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 只填充队列的可用容量;消费后由下一轮继续追赶,避免长时间故障恢复时瞬间过度扫描。
|
||||
for n := s.lastSlotNum + 1; n <= now && s.slotQueue.Len() < blockQueueLimit; n++ {
|
||||
s.slotQueue.In <- n
|
||||
s.lastSlotNum = n
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) slotDispatch(ctx context.Context) {
|
||||
@@ -179,14 +167,14 @@ func (s *solana) slotDispatch(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *solana) slotParse(n any) {
|
||||
slot := n.(int64)
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":0,"transactionDetails":"full","rewards":false}]}`, slot))
|
||||
slot := n.(int)
|
||||
post := solanaGetBlockPayload(slot)
|
||||
network := conf.Solana
|
||||
|
||||
conf.RecordSuccess(network)
|
||||
resp, err := s.client.Post(model.Endpoint(conf.Solana), "application/json", bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error sending request:", err)
|
||||
|
||||
return
|
||||
@@ -195,6 +183,7 @@ func (s *solana) slotParse(n any) {
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
@@ -203,65 +192,108 @@ func (s *solana) slotParse(n any) {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.slotQueue.In <- slot
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Unix(gjson.GetBytes(body, "result.blockTime").Int(), 0)
|
||||
result, err := validateSolanaBlockResponse(body)
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error JSON-RPC response:", err)
|
||||
|
||||
for _, trans := range gjson.GetBytes(body, "result.transactions").Array() {
|
||||
hash := trans.Get("transaction.signatures.0").String()
|
||||
return
|
||||
}
|
||||
|
||||
// 解析账号索引
|
||||
accountKeys := make([]string, 0)
|
||||
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
|
||||
conf.RecordSuccess(network, cast.ToString(slot))
|
||||
s.resetSlotRetry(slot)
|
||||
if result.Type == gjson.Null {
|
||||
log.Task.Info(fmt.Sprintf("区块已跳过(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Unix(result.Get("blockTime").Int(), 0)
|
||||
|
||||
for _, trans := range result.Get("transactions").Array() {
|
||||
if transfers := s.parseTransaction(trans, slot, timestamp); len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
|
||||
}
|
||||
|
||||
// parseTransaction 解析单笔交易中的 USDT/USDC 转账;getBlock 返回的交易项与 getTransaction 的结果结构相同,都可以传入
|
||||
func (s *solana) parseTransaction(trans gjson.Result, slot int, timestamp time.Time) []transfer {
|
||||
if !solanaTxSucceeded(trans.Get("meta.err")) {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
hash := trans.Get("transaction.signatures.0").String()
|
||||
|
||||
// 解析账号索引
|
||||
accountKeys := make([]string, 0)
|
||||
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
for _, v := range []string{"readonly", "writable"} {
|
||||
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
for _, v := range []string{"readonly", "writable"} {
|
||||
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
|
||||
// 查找SPL Token索引
|
||||
splTokenIndex := int64(-1)
|
||||
for i, v := range accountKeys {
|
||||
if v == conf.SolSplToken {
|
||||
splTokenIndex = int64(i)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// SPL Token的Mint地址,即不包含 Token 交易信息
|
||||
if splTokenIndex == -1 {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解析 Token 账户 【Token Wallet => Owner Wallet】
|
||||
tokenAccountMap := make(map[string]solanaTokenOwner)
|
||||
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
|
||||
for _, itm := range trans.Get("meta." + v).Array() {
|
||||
tradeType, ok := model.GetContractTrade(itm.Get("mint").String())
|
||||
if !ok || itm.Get("programId").String() != conf.SolSplToken {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
tokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = solanaTokenOwner{
|
||||
TradeType: tradeType,
|
||||
Address: itm.Get("owner").String(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 查找SPL Token索引
|
||||
splTokenIndex := int64(-1)
|
||||
for i, v := range accountKeys {
|
||||
if v == conf.SolSplToken {
|
||||
splTokenIndex = int64(i)
|
||||
transArr := make([]transfer, 0)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// SPL Token的Mint地址,即不包含 Token 交易信息
|
||||
if splTokenIndex == -1 {
|
||||
// 解析外部指令
|
||||
for _, instr := range trans.Get("transaction.message.instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析 Token 账户 【Token Wallet => Owner Wallet】
|
||||
tokenAccountMap := make(map[string]solanaTokenOwner)
|
||||
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
|
||||
for _, itm := range trans.Get("meta." + v).Array() {
|
||||
tradeType, ok := model.GetContractTrade(itm.Get("mint").String())
|
||||
if !ok || itm.Get("programId").String() != conf.SolSplToken {
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
tokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = solanaTokenOwner{
|
||||
TradeType: tradeType,
|
||||
Address: itm.Get("owner").String(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transArr := make([]transfer, 0)
|
||||
|
||||
// 解析外部指令
|
||||
for _, instr := range trans.Get("transaction.message.instructions").Array() {
|
||||
// 解析内部指令
|
||||
for _, itm := range trans.Get("meta.innerInstructions").Array() {
|
||||
for _, instr := range itm.Get("instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
@@ -269,41 +301,136 @@ func (s *solana) slotParse(n any) {
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
|
||||
}
|
||||
|
||||
// 解析内部指令
|
||||
for _, itm := range trans.Get("meta.innerInstructions").Array() {
|
||||
for _, instr := range itm.Get("instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤无关交易
|
||||
result := make([]transfer, 0)
|
||||
for _, t := range transArr {
|
||||
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
t.TxHash = hash
|
||||
t.Network = conf.Solana
|
||||
t.BlockNum = slot
|
||||
t.Timestamp = timestamp
|
||||
|
||||
result = append(result, t)
|
||||
}
|
||||
|
||||
if len(result) > 0 {
|
||||
transferQueue.In <- result
|
||||
}
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
|
||||
// 过滤无关交易
|
||||
result := make([]transfer, 0)
|
||||
for _, t := range transArr {
|
||||
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
t.TxHash = hash
|
||||
t.Network = conf.Solana
|
||||
t.BlockNum = slot
|
||||
t.Timestamp = timestamp
|
||||
|
||||
result = append(result, t)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 执行失败的交易同样会被打包进区块,指令和代币余额也照常保留,但转账已经回滚;只有 err 为 null 才算执行成功
|
||||
func solanaTxSucceeded(err gjson.Result) bool {
|
||||
return err.Exists() && err.Type == gjson.Null
|
||||
}
|
||||
|
||||
// getSignatureStatuses 对执行失败的交易同样返回 finalized,必须同时检查 err
|
||||
func solanaSignatureFinalized(status gjson.Result) bool {
|
||||
return status.Get("confirmationStatus").String() == "finalized" && solanaTxSucceeded(status.Get("err"))
|
||||
}
|
||||
|
||||
// Solana JSON-RPC 错误码,参考 https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs
|
||||
const (
|
||||
solanaErrSlotSkipped = -32007
|
||||
solanaErrLongTermStorageSlotSkipped = -32009
|
||||
)
|
||||
|
||||
func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
|
||||
if !gjson.ValidBytes(body) {
|
||||
return gjson.Result{}, fmt.Errorf("invalid JSON response")
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if rpcErr := data.Get("error"); rpcErr.Exists() {
|
||||
switch rpcErr.Get("code").Int() {
|
||||
case solanaErrSlotSkipped, solanaErrLongTermStorageSlotSkipped: // 被跳过的 slot 没有区块,按空 slot 处理
|
||||
return gjson.Result{Type: gjson.Null}, nil
|
||||
}
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("RPC error: %s", rpcErr.Raw)
|
||||
}
|
||||
|
||||
result := data.Get("result")
|
||||
if !result.Exists() {
|
||||
return gjson.Result{}, fmt.Errorf("missing result")
|
||||
}
|
||||
if result.Type != gjson.Null && !result.Get("transactions").Exists() {
|
||||
return gjson.Result{}, fmt.Errorf("missing result.transactions")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *solana) scheduleSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
if _, ok := s.retryScheduled[slot]; ok {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
attempt := s.retryAttempts[slot] + 1
|
||||
if attempt > solanaSlotMaxRetries { // 放弃该 slot,否则向前扫描会一直暂停
|
||||
delete(s.retryAttempts, slot)
|
||||
s.retryMu.Unlock()
|
||||
log.Task.Error(fmt.Sprintf("Solana slot %d 连续 %d 次扫描失败,已放弃,该 slot 内的付款需要人工核对", slot, solanaSlotMaxRetries))
|
||||
|
||||
return
|
||||
}
|
||||
s.retryAttempts[slot] = attempt
|
||||
|
||||
// 待重试的 slot 数量有限,到期直接入队;不再因队列堆积而延后,否则堆积会被计为失败次数
|
||||
var timer *time.Timer
|
||||
timer = time.AfterFunc(solanaRetryDelay(attempt), func() {
|
||||
s.retryMu.Lock()
|
||||
if s.retryScheduled[slot] != timer {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
delete(s.retryScheduled, slot)
|
||||
s.retryMu.Unlock()
|
||||
|
||||
s.slotQueue.In <- slot
|
||||
})
|
||||
s.retryScheduled[slot] = timer
|
||||
s.retryMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *solana) resetSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
delete(s.retryAttempts, slot)
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) pendingSlotRetryCount() int {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
return len(s.retryAttempts)
|
||||
}
|
||||
|
||||
// 单个 slot 最多重试 10 次,按 solanaRetryDelay 约 7 分钟
|
||||
const solanaSlotMaxRetries = 10
|
||||
|
||||
func solanaRetryDelay(attempt int) time.Duration {
|
||||
delays := [...]time.Duration{2 * time.Second, 5 * time.Second, 15 * time.Second, 30 * time.Second, time.Minute}
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
if attempt > len(delays) {
|
||||
attempt = len(delays)
|
||||
}
|
||||
|
||||
return delays[attempt-1]
|
||||
}
|
||||
|
||||
func (s *solana) parseTransfer(instr gjson.Result, accountKeys []string, tokenAccountMap map[string]solanaTokenOwner) transfer {
|
||||
@@ -361,15 +488,6 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var handle = func(o model.Order) {
|
||||
if model.GetC(model.BlockOffsetConfirm) == "1" {
|
||||
if s.lastSlotNum == 0 {
|
||||
return
|
||||
}
|
||||
if s.lastSlotNum-o.RefBlockNum < s.slotConfirmedOffset {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getSignatureStatuses","params":[["%s"],{"searchTransactionHistory":true}]}`, o.RefHash))
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
|
||||
resp, err := s.client.Do(req)
|
||||
@@ -401,7 +519,13 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if data.Get("result.value.0.confirmationStatus").String() == "finalized" {
|
||||
// 用同一响应里节点当前的 slot 计算确认数,不依赖向前扫描进度:扫描在没有待支付订单时会暂停,重启后为 0
|
||||
if model.GetC(model.BlockOffsetConfirm) == "1" && data.Get("result.context.slot").Int()-int64(o.RefBlockNum) < int64(s.slotConfirmedOffset) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if solanaSignatureFinalized(data.Get("result.value.0")) {
|
||||
|
||||
markFinalConfirmed(o)
|
||||
}
|
||||
@@ -418,3 +542,51 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (s *solana) lookbackSlots(ctx context.Context) {
|
||||
if syncBreak(conf.Solana, s.slotQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
s.lookbackMu.Lock()
|
||||
defer s.lookbackMu.Unlock()
|
||||
|
||||
if s.lookbackNext == 0 {
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Solana)
|
||||
if !validSolanaLookbackRange(start, end) {
|
||||
log.Task.Warn("Solana 回溯区块范围无效,稍后重试:", start, "-", end)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
s.lookbackNext = int(start)
|
||||
s.lookbackEnd = int(end)
|
||||
s.lookbackOrderIDs = orderIDs
|
||||
}
|
||||
|
||||
for s.lookbackNext <= s.lookbackEnd && s.slotQueue.Len() < blockQueueLimit {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.slotQueue.In <- s.lookbackNext
|
||||
s.lookbackNext++
|
||||
}
|
||||
|
||||
if s.lookbackNext > s.lookbackEnd {
|
||||
markLookbackDone(s.lookbackOrderIDs)
|
||||
s.lookbackNext = 0
|
||||
s.lookbackEnd = 0
|
||||
s.lookbackOrderIDs = nil
|
||||
}
|
||||
}
|
||||
|
||||
func validSolanaLookbackRange(start, end int64) bool {
|
||||
return start > 0 && end >= start
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func TestSolanaConfirmOffsetUsesRPCSlot(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
confirmations int
|
||||
want int
|
||||
}{
|
||||
{name: "enough confirmations", confirmations: 100, want: model.OrderStatusSuccess},
|
||||
{name: "waiting for confirmations", confirmations: 25, want: model.OrderStatusConfirming},
|
||||
}
|
||||
|
||||
const slot = 451914288
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
// 主网 getSignatureStatuses 对该交易的真实返回,只改 context.slot
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, slot+tt.confirmations, slot)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockOffsetConfirm: "1"})
|
||||
|
||||
order := createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "390.990618",
|
||||
Money: "2736.93",
|
||||
Address: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe",
|
||||
Status: model.OrderStatusConfirming,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
NotifyUrl: srv.URL + "/notify",
|
||||
RefHash: "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6",
|
||||
RefBlockNum: slot,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
|
||||
s := newSolana() // lastSlotNum 为 0,相当于重启后或扫描已暂停
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId).Status; got != tt.want {
|
||||
t.Fatalf("order status = %d, want %d", got, tt.want)
|
||||
}
|
||||
if tt.want == model.OrderStatusSuccess {
|
||||
waitOrderNotified(t, order.TradeId)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func scanSolanaTestBlock(t *testing.T, block []byte) []transfer {
|
||||
t.Helper()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(block)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
s := newSolana()
|
||||
s.slotParse(solanaFixtureSlot(block))
|
||||
|
||||
return drainTransferQueue()
|
||||
}
|
||||
|
||||
func TestSolanaTxSucceeded(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tx string
|
||||
want bool
|
||||
}{
|
||||
{name: "succeeded", tx: `{"meta":{"err":null}}`, want: true},
|
||||
{name: "instruction error", tx: `{"meta":{"err":{"InstructionError":[1,{"Custom":6001}]}}}`},
|
||||
{name: "missing err", tx: `{"meta":{}}`},
|
||||
{name: "missing meta", tx: `{"meta":null}`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := solanaTxSucceeded(gjson.Get(tt.tx, "meta.err")); got != tt.want {
|
||||
t.Fatalf("solanaTxSucceeded = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotParseSkipsFailedTransactions(t *testing.T) {
|
||||
tests := []struct {
|
||||
fixture string
|
||||
// 把 meta.err 改为 null 后应解析出的转账数,证明没有转账只是因为交易失败
|
||||
transfersIfSucceeded int
|
||||
}{
|
||||
{fixture: "failed_v1_transfer.json", transfersIfSucceeded: 3},
|
||||
{fixture: "failed_v0_inner_transfer.json", transfersIfSucceeded: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.fixture, func(t *testing.T) {
|
||||
block := readSolanaFixture(t, tt.fixture)
|
||||
if got := scanSolanaTestBlock(t, block); len(got) != 0 {
|
||||
t.Fatalf("failed transaction produced %d transfers: %+v", len(got), got)
|
||||
}
|
||||
|
||||
errRaw := gjson.GetBytes(block, "result.transactions.0.meta.err").Raw
|
||||
succeeded := bytes.Replace(block, []byte(`"err":`+errRaw), []byte(`"err":null`), 1)
|
||||
if bytes.Equal(succeeded, block) {
|
||||
t.Fatalf("fixture has no meta.err to clear")
|
||||
}
|
||||
if got := scanSolanaTestBlock(t, succeeded); len(got) != tt.transfersIfSucceeded {
|
||||
t.Fatalf("transfers = %d, want %d", len(got), tt.transfersIfSucceeded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotParseKeepsSucceededTransactions(t *testing.T) {
|
||||
got := scanSolanaTestBlock(t, readSolanaFixture(t, "success_v0_inner_transfer.json"))
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("transfers = %d, want 1", len(got))
|
||||
}
|
||||
|
||||
tr := got[0]
|
||||
if tr.TxHash != "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6" ||
|
||||
tr.TradeType != model.UsdcSolana ||
|
||||
tr.RecvAddress != "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe" ||
|
||||
tr.Amount.String() != "390.990618" {
|
||||
t.Fatalf("unexpected transfer: %+v", tr)
|
||||
}
|
||||
}
|
||||
|
||||
// 主网 getSignatureStatuses 的真实返回
|
||||
const (
|
||||
solanaFailedSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":{"InstructionError":[1,{"Custom":6001}]},"slot":458281527,"status":{"Err":{"InstructionError":[1,{"Custom":6001}]}}}`
|
||||
solanaSucceededSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":451914288,"status":{"Ok":null}}`
|
||||
)
|
||||
|
||||
func TestSolanaSignatureFinalized(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
want bool
|
||||
}{
|
||||
{name: "finalized", status: solanaSucceededSignatureStatus, want: true},
|
||||
{name: "finalized but failed", status: solanaFailedSignatureStatus},
|
||||
{name: "confirmed", status: `{"confirmationStatus":"confirmed","confirmations":12,"err":null,"slot":451914288,"status":{"Ok":null}}`},
|
||||
{name: "not found", status: `null`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := solanaSignatureFinalized(gjson.Parse(tt.status)); got != tt.want {
|
||||
t.Fatalf("solanaSignatureFinalized = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaTradeConfirmIgnoresFailedTransaction(t *testing.T) {
|
||||
var notified atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
notified.Store(true)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":458281967},"value":[%s]},"id":1}`, solanaFailedSignatureStatus)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
order := createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "225.966818",
|
||||
Money: "1581.77",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: model.OrderStatusConfirming,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
NotifyUrl: srv.URL + "/notify",
|
||||
RefHash: "53bZ2UeqMGryYjbjKgB2nAo8umAMsPTP4dzBhR94SdV7f4YaxDvWqEdL5WQ46JSHsmLph3hBmEdHzTMdnYKMsbRz",
|
||||
RefBlockNum: 458281527,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
|
||||
s := newSolana()
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
|
||||
t.Fatalf("order status = %d after failed transaction, want confirming", got.Status)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if notified.Load() {
|
||||
t.Fatalf("callback sent for failed transaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func newSolanaSlotTestServer(t *testing.T, head *atomic.Int64) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":%d,"id":1}`, head.Load())
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
func createSolanaWaitingOrder(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "1.23",
|
||||
Money: "8.61",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: model.OrderStatusWaiting,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
}
|
||||
|
||||
// 落后阈值设为 10,用 20 个 slot 的落后量验证,队列不会超过 chanx 的初始容量
|
||||
const solanaTestMaxDiff = 10
|
||||
|
||||
func TestSolanaForwardCatchesUpWhileOrdersActive(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
head.Store(last + 2*solanaTestMaxDiff)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last+2*solanaTestMaxDiff {
|
||||
t.Fatalf("lastSlotNum = %d, want %d", s.lastSlotNum, last+2*solanaTestMaxDiff)
|
||||
}
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != last+1 {
|
||||
t.Fatalf("first queued slot = %d, want %d: slots were skipped", got, last+1)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("no slot queued: slots %d-%d were skipped", last+1, last+2*solanaTestMaxDiff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaForwardSkipsAfterIdle(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
head.Store(last + 2*solanaTestMaxDiff)
|
||||
s.syncSlotForward(t.Context()) // 没有订单,暂停扫描
|
||||
if s.lastSlotNum != last {
|
||||
t.Fatalf("lastSlotNum = %d while idle, want %d", s.lastSlotNum, last)
|
||||
}
|
||||
|
||||
createSolanaWaitingOrder(t)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != last+2*solanaTestMaxDiff || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to %d after idle", s.lastSlotNum, s.slotQueue.Len(), last+2*solanaTestMaxDiff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaForwardSkipsOnStartup(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
s := newSolana()
|
||||
head.Store(458000000)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != 458000000 || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to the latest slot on startup", s.lastSlotNum, s.slotQueue.Len())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
// 预期结果由独立的解码脚本从主网交易得出:只统计两端代币账户都在 token balances 中的 USDT/USDC transfer、transferChecked
|
||||
func TestSolanaParseTransactionMainnetFixtures(t *testing.T) {
|
||||
type want struct {
|
||||
from, to, amount string
|
||||
tradeType model.TradeType
|
||||
}
|
||||
tests := []struct {
|
||||
fixture string
|
||||
want []want
|
||||
}{
|
||||
{fixture: "success_legacy_transfer.json", want: []want{
|
||||
{from: "218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn", to: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", amount: "5.36", tradeType: model.UsdtSolana},
|
||||
}},
|
||||
{fixture: "success_legacy_transfer_checked.json", want: []want{
|
||||
{from: "8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH", to: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", amount: "0.0024", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_transfer_creates_token_account.json", want: []want{ // 同一笔交易里先创建收款方代币账户(非 ATA)
|
||||
{from: "Bj7j6d8sybC7rLTmGMCB4K4p6yC1v4RQvdAptDzTiURv", to: "8YKSSNbwE72ftktZS3V1NXvd8ekHzVfLk7GkBsvy8E2i", amount: "2560.021449", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_v0_inner_transfer.json", want: []want{ // 地址查找表 + 内部指令
|
||||
{from: "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC", to: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe", amount: "390.990618", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_v1_transfer.json", want: []want{
|
||||
{from: "2LAYGGSiF3QfyQEG1Gb3UGAsuzvD21zjHEW88v2XZ7cW", to: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", amount: "103.347262", tradeType: model.UsdcSolana},
|
||||
{from: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", to: "6EVgUURuvprazVdpd717E9uqruHcqRPbhRKDm5Czdidu", amount: "103.347262", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "failed_v1_transfer.json"},
|
||||
{fixture: "failed_v0_inner_transfer.json"},
|
||||
}
|
||||
|
||||
s := &solana{}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.fixture, func(t *testing.T) {
|
||||
block := readSolanaFixture(t, tt.fixture)
|
||||
trans := gjson.GetBytes(block, "result.transactions.0")
|
||||
slot := solanaFixtureSlot(block)
|
||||
timestamp := time.Unix(gjson.GetBytes(block, "result.blockTime").Int(), 0)
|
||||
|
||||
got := s.parseTransaction(trans, slot, timestamp)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("transfers = %d, want %d: %+v", len(got), len(tt.want), got)
|
||||
}
|
||||
for i, w := range tt.want {
|
||||
g := got[i]
|
||||
if g.FromAddress != w.from || g.RecvAddress != w.to || g.Amount.String() != w.amount || g.TradeType != w.tradeType {
|
||||
t.Fatalf("transfer %d = %s -> %s %s %s, want %s -> %s %s %s", i, g.FromAddress, g.RecvAddress, g.Amount, g.TradeType, w.from, w.to, w.amount, w.tradeType)
|
||||
}
|
||||
if g.TxHash != trans.Get("transaction.signatures.0").String() || g.Network != conf.Solana || g.BlockNum != slot || !g.Timestamp.Equal(timestamp) {
|
||||
t.Fatalf("transfer %d metadata = %s %s %d %s", i, g.TxHash, g.Network, g.BlockNum, g.Timestamp)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
// 订单过期后,按收款账户的链上历史对账一次。
|
||||
// 扫块每个 slot 只有一次机会,跳块、放弃重试的 slot、重启、回溯范围不完整都会让有效期内的付款漏掉;
|
||||
// 收款账户的签名列表是独立的链上历史,可以把这些付款找回来。
|
||||
|
||||
const (
|
||||
solanaReconcileDelay = time.Minute // 过期后等待交易 finalized 再对账
|
||||
solanaReconcileWindow = 2 * time.Hour // 只对最近过期的订单对账
|
||||
solanaSignaturePageLimit = 1000
|
||||
|
||||
solanaAssociatedTokenProgram = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
|
||||
)
|
||||
|
||||
// solanaReconciled 记录已完成对账的订单 ID;RPC 失败的订单不记录,下一轮重试
|
||||
var solanaReconciled sync.Map // key: int64 order ID, value: struct{}
|
||||
|
||||
func (s *solana) reconcileExpiredOrders(ctx context.Context) {
|
||||
now := time.Now()
|
||||
var orders []model.Order
|
||||
model.Db.Where("status = ? and trade_type in (?)", model.OrderStatusExpired, model.GetNetworkTrades(conf.Solana)).
|
||||
Where("expired_at > ? and expired_at < ?", now.Add(-solanaReconcileWindow), now.Add(-solanaReconcileDelay)).
|
||||
Find(&orders)
|
||||
|
||||
for _, o := range orders {
|
||||
if ctx.Err() != nil {
|
||||
|
||||
return
|
||||
}
|
||||
if _, done := solanaReconciled.Load(o.ID); done {
|
||||
|
||||
continue
|
||||
}
|
||||
if err := s.reconcileOrder(ctx, o); err != nil {
|
||||
log.Task.Warn(fmt.Sprintf("Solana 订单对账失败,稍后重试 %s:%v", o.TradeId, err))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
solanaReconciled.Store(o.ID, struct{}{})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) reconcileOrder(ctx context.Context, o model.Order) error {
|
||||
accounts, err := s.tokenAccounts(ctx, orderMatchAddress(o), model.GetTradeContract(o.TradeType))
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, account := range accounts {
|
||||
signatures, err := s.orderSignatures(ctx, account, o)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, signature := range signatures {
|
||||
var used int64
|
||||
model.Db.Model(&model.Order{}).Where("ref_hash = ?", signature).Count(&used)
|
||||
if used > 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
trans, err := s.rpcCall(ctx, "getTransaction", signature,
|
||||
map[string]any{"encoding": "json", "maxSupportedTransactionVersion": 1, "commitment": "finalized"})
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
if trans.Type == gjson.Null {
|
||||
|
||||
return fmt.Errorf("getTransaction %s: transaction not found", signature)
|
||||
}
|
||||
|
||||
timestamp := time.Unix(trans.Get("blockTime").Int(), 0)
|
||||
for _, t := range s.parseTransaction(trans, int(trans.Get("slot").Int()), timestamp) {
|
||||
if !orderTransferMatch(o, t) {
|
||||
|
||||
continue
|
||||
}
|
||||
if err := o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp, t.Amount); err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("Solana 对账找回付款 %s:%s", o.TradeId, t.TxHash))
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// tokenAccounts 返回钱包在该 mint 下的代币账户:总是包含关联代币账户(ATA),节点支持 getTokenAccountsByOwner 时再加上其他代币账户。
|
||||
// 部分节点(如 publicnode 免费节点)不提供 getTokenAccountsByOwner,此时只检查 ATA,绝大多数付款都转入 ATA。
|
||||
func (s *solana) tokenAccounts(ctx context.Context, owner, mint string) ([]string, error) {
|
||||
ata, err := solanaAssociatedTokenAccount(owner, mint)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accounts := []string{ata}
|
||||
result, err := s.rpcCall(ctx, "getTokenAccountsByOwner", owner, map[string]any{"mint": mint},
|
||||
map[string]any{"encoding": "base64", "dataSlice": map[string]int{"offset": 0, "length": 0}, "commitment": "finalized"})
|
||||
if err != nil {
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
for _, account := range result.Get("value.#.pubkey").Array() {
|
||||
if account.String() != ata {
|
||||
accounts = append(accounts, account.String())
|
||||
}
|
||||
}
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// solanaAssociatedTokenAccount 按 Associated Token Account 程序的规则推导地址:
|
||||
// seeds = [钱包, Token 程序, mint],从 bump 255 往下找第一个不在 ed25519 曲线上的哈希
|
||||
func solanaAssociatedTokenAccount(owner, mint string) (string, error) {
|
||||
seeds := [][]byte{base58.Decode(owner), base58.Decode(conf.SolSplToken), base58.Decode(mint)}
|
||||
for _, seed := range seeds {
|
||||
if len(seed) != 32 {
|
||||
|
||||
return "", fmt.Errorf("invalid Solana address: %s / %s", owner, mint)
|
||||
}
|
||||
}
|
||||
|
||||
program := base58.Decode(solanaAssociatedTokenProgram)
|
||||
for bump := 255; bump >= 0; bump-- {
|
||||
h := sha256.New()
|
||||
for _, seed := range seeds {
|
||||
h.Write(seed)
|
||||
}
|
||||
h.Write([]byte{byte(bump)})
|
||||
h.Write(program)
|
||||
h.Write([]byte("ProgramDerivedAddress"))
|
||||
|
||||
addr := h.Sum(nil)
|
||||
if _, err := new(edwards25519.Point).SetBytes(addr); err != nil {
|
||||
|
||||
return base58.Encode(addr), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("no associated token account for %s / %s", owner, mint)
|
||||
}
|
||||
|
||||
// orderSignatures 返回代币账户在订单有效期内执行成功的交易签名;签名按时间倒序分页返回
|
||||
func (s *solana) orderSignatures(ctx context.Context, account string, o model.Order) ([]string, error) {
|
||||
var result []string
|
||||
opts := map[string]any{"limit": solanaSignaturePageLimit, "commitment": "finalized"}
|
||||
for {
|
||||
page, err := s.rpcCall(ctx, "getSignaturesForAddress", account, opts)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := page.Array()
|
||||
for _, itm := range items {
|
||||
if !itm.Get("blockTime").Exists() || itm.Get("blockTime").Type == gjson.Null {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
at := time.Unix(itm.Get("blockTime").Int(), 0)
|
||||
if !o.CreatedAt.Before(at) { // 已早于订单创建时间
|
||||
|
||||
return result, nil
|
||||
}
|
||||
if o.ExpiredAt.After(at) && solanaTxSucceeded(itm.Get("err")) {
|
||||
result = append(result, itm.Get("signature").String())
|
||||
}
|
||||
}
|
||||
if len(items) < solanaSignaturePageLimit {
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
opts["before"] = items[len(items)-1].Get("signature").String()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) rpcCall(ctx context.Context, method string, params ...any) (gjson.Result, error) {
|
||||
post, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s response status code %d", method, resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
if !gjson.ValidBytes(body) {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s invalid JSON response", method)
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if rpcErr := data.Get("error"); rpcErr.Exists() {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s RPC error: %s", method, rpcErr.Raw)
|
||||
}
|
||||
if !data.Get("result").Exists() {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s missing result", method)
|
||||
}
|
||||
|
||||
return data.Get("result"), nil
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
const (
|
||||
reconcileTestOwner = "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe"
|
||||
reconcileTestSignature = "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6"
|
||||
reconcileTestSlot = 451914288
|
||||
)
|
||||
|
||||
type reconcileTestRPC struct {
|
||||
blockTime int64 // 交易时间,同时用于签名列表和 getTransaction
|
||||
signatureErr string // 签名列表里的 err 字段
|
||||
paidAccount string // 签名列表里有这笔付款的代币账户,默认是收款钱包的 ATA
|
||||
extraAccount string // getTokenAccountsByOwner 额外返回的代币账户;为空时该方法报错,模拟 publicnode 免费节点
|
||||
failSignatures atomic.Bool
|
||||
getTransaction atomic.Int64
|
||||
}
|
||||
|
||||
// 按 JSON-RPC 方法返回;getTransaction 使用主网交易 success_v0_inner_transfer.json,只改 blockTime
|
||||
func newReconcileTestServer(t *testing.T, rpc *reconcileTestRPC) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
ata, err := solanaAssociatedTokenAccount(reconcileTestOwner, model.GetTradeContract(model.UsdcSolana))
|
||||
if err != nil {
|
||||
t.Fatalf("derive ATA: %v", err)
|
||||
}
|
||||
if rpc.paidAccount == "" {
|
||||
rpc.paidAccount = ata
|
||||
}
|
||||
|
||||
trans := gjson.GetBytes(readSolanaFixture(t, "success_v0_inner_transfer.json"), "result.transactions.0").Raw
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
switch gjson.GetBytes(body, "method").String() {
|
||||
case "getTokenAccountsByOwner":
|
||||
if rpc.extraAccount == "" {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32602,"message":"Indexed requests require a personal token"},"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"pubkey":"%s","account":{}},{"pubkey":"%s","account":{}}]},"id":1}`, reconcileTestSlot+1000, ata, rpc.extraAccount)
|
||||
case "getSignaturesForAddress":
|
||||
if rpc.failSignatures.Load() {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind"},"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
if gjson.GetBytes(body, "params.0").String() != rpc.paidAccount {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","result":[],"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":[{"signature":"%s","slot":%d,"err":%s,"memo":null,"blockTime":%d,"confirmationStatus":"finalized"}],"id":1}`, reconcileTestSignature, reconcileTestSlot, rpc.signatureErr, rpc.blockTime)
|
||||
case "getSignatureStatuses":
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, reconcileTestSlot+1000, reconcileTestSlot)
|
||||
case "getTransaction":
|
||||
rpc.getTransaction.Add(1)
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"slot":%d,"blockTime":%d,%s,"id":1}`, reconcileTestSlot, rpc.blockTime, trans[1:])
|
||||
default:
|
||||
t.Errorf("unexpected method: %s", body)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
func createReconcileTestOrder(t *testing.T, tradeID, amount string) model.Order {
|
||||
t.Helper()
|
||||
|
||||
return createTestOrder(t, model.Order{
|
||||
NotifyUrl: model.GetC(model.RpcEndpointSolana) + "/notify",
|
||||
OrderId: "merchant-" + tradeID,
|
||||
TradeId: tradeID,
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: amount,
|
||||
Money: "2736.93",
|
||||
Address: reconcileTestOwner,
|
||||
Status: model.OrderStatusExpired,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
ExpiredAt: time.Now().Add(-5 * time.Minute),
|
||||
}, time.Now().Add(-15*time.Minute))
|
||||
}
|
||||
|
||||
func initReconcileTest(t *testing.T, rpc *reconcileTestRPC) *solana {
|
||||
t.Helper()
|
||||
|
||||
srv := newReconcileTestServer(t, rpc)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
solanaReconciled.Clear()
|
||||
s := newSolana()
|
||||
|
||||
return &s
|
||||
}
|
||||
|
||||
func TestSolanaReconcileFindsMissedPayment(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
|
||||
got := getTestOrder(t, order.TradeId)
|
||||
if got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature || got.RefBlockNum != reconcileTestSlot ||
|
||||
got.FromAddress != "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC" {
|
||||
t.Fatalf("order = status %d ref %s slot %d from %s, want confirming with the payment", got.Status, got.RefHash, got.RefBlockNum, got.FromAddress)
|
||||
}
|
||||
if got.ConfirmedAt == nil || got.ConfirmedAt.Unix() != rpc.blockTime {
|
||||
t.Fatalf("confirmed_at = %v, want the transaction time", got.ConfirmedAt)
|
||||
}
|
||||
|
||||
// 之后按原流程确认并回调:订单虽已过期,但付款时间在有效期内
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusSuccess {
|
||||
t.Fatalf("order status = %d after confirm, want success", got.Status)
|
||||
}
|
||||
waitOrderNotified(t, order.TradeId)
|
||||
}
|
||||
|
||||
func TestSolanaReconcileSkipsUnmatchedPayments(t *testing.T) {
|
||||
inWindow := time.Now().Add(-10 * time.Minute).Unix()
|
||||
tests := []struct {
|
||||
name string
|
||||
blockTime int64
|
||||
signatureErr string
|
||||
amount string
|
||||
usedByOtherOrder bool
|
||||
wantGetTransaction int64
|
||||
}{
|
||||
{name: "failed transaction", blockTime: inWindow, signatureErr: `{"InstructionError":[1,{"Custom":6001}]}`, amount: "390.990618"},
|
||||
{name: "paid before order created", blockTime: time.Now().Add(-30 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
|
||||
{name: "paid after expiry", blockTime: time.Now().Add(-2 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
|
||||
{name: "signature used by another order", blockTime: inWindow, signatureErr: "null", amount: "390.990618", usedByOtherOrder: true},
|
||||
{name: "amount mismatch", blockTime: inWindow, signatureErr: "null", amount: "1.23", wantGetTransaction: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: tt.blockTime, signatureErr: tt.signatureErr}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", tt.amount)
|
||||
if tt.usedByOtherOrder {
|
||||
other := createReconcileTestOrder(t, "trade-order-2", "100")
|
||||
other.Status = model.OrderStatusSuccess
|
||||
other.RefHash = reconcileTestSignature
|
||||
model.Db.Save(&other)
|
||||
}
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired || got.RefHash != "" {
|
||||
t.Fatalf("order = status %d ref %s, want unchanged", got.Status, got.RefHash)
|
||||
}
|
||||
if got := rpc.getTransaction.Load(); got != tt.wantGetTransaction {
|
||||
t.Fatalf("getTransaction calls = %d, want %d", got, tt.wantGetTransaction)
|
||||
}
|
||||
if _, done := solanaReconciled.Load(order.ID); !done {
|
||||
t.Fatalf("order not marked as reconciled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileRetriesOnRPCError(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
rpc.failSignatures.Store(true)
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if _, done := solanaReconciled.Load(order.ID); done {
|
||||
t.Fatalf("order marked as reconciled after RPC error")
|
||||
}
|
||||
|
||||
rpc.failSignatures.Store(false)
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
|
||||
t.Fatalf("order status = %d after retry, want confirming", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileOnlyRecentlyExpiredOrders(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
order.ExpiredAt = time.Now().Add(-30 * time.Second) // 还没到对账延迟,交易可能尚未 finalized
|
||||
model.Db.Save(&order)
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired {
|
||||
t.Fatalf("order status = %d, want expired until the reconcile delay passes", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileChecksOtherTokenAccounts(t *testing.T) {
|
||||
const other = "ReconcileTestTokenAccount111111111111111111"
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null", paidAccount: other, extraAccount: other}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature {
|
||||
t.Fatalf("order = status %d ref %s, want the payment to the non-ATA token account", got.Status, got.RefHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaAssociatedTokenAccount(t *testing.T) {
|
||||
tests := []struct {
|
||||
owner, mint, want string
|
||||
}{
|
||||
// 主网交易中的代币账户(success_legacy_transfer.json、success_legacy_transfer_checked.json)
|
||||
{owner: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", mint: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", want: "Hwnrd47xhiULAjwLThEnuxnVTCwJyr5phkfwDyB58ns1"},
|
||||
{owner: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", want: "9un7p7bo7Y4TBwVdsQZTWtLZtkvW9hAUzdeV7mardWo5"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got, err := solanaAssociatedTokenAccount(tt.owner, tt.mint); err != nil || got != tt.want {
|
||||
t.Fatalf("ATA(%s, %s) = %s, %v; want %s", tt.owner, tt.mint, got, err, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := solanaAssociatedTokenAccount("not-an-address", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); err == nil {
|
||||
t.Fatalf("invalid owner accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
// 模拟重试定时器到期并再次扫描失败:取消定时器,下一次 scheduleSlotRetry 计为新的失败
|
||||
func (s *solana) expireSlotRetryTimer(slot int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) stopSlotRetryTimers() {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
for slot, timer := range s.retryScheduled {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotRetryGivesUpAfterMaxRetries(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32001,"message":"Block 457000000 cleaned up, does not exist on node. First available block: 457100000"},"id":1}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 457000000
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
for i := 1; i <= solanaSlotMaxRetries; i++ {
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 1 {
|
||||
t.Fatalf("after %d failures pending retries = %d, want 1", i, got)
|
||||
}
|
||||
s.expireSlotRetryTimer(slot)
|
||||
}
|
||||
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries = %d after giving up, forward sync stays paused", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("slot still scheduled after giving up")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestSolanaGetBlockPayloadSupportsVersionOne(t *testing.T) {
|
||||
payload := string(solanaGetBlockPayload(456519571))
|
||||
if !strings.Contains(payload, `"maxSupportedTransactionVersion":1`) {
|
||||
t.Fatalf("payload does not support Solana v1 transactions: %s", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSolanaBlockResponse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantErr bool
|
||||
wantSkipped bool
|
||||
}{
|
||||
{name: "valid empty block", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000,"transactions":[]},"id":1}`},
|
||||
{name: "null result", body: `{"jsonrpc":"2.0","result":null,"id":1}`, wantSkipped: true},
|
||||
{name: "slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32007,"message":"Slot 300000092 was skipped, or missing due to ledger jump to recent snapshot"},"id":1}`, wantSkipped: true},
|
||||
{name: "long-term storage slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32009,"message":"Slot 300000092 was skipped, or missing in long-term storage"},"id":1}`, wantSkipped: true},
|
||||
{name: "block not available", body: `{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 456731994"},"id":1}`, wantErr: true},
|
||||
{name: "unsupported transaction version", body: `{"jsonrpc":"2.0","error":{"code":-32015,"message":"Transaction version (1) is not supported by the requesting client"},"id":1}`, wantErr: true},
|
||||
{name: "missing result", body: `{"jsonrpc":"2.0","id":1}`, wantErr: true},
|
||||
{name: "missing transactions", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000},"id":1}`, wantErr: true},
|
||||
{name: "invalid json", body: `<html>rate limited</html>`, wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := validateSolanaBlockResponse([]byte(tt.body))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil && (result.Type == gjson.Null) != tt.wantSkipped {
|
||||
t.Fatalf("skipped = %v, want %v", result.Type == gjson.Null, tt.wantSkipped)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaRetryDelayIsBounded(t *testing.T) {
|
||||
tests := []struct {
|
||||
attempt int
|
||||
want time.Duration
|
||||
}{
|
||||
{attempt: 1, want: 2 * time.Second},
|
||||
{attempt: 2, want: 5 * time.Second},
|
||||
{attempt: 3, want: 15 * time.Second},
|
||||
{attempt: 4, want: 30 * time.Second},
|
||||
{attempt: 5, want: time.Minute},
|
||||
{attempt: 100, want: time.Minute},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := solanaRetryDelay(tt.attempt); got != tt.want {
|
||||
t.Fatalf("attempt %d delay = %s, want %s", tt.attempt, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidSolanaLookbackRange(t *testing.T) {
|
||||
tests := []struct {
|
||||
start int64
|
||||
end int64
|
||||
want bool
|
||||
}{
|
||||
{start: 458225400, end: 458225500, want: true},
|
||||
{start: 0, end: 0, want: false},
|
||||
{start: 0, end: 458225500, want: false},
|
||||
{start: 458225500, end: 458225400, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := validSolanaLookbackRange(tt.start, tt.end); got != tt.want {
|
||||
t.Fatalf("validSolanaLookbackRange(%d, %d) = %v, want %v", tt.start, tt.end, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"jsonrpc":"2.0","id":1,"result":{"blockTime":1791453359,"blockHeight":432548102,"parentSlot":454510625,"blockhash":"5z9SXEcj1JJKXtZVyr6qkD9NKuTPivkkypCDUdSMqKkx","transactions":[{"meta":{"computeUnitsConsumed":274,"costUnits":2648,"err":null,"fee":10000,"innerInstructions":[],"loadedAddresses":{"readonly":[],"writable":[]},"logMessages":["Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 145 of 400000 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 129 of 399855 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success"],"postBalances":[378107467,0,0,1488440,200654906],"postTokenBalances":[{"accountIndex":3,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"61535189","decimals":6,"uiAmount":61.535189,"uiAmountString":"61.535189"}}],"preBalances":[376629027,0,1488440,1488440,200654906],"preTokenBalances":[{"accountIndex":2,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"5360000","decimals":6,"uiAmount":5.36,"uiAmountString":"5.36"}},{"accountIndex":3,"mint":"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB","owner":"Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"56175189","decimals":6,"uiAmount":56.175189,"uiAmountString":"56.175189"}}],"rewards":null,"status":{"Ok":null}},"transaction":{"message":{"accountKeys":["Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b","218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn","DurdksnNzKrvd41SuucDRGipUtHSJUzksubVao47B9Ui","Hwnrd47xhiULAjwLThEnuxnVTCwJyr5phkfwDyB58ns1","TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],"header":{"numReadonlySignedAccounts":1,"numReadonlyUnsignedAccounts":1,"numRequiredSignatures":2},"instructions":[{"accounts":[2,3,1,1],"data":"3azxBPgCGsJw","programIdIndex":4,"stackHeight":1},{"accounts":[2,0,1,1],"data":"A","programIdIndex":4,"stackHeight":1}],"recentBlockhash":"HKXJmoBsY4nC9RY8aC6MjMph1BcMdq5cCmJuhQ4KwR6X"},"signatures":["5UKT7CpNSESsPw7xg7UHMKHD1M4UqaCDRCLPjTqkTmtXWvi3R6z4codAyYUKJitHRgeVQoyyqhC4iwsmcGvi1b2M","5A4enkfBgsaWB53V45UcQZgedAkTmvsMQ3HBPd8rUFGUyQR32v7CNR4bt9582bv6ZnbLD54BXtQ6FaiJ81qGKrNY"]},"version":"legacy"}]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"jsonrpc":"2.0","id":1,"result":{"blockTime":1791803694,"blockHeight":434063612,"parentSlot":456026590,"blockhash":"5dam2f4AiJqFKZmUn9bY6eXaqMRvL6AfnxPDj2aw2dZ1","transactions":[{"meta":{"computeUnitsConsumed":234,"costUnits":2188,"err":null,"fee":5000,"innerInstructions":[],"loadedAddresses":{"readonly":[],"writable":[]},"logMessages":["Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 105 of 400000 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 129 of 399895 compute units","Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success"],"postBalances":[1565660,89622429437,0,1488440,549535699757,230130698],"postTokenBalances":[{"accountIndex":3,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"735887428","decimals":6,"uiAmount":735.887428,"uiAmountString":"735.887428"}}],"preBalances":[1570660,89620940997,1488440,1488440,549535699757,230130698],"preTokenBalances":[{"accountIndex":2,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"2400","decimals":6,"uiAmount":0.0024,"uiAmountString":"0.0024"}},{"accountIndex":3,"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"735885028","decimals":6,"uiAmount":735.885028,"uiAmountString":"735.885028"}}],"rewards":null,"status":{"Ok":null}},"transaction":{"message":{"accountKeys":["8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH","8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv","9qo8j8q8RbfrjKrNuYRinwbPPzuRjCPrTuNv8qbqkPzz","9un7p7bo7Y4TBwVdsQZTWtLZtkvW9hAUzdeV7mardWo5","EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"],"header":{"numReadonlySignedAccounts":0,"numReadonlyUnsignedAccounts":2,"numRequiredSignatures":1},"instructions":[{"accounts":[2,4,3,0],"data":"hKr7pdRPTzpPf","programIdIndex":5,"stackHeight":1},{"accounts":[2,1,0,0],"data":"A","programIdIndex":5,"stackHeight":1}],"recentBlockhash":"9J7owuh66Xrx2ZfZziZhyQ4o7yEcwnQPeWmsyoU3DgK2"},"signatures":["3D3jCbXnRspBEzJZJ7devvJSyN27QbMSpzMkXjtsAfXHvWSw9PhqSvTxrwGeEJCZ7cy9cV6gnY4agr5cNaEjaFLY"]},"version":"legacy"}]}}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,108 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
applog "github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
// 任务测试的公共环境:临时日志目录、临时 SQLite 和主网交易 fixture
|
||||
|
||||
func initTaskTestEnv(t *testing.T, kv map[model.ConfKey]string) {
|
||||
t.Helper()
|
||||
|
||||
if err := applog.Init(filepath.Join(t.TempDir(), "logs")); err != nil {
|
||||
t.Fatalf("init log: %v", err)
|
||||
}
|
||||
t.Cleanup(applog.Close)
|
||||
|
||||
if err := model.Init(filepath.Join(t.TempDir(), "task-test.db"), ""); err != nil {
|
||||
t.Fatalf("init db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if db, err := model.Db.DB(); err == nil {
|
||||
_ = db.Close()
|
||||
}
|
||||
})
|
||||
|
||||
for k, v := range kv {
|
||||
model.Db.Model(&model.Conf{}).Where("k = ?", k).Update("v", v)
|
||||
}
|
||||
model.RefreshC()
|
||||
}
|
||||
|
||||
func createTestOrder(t *testing.T, o model.Order, created time.Time) model.Order {
|
||||
t.Helper()
|
||||
|
||||
at := model.Datetime(created)
|
||||
o.CreatedAt = &at
|
||||
o.UpdatedAt = &at
|
||||
if o.ConfirmedAt == nil {
|
||||
o.ConfirmedAt = &created
|
||||
}
|
||||
if err := model.Db.Create(&o).Error; err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
func getTestOrder(t *testing.T, tradeID string) model.Order {
|
||||
t.Helper()
|
||||
|
||||
var o model.Order
|
||||
if err := model.Db.Where("trade_id = ?", tradeID).First(&o).Error; err != nil {
|
||||
t.Fatalf("get order: %v", err)
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
// 订单成功后回调在协程中执行,等它写完最后一条日志,避免测试清理临时目录时仍有写入
|
||||
func waitOrderNotified(t *testing.T, tradeID string) {
|
||||
t.Helper()
|
||||
|
||||
file := filepath.Join(applog.GetPath(), "bepusdt.log")
|
||||
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
||||
body, _ := os.ReadFile(file)
|
||||
if strings.Contains(string(body), "订单回调成功") && strings.Contains(string(body), tradeID) {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("order %s callback not finished", tradeID)
|
||||
}
|
||||
|
||||
// 主网交易,每个文件是只含这一笔交易的 getBlock 响应
|
||||
func readSolanaFixture(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
|
||||
body, err := os.ReadFile(filepath.Join("testdata", "solana", name))
|
||||
if err != nil {
|
||||
t.Fatalf("read fixture: %v", err)
|
||||
}
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
// 返回 slotParse 写入 transferQueue 的转账
|
||||
func drainTransferQueue() []transfer {
|
||||
var result []transfer
|
||||
for {
|
||||
select {
|
||||
case items := <-transferQueue.Out:
|
||||
result = append(result, items...)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func solanaFixtureSlot(block []byte) int {
|
||||
return int(gjson.GetBytes(block, "result.parentSlot").Int()) + 1
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
blockapi "github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
tgo "github.com/xssnick/tonutils-go/ton"
|
||||
)
|
||||
|
||||
const tonMasterChainID = -1
|
||||
const tonMasterShard = int64(-0x8000000000000000)
|
||||
const tonOpInternalTransfer = uint32(0x178d4519)
|
||||
const tonBlockRetryMaxDelay = 15 * time.Second
|
||||
|
||||
type tonShardRange struct {
|
||||
Workchain int32
|
||||
Shard int64
|
||||
Start uint32
|
||||
End uint32
|
||||
}
|
||||
|
||||
type tonShardKey struct {
|
||||
Workchain int32
|
||||
Shard int64
|
||||
}
|
||||
|
||||
type ton struct {
|
||||
lastBlockSeqno uint32
|
||||
blockScanQueue *chanx.UnboundedChan[uint32]
|
||||
clientOnce sync.Once
|
||||
api tgo.APIClientWrapped
|
||||
}
|
||||
|
||||
var tn ton
|
||||
|
||||
func init() {
|
||||
tn = ton{
|
||||
blockScanQueue: chanx.NewUnboundedChan[uint32](context.Background(), 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: tn.syncMBSeqnoForward})
|
||||
Register(Task{Duration: time.Second, Callback: tn.blockDispatch})
|
||||
Register(Task{Duration: time.Second * 3, Callback: tn.tradeConfirmHandle})
|
||||
Register(Task{Duration: time.Second * 15, Callback: tn.lookbackBlocks})
|
||||
}
|
||||
|
||||
func (t *ton) syncMBSeqnoForward(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
if t.syncBreak() {
|
||||
time.Sleep(time.Second * 3)
|
||||
continue
|
||||
}
|
||||
|
||||
// 初始化:首次获取当前最新高度作为起点
|
||||
if t.lastBlockSeqno == 0 {
|
||||
mb, err := t.client().CurrentMasterchainInfo(ctx)
|
||||
if err != nil {
|
||||
log.Task.Warn(fmt.Sprintf("get current masterchain info: %v", err))
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
t.lastBlockSeqno = mb.SeqNo - 1
|
||||
}
|
||||
|
||||
nextSeqno := t.lastBlockSeqno + 1
|
||||
|
||||
// 阻塞直到 nextSeqno 在节点上可用,无需轮询
|
||||
mb, err := t.client().WaitForBlock(nextSeqno).GetMasterchainInfo(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
log.Task.Warn(fmt.Sprintf("WaitForBlock GetMasterchainInfo err: %v", err))
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
now := mb.SeqNo
|
||||
|
||||
// 区块高度变化过大,强制丢块重扫
|
||||
if now-t.lastBlockSeqno > cast.ToUint32(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
t.lastBlockSeqno = now - 1
|
||||
}
|
||||
|
||||
// 待扫描区块入列
|
||||
for n := t.lastBlockSeqno + 1; n <= now; n++ {
|
||||
t.blockScanQueue.In <- n
|
||||
}
|
||||
|
||||
t.lastBlockSeqno = now
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ton) blockDispatch(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case n, ok := <-t.blockScanQueue.Out:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := retryTonBlock(ctx, n, time.Second, func(seqno uint32) error {
|
||||
err := t.blockParse(ctx, seqno)
|
||||
if err != nil {
|
||||
log.Task.Warn(fmt.Sprintf("Ton 区块扫描失败,将重试 seqno=%d: %v", seqno, err))
|
||||
}
|
||||
|
||||
return err
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ton) blockParse(parent context.Context, seqno uint32) error {
|
||||
var ctx, cancel = context.WithTimeout(parent, time.Second*60)
|
||||
defer cancel()
|
||||
|
||||
mb, err := t.client().LookupBlock(ctx, tonMasterChainID, tonMasterShard, seqno)
|
||||
if err != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("lookup master block: %w", err)
|
||||
}
|
||||
|
||||
shardsTip, err := t.client().GetBlockShardsInfo(ctx, mb)
|
||||
if err != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("get current shards info: %w", err)
|
||||
}
|
||||
|
||||
var previousShards []*tgo.BlockIDExt
|
||||
if seqno > 0 {
|
||||
previousMB, lookupErr := t.client().LookupBlock(ctx, tonMasterChainID, tonMasterShard, seqno-1)
|
||||
if lookupErr != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("lookup previous master block: %w", lookupErr)
|
||||
}
|
||||
|
||||
previousShards, err = t.client().GetBlockShardsInfo(ctx, previousMB)
|
||||
if err != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("get previous shards info: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, shardRange := range tonShardRanges(previousShards, shardsTip) {
|
||||
for s := shardRange.Start; s <= shardRange.End; s++ {
|
||||
shardBlock, err := t.client().LookupBlock(ctx, shardRange.Workchain, shardRange.Shard, s)
|
||||
if err != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("lookup shard block workchain=%d shard=%d seqno=%d: %w", shardRange.Workchain, shardRange.Shard, s, err)
|
||||
}
|
||||
|
||||
if err := t.processShard(ctx, shardBlock, seqno); err != nil {
|
||||
conf.RecordFailure(conf.Ton)
|
||||
|
||||
return fmt.Errorf("process shard block workchain=%d shard=%d seqno=%d: %w", shardRange.Workchain, shardRange.Shard, s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
conf.RecordSuccess(conf.Ton, cast.ToString(seqno))
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(Ton): %d 成功率:%s", seqno, conf.GetSuccessRate(conf.Ton)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func tonShardRanges(previous, current []*tgo.BlockIDExt) []tonShardRange {
|
||||
previousTips := make(map[tonShardKey]uint32, len(previous))
|
||||
for _, tip := range previous {
|
||||
key := tonShardKey{Workchain: tip.Workchain, Shard: tip.Shard}
|
||||
previousTips[key] = tip.SeqNo
|
||||
}
|
||||
|
||||
ranges := make([]tonShardRange, 0, len(current))
|
||||
for _, tip := range current {
|
||||
start := tip.SeqNo
|
||||
key := tonShardKey{Workchain: tip.Workchain, Shard: tip.Shard}
|
||||
if previousSeqno, ok := previousTips[key]; ok {
|
||||
if previousSeqno >= tip.SeqNo {
|
||||
continue
|
||||
}
|
||||
start = previousSeqno + 1
|
||||
}
|
||||
|
||||
ranges = append(ranges, tonShardRange{
|
||||
Workchain: tip.Workchain,
|
||||
Shard: tip.Shard,
|
||||
Start: start,
|
||||
End: tip.SeqNo,
|
||||
})
|
||||
}
|
||||
|
||||
return ranges
|
||||
}
|
||||
|
||||
func retryTonBlock(ctx context.Context, seqno uint32, initialDelay time.Duration, process func(uint32) error) error {
|
||||
delay := initialDelay
|
||||
for {
|
||||
if err := process(seqno); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if delay <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
if delay < tonBlockRetryMaxDelay {
|
||||
delay *= 2
|
||||
if delay > tonBlockRetryMaxDelay {
|
||||
delay = tonBlockRetryMaxDelay
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ton) syncBreak() bool {
|
||||
if t.blockScanQueue.Len() >= blockQueueLimit {
|
||||
log.Task.Warn("ton 同步阻塞,当前区块消费堆积数量:", t.blockScanQueue.Len())
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if mqttSubscribed(conf.Ton) {
|
||||
return false
|
||||
}
|
||||
|
||||
trade := []model.TradeType{model.UsdtTon, model.TonGram}
|
||||
if hasLookbackOrders(trade) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var count int64
|
||||
model.Db.Model(&model.Wallet{}).Where("other_notify = ? and trade_type in (?)", model.WaOtherEnable, trade).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *ton) processShard(ctx context.Context, shard *tgo.BlockIDExt, seqno uint32) error {
|
||||
data, err := t.client().GetBlockData(ctx, shard)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
txs, err := data.ListTransactions()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var transfers = make([]transfer, 0)
|
||||
for _, tx := range txs {
|
||||
if tonTrans, ok := t.parseTonTransfer(tx, seqno); ok {
|
||||
transfers = append(transfers, tonTrans)
|
||||
}
|
||||
if jettonTrans, ok := t.parseInternalTransfer(shard, tx, seqno); ok {
|
||||
transfers = append(transfers, jettonTrans)
|
||||
}
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// https://github.com/ton-blockchain/TEPs/blob/63fc78718dd9930f3e106954ebec743c3ad07993/text/0074-jettons-standard.md?plain=1#L226
|
||||
// https://github.com/ton-blockchain/token-contract/blob/1182ad99413242f09925d50e70ccb7e0e09f94d4/ft/jetton-wallet.fc#L43
|
||||
func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
|
||||
if tx.IO.In == nil {
|
||||
return transfer{}, false
|
||||
}
|
||||
in, ok := tx.IO.In.Msg.(*tlb.InternalMessage)
|
||||
if !ok || in.Bounced || in.Body == nil {
|
||||
return transfer{}, false
|
||||
}
|
||||
s, err := in.Body.BeginParse()
|
||||
if err != nil || s.BitsLeft() < 32 {
|
||||
return transfer{}, false
|
||||
}
|
||||
v, err := s.LoadUInt(32)
|
||||
if err != nil || uint32(v) != tonOpInternalTransfer {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
transOrd, ok := tx.Description.(tlb.TransactionDescriptionOrdinary)
|
||||
if !ok {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
compute, ok := transOrd.ComputePhase.Phase.(tlb.ComputePhaseVM)
|
||||
if !ok || !compute.Success {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
if transOrd.ActionPhase == nil || !transOrd.ActionPhase.Success {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
if err = s.SkipBits(64); err != nil {
|
||||
return transfer{}, false
|
||||
}
|
||||
amount, err := s.LoadBigCoins()
|
||||
if err != nil || amount.Sign() <= 0 {
|
||||
return transfer{}, false
|
||||
}
|
||||
fromOwner, err := s.LoadAddr()
|
||||
if err != nil {
|
||||
return transfer{}, false
|
||||
}
|
||||
if fromOwner.Type() != address.StdAddress {
|
||||
fromOwner = address.NewAddress(0, byte(fromOwner.Workchain()), fromOwner.Data())
|
||||
}
|
||||
|
||||
toJetton := address.NewAddress(0, byte(shard.Workchain), tx.AccountAddr)
|
||||
|
||||
return transfer{
|
||||
Network: conf.Ton,
|
||||
TxHash: hex.EncodeToString(tx.Hash),
|
||||
Amount: decimal.NewFromBigInt(amount, conf.UsdtTonDecimals),
|
||||
FromAddress: fromOwner.Bounce(false).String(),
|
||||
RecvAddress: toJetton.Bounce(false).String(),
|
||||
Timestamp: time.Unix(int64(tx.Now), 0),
|
||||
TradeType: model.UsdtTon,
|
||||
BlockNum: int(blockNum),
|
||||
}, true
|
||||
}
|
||||
|
||||
func (t *ton) parseTonTransfer(tx *tlb.Transaction, blockNum uint32) (transfer, bool) {
|
||||
in := tx.IO.In
|
||||
if in == nil {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
msg, ok := in.Msg.(*tlb.InternalMessage)
|
||||
if !ok {
|
||||
return transfer{}, false
|
||||
}
|
||||
if msg.Bounced {
|
||||
return transfer{}, false
|
||||
}
|
||||
if msg.Amount.Nano().Sign() <= 0 {
|
||||
return transfer{}, false
|
||||
}
|
||||
if msg.Body.BitsSize() != 0 {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
return transfer{
|
||||
Network: conf.Ton,
|
||||
TxHash: hex.EncodeToString(tx.Hash),
|
||||
FromAddress: msg.SrcAddr.Bounce(false).String(),
|
||||
RecvAddress: msg.DstAddr.Bounce(false).String(),
|
||||
Timestamp: time.Unix(int64(tx.Now), 0),
|
||||
Amount: decimal.NewFromBigInt(msg.Amount.Nano(), conf.TonTonDecimals),
|
||||
TradeType: model.TonGram,
|
||||
BlockNum: int(blockNum),
|
||||
}, true
|
||||
}
|
||||
|
||||
func (t *ton) tradeConfirmHandle(context.Context) {
|
||||
var orders = getConfirmingOrders([]model.TradeType{model.UsdtTon, model.TonGram})
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, order := range orders {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
// 一旦某笔交易所在的 shard block 被 MasterChain block 引用(commit),则该交易获得最终性(finality)。
|
||||
markFinalConfirmed(order)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (t *ton) client() tgo.APIClientWrapped {
|
||||
t.clientOnce.Do(func() {
|
||||
t.api = utils.NewTonClient(model.GetC(model.RpcGlobalConfigUrlTon))
|
||||
})
|
||||
|
||||
return t.api
|
||||
}
|
||||
|
||||
func (t *ton) lookbackBlocks(ctx context.Context) {
|
||||
if t.syncBreak() {
|
||||
return
|
||||
}
|
||||
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Ton)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Ton)
|
||||
if start <= 0 || end < start {
|
||||
log.Task.Warn(fmt.Sprintf("Ton 回溯高度范围无效: start=%d end=%d", start, end))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for i := start; i <= end; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
if t.syncBreak() {
|
||||
return
|
||||
}
|
||||
if err := retryTonBlock(ctx, uint32(i), time.Second, func(seqno uint32) error {
|
||||
err := t.blockParse(ctx, seqno)
|
||||
if err != nil {
|
||||
log.Task.Warn(fmt.Sprintf("Ton 历史区块扫描失败,将重试 seqno=%d: %v", seqno, err))
|
||||
}
|
||||
|
||||
return err
|
||||
}); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond * 200) // 速率控制
|
||||
}
|
||||
|
||||
markLookbackDone(orderIDs)
|
||||
}
|
||||
+176
-43
@@ -4,11 +4,13 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notifier"
|
||||
"github.com/v03413/bepusdt/app/task/notify"
|
||||
@@ -16,14 +18,14 @@ import (
|
||||
)
|
||||
|
||||
type transfer struct {
|
||||
Network string
|
||||
TxHash string
|
||||
Amount decimal.Decimal
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType model.TradeType
|
||||
BlockNum int64
|
||||
Network string `json:"network"`
|
||||
TxHash string `json:"tx_hash"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
FromAddress string `json:"from_address"`
|
||||
RecvAddress string `json:"recv_address"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
TradeType model.TradeType `json:"trade_type"`
|
||||
BlockNum int `json:"block_num"`
|
||||
}
|
||||
|
||||
type resource struct {
|
||||
@@ -40,7 +42,10 @@ var resourceQueue = chanx.NewUnboundedChan[[]resource](context.Background(), 30)
|
||||
var notOrderQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 非订单队列
|
||||
var transferQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 交易转账队列
|
||||
|
||||
const batchInterval = time.Second * 1 // 批处理缓解数据库读取压力
|
||||
// lookbackDone 记录已触发过回溯的订单 ID,每个订单只回溯一次。
|
||||
var lookbackDone sync.Map // key: int64 order ID, value: struct{}
|
||||
|
||||
const batchInterval = time.Second * 1 // 批处理缓解数据库读取压力
|
||||
const orderCheckInterval = time.Second * 10 // 订单过期检查间隔
|
||||
|
||||
func init() {
|
||||
@@ -67,26 +72,29 @@ func orderTransferHandle(ctx context.Context) {
|
||||
case <-ticker.C:
|
||||
// 每10秒强制检查一次过期订单,即使没有交易,防止无交易时订单不过期
|
||||
var shouldCheck = time.Since(lastCheckTime) >= orderCheckInterval
|
||||
if len(batch) == 0 && !shouldCheck {
|
||||
continue
|
||||
}
|
||||
|
||||
if shouldCheck {
|
||||
lastCheckTime = time.Now()
|
||||
}
|
||||
|
||||
var other = make([]transfer, 0)
|
||||
// getAllWaitingOrders 内部包含过期检查逻辑
|
||||
var orders = getAllWaitingOrders()
|
||||
if len(batch) == 0 {
|
||||
if shouldCheck {
|
||||
expireWaitingOrders()
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var other = make([]transfer, 0)
|
||||
var orders = getReceivableOrders()
|
||||
|
||||
for _, t := range batch {
|
||||
// 判断数额是否在允许范围内
|
||||
if !model.IsAmountValid(t.TradeType, t.Amount) {
|
||||
continue
|
||||
}
|
||||
|
||||
mqttPublish(t)
|
||||
|
||||
key := fmt.Sprintf("%s%s", t.RecvAddress, t.TradeType)
|
||||
orderList, ok := orders[key]
|
||||
if !ok {
|
||||
@@ -95,21 +103,19 @@ func orderTransferHandle(ctx context.Context) {
|
||||
}
|
||||
|
||||
var matched bool
|
||||
for _, o := range orderList {
|
||||
// 金额前缀匹配
|
||||
if !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
|
||||
for i, o := range orderList {
|
||||
if !orderTransferMatch(o, t) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 有效期检测
|
||||
if !o.CreatedAt.Before(t.Timestamp) || !o.ExpiredAt.After(t.Timestamp) {
|
||||
|
||||
// 订单匹配 进入确认流程
|
||||
if err := o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp, t.Amount); err != nil {
|
||||
log.Task.Warn("mark order confirming failed:", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 找到匹配的订单
|
||||
o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp)
|
||||
// 从内存 map 中移除已匹配订单,防止同批次其他 transfer 重复匹配
|
||||
orders[key] = append(orderList[:i], orderList[i+1:]...)
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
@@ -124,10 +130,36 @@ func orderTransferHandle(ctx context.Context) {
|
||||
}
|
||||
|
||||
batch = batch[:0]
|
||||
|
||||
if shouldCheck {
|
||||
expireWaitingOrders()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func orderTransferMatch(o model.Order, t transfer) bool {
|
||||
if o.TradeType != t.TradeType || orderMatchAddress(o) != t.RecvAddress {
|
||||
return false
|
||||
}
|
||||
if !o.AddressLocked && !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
return false
|
||||
}
|
||||
if !o.CreatedAt.Before(t.Timestamp) || !o.ExpiredAt.After(t.Timestamp) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func orderMatchAddress(o model.Order) string {
|
||||
if o.MatchAddress != "" {
|
||||
return o.MatchAddress
|
||||
}
|
||||
|
||||
return o.Address
|
||||
}
|
||||
|
||||
func notOrderTransferHandle(ctx context.Context) {
|
||||
var batch = make([]transfer, 0, 1000)
|
||||
ticker := time.NewTicker(batchInterval)
|
||||
@@ -224,29 +256,119 @@ func tronResourceHandle(ctx context.Context) {
|
||||
|
||||
func markFinalConfirmed(o model.Order) {
|
||||
o.SetSuccess()
|
||||
|
||||
go notify.Handle(o) // 订单回调
|
||||
go notifier.Success(o) // 消息通知
|
||||
notifyOrderSuccess(o)
|
||||
}
|
||||
|
||||
func getAllWaitingOrders() map[string][]model.Order {
|
||||
var tradeOrders = model.GetOrderByStatus(model.OrderStatusWaiting)
|
||||
var data = make(map[string][]model.Order)
|
||||
for _, t := range tradeOrders {
|
||||
if time.Now().Unix() >= t.ExpiredAt.Unix() { // 订单过期
|
||||
t.SetExpired()
|
||||
notify.Bepusdt(t)
|
||||
func receivableOrderStatuses() []int {
|
||||
return []int{model.OrderStatusWaiting, model.OrderStatusExpired, model.OrderStatusConfirming}
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
func getReceivableOrders() map[string][]model.Order {
|
||||
var orders []model.Order
|
||||
db := model.Db.Where("status in (?)", receivableOrderStatuses()).
|
||||
Where("expired_at > ?", time.Now().Add(model.GetLookbackHour())).
|
||||
Order("created_at asc")
|
||||
db.Find(&orders)
|
||||
|
||||
key := t.Address + string(t.TradeType)
|
||||
data := make(map[string][]model.Order)
|
||||
for _, t := range orders {
|
||||
key := orderMatchAddress(t) + string(t.TradeType)
|
||||
data[key] = append(data[key], t)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func hasLookbackOrders(tradeType []model.TradeType) bool {
|
||||
var count int64
|
||||
db := model.Db.Model(&model.Order{}).
|
||||
Where("status in (?)", receivableOrderStatuses()).
|
||||
Where("expired_at > ?", time.Now().Add(model.GetLookbackHour()))
|
||||
if len(tradeType) > 0 {
|
||||
db = db.Where("trade_type in (?)", tradeType)
|
||||
}
|
||||
|
||||
db.Count(&count)
|
||||
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func getLookbackUnix(network model.Network) (startAt, endAt int64, ok bool) {
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(network)
|
||||
if ok {
|
||||
markLookbackDone(orderIDs)
|
||||
}
|
||||
|
||||
return startAt, endAt, ok
|
||||
}
|
||||
|
||||
func pendingLookbackUnix(network model.Network) (startAt, endAt int64, orderIDs []int64, ok bool) {
|
||||
trade := model.GetNetworkTrades(network)
|
||||
if len(trade) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
lookback := time.Now().Add(model.GetLookbackHour())
|
||||
var all []model.Order
|
||||
model.Db.Model(&model.Order{}).
|
||||
Where("status in (?) and trade_type in (?)", receivableOrderStatuses(), trade).
|
||||
Where("expired_at > ?", lookback).
|
||||
Order("created_at asc").
|
||||
Find(&all)
|
||||
|
||||
// 过滤掉已经回溯过的订单
|
||||
pending := make([]model.Order, 0, len(all))
|
||||
for _, o := range all {
|
||||
if _, done := lookbackDone.Load(o.ID); !done {
|
||||
pending = append(pending, o)
|
||||
}
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
return
|
||||
}
|
||||
orderIDs = make([]int64, 0, len(pending))
|
||||
for _, o := range pending {
|
||||
orderIDs = append(orderIDs, o.ID)
|
||||
}
|
||||
|
||||
// 起点:最早的创建时间(已按 created_at asc 排序)
|
||||
startAt = pending[0].CreatedAt.Time().Unix()
|
||||
|
||||
// 终点:覆盖每个订单的有效期,取各订单 min(过期时间, 当前时间) 的最大值
|
||||
now := time.Now()
|
||||
endAt = startAt
|
||||
for _, o := range pending {
|
||||
end := o.ExpiredAt
|
||||
if end.After(now) {
|
||||
end = now
|
||||
}
|
||||
if end.Unix() > endAt {
|
||||
endAt = end.Unix()
|
||||
}
|
||||
}
|
||||
|
||||
ok = true
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func markLookbackDone(orderIDs []int64) {
|
||||
for _, orderID := range orderIDs {
|
||||
lookbackDone.Store(orderID, struct{}{})
|
||||
}
|
||||
}
|
||||
|
||||
func expireWaitingOrders() {
|
||||
for _, t := range model.GetOrderByStatus(model.OrderStatusWaiting) {
|
||||
if time.Now().Unix() < t.ExpiredAt.Unix() {
|
||||
continue
|
||||
}
|
||||
|
||||
t.SetExpired()
|
||||
notify.Bepusdt(t)
|
||||
}
|
||||
}
|
||||
|
||||
func getConfirmingOrders(tradeType []model.TradeType) []model.Order {
|
||||
var orders = make([]model.Order, 0)
|
||||
var data = make([]model.Order, 0)
|
||||
@@ -259,10 +381,12 @@ func getConfirmingOrders(tradeType []model.TradeType) []model.Order {
|
||||
|
||||
for _, order := range orders {
|
||||
if time.Now().Unix() >= order.ExpiredAt.Unix() {
|
||||
order.SetFailed()
|
||||
notify.Bepusdt(order)
|
||||
if order.ConfirmedAt == nil || order.ConfirmedAt.IsZero() || !order.ConfirmedAt.Before(order.ExpiredAt) {
|
||||
order.SetFailed()
|
||||
notify.Bepusdt(order)
|
||||
|
||||
continue
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
data = append(data, order)
|
||||
@@ -277,10 +401,20 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
|
||||
case model.Classic:
|
||||
return amount.String() == target
|
||||
case model.HasPrefix:
|
||||
return strings.HasPrefix(amount.String(), target)
|
||||
s := amount.String()
|
||||
if !strings.HasPrefix(s, target) {
|
||||
return false
|
||||
}
|
||||
rest := s[len(target):]
|
||||
if rest == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
return strings.Contains(target, ".") || strings.HasPrefix(rest, ".")
|
||||
case model.RoundOff:
|
||||
t, err := decimal.NewFromString(target)
|
||||
if err != nil {
|
||||
log.Warn(err.Error())
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -288,7 +422,6 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
|
||||
_, precision := model.GetAtomicity(model.TradeType(tradeType)) // 标准精度
|
||||
precision2 := abs(t.Exponent()) // 实际精度
|
||||
if precision2 != precision {
|
||||
|
||||
precision = precision2
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func TestPendingLookbackUnixCoversEveryOrderWindow(t *testing.T) {
|
||||
type window struct {
|
||||
created, expired time.Duration // 相对当前时间
|
||||
status int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
orders []window
|
||||
wantEnd time.Duration
|
||||
}{
|
||||
{
|
||||
name: "expired and waiting",
|
||||
orders: []window{{-40 * time.Minute, -30 * time.Minute, model.OrderStatusExpired}, {-5 * time.Minute, 5 * time.Minute, model.OrderStatusWaiting}},
|
||||
wantEnd: 0,
|
||||
},
|
||||
{
|
||||
name: "earlier order expires later",
|
||||
orders: []window{{-60 * time.Minute, -10 * time.Minute, model.OrderStatusExpired}, {-40 * time.Minute, -30 * time.Minute, model.OrderStatusExpired}},
|
||||
wantEnd: -10 * time.Minute,
|
||||
},
|
||||
{
|
||||
name: "all waiting",
|
||||
orders: []window{{-5 * time.Minute, 5 * time.Minute, model.OrderStatusWaiting}},
|
||||
wantEnd: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentLookbackHour: "3"})
|
||||
lookbackDone.Clear()
|
||||
|
||||
now := time.Now()
|
||||
for i, w := range tt.orders {
|
||||
createTestOrder(t, model.Order{
|
||||
OrderId: fmt.Sprintf("merchant-order-%d", i),
|
||||
TradeId: fmt.Sprintf("trade-order-%d", i),
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: fmt.Sprintf("1.%02d", i),
|
||||
Money: "7.00",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: w.status,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
ExpiredAt: now.Add(w.expired),
|
||||
}, now.Add(w.created))
|
||||
}
|
||||
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
|
||||
if !ok || len(orderIDs) != len(tt.orders) {
|
||||
t.Fatalf("ok = %v, orders = %d, want %d", ok, len(orderIDs), len(tt.orders))
|
||||
}
|
||||
if want := now.Add(tt.orders[0].created).Unix(); startAt != want {
|
||||
t.Fatalf("startAt = %d, want %d", startAt, want)
|
||||
}
|
||||
if want := now.Add(tt.wantEnd).Unix(); endAt < want-1 || endAt > want+1 {
|
||||
t.Fatalf("endAt is %s before now, want %s", now.Sub(time.Unix(endAt, 0)).Round(time.Second), -tt.wantEnd)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+122
-53
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
blockapi "github.com/v03413/bepusdt/app/core"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
@@ -32,11 +33,14 @@ var usdtTrc20ContractAddress = []byte{0x41, 0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd,
|
||||
var usdcTrc20ContractAddress = []byte{0x41, 0x34, 0x87, 0xb6, 0x3d, 0x30, 0xb5, 0xb2, 0xc8, 0x7f, 0xb7, 0xff, 0xa8, 0xbc, 0xfa, 0xde, 0x38, 0xea, 0xac, 0x1a, 0xbe}
|
||||
|
||||
type tron struct {
|
||||
lastBlockNum int64
|
||||
blockConfirmedOffset int64
|
||||
blockScanQueue *chanx.UnboundedChan[int64]
|
||||
lastBlockNum int
|
||||
blockConfirmedOffset int
|
||||
blockScanQueue *chanx.UnboundedChan[int]
|
||||
conn map[string]*grpc.ClientConn
|
||||
connMu sync.RWMutex
|
||||
retryMu sync.Mutex
|
||||
retryAttempts map[int]int
|
||||
retryScheduled map[int]*time.Timer
|
||||
}
|
||||
|
||||
var tr tron
|
||||
@@ -46,14 +50,17 @@ func init() {
|
||||
Register(Task{Duration: time.Second, Callback: tr.blockDispatch})
|
||||
Register(Task{Duration: time.Second * 3, Callback: tr.syncBlocksForward})
|
||||
Register(Task{Duration: time.Second * 5, Callback: tr.tradeConfirmHandle})
|
||||
Register(Task{Duration: time.Second * 15, Callback: tr.lookbackBlocks})
|
||||
}
|
||||
|
||||
func newTron() tron {
|
||||
return tron{
|
||||
lastBlockNum: 0,
|
||||
blockConfirmedOffset: 30,
|
||||
blockScanQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
blockScanQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
|
||||
conn: make(map[string]*grpc.ClientConn),
|
||||
retryAttempts: make(map[int]int),
|
||||
retryScheduled: make(map[int]*time.Timer),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,11 +88,10 @@ func (t *tron) syncBlocksForward(context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var now = block.BlockHeader.RawData.Number
|
||||
var now = int(block.BlockHeader.RawData.Number)
|
||||
|
||||
// 区块高度变化过大,强制丢块重扫
|
||||
if now-t.lastBlockNum > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
t.syncBlocksBackward(now)
|
||||
if now-t.lastBlockNum > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
t.lastBlockNum = now - 1
|
||||
}
|
||||
|
||||
@@ -104,41 +110,32 @@ func (t *tron) syncBlocksForward(context.Context) {
|
||||
t.lastBlockNum = now
|
||||
}
|
||||
|
||||
// syncBlocksBackward 反向同步区块,针对程序启动前就已经存在待支付订单时,补齐之前的区块数据,自适应偏移数量
|
||||
func (t *tron) syncBlocksBackward(now int64) {
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(conf.Tron)
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Order("created_at asc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
|
||||
func (t *tron) lookbackBlocks(ctx context.Context) {
|
||||
if t.syncBreak() {
|
||||
return
|
||||
}
|
||||
|
||||
// 波场出块速度大概3秒一个,同时再冗余5个区块
|
||||
num := (time.Now().Unix() - o.CreatedAt.Time().Unix() + 1) / 3 // 计算需要反向扫描的区块数量
|
||||
start := now - num - 5 // 计算反向扫描的起始区块高度
|
||||
startAt, endAt, ok := getLookbackUnix(conf.Tron)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for b := now; b >= start; {
|
||||
if t.syncBreak() {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < 10 && b >= start; i++ {
|
||||
t.blockScanQueue.In <- b
|
||||
b--
|
||||
}
|
||||
|
||||
<-ticker.C
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Tron)
|
||||
for i := int(start); i <= int(end); i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
}()
|
||||
if t.syncBreak() {
|
||||
return
|
||||
}
|
||||
t.blockScanQueue.In <- i
|
||||
time.Sleep(time.Millisecond * 250) // 速率控制
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tron) blockDispatch(context.Context) {
|
||||
func (t *tron) blockDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(2, t.blockParse)
|
||||
if err != nil {
|
||||
log.Task.Warn("Error creating pool:", err)
|
||||
@@ -148,17 +145,25 @@ func (t *tron) blockDispatch(context.Context) {
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range t.blockScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
t.blockScanQueue.In <- n
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case n, ok := <-t.blockScanQueue.Out:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := p.Invoke(n); err != nil {
|
||||
t.scheduleBlockRetry(n, 0)
|
||||
|
||||
log.Task.Warn("Tron Error invoking process block:", err)
|
||||
log.Task.Warn("Tron Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tron) blockParse(n any) {
|
||||
var num = n.(int64)
|
||||
var num = n.(int)
|
||||
|
||||
var conn *grpc.ClientConn
|
||||
var err error
|
||||
@@ -168,19 +173,20 @@ func (t *tron) blockParse(n any) {
|
||||
return
|
||||
}
|
||||
|
||||
conf.RecordSuccess(conf.Tron)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
|
||||
bok, err2 := api.NewWalletClient(conn).GetBlockByNum2(ctx, &api.NumberMessage{Num: num})
|
||||
bok, err2 := api.NewWalletClient(conn).GetBlockByNum2(ctx, &api.NumberMessage{Num: int64(num)})
|
||||
cancel()
|
||||
if err2 != nil {
|
||||
conf.RecordFailure(conf.Tron)
|
||||
t.blockScanQueue.In <- num
|
||||
t.scheduleBlockRetry(num, 0)
|
||||
log.Task.Warn("GetBlockByNum2 ", err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
conf.RecordSuccess(conf.Tron, cast.ToString(num))
|
||||
t.resetBlockRetry(num)
|
||||
|
||||
var resources = make([]resource, 0)
|
||||
var transfers = make([]transfer, 0)
|
||||
var timestamp = time.UnixMilli(bok.GetBlockHeader().GetRawData().GetTimestamp())
|
||||
@@ -250,7 +256,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: t.base58CheckEncode(foo.ToAddress),
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.TronTrx,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -280,7 +286,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.UsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -306,7 +312,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -321,7 +327,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: to,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -332,7 +338,6 @@ func (t *tron) blockParse(n any) {
|
||||
if len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
if len(resources) > 0 {
|
||||
resourceQueue.In <- resources
|
||||
}
|
||||
@@ -474,14 +479,17 @@ func (t *tron) syncBreak() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
var count int64 = 0
|
||||
if mqttSubscribed(conf.Tron) {
|
||||
return false
|
||||
}
|
||||
|
||||
trade := []model.TradeType{model.TronTrx, model.UsdtTrc20, model.UsdcTrc20}
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Count(&count)
|
||||
if count > 0 {
|
||||
if hasLookbackOrders(trade) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var count int64 = 0
|
||||
model.Db.Model(&model.Wallet{}).Where("other_notify = ? and trade_type in (?)", model.WaOtherEnable, trade).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
@@ -491,6 +499,67 @@ func (t *tron) syncBreak() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *tron) scheduleBlockRetry(num int, delay time.Duration) {
|
||||
t.retryMu.Lock()
|
||||
if _, ok := t.retryScheduled[num]; ok {
|
||||
t.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
attempt := t.retryAttempts[num] + 1
|
||||
t.retryAttempts[num] = attempt
|
||||
|
||||
if delay <= 0 {
|
||||
delay = tronRetryDelay(attempt)
|
||||
}
|
||||
|
||||
var timer *time.Timer
|
||||
timer = time.AfterFunc(delay, func() {
|
||||
t.retryMu.Lock()
|
||||
if t.retryScheduled[num] != timer {
|
||||
t.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
delete(t.retryScheduled, num)
|
||||
t.retryMu.Unlock()
|
||||
|
||||
if t.blockScanQueue.Len() >= blockQueueLimit {
|
||||
log.Task.Warn("Tron 重试延后,当前区块消费堆积数量:", t.blockScanQueue.Len())
|
||||
t.scheduleBlockRetry(num, delay)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
t.blockScanQueue.In <- num
|
||||
})
|
||||
t.retryScheduled[num] = timer
|
||||
t.retryMu.Unlock()
|
||||
}
|
||||
|
||||
func (t *tron) resetBlockRetry(num int) {
|
||||
t.retryMu.Lock()
|
||||
defer t.retryMu.Unlock()
|
||||
|
||||
delete(t.retryAttempts, num)
|
||||
if timer, ok := t.retryScheduled[num]; ok {
|
||||
timer.Stop()
|
||||
delete(t.retryScheduled, num)
|
||||
}
|
||||
}
|
||||
|
||||
func tronRetryDelay(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
if attempt > 5 {
|
||||
attempt = 5
|
||||
}
|
||||
|
||||
return time.Duration(1<<uint(attempt-1)) * 5 * time.Second
|
||||
}
|
||||
|
||||
func (t *tron) client() (*grpc.ClientConn, error) {
|
||||
var endpoint = model.Endpoint(conf.Tron)
|
||||
|
||||
@@ -521,7 +590,7 @@ func (t *tron) client() (*grpc.ClientConn, error) {
|
||||
c.Close()
|
||||
}
|
||||
|
||||
conn, err := utils.NewTronGrpcClient(endpoint, model.GetK(model.RpcEndpointTronGridApiKey))
|
||||
conn, err := utils.NewTronGrpcClient(endpoint, model.GetTronGridApiKeys())
|
||||
if err != nil {
|
||||
|
||||
return nil, fmt.Errorf("连接失败: %w", err)
|
||||
|
||||
+3
-1
@@ -12,7 +12,8 @@ import (
|
||||
func xlayerInit() {
|
||||
ctx := context.Background()
|
||||
xlayer := evm{
|
||||
Network: conf.Xlayer,
|
||||
Network: conf.Xlayer,
|
||||
LookbackInterval: time.Millisecond * 300,
|
||||
Block: block{
|
||||
RollDelayOffset: 3,
|
||||
ConfirmedOffset: 12,
|
||||
@@ -24,4 +25,5 @@ func xlayerInit() {
|
||||
Register(Task{Callback: xlayer.blockDispatch})
|
||||
Register(Task{Callback: xlayer.syncBlocksForward, Duration: time.Second * 3})
|
||||
Register(Task{Callback: xlayer.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: xlayer.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/liteclient"
|
||||
tgo "github.com/xssnick/tonutils-go/ton"
|
||||
"github.com/xssnick/tonutils-go/ton/jetton"
|
||||
)
|
||||
|
||||
func IsValidTonAddress(value string) bool {
|
||||
if !strings.HasPrefix(value, "UQ") {
|
||||
return false
|
||||
}
|
||||
|
||||
_, err := address.ParseAddr(value)
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func NewTonClient(configUrl string) tgo.APIClientWrapped {
|
||||
pool := liteclient.NewConnectionPool()
|
||||
if err := pool.AddConnectionsFromConfigUrl(context.Background(), configUrl); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return tgo.NewAPIClient(pool).WithRetryTimeout(3, time.Second*5)
|
||||
}
|
||||
|
||||
func GetJettonWalletAddr(api tgo.APIClientWrapped, master *address.Address, owner *address.Address) (*address.Address, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
|
||||
client := jetton.NewJettonMasterClient(api, master)
|
||||
wallet, err := client.GetJettonWallet(ctx, owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return wallet.Address(), err
|
||||
}
|
||||
+8
-6
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// NewTronGrpcClient 目前很多 TRON API 基本都有QPS限制,过于激进或者过于保守的重试策略都不合适
|
||||
func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
func NewTronGrpcClient(apiNode string, apiKey []string) (*grpc.ClientConn, error) {
|
||||
apiNode = strings.TrimSpace(apiNode)
|
||||
if apiNode == "" {
|
||||
return nil, errors.New("tron api node address is empty")
|
||||
@@ -41,7 +41,7 @@ func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
}),
|
||||
}
|
||||
|
||||
if apiKey != "" {
|
||||
if len(apiKey) > 0 {
|
||||
opts = append(opts,
|
||||
grpc.WithUnaryInterceptor(tronGridApiKeyUnaryInterceptor(apiKey)),
|
||||
grpc.WithStreamInterceptor(tronGridApiKeyStreamInterceptor(apiKey)),
|
||||
@@ -51,18 +51,20 @@ func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
return grpc.NewClient(apiNode, opts...)
|
||||
}
|
||||
|
||||
func tronGridApiKeyUnaryInterceptor(apiKey string) grpc.UnaryClientInterceptor {
|
||||
func tronGridApiKeyUnaryInterceptor(apiKeys []string) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply interface{},
|
||||
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKey)
|
||||
i := time.Now().UnixMicro() % int64(len(apiKeys))
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKeys[i])
|
||||
return invoker(ctx, method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func tronGridApiKeyStreamInterceptor(apiKey string) grpc.StreamClientInterceptor {
|
||||
func tronGridApiKeyStreamInterceptor(apiKeys []string) grpc.StreamClientInterceptor {
|
||||
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn,
|
||||
method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKey)
|
||||
i := time.Now().UnixMicro() % int64(len(apiKeys))
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKeys[i])
|
||||
return streamer(ctx, desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
@@ -16,6 +18,7 @@ import (
|
||||
"unicode"
|
||||
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/gin-gonic/gin"
|
||||
nid "github.com/matoous/go-nanoid/v2"
|
||||
)
|
||||
|
||||
@@ -206,6 +209,22 @@ func StrSha256(str string) string {
|
||||
return fmt.Sprintf("%x", hash.Sum(nil))
|
||||
}
|
||||
|
||||
func IsAllowedCallbackURL(raw string) bool {
|
||||
// IsAllowedCallbackURL 校验回调/跳转地址格式是否合法
|
||||
// 规则:必须是合法 URL,且 scheme 只允许 http 或 https
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
u, err := url.ParseRequestURI(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
return u.Host != ""
|
||||
}
|
||||
|
||||
// GetRequestHost 识别完整的请求主机地址
|
||||
func GetRequestHost(r *http.Request) string {
|
||||
scheme := "http"
|
||||
@@ -236,3 +255,30 @@ func GetRequestHost(r *http.Request) string {
|
||||
|
||||
return scheme + "://" + r.Host
|
||||
}
|
||||
|
||||
// ClientFingerprint 客户端指纹
|
||||
func ClientFingerprint(ctx *gin.Context) string {
|
||||
ip := ctx.ClientIP()
|
||||
|
||||
if parsed := net.ParseIP(ip); parsed != nil {
|
||||
if v4 := parsed.To4(); v4 != nil {
|
||||
ip = fmt.Sprintf("%d.%d.%d.0", v4[0], v4[1], v4[2])
|
||||
} else if v6 := parsed.To16(); v6 != nil {
|
||||
var masked [16]byte
|
||||
copy(masked[:8], v6[:8])
|
||||
ip = net.IP(masked[:]).String()
|
||||
}
|
||||
}
|
||||
|
||||
parts := []string{
|
||||
ip,
|
||||
ctx.GetHeader("User-Agent"),
|
||||
ctx.GetHeader("Accept-Language"),
|
||||
ctx.GetHeader("Accept-Encoding"),
|
||||
ctx.GetHeader("Accept"),
|
||||
ctx.GetHeader("Sec-CH-UA"),
|
||||
ctx.GetHeader("Sec-CH-UA-Platform"),
|
||||
}
|
||||
|
||||
return StrSha256(strings.Join(parts, "|"))
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
FROM node:25.2.1 AS web_builder
|
||||
|
||||
# 安装 pnpm
|
||||
RUN npm install -g pnpm
|
||||
RUN npm install -g pnpm@10
|
||||
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/pnpm-lock.yaml ./
|
||||
@@ -11,7 +11,7 @@ RUN pnpm install --frozen-lockfile --shamefully-hoist
|
||||
COPY web/ ./
|
||||
RUN pnpm run build:prod
|
||||
|
||||
FROM golang:1.24.3-alpine3.20 AS builder
|
||||
FROM golang:1.26.2-alpine3.23 AS builder
|
||||
|
||||
ENV GO111MODULE=on
|
||||
WORKDIR /go/release
|
||||
Binary file not shown.
@@ -1,53 +1,3 @@
|
||||
# 异次元发卡 BEpusdt 对接指南
|
||||
# 异次元发卡 BEpusdt 对接
|
||||
|
||||
异次元应用商店提供的 `Epusdt` 插件存在一些问题,本文档提供优化适配版本的安装和配置方案。
|
||||
|
||||
## 对接流程
|
||||
|
||||
### 1. 前置条件
|
||||
|
||||
请先按照异次元官方文档完成 `Epusdt` 支付插件的标准安装流程。
|
||||
|
||||
- 位置:应用商店 → 支付接口
|
||||
- 搜索并安装官方 `Epusdt` 插件
|
||||
|
||||
### 2. 插件更新
|
||||
|
||||
[下载兼容适配版本](https://raw.githubusercontent.com/v03413/bepusdt/refs/heads/main/docs/api/acg-faka/Epusdt.zip)
|
||||
|
||||
**安装步骤:**
|
||||
|
||||
1. 进入异次元网站根目录
|
||||
2. 定位到 `app/Plugins/Epusdt` 目录
|
||||
3. 删除目录内所有文件
|
||||
4. 解压下载的插件包,将所有文件移入该目录
|
||||
|
||||
**权限配置:**
|
||||
|
||||
⚠️ 确保插件目录权限为 `www:www`(通常为默认配置)。如权限不符,请执行:
|
||||
|
||||
```bash
|
||||
chown -R www:www app/Plugins/Epusdt
|
||||
chmod -R 755 app/Plugins/Epusdt
|
||||
```
|
||||
|
||||
### 3. 插件配置
|
||||
|
||||
在异次元后台进行以下配置:
|
||||
|
||||
| 配置项 | 说明 | 示例 |
|
||||
|------|------------------------------|----------------------------|
|
||||
| 支付网关 | 必须以 `http(s)://` 开头,以 `/` 结尾 | `https://api.example.com/` |
|
||||
| 对接密钥 | 从 BEpusdt 后台获取 | - |
|
||||
| 法币单位 | 按需选择,默认推荐 `CNY` | `CNY` `USD` `JPY` |
|
||||
|
||||
### 4. 创建支付方式
|
||||
|
||||
在异次元后台完成以下操作:
|
||||
|
||||
1. 导航到:支付接口 → 添加支付
|
||||
2. 选择支付插件:`BEpusdt`
|
||||
3. 根据业务需求填写相关参数
|
||||
4. 保存配置
|
||||
|
||||
配置完成后,系统将自动启用该支付方式。
|
||||
当前异次元官方应用商店里面已经上架了支付插件`BEpusdt`,直接在商店搜索安装使用即可。
|
||||
+113
-129
@@ -1,5 +1,11 @@
|
||||
## 📚 API 对接文档
|
||||
|
||||
> 📡 **MQTT 实时推送**:系统支持将扫描到的链上交易广播到 MQTT 服务器,其它系统通过订阅即可实时获取数据,无需轮询
|
||||
> API。详见 [《MQTT 对接开发文档》](./mqtt.md)。
|
||||
|
||||
> 💡 **推荐阅读**:在开始对接前,建议先阅读 [《BEpusdt 执行原理说明》](./how-it-works.md)
|
||||
> ,了解订单匹配机制、金额匹配模式与汇率浮动等核心原理,有助于更准确地理解本文档中的参数设计。
|
||||
|
||||
### 基础信息
|
||||
|
||||
**认证方式**:签名认证(详见[签名算法](#签名算法))
|
||||
@@ -12,6 +18,17 @@
|
||||
|
||||
## 接口列表
|
||||
|
||||
> **两种订单模式说明**
|
||||
>
|
||||
> BEpusdt 的订单创建接口支持两种工作模式,通过 `amount` 参数决定:
|
||||
>
|
||||
> | 模式 | 触发条件 | 地址分配 | 匹配规则 | 典型场景 |
|
||||
> |------|---------|---------|---------|---------|
|
||||
> | **普通模式** | `amount > 0` | 地址 + 金额同时锁定 | 到账金额须匹配订单金额(±匹配容差) | 商城购物、固定金额收款 |
|
||||
> | **独占模式** | `amount = 0` 或不传 | 仅锁定地址,金额不限 | 任意金额到账均触发回调 | 充值场景、钱包监控、不定额收款 |
|
||||
>
|
||||
> 独占模式下,回调中的 `amount`(法币)和 `actual_amount`(加密货币)均以**实际到账金额**为准,创建订单时无需预设金额。
|
||||
|
||||
### 1. 创建交易
|
||||
|
||||
创建支付订单并获取收银台付款地址。
|
||||
@@ -29,15 +46,15 @@ POST /api/v1/order/create-transaction
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| amount | number | ✅ | 支付金额(法币金额) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| amount | number | ❌ | 支付金额(法币金额);留空或传 `0` 则进入**地址独占模式**,收到任意金额均触发回调(详见[执行原理](./how-it-works.md)) |
|
||||
| trade_type | string | ❌ | 交易类型,默认 `usdt.trc20`<br/>完整列表:[trade-type.md](../trade-type.md) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| address | string | ❌ | 指定收款地址(留空则自动分配) |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 120 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 120 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| rate | string | ❌ | 强制指定汇率,支持多种写法:<br/>• `7.4` - 固定汇率 7.4<br/>• `~1.02` - 最新汇率上浮 2%<br/>• `~0.97` - 最新汇率下浮 3%<br/>• `+0.3` - 最新汇率加 0.3<br/>• `-0.2` - 最新汇率减 0.2<br/>留空则使用系统配置汇率 |
|
||||
|
||||
#### 请求示例
|
||||
@@ -72,7 +89,7 @@ POST /api/v1/order/create-transaction
|
||||
| data.status | string | 订单状态,1 表示待付款 |
|
||||
| data.token | string | 收款地址 |
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台付款链接地址 |
|
||||
| data.payment_url | string | 收银台付款链接地址 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
|
||||
@@ -99,9 +116,8 @@ POST /api/v1/order/create-transaction
|
||||
|
||||
---
|
||||
|
||||
### 2. 取消交易订单
|
||||
|
||||
取消指定订单,系统将停止监控该订单并释放金额占用。
|
||||
<details>
|
||||
<summary><strong>2. 取消交易</strong> 取消指定订单,系统将停止监控该订单并释放金额占用。</summary>
|
||||
|
||||
#### 请求地址
|
||||
|
||||
@@ -138,13 +154,14 @@ POST /api/v1/order/cancel-transaction
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 3. 创建订单
|
||||
<details>
|
||||
<summary><strong>3. 创建订单</strong> 创建收银台订单,让用户在付款页自由选择支付方式。</summary>
|
||||
|
||||
创建支付订单并获取收银台付款链接,让用户自由选择已添加的付款方式。
|
||||
|
||||
> **注意**:使用相同 `order_id` 创建订单时,系统会根据最新参数重建订单(订单金额、交易类型、收款地址、法币类型),同时超时时间重置。这意味着商户可以基于同一订单号实现独立收银台,灵活变更支付参数。
|
||||
> **注意**:使用相同 `order_id` 创建订单时,系统会根据最新参数重建订单(订单金额、交易类型、收款地址、法币类型),同时超时时间重置。
|
||||
|
||||
#### 请求地址
|
||||
|
||||
@@ -154,17 +171,20 @@ POST /api/v1/order/create-order
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| amount | number | ✅ | 支付金额(法币金额) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| currencies | string | ❌ | 限定交易币种,留空则提不限制付款币种。<br/>多个币种请使用半角逗号分隔,黑名单模式以短横线开头。<br/>例如可配置为:<br/>`USDT`(仅限 USDT)<br/>`USDT,USDC` (限 USDT/USDC)<br/>`-ETH,-BNB` (表示排除 ETH/BNB 两个币种) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 180 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| amount | number | ❌ | 支付金额(法币金额);留空或传 `0` 则进入**地址独占模式**,收到任意金额均触发回调(详见[执行原理](./how-it-works.md)) |
|
||||
| currencies | string | ❌ | 限定交易币种,留空则不限制付款币种。<br/>多个币种请使用半角逗号分隔,黑名单模式以短横线开头。<br/>例如:<br/>`USDT`(仅限 USDT)<br/>`USDT,USDC` (限 USDT/USDC)<br/>`-ETH,-BNB` (排除 ETH/BNB) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 180 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| reselect | boolean | ❌ | 是否允许用户确认付款币种/网络后再次返回重选。<br/>仅对 `create-order` 创建的收银台订单生效;不传则使用后台“订单交易类型重选”全局开关,默认开启 |
|
||||
|
||||
> 传入 `reselect` 时,该参数需要参与签名计算。boolean 值按 JSON 布尔值传递,并按 `true` / `false` 小写字符串参与签名拼接。
|
||||
|
||||
#### 请求示例
|
||||
|
||||
@@ -178,6 +198,7 @@ POST /api/v1/order/create-order
|
||||
"notify_url": "https://example.com/notify",
|
||||
"redirect_url": "https://example.com/success",
|
||||
"timeout": 1200,
|
||||
"reselect": true,
|
||||
"signature": "1cd4b52df5587cfb1968b0c0c6e156cd"
|
||||
}
|
||||
```
|
||||
@@ -188,7 +209,6 @@ POST /api/v1/order/create-order
|
||||
|----------------------|--------|--------------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 订单数据 |
|
||||
| data.fiat | string | 交易法币类型 |
|
||||
| data.trade_id | string | 系统交易 ID |
|
||||
| data.order_id | string | 商户订单编号 |
|
||||
@@ -196,8 +216,7 @@ POST /api/v1/order/create-order
|
||||
| data.status | string | 订单状态,1 表示待付款 |
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台订单链接 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
| data.reselect | boolean | 当前订单是否允许用户确认付款币种/网络后再次返回重选。该值与 `/api/v1/pay/info` 的 `reselect` 语义一致,取自订单当前状态与订单自身配置 |
|
||||
|
||||
#### 响应示例
|
||||
|
||||
@@ -211,19 +230,23 @@ POST /api/v1/order/create-order
|
||||
"order_id": "20250120001",
|
||||
"amount": "28.88",
|
||||
"expiration_time": 1200,
|
||||
"payment_url": "https://example.com/pay/order/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
"reselect": true,
|
||||
"payment_url": "https://example.com/pay/cashier/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
> `reselect` 为 `true` 时,收银台可在用户选定付款币种/网络后提供“返回重选”入口;为 `false` 时,用户确认付款方式后不能再次切换。普通 `create-transaction` 创建的订单不支持交易类型重选。
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 4. 更新订单付款方式
|
||||
<details>
|
||||
<summary><strong>4. 更新订单付款方式</strong> 为收银台订单选定支付链,获取具体收款地址与金额。</summary>
|
||||
|
||||
用于向订单付款链接传递付款方式,得到收银台付款地址。
|
||||
|
||||
> **注意**:使用相同 `trade_id` 更新订单时,系统会根据最新交易类型更新订单付款方式。
|
||||
> **注意**:使用相同 `trade_id` 更新订单时,系统会根据最新交易类型更新订单付款方式。若订单已选定付款方式,则只有 `reselect` 为 `true` 且订单仍处于待支付状态时,才允许再次调用本接口切换付款币种/网络。
|
||||
|
||||
#### 请求地址
|
||||
|
||||
@@ -233,11 +256,11 @@ POST /api/v1/pay/update-order
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ✅ | 加密货币币种<br/>您已添加的加密货币币种,可选:`USDT`、`USDC`、`TRX` 等。 |
|
||||
| network | string | ✅ | 加密货币所属的网络名<br/>例如:`tron`、`polygon`、`bsc` 等。 |
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|----------|--------|----|-------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ✅ | 加密货币币种,可选:`USDT`、`USDC`、`TRX` 等 |
|
||||
| network | string | ✅ | 加密货币所属网络,如:`tron`、`polygon`、`bsc` 等 |
|
||||
|
||||
#### 请求示例
|
||||
|
||||
@@ -254,8 +277,6 @@ POST /api/v1/pay/update-order
|
||||
| 参数名 | 类型 | 说明 |
|
||||
|----------------------|--------|--------------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 订单数据 |
|
||||
| data.fiat | string | 交易法币类型 |
|
||||
| data.trade_id | string | 系统交易 ID |
|
||||
| data.order_id | string | 商户订单编号 |
|
||||
@@ -263,9 +284,7 @@ POST /api/v1/pay/update-order
|
||||
| data.actual_amount | string | 实际支付金额(加密货币) |
|
||||
| data.status | string | 订单状态,1 表示待付款 |
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台订单链接 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
| data.payment_url | string | 收银台付款链接 |
|
||||
|
||||
#### 响应示例
|
||||
|
||||
@@ -281,65 +300,56 @@ POST /api/v1/pay/update-order
|
||||
"actual_amount": "4.25",
|
||||
"expiration_time": 1200,
|
||||
"status": 1,
|
||||
"payment_url": "https://example.com/pay/order/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
"payment_url": "https://example.com/pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 订单可用付款方式列表:
|
||||
|
||||
## 接口说明
|
||||
- **URL**:`POST /api/v1/pay/methods`
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 请求参数
|
||||
<details>
|
||||
<summary><strong>5. 订单可用付款方式列表</strong> 返回指定订单当前所有可用的支付方式及实时报价。</summary>
|
||||
|
||||
### 请求体(JSON)
|
||||
#### 请求地址
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| trade_id | string | 是 | 系统交易 ID |
|
||||
| currency | string | 否 | 货币名称(如 USDT / USDC / TRX),不传则返回全部可用方式 |
|
||||
```http
|
||||
POST /api/v1/pay/methods
|
||||
```
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|----------|--------|----|---------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ❌ | 货币名称(如 USDT / USDC / TRX),不传则返回全部可用方式 |
|
||||
|
||||
#### 请求示例
|
||||
|
||||
### 请求示例
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### methods 字段说明
|
||||
|
||||
## 响应参数
|
||||
| 字段 | 类型 | 说明 |
|
||||
|-------------------|---------|--------------|
|
||||
| amount | string | 应付金额(法币) |
|
||||
| actual_amount | string | 实际支付金额(加密货币) |
|
||||
| fiat | string | 法币单位 |
|
||||
| exchange_rate | string | 汇率 |
|
||||
| currency | string | 货币名称 |
|
||||
| network | string | 网络名称 |
|
||||
| token_net_name | string | 代币协议标准名 |
|
||||
| token_custom_name | string | 用户自定义显示名称 |
|
||||
| is_popular | boolean | 是否为流行网络 |
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 数据对象 |
|
||||
| data.methods | array | 可用付款方式列表 |
|
||||
#### 响应示例
|
||||
|
||||
### methods 字段说明
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| amount | number | 应付金额(法币) |
|
||||
| actual_amount | number | 实际支付金额(加密货币) |
|
||||
| fiat | string | 应付金额法币单位 |
|
||||
| exchange_rate | number | 汇率 |
|
||||
| currency | string | 货币名称 |
|
||||
| network | string | 网络名称 |
|
||||
| token_net_name | string | 代币协议标准名 |
|
||||
| token_custom_name | string | 用户自定义显示名称 |
|
||||
| is_popular | boolean | 是否为流行网络 |
|
||||
|
||||
---
|
||||
|
||||
## 响应示例
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
@@ -350,63 +360,27 @@ POST /api/v1/pay/update-order
|
||||
"amount": "28.88",
|
||||
"actual_amount": "4.25",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"exchange_rate": "6.79",
|
||||
"currency": "USDT",
|
||||
"network": "bsc",
|
||||
"token_net_name": "BEP20",
|
||||
"token_custom_name": "",
|
||||
"is_popular": true
|
||||
},
|
||||
{
|
||||
"amount": "28.88",
|
||||
"actual_amount": "4.25",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"currency": "USDC",
|
||||
"network": "arbitrum",
|
||||
"token_net_name": "Arbitrum",
|
||||
"token_custom_name": "ARBITRUM-ONE",
|
||||
"is_popular": true
|
||||
},
|
||||
{
|
||||
"amount": "34.28",
|
||||
"actual_amount": "10",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"currency": "TRX",
|
||||
"network": "tron",
|
||||
"token_net_name": "TRC20",
|
||||
"token_custom_name": "",
|
||||
"is_popular": true
|
||||
},
|
||||
"is_popular": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
TODO: `is_popular` 当前临时返回为 `false` 待后期完善该功能。
|
||||
> TODO: `is_popular` 与 `token_custom_name` 当前为占位值,待后期完善。
|
||||
|
||||
TODO: `token_custom_name` 当前临时返回为空字符串,待后期完善该功能。
|
||||
|
||||
## 如果货币不存在则不响应内容
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"methods": [
|
||||
]
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 6. 支付回调通知
|
||||
|
||||
订单状态变更时,系统会向 `notify_url` 发送 POST 请求。
|
||||
<details>
|
||||
<summary><strong>6. 支付回调通知</strong> 订单状态变更时系统主动推送至 <code>notify_url</code>。</summary>
|
||||
|
||||
#### 通知参数
|
||||
|
||||
@@ -438,12 +412,15 @@ TODO: `token_custom_name` 当前临时返回为空字符串,待后期完善该
|
||||
|
||||
#### 响应要求
|
||||
|
||||
- **成功响应**:返回字符串 `success`(不区分大小写)
|
||||
- **失败响应**:返回其他内容,系统将重试通知
|
||||
- **成功**:返回字符串 `success`(不区分大小写)
|
||||
- **失败**:返回其他内容,系统将按退避策略重试通知
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 签名算法
|
||||
<details>
|
||||
<summary><strong>签名算法</strong></summary>
|
||||
|
||||
### 签名流程
|
||||
|
||||
@@ -490,7 +467,8 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
|
||||
### 代码参考
|
||||
|
||||
- **PHP 实现**:[点击查看](https://github.com/v03413/Epay-BEpusdt/blob/b7fa8fd608d71ce50e0f8eabb1717783c96761ac/bepusdt_plugin.php#L108:L127)
|
||||
- **PHP 实现
|
||||
**:[点击查看](https://github.com/v03413/Epay-BEpusdt/blob/b7fa8fd608d71ce50e0f8eabb1717783c96761ac/bepusdt_plugin.php#L108:L127)
|
||||
- **Python 实现**:[BEpusdt Python SDK](https://github.com/luoyanglang/bepusdt-python-sdk)
|
||||
|
||||
### 签名规则总结
|
||||
@@ -503,9 +481,12 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
| 必须按字典序排序 | 确保双方计算结果一致 |
|
||||
| MD5 结果必须小写 | 统一使用小写字母 |
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
<details>
|
||||
<summary><strong>常见问题</strong></summary>
|
||||
|
||||
### 1. 如何获取 API Token?
|
||||
|
||||
@@ -513,10 +494,11 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
|
||||
### 2. 订单重建机制是什么?
|
||||
|
||||
当使用相同 `order_id` 创建订单时:
|
||||
当使用相同 `order_id` 创建订单时,不同接口的处理方式不同:
|
||||
|
||||
- ✅ 更新订单金额、交易类型、收款地址、法币类型
|
||||
- ✅ **会** 重置超时时间
|
||||
- `create-transaction`:如果旧订单仍处于待支付状态,会按新参数重建订单,并重新计算超时时间
|
||||
- `create-order`:如果旧订单仍处于待支付状态,会返回已有订单,不会重置超时时间;后续调用 `update-order` 选择或重选付款币种/网络时,也会保留订单剩余有效期
|
||||
- 已支付成功或确认中的订单不会被重建
|
||||
|
||||
### 3. 支持哪些交易类型?
|
||||
|
||||
@@ -543,6 +525,8 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
4. 测试回调通知处理逻辑
|
||||
5. 确认超时和取消场景
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 104 KiB |
@@ -1,202 +1,67 @@
|
||||
# Dujiao-Next 对接教程
|
||||
# DuJiao Next 对接 BEpusdt 集成指南
|
||||
|
||||
本文档介绍如何在 [Dujiao-Next](https://github.com/dujiao-next/dujiao-next)(独角next)中对接 BEpusdt。
|
||||
**当前教程针对的是新版独角 [Dujiao Next](https://dujiao-next.com/),旧版独角数卡对接[请看这个](../dujiaoka/dujiaoka.md)**
|
||||
|
||||
## 前置条件
|
||||
## 前提条件
|
||||
|
||||
- BEpusdt 已成功安装并运行
|
||||
- Dujiao-Next 已部署
|
||||
在开始配置前,请确保已满足以下条件:
|
||||
|
||||
**BEpusdt 部署信息**
|
||||
|
||||
- API 服务地址:`https://your-bepusdt.com`
|
||||
- API 密钥:`your_api_token`
|
||||
|
||||
**DuJiao Next 部署信息**
|
||||
|
||||
- 部署地址:`https://your-dujiao.com`
|
||||
- 已进入后台管理界面
|
||||
- 已找到支付渠道管理 > 新增渠道功能
|
||||
|
||||
## 配置步骤
|
||||
|
||||
### 1. 进入支付渠道配置
|
||||
在 DuJiao Next 后台中选择渠道类型为 BEpusdt,按照以下格式进行配置。
|
||||
|
||||
Dujiao-Next 后台 → 支付渠道 → 新增渠道
|
||||

|
||||
|
||||
### 2. 基本参数填写
|
||||
**必填配置项**
|
||||
|
||||
| 参数名称 | 填写内容 | 说明 |
|
||||
|---------|---------|------|
|
||||
| 渠道名称 | USDT-TRC20 支付 | 自定义名称,建议包含币种 |
|
||||
| 渠道类型 | `epusdt` | 固定值,选择 BEpusdt |
|
||||
| 支付方式 | `usdt-trc20` / `usdc-trc20` / `trx` | 选择支持的币种 |
|
||||
| 交互方式 | `qr` 或 `redirect` | 二维码或跳转收银台 |
|
||||
| 配置项 | 说明 | 示例 |
|
||||
|-----------|--------------------|----------------------------------------------------|
|
||||
| 网关地址 | BEpusdt 的 API 服务地址 | `https://your-bepusdt.com` |
|
||||
| API Token | BEpusdt 的 API 密钥 | `your_api_token` |
|
||||
| 支付币种 | 支持的加密资产类型,严格区分大小写 | `usdt.trc20` |
|
||||
| 法币类型 | 支持的法定货币类型 | `CNY`、`USD`、`EUR`、`JPY`、`GBP` |
|
||||
| 异步通知地址 | 交易完成时的服务器异步回调地址 | `https://your-dujiao.com/api/v1/payments/callback` |
|
||||
| 同步回跳地址 | 用户支付完成后的页面跳转地址 | `https://your-dujiao.com/pay` |
|
||||
|
||||
### 3. 支持的渠道类型
|
||||
**配置说明**
|
||||
|
||||
Dujiao-Next 支持以下 BEpusdt 币种:
|
||||
- **支付币种**:详见 [支持的币种列表](https://github.com/v03413/BEpusdt/blob/main/docs/trade-type.md),必须严格区分大小写。
|
||||
- **法币类型**:仅支持 `CNY`、`USD`、`EUR`、`JPY`、`GBP` 五种,必须严格区分大小写。
|
||||
|
||||
| 渠道类型 | 说明 | 对应 trade_type |
|
||||
|---------|------|----------------|
|
||||
| `usdt-trc20` | USDT (TRC20) | `usdt.trc20` |
|
||||
| `usdc-trc20` | USDC (TRC20) | `usdc.trc20` |
|
||||
| `trx` | TRX | `tron.trx` |
|
||||
**⚠️ 重要说明:异步通知地址和同步回跳地址**
|
||||
|
||||
> **注意**:选择渠道类型后,系统会自动设置对应的 `trade_type`,无需手动填写。
|
||||
这两个地址的路由部分 **严格按要求修改**,只需将域名部分替换为您实际部署的 DuJiao Next 服务器地址:
|
||||
|
||||
### 4. 渠道配置参数
|
||||
- **异步通知地址**:`https://your-dujiao.com/api/v1/payments/callback`
|
||||
- 路由固定为 `/api/v1/payments/callback`
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `https://example.com/api/v1/payments/callback`
|
||||
|
||||
在「渠道配置」中填写以下 JSON:
|
||||
- **同步回跳地址**:`https://your-dujiao.com/pay`
|
||||
- 路由固定为 `/pay`
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `https://example.com/pay`
|
||||
|
||||
```json
|
||||
{
|
||||
"gateway_url": "https://your-bepusdt-domain.com",
|
||||
"auth_token": "your-api-token",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://your-api-domain.com/api/v1/payments/callback",
|
||||
"return_url": "https://your-user-domain.com/pay"
|
||||
}
|
||||
```
|
||||
## 配置验证
|
||||
|
||||
### 5. 配置参数说明
|
||||
配置完成后,请按照以下步骤进行测试:
|
||||
|
||||
| 参数 | 必填 | 说明 | 示例 |
|
||||
|------|------|------|------|
|
||||
| `gateway_url` | ✅ | BEpusdt 网关地址 | `https://pay.example.com` |
|
||||
| `auth_token` | ✅ | BEpusdt API Token | 从 BEpusdt 后台获取 |
|
||||
| `trade_type` | ❌ | 交易类型(自动设置) | `usdt.trc20` / `usdc.trc20` / `tron.trx` |
|
||||
| `fiat` | ❌ | 法币类型,默认 `CNY` | `CNY` / `USD` |
|
||||
| `notify_url` | ✅ | 异步回调地址 | `https://api.example.com/api/v1/payments/callback` |
|
||||
| `return_url` | ✅ | 支付成功跳转地址 | `https://shop.example.com/pay` |
|
||||
1. 进入 DuJiao Next 前台,进行支付测试。
|
||||
2. 观察是否正常跳转到支付页面。
|
||||
|
||||
> **重要提示**:
|
||||
> - `trade_type` 会根据「支付方式」自动设置,无需在配置中填写
|
||||
> - `notify_url` 路径必须是 `/api/v1/payments/callback`(不是 `/api/public/payment/callback`)
|
||||
> - `return_url` 路径必须是 `/pay`(不是 `/order` 或 `/payment`)
|
||||
## 故障排查
|
||||
|
||||
## 获取 API Token
|
||||
若出现网关错误提示,请按照以下步骤排查:
|
||||
|
||||
1. 登录 BEpusdt 后台
|
||||
2. 系统管理 → 基本设置 → API 设置
|
||||
3. 复制「对接令牌」
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 示例 1:USDT-TRC20 支付
|
||||
|
||||
```
|
||||
渠道名称: USDT-TRC20 支付
|
||||
渠道类型: epusdt
|
||||
支付方式: usdt-trc20
|
||||
交互方式: qr
|
||||
|
||||
渠道配置:
|
||||
{
|
||||
"gateway_url": "http://127.0.0.1:8088",
|
||||
"auth_token": "your-token-here",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://api.example.com/api/v1/payments/callback",
|
||||
"return_url": "https://shop.example.com/pay"
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 2:TRX 支付
|
||||
|
||||
```
|
||||
渠道名称: TRX 支付
|
||||
渠道类型: epusdt
|
||||
支付方式: trx
|
||||
交互方式: redirect
|
||||
|
||||
渠道配置:
|
||||
{
|
||||
"gateway_url": "http://127.0.0.1:8088",
|
||||
"auth_token": "your-token-here",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://api.example.com/api/v1/payments/callback",
|
||||
"return_url": "https://shop.example.com/pay"
|
||||
}
|
||||
```
|
||||
|
||||
## 回调机制说明
|
||||
|
||||
### 异步通知(notify_url)
|
||||
|
||||
BEpusdt 会在支付状态变化时,向 `notify_url` 发送 POST 请求:
|
||||
|
||||
```
|
||||
POST /api/v1/payments/callback
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
order_id=xxx&trade_id=xxx&amount=xxx&actual_amount=xxx&token=xxx&...&signature=xxx
|
||||
```
|
||||
|
||||
Dujiao-Next 会验证签名并更新订单状态。
|
||||
|
||||
### 同步跳转(return_url)
|
||||
|
||||
用户支付完成后,BEpusdt 会跳转到 `return_url`,并附带参数:
|
||||
|
||||
```
|
||||
https://shop.example.com/pay?order_id=xxx&epusdt_return=1
|
||||
```
|
||||
|
||||
Dujiao-Next 前端会检测 `epusdt_return=1` 参数,自动查询订单状态并显示支付结果。
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 1. 支付创建失败
|
||||
|
||||
**可能原因**:
|
||||
- `gateway_url` 配置错误或 BEpusdt 服务未运行
|
||||
- `auth_token` 与 BEpusdt 配置不一致
|
||||
- 网络连接问题(检查防火墙)
|
||||
|
||||
**解决方法**:
|
||||
- 检查 BEpusdt 服务状态:`curl http://your-bepusdt/health`
|
||||
- 验证 API Token 是否正确
|
||||
- 查看 Dujiao-Next 后端日志
|
||||
|
||||
### 2. 回调未收到或订单状态未更新
|
||||
|
||||
**可能原因**:
|
||||
- `notify_url` 配置错误(路径必须是 `/api/v1/payments/callback`)
|
||||
- BEpusdt 无法访问回调地址(网络/防火墙问题)
|
||||
- 签名验证失败
|
||||
|
||||
**解决方法**:
|
||||
- 确认回调地址可被外网访问:`curl https://your-api/api/v1/payments/callback`
|
||||
- 检查 BEpusdt 日志中的回调错误
|
||||
- 检查 Dujiao-Next 后端日志中的签名验证信息
|
||||
|
||||
### 3. 支付完成后跳转错误
|
||||
|
||||
**可能原因**:
|
||||
- `return_url` 路径配置错误(必须是 `/pay` 不是 `/payment` 或 `/order`)
|
||||
- 前端路由配置问题
|
||||
|
||||
**解决方法**:
|
||||
- 确认 `return_url` 配置为:`https://your-user-domain.com/pay`
|
||||
- 清除浏览器缓存后重试
|
||||
|
||||
### 4. 签名验证失败
|
||||
|
||||
**可能原因**:
|
||||
- `auth_token` 不一致(注意前后空格)
|
||||
- 回调参数被中间件修改
|
||||
|
||||
**解决方法**:
|
||||
- 确保 `auth_token` 完全一致
|
||||
- 检查是否有反向代理修改了请求参数
|
||||
|
||||
### 5. 金额不匹配
|
||||
|
||||
**可能原因**:
|
||||
- 汇率波动导致实际支付金额与订单金额不同
|
||||
- BEpusdt 配置的汇率源问题
|
||||
|
||||
**解决方法**:
|
||||
- BEpusdt 会返回 `actual_amount`(实际支付金额),Dujiao-Next 会记录此金额
|
||||
- 可在订单详情中查看实际支付金额
|
||||
|
||||
## 技术支持
|
||||
|
||||
- Dujiao-Next: [GitHub Issues](https://github.com/dujiao-next/dujiao-next/issues)
|
||||
- BEpusdt: [Telegram 群组](https://t.me/BEpusdtChat)
|
||||
|
||||
---
|
||||
|
||||
**贡献者**: 狼哥 ([@luoyanglang](https://github.com/luoyanglang) | Telegram: [@luoyanglang](https://t.me/luoyanglang))
|
||||
|
||||
> 本文档适用于 Dujiao-Next 最新版本和 BEpusdt 最新版本
|
||||
> 最后更新:2026-02-13
|
||||
- **检查网络连通性**:确认 DuJiao Next API 所在服务器能够正常访问 BEpusdt API 地址。
|
||||
- **检查 API Token**:确认所配置的 API Token 与 BEpusdt 中的密钥一致。
|
||||
- **查看日志**:检查 DuJiao Next 和 BEpusdt 的应用日志,获取更详细的错误信息。
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 90 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
@@ -0,0 +1,79 @@
|
||||
# EdgeKey 对接 BEpusdt 教程
|
||||
|
||||
**当前教程对接BEpusdt(v1.23.5)通过测试验收**
|
||||
|
||||
## 配置步骤
|
||||
|
||||
**配置说明**
|
||||
|
||||
- **网关地址**:只需填写域名,如 `https://test.shop.com`,系统会自动拼接 API 路径(`/api/v1/order/create-order`)。
|
||||
- **App ID 和 App Secret**:在 BEpusdt 后台「系统管理 → 基本设置 → API 设置」中获取。
|
||||
- **支付币种**:用户在 BEpusdt 收银台页面自由选择支付币种,具体在 BEpusdt 后台配置。
|
||||
|
||||
**配置步骤示例**:
|
||||
1. 登录 EdgeKey 管理后台
|
||||
2. 进入「支付配置」页面
|
||||
3. 选择 BEpusdt 标签页
|
||||
4. 填写具体配置
|
||||
5. 启用支付方式:点击右上角的启用开关
|
||||
6. 保存配置:点击「保存配置」按钮
|
||||
|
||||

|
||||
|
||||
### 重要提示
|
||||
填写完配置信息后,点击右上角的 **启用** 开关,然后点击 **保存配置** 按钮。
|
||||
⚠️ **重要提示**:启用支付前,请先前往「站点设置」配置网站地址,否则无法获取支付结果。
|
||||
|
||||

|
||||
|
||||
## 配置字段说明
|
||||
|
||||
**通用字段说明**:
|
||||
- **显示名称**:支付方式在前台显示的名称,用户可自定义
|
||||
- **网关地址**:支付网关服务域名,系统会自动处理接口路径
|
||||
- **Notify URL**:异步通知地址,支付完成后系统会回调此地址
|
||||
- **Return URL**:同步回跳地址,用户支付完成后跳转的页面
|
||||
|
||||
**BEpusdt专用字段**:
|
||||
- **App ID**:BEpusdt后台获取的应用ID
|
||||
- **App Secret**:BEpusdt后台获取的应用密钥(API密钥)
|
||||
|
||||
|
||||
## 异步通知地址和同步回跳地址
|
||||
|
||||
这两个地址的路由部分 **严格按要求填写**,只需将域名部分替换为您实际部署的 EdgeKey 服务器地址:
|
||||
|
||||
- **异步通知地址**:`/api/payments/bepusdt/notify`
|
||||
- 路由固定为 `/api/payments/bepusdt/notify`
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `/api/payments/bepusdt/notify`
|
||||
|
||||
- **同步回跳地址**:`/order/{orderNo}?token={token}`
|
||||
- 路由固定为 `/order/{orderNo}?token={token}`(`:orderNo` 和 `{token}` 为动态参数)
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `/order/{orderNo}?token={token}`
|
||||
|
||||
## 配置验证
|
||||
|
||||
配置完成后,请按照以下步骤进行测试:
|
||||
|
||||
1. 进入 EdgeKey 前台,选择一个商品进行购买。
|
||||
2. 在结算页面选择 BEpusdt 支付方式。
|
||||
3. 观察是否正常跳转到收银台页面。
|
||||
|
||||
## 故障排查
|
||||
|
||||
若出现网关错误提示,请按照以下步骤排查:
|
||||
|
||||
- **检查网络连通性**:确认 EdgeKey 服务器能够正常访问 BEpusdt API 地址。
|
||||
- **检查 App ID 和 App Secret**:确认所配置的 App ID 和 App Secret 与 BEpusdt 中的一致。
|
||||
- **检查回调地址**:确保异步通知地址可以从外部访问,且格式正确。
|
||||
- **检查站点设置**:确保在「站点设置」中配置了正确的网站地址。
|
||||
- **查看日志**:检查 EdgeKey 和 BEpusdt 的应用日志,获取更详细的错误信息。
|
||||
|
||||
## BEpusdt 工作模式
|
||||
|
||||
本项目使用 **收银台模式**(`/api/v1/order/create-order`),用户在 BEpusdt 收银台页面自由选择支付链,无需在代码中指定 `trade_type`。
|
||||
|
||||
## 相关链接
|
||||
|
||||
- [BEpusdt 项目主页](https://github.com/v03413/bepusdt)
|
||||
- [EdgeKey 项目主页](https://github.com/34892002/edgeKey)
|
||||
@@ -0,0 +1,508 @@
|
||||
# BEpusdt 执行原理说明
|
||||
|
||||
> 本文档基于源代码逐层拆解 BEpusdt 的核心运行机制,适合开发者对接或二次开发时参考。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
1. [底层区块扫描](#1-底层区块链持续扫描)
|
||||
2. [订单匹配原理](#2-订单匹配原理)
|
||||
3. [地址独占模式](#3-地址独占模式)
|
||||
4. [汇率浮动说明](#4-汇率浮动说明)
|
||||
|
||||
---
|
||||
|
||||
## 1. 底层区块链持续扫描
|
||||
|
||||
### 1.1 整体扫描架构
|
||||
|
||||
BEpusdt 的区块扫描采用 **全链路扫块 + 本地匹配** 的方式,而非对每个地址发起单独的查询请求。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ 区块链网络节点 (RPC) │
|
||||
│ Tron gRPC EVM JSON-RPC (BSC / ETH / Polygon…) │
|
||||
└──────────┬──────────────────────────┬───────────────────────────┘
|
||||
│ 每 ~3s 拉取最新区块高度 │ 每 ~5s 拉取最新区块高度
|
||||
▼ ▼
|
||||
┌──────────────────┐ ┌──────────────────────┐
|
||||
│ syncBlocksForward│ │ syncBlocksForward │
|
||||
│ (Tron 正向同步) │ │ (EVM 正向同步) │
|
||||
└────────┬─────────┘ └──────────┬───────────┘
|
||||
│ 待扫区块编号入队 │ 待扫区块范围入队 (批量最多10个)
|
||||
▼ ▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ blockScanQueue (无界异步队列) │
|
||||
│ chanx.UnboundedChan · 最大堆积 100 个 │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│ 消费
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ blockDispatch (goroutine worker pool) │
|
||||
│ Tron: 2 个并发 Worker EVM: 3 个并发 Worker │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│ 解析完成
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ transferQueue │
|
||||
│ 提取出的 transfer 记录入队 │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ orderTransferHandle (订单匹配) │
|
||||
└────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
> 源码位置:`app/task/tron.go` · `app/task/evm.go` · `app/task/transfer.go`
|
||||
|
||||
---
|
||||
|
||||
### 1.2 扫块两种方向
|
||||
|
||||
| 方向 | 触发条件 | 目的 |
|
||||
|---------------------------------|--------------------|-----------------------------|
|
||||
| **正向扫描** (`syncBlocksForward`) | 定时循环 | 实时跟随链上最新区块,保证新交易不漏掉 |
|
||||
| **反向扫描** (`syncBlocksBackward`) | 程序首次启动,或检测到已有待支付订单 | 补扫程序 **未运行期间** 产生的历史区块,防止漏单 |
|
||||
|
||||
反向扫描回溯量的计算逻辑(以 Tron 为例):
|
||||
|
||||
```
|
||||
回溯区块数 = (当前时间 - 最早待支付订单创建时间) / 3秒(波场出块速度) + 冗余5个区块
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 对比「单地址轮询」的优势
|
||||
|
||||
市面上许多同类项目的做法是:对每个收款地址,定时调用 `getTransactionsByAddress` 之类的 API 来查询该地址的交易记录。
|
||||
|
||||
BEpusdt 采用 **全量扫块** 的策略,具体区别如下:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ 传统「单地址轮询」模式 │
|
||||
│ │
|
||||
│ 地址A ──→ getTransactions(A) ──→ API 调用 ×1 │
|
||||
│ 地址B ──→ getTransactions(B) ──→ API 调用 ×1 │
|
||||
│ 地址C ──→ getTransactions(C) ──→ API 调用 ×1 │
|
||||
│ ⋮ ⋮ │
|
||||
│ 地址N ──→ getTransactions(N) ──→ API 调用 ×N │
|
||||
│ │
|
||||
│ 总 API 调用次数 = 地址数量 × 轮询频率 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ BEpusdt「全量扫块」模式 │
|
||||
│ │
|
||||
│ 区块 #N ──→ getBlock(N) ──→ API 调用 ×1 │
|
||||
│ │ │
|
||||
│ ├─ 解析出所有 transfer │
|
||||
│ └─ 本地内存匹配:地址A / 地址B / 地址C / … 地址N │
|
||||
│ │
|
||||
│ 总 API 调用次数 = 区块数 (与地址数量无关) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**核心优势:**
|
||||
|
||||
| 维度 | 单地址轮询 | 全量扫块 (BEpusdt) |
|
||||
|----------|------------------|-------------------|
|
||||
| API 调用量 | 与地址数线性增长 | **固定**,与地址数无关 |
|
||||
| RPC 节点压力 | 高(易触发限流) | **低**,易满足免费节点限额 |
|
||||
| 地址扩展性 | 增加地址 = 增加 API 压力 | **随意添加**地址,无额外成本 |
|
||||
| 实时性 | 受限于轮询间隔 | 与出块速度对齐(秒级) |
|
||||
| 漏单风险 | 较高(轮询窗口期) | **低**,区块连续无跳跃 |
|
||||
| 历史回溯 | 依赖节点接口能力 | **内建支持**,自动补扫历史区块 |
|
||||
|
||||
---
|
||||
|
||||
### 1.4 Tron 与 EVM 扫块的技术差异
|
||||
|
||||
| 项目 | Tron | EVM 系列 |
|
||||
|-------------|-------------------|--------------------------------------|
|
||||
| 通信协议 | gRPC(长连接复用) | HTTP JSON-RPC |
|
||||
| 出块时间 | ~3 秒 | 1~12 秒不等 |
|
||||
| 扫块触发频率 | 每 3 秒 | 每 5 秒 |
|
||||
| 每次批量区块数 | 1 个 | 最多 10 个 |
|
||||
| Token 事件解析 | 手动解析合约 ABI 数据 | `eth_getLogs` + ERC-20 Transfer 事件签名 |
|
||||
| Gas Free 支持 | ✅ 特殊解析 GasFree 合约 | — |
|
||||
|
||||
---
|
||||
|
||||
## 2. 订单匹配原理
|
||||
|
||||
### 2.1 匹配键:地址 + 交易类型
|
||||
|
||||
系统在内存中维护一张等待匹配的订单索引表,Key 由 **收款地址 + 交易类型** 组成:
|
||||
|
||||
```go
|
||||
// app/task/transfer.go · getAllWaitingOrders()
|
||||
key := t.Address + string(t.TradeType)
|
||||
// 例:
|
||||
// "TRX123...abcusdt.trc20"
|
||||
// "0xABC...defusdt.bep20"
|
||||
```
|
||||
|
||||
每当从区块中解析出一笔 `transfer`,就以 `RecvAddress + TradeType` 为 Key 在索引表中查找候选订单,再进一步做金额比对。
|
||||
|
||||
---
|
||||
|
||||
### 2.2 同地址同金额冲突的处理
|
||||
|
||||
**创建订单时**的冲突检测与自动规避(`app/model/order.go · CalcTradeAmount`):
|
||||
|
||||
```
|
||||
创建订单
|
||||
│
|
||||
▼
|
||||
查询当前所有「等待中」和「确认中」的订单
|
||||
│
|
||||
▼
|
||||
构建冲突锁表:lock["地址+金额"] = true
|
||||
│
|
||||
▼
|
||||
计算本次订单金额(法币 ÷ 汇率,保留精度)
|
||||
│
|
||||
▼
|
||||
检查 lock["地址A + 金额X"] 是否存在?
|
||||
│
|
||||
├─ 不存在 ──→ 直接分配,订单创建成功
|
||||
│
|
||||
└─ 已存在 ──→ 金额 += 1个原子精度单位,重新检查
|
||||
最多尝试 100 次,超出则报错
|
||||
|
||||
```
|
||||
|
||||
**示例:**
|
||||
|
||||
```
|
||||
已有订单:地址A / 10.01 USDT
|
||||
新订单金额计算结果也是:10.01 USDT
|
||||
→ 冲突!自动调整为 10.02 USDT
|
||||
再有同地址订单:
|
||||
→ 调整为 10.03 USDT
|
||||
```
|
||||
|
||||
**扫块匹配时**的防重(`app/task/transfer.go · orderTransferHandle`):
|
||||
|
||||
同一批次 `transfer` 中,一旦某笔交易匹配了订单,该订单会被**立即从内存 Map 中移除**,确保批次内其他 transfer 不会重复命中同一订单。
|
||||
|
||||
---
|
||||
|
||||
### 2.3 金额匹配三种模式
|
||||
|
||||
系统提供三种金额匹配策略,可在后台「支付设置」中配置(`payment_match_mode`):
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式一:Classic(经典精确匹配) │
|
||||
│ │
|
||||
│ 规则:实际到账金额字符串 == 订单金额字符串(完全相等) │
|
||||
│ │
|
||||
│ 订单金额:10.01 │
|
||||
│ 到账金额:10.01 ✅ 匹配 │
|
||||
│ 到账金额:10.011 ❌ 不匹配 │
|
||||
│ 到账金额:10.02 ❌ 不匹配 │
|
||||
│ │
|
||||
│ 适用场景:对收款金额精确控制,防止多付混淆 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式二:HasPrefix(前缀匹配 / 允许多付) │
|
||||
│ │
|
||||
│ 规则:实际到账金额以订单金额为前缀,允许多付小数 │
|
||||
│ │
|
||||
│ 订单金额:10.01 │
|
||||
│ 到账金额:10.01 ✅ 匹配(完全等于) │
|
||||
│ 到账金额:10.011 ✅ 匹配(以 10.01 为前缀) │
|
||||
│ 到账金额:10.019 ✅ 匹配(以 10.01 为前缀) │
|
||||
│ 到账金额:10.02 ❌ 不匹配 │
|
||||
│ │
|
||||
│ 适用场景:用户手动转账时可能多付小数,允许容错 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式三:RoundOff(数值修约 / 四舍五入) │
|
||||
│ │
|
||||
│ 规则:将两边金额按精度四舍五入后比较 │
|
||||
│ 精度取:订单金额的实际小数位 与 币种标准精度 中较大值 │
|
||||
│ │
|
||||
│ 订单金额:10.01 (精度2位) │
|
||||
│ 到账金额:10.014 → 四舍五入 → 10.01 ✅ 匹配 │
|
||||
│ 到账金额:10.015 → 四舍五入 → 10.02 ❌ 不匹配 │
|
||||
│ 到账金额:10.009 → 四舍五入 → 10.01 ✅ 匹配 │
|
||||
│ │
|
||||
│ 适用场景:链上转账因精度截断导致微小误差,允许容错 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
> 源码位置:`app/task/transfer.go · amountMatch()`
|
||||
|
||||
---
|
||||
|
||||
### 2.4 完整匹配流程图
|
||||
|
||||
```
|
||||
区块扫描 ──→ 解析出 transfer 列表 ──→ transferQueue
|
||||
│
|
||||
▼
|
||||
每 1 秒批量处理(batchInterval)
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 获取所有等待中订单 │
|
||||
│ 构建内存索引 Map │
|
||||
│ Key = 地址 + 交易类型 │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
遍历 transfer 列表
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ 按 Key 查找候选订单 │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ 金额范围是否合法? │
|
||||
└──────────┬──────────┘
|
||||
否 ↙ ↘ 是
|
||||
进入非订单流 检查独占 or amountMatch
|
||||
(notOrderQueue) │
|
||||
┌──────▼──────┐
|
||||
│ 有效期验证 │
|
||||
│ 创建时间 < │
|
||||
│ 交易时间 < │
|
||||
│ 过期时间 │
|
||||
└──────┬──────┘
|
||||
│ 通过
|
||||
┌──────▼──────┐
|
||||
│ 内存移除订单 │
|
||||
│ 标记确认中 │
|
||||
│ 写入区块/Hash │
|
||||
└──────┬──────┘
|
||||
│
|
||||
等待区块确认偏移
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ 标记成功 │
|
||||
│ 触发回调 │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 地址独占模式
|
||||
|
||||
### 3.1 什么是地址独占
|
||||
|
||||
普通订单:分配 **地址 + 金额**,系统根据「地址+金额」双重维度匹配交易。
|
||||
|
||||
地址独占模式:**只分配地址,不指定金额**。该地址在订单存续期间被独占,任何金额的收款都会触发回调。
|
||||
|
||||
**触发条件:** 创建订单时不传 `amount` 字段(或传 `0`)。
|
||||
|
||||
```go
|
||||
// app/handler/epusdt/epusdt.go · CreateTransaction()
|
||||
AddressLocked: req.Amount == 0, // 金额为0 → 独占模式
|
||||
|
||||
// app/model/trade.go · BuildOrder()
|
||||
AddressLocked: p.Money.IsZero(), // 零值订单 → 地址锁定
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.2 地址独占分配逻辑
|
||||
|
||||
```
|
||||
创建独占订单
|
||||
│
|
||||
▼
|
||||
LockTradeAddress(addressPool, tradeType)
|
||||
│
|
||||
遍历所有可用地址
|
||||
│
|
||||
├─ 地址A:查询是否有「等待中」或「确认中」的独占订单?
|
||||
│ → 有 → 跳过(该地址已被占用)
|
||||
│ → 无 → ✅ 分配此地址,Amount = "0"
|
||||
│
|
||||
├─ 地址B:同上检测 …
|
||||
│
|
||||
└─ 全部地址已被占用 → 返回错误「暂无可用钱包地址」
|
||||
```
|
||||
|
||||
> 独占模式下,同一地址不会同时存在两个有效的独占订单。
|
||||
|
||||
---
|
||||
|
||||
### 3.3 独占订单的匹配行为
|
||||
|
||||
```go
|
||||
// app/task/transfer.go · orderTransferHandle()
|
||||
// 独占订单跳过金额匹配,任何入账均可命中
|
||||
if !o.AddressLocked && !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
continue // 普通订单:金额不符则跳过
|
||||
}
|
||||
// 独占订单:o.AddressLocked = true,直接跳过此 if,进入有效期检查
|
||||
```
|
||||
|
||||
收款后,系统用实际到账金额和订单创建时锁定的汇率,**动态计算法币金额**并写入订单:
|
||||
|
||||
```go
|
||||
// app/model/order.go · MarkConfirming()
|
||||
if o.AddressLocked {
|
||||
rate, _ := decimal.NewFromString(o.Rate)
|
||||
o.Amount = amount.String() // 实际到账加密货币数量
|
||||
o.Money = rate.Mul(amount).String() // 折算法币金额
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.4 独占模式 vs 普通模式对比
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 普通订单(带金额) │
|
||||
│ │
|
||||
│ 创建 → 分配:地址A + 金额 10.01 USDT │
|
||||
│ 收款条件:必须向地址A 转入 10.01 USDT(±匹配模式容差) │
|
||||
│ 回调内容:包含约定金额 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 独占订单(不带金额) │
|
||||
│ │
|
||||
│ 创建 → 分配:地址A(独占,金额=0) │
|
||||
│ 收款条件:向地址A 转入 任意金额(大于监控最小金额即可) │
|
||||
│ 回调内容:包含实际到账金额 + 汇率折算法币金额 │
|
||||
│ 典型用途:充值场景、不定额收款、钱包监控 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 汇率浮动说明
|
||||
|
||||
### 4.1 汇率来源
|
||||
|
||||
BEpusdt 通过 **CoinGecko API** 定期同步加密货币对多种法币(CNY / USD / JPY / EUR / GBP)的实时汇率。
|
||||
|
||||
```
|
||||
定时任务(默认间隔 3600 秒)
|
||||
│
|
||||
▼
|
||||
GET https://api.coingecko.com/api/v3/simple/price
|
||||
?ids=tether,usd-coin,tron,binancecoin,ethereum
|
||||
&vs_currencies=cny,usd,jpy,eur,gbp
|
||||
│
|
||||
▼
|
||||
写入数据库 bep_rate 表
|
||||
(含 raw_rate 原始汇率 + syntax 浮动语法 + 最终 rate)
|
||||
```
|
||||
|
||||
> 同步间隔可在后台「系统设置」中调整,最短可设置为数秒级。
|
||||
|
||||
---
|
||||
|
||||
### 4.2 汇率浮动语法
|
||||
|
||||
除直接使用 CoinGecko 的原始汇率外,系统支持为每种 **加密货币 × 法币** 对单独设置浮动语法,实现灵活调价。
|
||||
|
||||
浮动语法规则(配置键:`rate_float_<CRYPTO>_<FIAT>`,如 `rate_float_USDT_CNY`):
|
||||
|
||||
```
|
||||
┌────────────┬───────────────────────────────────────────────────────┐
|
||||
│ 语法格式 │ 说明 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ 7.25 │ 固定汇率,直接使用该数值,忽略 CoinGecko 原始价格 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ ~1.05 │ 乘以系数:最终汇率 = 原始汇率 × 1.05(上浮 5%) │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ +0.1 │ 加固定值:最终汇率 = 原始汇率 + 0.1 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ -0.05 │ 减固定值:最终汇率 = 原始汇率 - 0.05 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ (空) │ 不浮动,直接使用 CoinGecko 原始汇率 │
|
||||
└────────────┴───────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**示例计算:**
|
||||
|
||||
```
|
||||
CoinGecko 当前 USDT/CNY = 7.2456
|
||||
|
||||
语法 ~1.03 → 最终汇率 = 7.2456 × 1.03 = 7.4630
|
||||
语法 +0.20 → 最终汇率 = 7.2456 + 0.20 = 7.4456
|
||||
语法 7.30 → 最终汇率 = 7.30(固定,不参考市价)
|
||||
语法 (空) → 最终汇率 = 7.2456(原始市价)
|
||||
```
|
||||
|
||||
> 最终汇率保留 4 位小数。源码:`app/model/rate.go · ParseFloatRate()`
|
||||
|
||||
---
|
||||
|
||||
### 4.3 汇率在订单生命周期中的作用
|
||||
|
||||
```
|
||||
创建订单
|
||||
│
|
||||
├─ 从 bep_rate 获取最新汇率(含浮动计算)
|
||||
│
|
||||
├─ 法币金额 ÷ 汇率 = 加密货币金额(按精度取整)
|
||||
│
|
||||
└─ 汇率快照写入订单 rate 字段(后续不再变更)
|
||||
│
|
||||
▼
|
||||
订单支付期间
|
||||
│
|
||||
汇率波动不影响本次订单
|
||||
│
|
||||
▼
|
||||
收款成功
|
||||
│
|
||||
├─ 普通订单:以创建时约定金额为准,回调包含法币金额
|
||||
│
|
||||
└─ 独占订单:以实际到账金额 × 快照汇率计算法币金额
|
||||
```
|
||||
|
||||
> 汇率快照机制保证了**下单瞬间确定交易金额**,不因支付期间行情波动而产生金额争议。
|
||||
|
||||
---
|
||||
|
||||
### 4.4 创建订单时指定汇率(高级用法)
|
||||
|
||||
API 支持通过 `rate` 参数**强制指定本次订单汇率**,此时将忽略数据库中的汇率记录:
|
||||
|
||||
```json
|
||||
POST /api/v1/epusdt/create
|
||||
{
|
||||
"order_id": "xxx",
|
||||
"amount": 100.0,
|
||||
"fiat": "CNY",
|
||||
"rate": "7.30",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
若传入 `rate` 参数,则浮动语法也不再生效,直接以传入值为准。
|
||||
|
||||
---
|
||||
|
||||
## 附录:关键配置项速查
|
||||
|
||||
| 配置键 | 默认值 | 说明 |
|
||||
|-------------------------|-----------|-----------------------------------------------|
|
||||
| `payment_match_mode` | `classic` | 金额匹配模式:`classic` / `has_prefix` / `round_off` |
|
||||
| `payment_timeout` | `1200` | 订单默认超时时间(秒),范围 180~3600 |
|
||||
| `rate_sync_interval` | `3600` | 汇率同步间隔(秒) |
|
||||
| `atom_usdt` | `0.01` | USDT 最小原子精度(影响同地址冲突递增步长) |
|
||||
| `block_height_max_diff` | `1000` | 区块高度跳跃容忍值,超过则强制重新对齐 |
|
||||
| `block_offset_confirm` | `0` | 开启后需等待 N 个区块确认才回调(防回滚) |
|
||||
| `monitor_min_amount` | `0.01` | 非订单监控最小入账金额 |
|
||||
| `rate_float_USDT_CNY` | (空) | USDT/CNY 汇率浮动语法 |
|
||||
|
||||
---
|
||||
|
||||
*文档生成时间:2026-04-14 · 基于 BEpusdt 源码分析*
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
# 📡 MQTT 对接开发文档
|
||||
|
||||
> 系统可将扫描到的交易信息广播到 MQTT 服务器,其它系统通过订阅 MQTT 即可实时获取数据。
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
BEpusdt 内置了 MQTT 发布能力,每当区块扫描器捕获到一笔**金额合法**的链上转账时,系统会立即将该交易信息以 JSON 格式发布到对应的
|
||||
MQTT Topic。
|
||||
|
||||
外部系统(如监控大屏、自动充值系统、风控系统等)只需连接同一 MQTT Broker 并订阅对应 Topic,即可**实时、被动地**获取链上交易数据,无需轮询
|
||||
API。
|
||||
|
||||
```
|
||||
区块链网络
|
||||
│
|
||||
▼
|
||||
BEpusdt(扫块)
|
||||
│ 检测到合法转账
|
||||
▼
|
||||
MQTT Broker(广播)
|
||||
│
|
||||
├──► 订阅方 A(充值系统)
|
||||
├──► 订阅方 B(数据分析)
|
||||
└──► 订阅方 C(监控告警)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 一、后台配置
|
||||
|
||||
在 BEpusdt 后台 → **系统管理 → 基本设置 → MQTT 设置** 中填写以下参数:
|
||||
|
||||
| 配置项 | 说明 | 示例 |
|
||||
|-----------|--------------------------------------------|---------------------|
|
||||
| MQTT Host | Broker 服务器地址(仅支持 TCP 模式) | `mqtt.example.com` |
|
||||
| MQTT Port | Broker 端口 | `1883` |
|
||||
| MQTT 用户名 | Broker 认证用户名,无认证可留空 | `admin` |
|
||||
| MQTT 密码 | Broker 认证密码,无认证可留空 | `password` |
|
||||
| 发布 QoS | 消息服务质量:`0` 最多一次 / `1` 至少一次 / `2` 恰好一次 | `1` |
|
||||
| 持续监控网络 | 需要**持续扫块**的网络列表,多个用英文逗号分隔;配置后即使无待支付订单也持续推送 | `tron,bsc,ethereum` |
|
||||
|
||||
> ⚠️ **注意**:系统当前仅支持 `tcp://` 连接协议,不支持 WebSocket(`ws://`)或 TLS(`ssl://`)。
|
||||
>
|
||||
> 客户端 ID 由系统自动生成,格式为 `BEpusdt {进程PID}`,每次启动可能不同,请勿依赖客户端 ID 做业务判断。
|
||||
|
||||
---
|
||||
|
||||
## 二、Topic 规则
|
||||
|
||||
系统按**区块链网络**维度发布消息,Topic 格式如下:
|
||||
|
||||
```
|
||||
bepusdt/transfer/{network}
|
||||
```
|
||||
|
||||
### 网络标识对照表
|
||||
|
||||
| 网络 | Topic | 支持币种 |
|
||||
|----------|-----------------------------|-------------------------------|
|
||||
| Tron | `bepusdt/transfer/tron` | USDT (TRC20)、USDC (TRC20)、TRX |
|
||||
| Ethereum | `bepusdt/transfer/ethereum` | USDT (ERC20)、USDC (ERC20)、ETH |
|
||||
| BSC | `bepusdt/transfer/bsc` | USDT (BEP20)、USDC (BEP20)、BNB |
|
||||
| Polygon | `bepusdt/transfer/polygon` | USDT、USDC |
|
||||
| Arbitrum | `bepusdt/transfer/arbitrum` | USDT、USDC |
|
||||
| Base | `bepusdt/transfer/base` | USDC |
|
||||
| Solana | `bepusdt/transfer/solana` | USDT、USDC |
|
||||
| Aptos | `bepusdt/transfer/aptos` | USDT、USDC |
|
||||
| X Layer | `bepusdt/transfer/xlayer` | USDT、USDC |
|
||||
| Plasma | `bepusdt/transfer/plasma` | USDT |
|
||||
|
||||
### 订阅示例
|
||||
|
||||
```
|
||||
# 仅订阅 Tron 网络
|
||||
bepusdt/transfer/tron
|
||||
|
||||
# 同时订阅 BSC 和 Polygon(分两次 Subscribe)
|
||||
bepusdt/transfer/bsc
|
||||
bepusdt/transfer/polygon
|
||||
|
||||
# 使用通配符订阅所有网络(MQTT v3.1.1)
|
||||
bepusdt/transfer/#
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、消息格式
|
||||
|
||||
消息体为 **UTF-8 编码的 JSON 字符串**,结构如下:
|
||||
|
||||
### 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|----------------|--------|----------------------------------------------|
|
||||
| `network` | string | 区块链网络标识,如 `tron`、`bsc`、`ethereum` |
|
||||
| `tx_hash` | string | 链上交易哈希(全局唯一,可作为幂等键) |
|
||||
| `amount` | string | 实际到账的**加密货币数量**(非法币金额) |
|
||||
| `from_address` | string | 发款方钱包地址 |
|
||||
| `recv_address` | string | 收款方钱包地址 |
|
||||
| `timestamp` | number | 交易发生时间,Unix 时间戳(秒) |
|
||||
| `trade_type` | string | 交易类型,完整列表见 [trade-type.md](../trade-type.md) |
|
||||
| `block_num` | number | 交易所在区块高度 |
|
||||
|
||||
### 消息示例
|
||||
|
||||
```json
|
||||
{
|
||||
"network": "tron",
|
||||
"tx_hash": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"amount": "4.25",
|
||||
"from_address": "TJRabPrwbZy45sbavfcjinPJC18iYKbPa5",
|
||||
"recv_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"timestamp": 1744732800,
|
||||
"trade_type": "usdt.trc20",
|
||||
"block_num": 68123456
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、注意事项
|
||||
|
||||
### 消息去重
|
||||
|
||||
同一笔交易**可能被发布多次**(例如系统重启、扫块重叠时),建议以 `tx_hash` 作为幂等键,在业务层去重处理。
|
||||
|
||||
### 消息触发时机
|
||||
|
||||
MQTT 消息在**扫块阶段**触发,此时交易已出现在区块链上,但系统层面尚未完成订单匹配或回调流程。如果需要确认订单是否支付成功,应以
|
||||
**订单回调通知**(`notify_url`)为准;MQTT 消息可作为辅助的实时感知手段。
|
||||
|
||||
### 金额过滤
|
||||
|
||||
系统仅广播金额在合法范围内的交易(由后台「监控最小金额」配置决定)。超出范围的链上转账不会触发 MQTT 推送。
|
||||
|
||||
### 网络断线重连
|
||||
|
||||
BEpusdt 的 MQTT 客户端已启用自动重连,断线后会自动恢复并重新订阅所有 Topic。订阅方同样建议使用支持自动重连的 MQTT 客户端库。
|
||||
|
||||
### QoS 建议
|
||||
|
||||
| 场景 | 推荐 QoS |
|
||||
|-------------------|--------|
|
||||
| 数据监控、日志记录(允许少量丢失) | `0` |
|
||||
| 充值到账、财务类业务(不能漏消息) | `1` |
|
||||
| 对消息重复极度敏感的场景 | `2` |
|
||||
|
||||
---
|
||||
|
||||
## 五、常见问题
|
||||
|
||||
**Q:MQTT 消息和订单回调(notify_url)有什么区别?**
|
||||
|
||||
> MQTT 是对**所有捕获到的合法链上转账**广播,不区分是否匹配到订单,实时性更高;订单回调仅针对成功匹配的支付订单,包含完整订单信息。两者可结合使用。
|
||||
|
||||
**Q:如何只监听特定收款地址的转账?**
|
||||
|
||||
> MQTT 消息包含 `recv_address` 字段,订阅方自行在消费逻辑中按地址过滤即可,Topic 层面暂不支持按地址过滤。
|
||||
|
||||
**Q:没有活跃订单时为什么收不到消息?**
|
||||
|
||||
> 默认情况下,BEpusdt 仅在有待支付订单时才对对应网络扫块。需在后台**「持续监控网络」**中填入目标网络标识(如 `tron,bsc`
|
||||
> ),才能保证无订单时也持续推送。
|
||||
|
||||
**Q:支持 WebSocket 或 TLS 连接吗?**
|
||||
|
||||
> 当前版本仅支持 TCP 模式(`tcp://`),暂不支持 `ws://` / `wss://` / `ssl://`。
|
||||
|
||||
**Q:`amount` 字段的单位是什么?**
|
||||
|
||||
> `amount` 为**加密货币数量**(如 USDT 数量),并非法币金额。例如 `"amount": "4.25"` 表示实际到账 4.25 USDT。
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
- [交易类型完整列表](../trade-type.md)
|
||||
- [API 对接文档](./api.md)
|
||||
- [订单回调通知](../notify/readme.md)
|
||||
- [BEpusdt GitHub](https://github.com/v03413/BEpusdt)
|
||||
+4
-2
@@ -15,9 +15,11 @@
|
||||
|
||||
以下是常见程序的对接文档,请根据您的实际需求选择相应教程进行配置。如遇问题,请仔细核对操作步骤,或在相关技术社区寻求协助。
|
||||
|
||||
- [独角数卡](./dujiaoka/dujiaoka.md)
|
||||
- [独角Dujiao-Next](./dujiao-next/dujiao-next.md)
|
||||
- [独角数卡(旧版)](./dujiaoka/dujiaoka.md)
|
||||
- [彩虹易支付](https://github.com/v03413/Epay-BEpusdt)
|
||||
- [WHMCS](https://github.com/v03413/whmcs-gateway-epusdt)
|
||||
- [异次元发卡](acg-faka/README.md)
|
||||
- [萌次元商城](./mcy-faka/mcy-shop.md)
|
||||
|
||||
- [EdgeKey](./edge-key/edge-key.md)
|
||||
- [WooCommerce/WordPress 收款插件-BEpusdt for WooCommerce](https://github.com/immonsterx/bepusdt-woocommerce)
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
# 收银台模板开发指南
|
||||
|
||||
本文档面向开发者,介绍收银台模板的**目录结构与开发规范**,帮助你完成两类任务:
|
||||
|
||||
- **修改默认模板**:在官方内置模板的基础上调整样式或逻辑
|
||||
- **新增自定义模板**:从零创建一套独立的收银台主题
|
||||
|
||||
---
|
||||
|
||||
## 模板目录结构
|
||||
|
||||
每套模板放在 `static/checkout/` 下的一个子目录中,目录名即模板的唯一标识。结构如下:
|
||||
|
||||
```
|
||||
<模板目录名>/
|
||||
├── checkout.json # 【必须】模板元数据
|
||||
├── views/
|
||||
│ └── checkout.html # 【必须】主模板 HTML
|
||||
└── assets/ # 【可选】静态资源
|
||||
├── css/
|
||||
├── js/
|
||||
├── img/
|
||||
└── locales/
|
||||
```
|
||||
|
||||
BEpusdt 启动时会扫描该目录,自动注册所有合法模板,并在后台「收银台模板」下拉框中展示。
|
||||
|
||||
---
|
||||
|
||||
## checkout.json
|
||||
|
||||
模板的元数据配置文件,用于在后台展示模板信息:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "模板显示名称",
|
||||
"author": "作者或团队",
|
||||
"desc": "一句话描述",
|
||||
"link": "模板主页或仓库地址"
|
||||
}
|
||||
```
|
||||
|
||||
`name` 为必填项,其余可选。
|
||||
|
||||
---
|
||||
|
||||
## views/checkout.html
|
||||
|
||||
标准的 Go `html/template` 文件。服务端只注入一个变量:
|
||||
|
||||
```
|
||||
{{ .trade_id }} // 当前订单的交易 ID
|
||||
```
|
||||
|
||||
**所有订单数据均通过前端 AJAX 请求获取**,不在服务端渲染。可以用任意前端框架或原生 JS 实现交互逻辑,参考官方模板
|
||||
`static/checkout/official/assets/js/checkout.js` 的写法。
|
||||
|
||||
---
|
||||
|
||||
## assets 静态资源
|
||||
|
||||
`assets/` 下的文件会被挂载到 `/checkout/<模板目录名>/assets/` 路由,在 HTML 中**必须使用绝对路径**引用:
|
||||
|
||||
```html
|
||||
|
||||
<link rel="stylesheet" href="/checkout/my-theme/assets/css/style.css">
|
||||
<script src="/checkout/my-theme/assets/js/main.js"></script>
|
||||
```
|
||||
|
||||
第三方 JS 库建议本地化放入 `assets/js/`,避免依赖外部 CDN。
|
||||
|
||||
---
|
||||
|
||||
## 任务一:修改默认模板
|
||||
|
||||
默认模板 `official` 的源文件位于 `static/checkout/official/`,直接在该目录下修改即可。
|
||||
|
||||
**1. 克隆源码**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/v03413/BEpusdt.git
|
||||
cd BEpusdt
|
||||
```
|
||||
|
||||
**2. 按需修改**
|
||||
|
||||
- 品牌色 → `static/checkout/official/assets/css/checkout.css` 中的 CSS 变量
|
||||
- Logo / 图标 → 替换 `static/checkout/official/assets/img/` 下的图片并更新引用
|
||||
- 页面结构 → 编辑 `static/checkout/official/views/checkout.html`
|
||||
- 交互逻辑 → 编辑 `static/checkout/official/assets/js/checkout.js`
|
||||
- 多语言文案 → 编辑 `static/checkout/official/assets/locales/zh.json`、`en.json`
|
||||
|
||||
**3. 重新编译**(见[部署与验证](#部署与验证))
|
||||
|
||||
---
|
||||
|
||||
## 任务二:新增自定义模板
|
||||
|
||||
**1. 创建目录**
|
||||
|
||||
```bash
|
||||
mkdir -p my-theme/views my-theme/assets/{css,js,img}
|
||||
```
|
||||
|
||||
**2. 编写 checkout.json**
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "My Theme",
|
||||
"author": "yourname",
|
||||
"desc": "简洁风格收银台",
|
||||
"link": ""
|
||||
}
|
||||
```
|
||||
|
||||
**3. 编写 views/checkout.html**
|
||||
|
||||
从 `{{ .trade_id }}` 获取交易 ID,通过 AJAX 调用后端接口拉取订单数据,轮询检测支付状态,完成后跳转。可直接参考官方模板的
|
||||
`checkout.js` 逻辑复用。
|
||||
|
||||
静态资源路径前缀为 `/checkout/my-theme/assets/`。
|
||||
|
||||
**4. 放置静态资源**
|
||||
|
||||
将 CSS、JS、图片等放入 `assets/` 对应子目录。
|
||||
|
||||
---
|
||||
|
||||
## 部署与验证
|
||||
|
||||
`static/checkout/` 目录通过 Go `//go:embed` 在**编译时**打包进程序二进制。这意味着:
|
||||
|
||||
- 新增或修改模板后,必须**重新编译**才能生效
|
||||
- 运行时无法热加载,不存在"上传到服务器某个路径"这种方式
|
||||
|
||||
### 步骤
|
||||
|
||||
**1. 将模板目录放入源码**
|
||||
|
||||
把你的模板目录放到 `static/checkout/` 下:
|
||||
|
||||
```
|
||||
static/checkout/
|
||||
├── official/ # 内置官方模板
|
||||
└── my-theme/ # 你的模板
|
||||
├── checkout.json
|
||||
├── views/
|
||||
│ └── checkout.html
|
||||
└── assets/
|
||||
```
|
||||
|
||||
**2. 重新编译**
|
||||
|
||||
```bash
|
||||
go build -o bepusdt ./main
|
||||
```
|
||||
|
||||
或使用项目已有的构建脚本/Dockerfile。
|
||||
|
||||
**3. 验证注册结果**
|
||||
|
||||
启动程序后查看日志,出现以下内容说明模板注册成功:
|
||||
|
||||
```
|
||||
前台收银模板注册成功: my-theme
|
||||
```
|
||||
|
||||
**4. 在后台切换模板**
|
||||
|
||||
进入 **系统管理 → 基本设置 → API 设置**,在「收银台模板」中选择对应模板名称并保存。
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `checkout.json` 缺失或 JSON 格式有误会导致程序启动失败
|
||||
- `views/checkout.html` 缺失时该模板会被跳过,不影响其他模板加载
|
||||
- 目录名会出现在 URL 中,建议用小写字母与连字符,如 `my-theme`
|
||||
+34
-5
@@ -27,7 +27,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
- `v03413/bepusdt:latest` - 稳定发行版(推荐生产环境使用)
|
||||
- `v03413/bepusdt:nightly` - 每日构建开发版(包含最新特性,适合测试环境)
|
||||
|
||||
## 数据持久化配置
|
||||
## 数据持久化
|
||||
|
||||
### SQLite 数据库(默认)
|
||||
|
||||
@@ -47,18 +47,45 @@ docker run -d --restart=unless-stopped -p 8080:8080 -v [挂载路径]:/var/lib/b
|
||||
docker run -d --restart=unless-stopped -p 8080:8080 -v /opt/bepusdt:/var/lib/bepusdt v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
### MySQL 数据库(可选)
|
||||
<details>
|
||||
<summary><strong>PostgreSQL 数据库(推荐)</strong></summary>
|
||||
|
||||
系统支持使用 MySQL 作为数据存储方案,适用于需要更强大数据库功能的场景。
|
||||
系统支持使用 PostgreSQL 作为数据存储方案,适用于生产环境。这是目前推荐的数据库方案。
|
||||
|
||||
**前置准备:**
|
||||
|
||||
- MySQL 版本:5.7 或更高版本
|
||||
- 需提前完成 MySQL 安装及安全配置
|
||||
- PostgreSQL 版本:18 或更高版本
|
||||
- 需提前完成 PostgreSQL 安装及安全配置
|
||||
- 已创建专用数据库(如 `bepusdt`)
|
||||
|
||||
**部署命令:**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--restart unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3 \
|
||||
v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
**配置说明:**
|
||||
|
||||
- 将 `user` 替换为 PostgreSQL 用户名
|
||||
- 将 `password` 替换为 PostgreSQL 密码
|
||||
- 将 `localhost:5432` 替换为 PostgreSQL 服务器地址和端口
|
||||
- 将 `bepusdt` 替换为实际数据库名称
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>MySQL 数据库(已弃用)</strong></summary>
|
||||
|
||||
> **注意:** MySQL 支持将逐步弃用,建议使用 PostgreSQL 替代。
|
||||
|
||||
系统仍支持使用 MySQL 作为数据存储方案,但不再推荐用于新部署。
|
||||
|
||||
**部署命令:**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--restart unless-stopped \
|
||||
@@ -74,6 +101,8 @@ docker run -d \
|
||||
- 将 `127.0.0.1:3306` 替换为 MySQL 服务器地址和端口
|
||||
- 将 `bepusdt` 替换为实际数据库名称(如需要)
|
||||
|
||||
</details>
|
||||
|
||||
## 部署验证
|
||||
|
||||
### 查看容器日志
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# BEpusdt 与 EPusdt 项目说明
|
||||
|
||||
## 项目背景
|
||||
|
||||
### EPusdt
|
||||
|
||||
EPusdt 是与独角数卡(开源数字商品销售系统)配套的个人 USDT 收款网关,两个项目由同一作者
|
||||
@assimon 开发。
|
||||
|
||||
### BEpusdt
|
||||
|
||||
BEpusdt 由独立作者开发;由于 EPusdt 在一段时间内缺乏积极维护,结合个人需求和对区块链技术的兴趣,才开发了 BEpusdt 项目。
|
||||
BEpusdt 项目名称含义:在 EPusdt 前添加字母 `B`(代表 `Better`),寓意更简单、更好用的 USDT 收款网关。
|
||||
|
||||
## 项目演进
|
||||
|
||||
| 时间 | 事件 |
|
||||
|-------------|-----------------------------|
|
||||
| 2022 年 3 月 | EPusdt 项目发布,4 月基本完善,后续基本无更新 |
|
||||
| 2023 年 10 月 | BEpusdt 项目建立,持续迭代更新至今 |
|
||||
| 2026 年 3 月 | EPusdt 项目转让给其他开发者接手维护 |
|
||||
|
||||
## ⚠️ 重要声明
|
||||
|
||||
**BEpusdt 与转让后的 EPusdt 项目没有任何联系、无共同维护者。两个项目完全独立运营。**
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢原作者 [@assimon](https://github.com/assimon) 开源的 EPusdt 项目,为本项目的诞生提供了灵感和参考。
|
||||
@@ -0,0 +1,48 @@
|
||||
# EVM RPC 节点配置指南
|
||||
|
||||
### RPC 节点在 BEpusdt 中的作用
|
||||
|
||||
BEpusdt 在区块扫描过程中,所有区块数据均通过 RPC 节点获取。因此,**RPC 节点的性能和稳定性直接影响系统的收款体验**。
|
||||
|
||||
## 内置公益节点
|
||||
|
||||
BEpusdt 默认内置了一批公益 RPC
|
||||
节点,详见[源代码配置](https://github.com/v03413/BEpusdt/blob/0e1e22cebbf4a2127786e62b2b8b4d2175054c0b/app/model/conf.go#L140)。
|
||||
|
||||
### 公益节点的局限性
|
||||
|
||||
- **稳定性难以保证**:公益节点由第三方维护,服务质量无法长期保障
|
||||
- **网络质量差异大**:部分 VPS 的网络状况本身较差,容易导致请求失败
|
||||
- **覆盖面不完整**:虽然这些节点已在开发中测试,但无法覆盖所有场景
|
||||
|
||||
这也是常见问题"为什么无法收款"或"为什么换台服务器就好了"的主要原因。
|
||||
|
||||
### 建议
|
||||
|
||||
- 优先选择大型云服务提供商的服务器部署 BEpusdt,确保国际网络连接质量
|
||||
- 在非必要情况下,考虑禁用钱包交易监控功能,以降低 RPC 节点的请求压力
|
||||
|
||||
## 第三方 RPC 服务
|
||||
|
||||
### Chainlist
|
||||
|
||||
**官网**:https://chainlist.org/
|
||||
|
||||
Chainlist 是一个聚合各类区块链网络 RPC 节点信息的平台,用户可以:
|
||||
|
||||
- 查找适合自己需求的 RPC 节点
|
||||
- 一键复制配置信息
|
||||
- 直接集成到应用中
|
||||
|
||||
> **注意**:第三方提供的节点质量需自行测试和评估。
|
||||
|
||||
### Nodies
|
||||
|
||||
**官网**:https://www.nodies.app/
|
||||
|
||||
Nodies 是一个商业 RPC 服务提供商,具有以下特点:
|
||||
|
||||
- 提供企业级的高质量 RPC 节点服务
|
||||
- 性能和稳定性有保障,适合生产环境使用
|
||||
- 提供免费配额,可满足个人单节点的使用需求
|
||||
- 需付费才能获得更高的配额和优先级支持
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user