Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e01e9809e | ||
|
|
e7a8dd9681 | ||
|
|
0ae8a9be0f | ||
|
|
647e1b96b1 | ||
|
|
ca239fbce4 | ||
|
|
963c80aaa0 | ||
|
|
be344b97f7 | ||
|
|
59d23a2dc7 | ||
|
|
8a91be6a15 | ||
|
|
8ff1bce889 | ||
|
|
5791328de4 | ||
|
|
566aa5a486 | ||
|
|
78db081b35 | ||
|
|
c592d3fb7a | ||
|
|
5cb1d6f099 | ||
|
|
ebff24a190 | ||
|
|
5a1f9def13 | ||
|
|
448cda9022 | ||
|
|
6784a98c8e | ||
|
|
d54669a8aa | ||
|
|
5b3a1ded6d | ||
|
|
144cdb8c40 | ||
|
|
9131b9d5c4 | ||
|
|
2fdb6e81d3 |
+5
-1
@@ -8,4 +8,8 @@ LOG=/var/log/bepusdt/
|
||||
SQLITE=/var/lib/bepusdt/sqlite.db
|
||||
|
||||
# PostgreSQL 数据库
|
||||
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
|
||||
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
|
||||
|
||||
# MySQL 数据库(本仓库支持;DSN 里 charset=utf8mb4&parseTime=True&loc=Local 不能省)
|
||||
# 优先级:MYSQL_DSN > POSTGRESQL_DSN > SQLITE
|
||||
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Docker Build (Gitea)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- 'ci/**'
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: git.viaeon.com
|
||||
IMAGE: git.viaeon.com/admin/bepusdt
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
name: Build and Push Docker Image
|
||||
runs-on: ubuntu
|
||||
env:
|
||||
RUNNER_TOOL_CACHE: /toolcache
|
||||
|
||||
steps:
|
||||
- name: Install Docker CLI
|
||||
run: |
|
||||
if ! command -v docker &> /dev/null; then
|
||||
if command -v apk &> /dev/null; then
|
||||
apk add --no-cache docker-cli git
|
||||
elif command -v apt-get &> /dev/null; then
|
||||
apt-get update && apt-get install -y docker.io git
|
||||
else
|
||||
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-24.0.7.tgz | tar xz -C /tmp
|
||||
mv /tmp/docker/docker /usr/local/bin/
|
||||
chmod +x /usr/local/bin/docker
|
||||
fi
|
||||
fi
|
||||
docker --version
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
- name: Prepare version
|
||||
id: ver
|
||||
run: |
|
||||
SHORT_SHA=$(git rev-parse --short=7 HEAD)
|
||||
BASE=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
|
||||
# 分支名可能带斜杠(ci/xxx),docker tag 不允许,统一换成短横线
|
||||
REF_SLUG=$(echo "${GITHUB_REF_NAME}" | tr '/' '-')
|
||||
echo "short_sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "ref_slug=${REF_SLUG}" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${BASE}-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "VERSION=${BASE}-${SHORT_SHA}"
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
run: |
|
||||
echo "${{ secrets.TOKEN }}" | docker login "${{ env.REGISTRY }}" -u "${{ github.actor }}" --password-stdin 2>&1
|
||||
|
||||
- name: Build Docker image
|
||||
run: |
|
||||
# latest 只给 main,特性分支别把 latest 顶掉
|
||||
TAGS="-t ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }} -t ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
|
||||
if [ "${GITHUB_REF_NAME}" = "main" ]; then TAGS="$TAGS -t ${{ env.IMAGE }}:latest"; fi
|
||||
docker build \
|
||||
--label "org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}" \
|
||||
--label "org.opencontainers.image.revision=${{ github.sha }}" \
|
||||
--build-arg "VERSION=${{ steps.ver.outputs.version }}" \
|
||||
$TAGS .
|
||||
|
||||
- name: Push Docker image
|
||||
run: |
|
||||
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}" 2>&1
|
||||
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}" 2>&1
|
||||
if [ "${GITHUB_REF_NAME}" = "main" ]; then docker push "${{ env.IMAGE }}:latest" 2>&1; fi
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "镜像已推送:"
|
||||
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}"
|
||||
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
|
||||
echo " ${{ env.IMAGE }}:latest"
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
days-before-issue-stale: 3
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "此议题由于30天内没有任何活动,现在标记为过时。"
|
||||
stale-issue-message: "此议题由于3天内没有任何活动,现在标记为过时。"
|
||||
close-issue-message: "此议题被标记为过时并且在7天内没有活动,因此已被关闭。请随时重新打开此议题以继续讨论。"
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
|
||||
+6
-1
@@ -9,4 +9,9 @@ dist/
|
||||
static/web
|
||||
static/secure
|
||||
*.log
|
||||
AGENTS.md
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
data/
|
||||
logs/
|
||||
mysqldata/
|
||||
pgdata/
|
||||
|
||||
@@ -57,6 +57,13 @@ Docker 快速启动,执行完命令打开地址`http://服务器IP:8080`即可
|
||||
```bash
|
||||
docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
> **本仓库(admin/BEPUSDT)额外提供:**
|
||||
> - CI 自动构建镜像并推到 `git.viaeon.com/admin/bepusdt`(`.gitea/workflows/docker.yaml`)
|
||||
> - 三份 compose 示例:`docker-compose.example.yml`(SQLite)、`docker-compose.postgres.example.yml`、
|
||||
> `docker-compose.mysql.example.yml`
|
||||
> - **新增 MySQL 支持**(`MYSQL_DSN`),上游只有 SQLite/PostgreSQL;用法见
|
||||
> [Docker 部署指南 · MySQL](docs/docker/docker.md)
|
||||
## 📃 技术文档
|
||||
|
||||
- 安装:[Docker](docs/docker/docker.md) [Linux](docs/linux/install.md) [1Panel](./docs/1panel/README.md) [宝塔](./docs/bt_panel/README.md)
|
||||
@@ -82,6 +89,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
|
||||
- **Telegram 群组**:[https://t.me/BEpusdtChat](https://t.me/BEpusdtChat)
|
||||
- **Telegram 频道**:[https://t.me/BEpusdtChannel](https://t.me/BEpusdtChannel)
|
||||
- **安全问题反馈/联系作者**:[contact@bepusdt.online](mailto:contact@bepusdt.online)
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ var PostgresDSNFlag = &cli.StringFlag{
|
||||
Sources: cli.EnvVars("POSTGRESQL_DSN"),
|
||||
}
|
||||
|
||||
var MysqlDSNFlag = &cli.StringFlag{
|
||||
Name: "mysql",
|
||||
Value: "",
|
||||
Usage: "MySQL 数据库连接字符串 (DSN),例如: user:pass@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s",
|
||||
Sources: cli.EnvVars("MYSQL_DSN"),
|
||||
}
|
||||
|
||||
var LogFlag = &cli.StringFlag{
|
||||
Name: "log",
|
||||
Value: "/var/log/bepusdt/",
|
||||
|
||||
+3
-2
@@ -15,11 +15,12 @@ import (
|
||||
var Reset = &cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "忘记密码时,此命令可重置账号密码登录入口",
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
sqlite := c.String("sqlite")
|
||||
postgres := c.String("postgres")
|
||||
if err := model.Init(sqlite, postgres); err != nil {
|
||||
mysql := c.String("mysql")
|
||||
if err := model.Init(sqlite, postgres, mysql); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -27,11 +27,12 @@ import (
|
||||
var Start = &cli.Command{
|
||||
Name: "start",
|
||||
Usage: "启动收款网关",
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, LogFlag, ListenFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag, LogFlag, ListenFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
postgres := c.String("postgres")
|
||||
mysql := c.String("mysql")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, postgres); err != nil {
|
||||
if err := model.Init(sqlite, postgres, mysql); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ const (
|
||||
)
|
||||
const (
|
||||
Classic MatchMode = "classic" // 经典模式,精确匹配
|
||||
HasPrefix MatchMode = "has_prefix" // 前缀匹配,允许多付
|
||||
HasPrefix MatchMode = "has_prefix" // 前缀匹配,按原子精度截断后比较,只容忍精度以下的多付
|
||||
RoundOff MatchMode = "round_off" // 数值修约,四舍五入,允许容错
|
||||
)
|
||||
|
||||
|
||||
+50
-5
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/v03413/bepusdt/app/model/migration"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -24,12 +25,17 @@ type AutoTimeAt struct {
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;not null;comment:最后更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
func Init(db, dsn string) error {
|
||||
if dsn != "" {
|
||||
return initPostgres(dsn)
|
||||
// Init 按优先级选择数据库:MySQL DSN > PostgreSQL DSN > SQLite 文件。
|
||||
// 三者互斥,填了哪个用哪个;都不填就走 SQLite(默认)。
|
||||
func Init(db, postgresDSN, mysqlDSN string) error {
|
||||
switch {
|
||||
case mysqlDSN != "":
|
||||
return initMysql(mysqlDSN)
|
||||
case postgresDSN != "":
|
||||
return initPostgres(postgresDSN)
|
||||
default:
|
||||
return initSqlite(db)
|
||||
}
|
||||
|
||||
return initSqlite(db)
|
||||
}
|
||||
|
||||
func initSqlite(db string) error {
|
||||
@@ -147,3 +153,42 @@ func Close() {
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("数据库资源关闭错误:%s", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func initMysql(dsn string) error {
|
||||
// 建议 DSN 里带上 charset=utf8mb4&parseTime=True&loc=Local,
|
||||
// 否则中文/时间字段会出问题:中文变 ?,时间按 UTC 存进去。
|
||||
Db, err = gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: dsn,
|
||||
DefaultStringSize: 256,
|
||||
SkipInitializeWithVersion: false,
|
||||
}), &gorm.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(30 * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var count int64
|
||||
Db.Model(&Conf{}).Count(&count)
|
||||
if count == 0 {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+2
-2
@@ -79,8 +79,8 @@ type Order struct {
|
||||
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"`
|
||||
ReturnUrl string `gorm:"column:return_url;type:varchar(1024);not null;default:'';comment:同步地址" json:"return_url"`
|
||||
NotifyUrl string `gorm:"column:notify_url;type:varchar(1024);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"`
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func TestAmountMatchHasPrefix(t *testing.T) {
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
|
||||
|
||||
cases := []struct {
|
||||
paid, order string
|
||||
want bool
|
||||
}{
|
||||
{"1.5", "1.5", true},
|
||||
{"1.50123", "1.5", true},
|
||||
{"1.509", "1.5", true},
|
||||
{"1.51", "1.5", false},
|
||||
{"1.4999", "1.5", false},
|
||||
{"2", "2", true},
|
||||
{"2.009", "2", true},
|
||||
{"2.01", "2", false},
|
||||
{"2.5", "2", false},
|
||||
{"10.379", "10.37", true},
|
||||
{"10.38", "10.37", false},
|
||||
{"20", "2", false},
|
||||
{"100.5", "100", false},
|
||||
{"123.456789", "123.45", true},
|
||||
// 订单金额小数位多于原子精度时按订单金额的小数位截断
|
||||
{"1.5059", "1.505", true},
|
||||
{"1.506", "1.505", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := amountMatch(decimal.RequireFromString(c.paid), c.order, string(model.UsdtTrc20))
|
||||
if got != c.want {
|
||||
t.Errorf("paid %s order %s: got %v, want %v", c.paid, c.order, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 同一地址并发订单按原子精度递增金额,截断后每笔付款最多对应其中一笔
|
||||
func TestAmountMatchHasPrefixConcurrentOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
|
||||
|
||||
orders := []string{"1.5", "1.51", "1.52"}
|
||||
payments := map[string]string{"1.5": "1.5", "1.50123": "1.5", "1.51": "1.51", "1.519": "1.51", "1.52": "1.52"}
|
||||
for paid, want := range payments {
|
||||
var matched []string
|
||||
for _, o := range orders {
|
||||
if amountMatch(decimal.RequireFromString(paid), o, string(model.UsdtTrc20)) {
|
||||
matched = append(matched, o)
|
||||
}
|
||||
}
|
||||
if len(matched) != 1 || matched[0] != want {
|
||||
t.Errorf("paid %s matched %v, want only %s", paid, matched, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
-7
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
@@ -37,6 +38,7 @@ type solana struct {
|
||||
retryMu sync.Mutex
|
||||
retryAttempts map[int]int
|
||||
retryScheduled map[int]*time.Timer
|
||||
retryStopped map[int]struct{}
|
||||
lookbackMu sync.Mutex
|
||||
lookbackNext int
|
||||
lookbackEnd int
|
||||
@@ -67,6 +69,7 @@ func newSolana() solana {
|
||||
client: utils.NewHttpClient(),
|
||||
retryAttempts: make(map[int]int),
|
||||
retryScheduled: make(map[int]*time.Timer),
|
||||
retryStopped: make(map[int]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +85,7 @@ func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
|
||||
return
|
||||
}
|
||||
if s.pendingSlotRetryCount() > 0 {
|
||||
if s.pendingSlotRetryCount() >= solanaForwardPauseRetries {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -199,6 +202,13 @@ func (s *solana) slotParse(n any) {
|
||||
}
|
||||
|
||||
result, err := validateSolanaBlockResponse(body)
|
||||
if errors.Is(err, errSolanaBlockCleanedUp) { // 节点已清理该 slot,重试也拿不到;放弃,不暂停向前扫描
|
||||
conf.RecordFailure(network)
|
||||
s.stopSlotRetry(slot)
|
||||
log.Task.Error(fmt.Sprintf("Solana slot %d 已被节点清理,无法扫描,该 slot 内的付款需要人工核对:%s", slot, err))
|
||||
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
@@ -334,10 +344,14 @@ func solanaSignatureFinalized(status gjson.Result) bool {
|
||||
|
||||
// Solana JSON-RPC 错误码,参考 https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs
|
||||
const (
|
||||
solanaErrBlockCleanedUp = -32001
|
||||
solanaErrSlotSkipped = -32007
|
||||
solanaErrLongTermStorageSlotSkipped = -32009
|
||||
)
|
||||
|
||||
// 节点只保留最近一段时间的区块,更早的 slot 返回 -32001,换一个时间重试也不会有
|
||||
var errSolanaBlockCleanedUp = errors.New("block cleaned up")
|
||||
|
||||
func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
|
||||
if !gjson.ValidBytes(body) {
|
||||
return gjson.Result{}, fmt.Errorf("invalid JSON response")
|
||||
@@ -348,6 +362,8 @@ func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
|
||||
switch rpcErr.Get("code").Int() {
|
||||
case solanaErrSlotSkipped, solanaErrLongTermStorageSlotSkipped: // 被跳过的 slot 没有区块,按空 slot 处理
|
||||
return gjson.Result{Type: gjson.Null}, nil
|
||||
case solanaErrBlockCleanedUp:
|
||||
return gjson.Result{}, fmt.Errorf("%w: %s", errSolanaBlockCleanedUp, rpcErr.Raw)
|
||||
}
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("RPC error: %s", rpcErr.Raw)
|
||||
@@ -366,6 +382,11 @@ func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
|
||||
|
||||
func (s *solana) scheduleSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
if _, stopped := s.retryStopped[slot]; stopped {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
if _, ok := s.retryScheduled[slot]; ok {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
@@ -400,6 +421,24 @@ func (s *solana) scheduleSlotRetry(slot int) {
|
||||
s.retryMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *solana) stopSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
delete(s.retryAttempts, slot)
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
s.retryStopped[slot] = struct{}{}
|
||||
s.retryMu.Unlock()
|
||||
|
||||
// 防止同一 slot 的并发请求在终态响应之后重新建立重试;并发请求结束后无需长期保留。
|
||||
time.AfterFunc(time.Minute, func() {
|
||||
s.retryMu.Lock()
|
||||
delete(s.retryStopped, slot)
|
||||
s.retryMu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *solana) resetSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
@@ -421,6 +460,10 @@ func (s *solana) pendingSlotRetryCount() int {
|
||||
// 单个 slot 最多重试 10 次,按 solanaRetryDelay 约 7 分钟
|
||||
const solanaSlotMaxRetries = 10
|
||||
|
||||
// 待重试的 slot 达到这个数量,说明节点整体故障,暂停向前扫描,避免新 slot 不断进入重试;
|
||||
// 个别 slot 失败时继续向前扫描,否则一个 slot 的重试会让之后的付款最多等约 7 分钟
|
||||
const solanaForwardPauseRetries = 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 {
|
||||
@@ -544,13 +587,28 @@ func (s *solana) tradeConfirmHandle(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *solana) lookbackSlots(ctx context.Context) {
|
||||
s.lookbackMu.Lock()
|
||||
defer s.lookbackMu.Unlock()
|
||||
|
||||
// 回溯到一半时订单已支付、取消,或已超出回溯时间,剩余区间不再需要。扫描空闲时这里不会执行到下面,
|
||||
// 不清空的话进度会一直保留,下一笔订单到来时接着扫这段旧 slot,节点可能早已清理
|
||||
if s.lookbackNext != 0 {
|
||||
pending, err := lookbackOrdersPending(s.lookbackOrderIDs)
|
||||
if err != nil { // 查询失败不等于订单已结束,保留进度,下一轮再判断
|
||||
log.Task.Warn("Solana 回溯订单查询失败,稍后重试:", err)
|
||||
|
||||
return
|
||||
}
|
||||
if !pending {
|
||||
log.Task.Info(fmt.Sprintf("Solana 回溯的订单已不需要回溯,丢弃剩余回溯区间 %d-%d", s.lookbackNext, s.lookbackEnd))
|
||||
s.resetLookback()
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -581,12 +639,16 @@ func (s *solana) lookbackSlots(ctx context.Context) {
|
||||
|
||||
if s.lookbackNext > s.lookbackEnd {
|
||||
markLookbackDone(s.lookbackOrderIDs)
|
||||
s.lookbackNext = 0
|
||||
s.lookbackEnd = 0
|
||||
s.lookbackOrderIDs = nil
|
||||
s.resetLookback()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) resetLookback() {
|
||||
s.lookbackNext = 0
|
||||
s.lookbackEnd = 0
|
||||
s.lookbackOrderIDs = nil
|
||||
}
|
||||
|
||||
func validSolanaLookbackRange(start, end int64) bool {
|
||||
return start > 0 && end >= start
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
// 模拟 n 个 slot 正在等待重试
|
||||
func (s *solana) setPendingSlotRetries(first, n int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
for slot := first; slot < first+n; slot++ {
|
||||
s.retryAttempts[slot] = 1
|
||||
}
|
||||
}
|
||||
|
||||
// 一个 slot 在等待重试时,向前扫描照常推进,之后的付款不用等它重试完
|
||||
func TestSolanaForwardContinuesWhileFewSlotsRetry(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
|
||||
s.setPendingSlotRetries(last-9, solanaForwardPauseRetries-1)
|
||||
head.Store(last + 5)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last+5 {
|
||||
t.Fatalf("lastSlotNum = %d, want %d: forward sync paused by one slot retry", s.lastSlotNum, last+5)
|
||||
}
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != last+1 {
|
||||
t.Fatalf("first queued slot = %d, want %d", got, last+1)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("no slot queued while one slot retries")
|
||||
}
|
||||
}
|
||||
|
||||
// 很多 slot 同时等待重试,说明节点整体故障,暂停向前扫描
|
||||
func TestSolanaForwardPausesWhileManySlotsRetry(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
|
||||
s.setPendingSlotRetries(last-solanaForwardPauseRetries, solanaForwardPauseRetries)
|
||||
head.Store(last + 5)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want forward sync paused at %d", s.lastSlotNum, s.slotQueue.Len(), last)
|
||||
}
|
||||
|
||||
s.resetSlotRetry(last - solanaForwardPauseRetries)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != last+5 {
|
||||
t.Fatalf("lastSlotNum = %d after retries dropped below threshold, want %d", s.lastSlotNum, last+5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func createSolanaLookbackOrder(t *testing.T, tradeID string, status int) model.Order {
|
||||
t.Helper()
|
||||
|
||||
return createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-" + tradeID,
|
||||
TradeId: tradeID,
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "1.23",
|
||||
Money: "8.61",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: status,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
}
|
||||
|
||||
// 上一笔订单回溯到一半就取消了;一周后新订单到来时,不能接着扫上一笔订单留下的旧 slot
|
||||
func TestSolanaLookbackDropsRangeOfFinishedOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
canceled := createSolanaLookbackOrder(t, "lookback-canceled", model.OrderStatusCanceled)
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
lookbackDone.Store(waiting.ID, struct{}{}) // 新订单的回溯不在本测试范围,避免请求区块高度接口
|
||||
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = 459552217, 459552221, []int64{canceled.ID}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
select {
|
||||
case slot := <-s.slotQueue.Out:
|
||||
t.Fatalf("queued slot %d from the range of a canceled order", slot)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
if s.lookbackNext != 0 || s.lookbackEnd != 0 || s.lookbackOrderIDs != nil {
|
||||
t.Fatalf("lookback progress kept: next = %d, end = %d, orders = %v", s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// 查询订单失败时不能当作订单已结束,保留进度,下一轮再判断
|
||||
func TestSolanaLookbackKeepsRangeOnDatabaseError(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
|
||||
const start, end = 462296900, 462296904
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
|
||||
db, err := model.Db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get db: %v", err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatalf("close db: %v", err)
|
||||
}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
if s.lookbackNext != start || s.lookbackEnd != end {
|
||||
t.Fatalf("lookback progress dropped on a database error: next = %d, end = %d", s.lookbackNext, s.lookbackEnd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaLookbackResumesRangeOfPendingOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
|
||||
const start, end = 462296900, 462296904
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
for want := start; want <= end; want++ {
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != want {
|
||||
t.Fatalf("queued slot = %d, want %d", got, want)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("slot %d not queued", want)
|
||||
}
|
||||
}
|
||||
if s.lookbackNext != 0 {
|
||||
t.Fatalf("lookbackNext = %d after the range was queued, want 0", s.lookbackNext)
|
||||
}
|
||||
if _, done := lookbackDone.Load(waiting.ID); !done {
|
||||
t.Fatalf("order %d not marked as looked back", waiting.ID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
const solanaBlockCleanedUpResponse = `{"jsonrpc":"2.0","error":{"code":-32001,"message":"Block 459552217 cleaned up, does not exist on node. First available block: 461715420"},"id":1}`
|
||||
|
||||
func TestValidateSolanaBlockResponseCleanedUp(t *testing.T) {
|
||||
if _, err := validateSolanaBlockResponse([]byte(solanaBlockCleanedUpResponse)); !errors.Is(err, errSolanaBlockCleanedUp) {
|
||||
t.Fatalf("error = %v, want errSolanaBlockCleanedUp", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发处理同一个 slot 时,较晚返回的普通错误不能在 BlockCleanedUp 已经终止后重新建立重试
|
||||
func TestSolanaSlotParseCleanedUpWinsConcurrentFailure(t *testing.T) {
|
||||
firstStarted := make(chan struct{})
|
||||
releaseFirst := make(chan struct{})
|
||||
var calls atomic.Int64
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) == 1 {
|
||||
close(firstStarted)
|
||||
<-releaseFirst
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 459552217
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
s.slotParse(slot)
|
||||
close(done)
|
||||
}()
|
||||
<-firstStarted
|
||||
s.slotParse(slot)
|
||||
close(releaseFirst)
|
||||
<-done
|
||||
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries after concurrent cleaned up = %d, want 0", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("concurrent failure rescheduled cleaned up slot")
|
||||
}
|
||||
}
|
||||
|
||||
// 节点已清理的 slot 只请求一次就放弃,不留下待重试记录,向前扫描不会因此暂停;之前因为限流留下的重试也一并清除
|
||||
func TestSolanaSlotParseGivesUpCleanedUpSlot(t *testing.T) {
|
||||
var cleaned atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !cleaned.Load() {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 459552217
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 1 {
|
||||
t.Fatalf("pending retries after 429 = %d, want 1", got)
|
||||
}
|
||||
s.expireSlotRetryTimer(slot)
|
||||
|
||||
cleaned.Store(true)
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries after cleaned up = %d, want 0: forward sync stays paused", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("cleaned up slot still scheduled for retry")
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func (s *solana) stopSlotRetryTimers() {
|
||||
|
||||
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}`))
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 457000000"},"id":1}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
+36
-28
@@ -305,14 +305,38 @@ func (t *ton) processShard(ctx context.Context, shard *tgo.BlockIDExt, seqno uin
|
||||
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) {
|
||||
// tonInboundMessage 提取交易的入站 internal 消息及其 ordinary 描述,两类转账解析共用
|
||||
func tonInboundMessage(tx *tlb.Transaction) (*tlb.InternalMessage, tlb.TransactionDescriptionOrdinary, bool) {
|
||||
var dsc tlb.TransactionDescriptionOrdinary
|
||||
if tx.IO.In == nil {
|
||||
return transfer{}, false
|
||||
return nil, dsc, false
|
||||
}
|
||||
in, ok := tx.IO.In.Msg.(*tlb.InternalMessage)
|
||||
if !ok || in.Bounced || in.Body == nil {
|
||||
return nil, dsc, false
|
||||
}
|
||||
if dsc, ok = tx.Description.(tlb.TransactionDescriptionOrdinary); !ok {
|
||||
return nil, dsc, false
|
||||
}
|
||||
if dsc.BouncePhase != nil {
|
||||
if _, ok = dsc.BouncePhase.Phase.(tlb.BouncePhaseOk); ok {
|
||||
return nil, dsc, false
|
||||
}
|
||||
}
|
||||
|
||||
return in, dsc, true
|
||||
}
|
||||
|
||||
// tonAccountAddr 统一输出为 non-bounceable 格式,与钱包 MatchAddr 保持一致
|
||||
func tonAccountAddr(addr *address.Address) string {
|
||||
return addr.Bounce(false).String()
|
||||
}
|
||||
|
||||
// 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) {
|
||||
in, dsc, ok := tonInboundMessage(tx)
|
||||
if !ok {
|
||||
return transfer{}, false
|
||||
}
|
||||
s, err := in.Body.BeginParse()
|
||||
@@ -324,17 +348,12 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
transOrd, ok := tx.Description.(tlb.TransactionDescriptionOrdinary)
|
||||
if !ok {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
compute, ok := transOrd.ComputePhase.Phase.(tlb.ComputePhaseVM)
|
||||
compute, ok := dsc.ComputePhase.Phase.(tlb.ComputePhaseVM)
|
||||
if !ok || !compute.Success {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
if transOrd.ActionPhase == nil || !transOrd.ActionPhase.Success {
|
||||
if dsc.ActionPhase == nil || !dsc.ActionPhase.Success {
|
||||
return transfer{}, false
|
||||
}
|
||||
|
||||
@@ -359,8 +378,8 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
|
||||
Network: conf.Ton,
|
||||
TxHash: hex.EncodeToString(tx.Hash),
|
||||
Amount: decimal.NewFromBigInt(amount, conf.UsdtTonDecimals),
|
||||
FromAddress: fromOwner.Bounce(false).String(),
|
||||
RecvAddress: toJetton.Bounce(false).String(),
|
||||
FromAddress: tonAccountAddr(fromOwner),
|
||||
RecvAddress: tonAccountAddr(toJetton),
|
||||
Timestamp: time.Unix(int64(tx.Now), 0),
|
||||
TradeType: model.UsdtTon,
|
||||
BlockNum: int(blockNum),
|
||||
@@ -368,30 +387,19 @@ func (t *ton) parseInternalTransfer(shard *tgo.BlockIDExt, tx *tlb.Transaction,
|
||||
}
|
||||
|
||||
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)
|
||||
msg, _, ok := tonInboundMessage(tx)
|
||||
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 {
|
||||
if msg.Amount.Nano().Sign() <= 0 || 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(),
|
||||
FromAddress: tonAccountAddr(msg.SrcAddr),
|
||||
RecvAddress: tonAccountAddr(msg.DstAddr),
|
||||
Timestamp: time.Unix(int64(tx.Now), 0),
|
||||
Amount: decimal.NewFromBigInt(msg.Amount.Nano(), conf.TonTonDecimals),
|
||||
TradeType: model.TonGram,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
tgo "github.com/xssnick/tonutils-go/ton"
|
||||
"github.com/xssnick/tonutils-go/tvm/cell"
|
||||
)
|
||||
|
||||
var (
|
||||
tonTestSrc = address.NewAddress(0, 0, make([]byte, 32))
|
||||
tonTestDst = address.NewAddress(0, 0, append(make([]byte, 31), 1))
|
||||
)
|
||||
|
||||
func tonTestTx(body *cell.Cell, nano uint64, dsc any) *tlb.Transaction {
|
||||
tx := &tlb.Transaction{AccountAddr: tonTestDst.Data(), Now: 1700000000, Hash: []byte{0xab}, Description: dsc}
|
||||
tx.IO.In = &tlb.Message{MsgType: tlb.MsgTypeInternal, Msg: &tlb.InternalMessage{
|
||||
SrcAddr: tonTestSrc,
|
||||
DstAddr: tonTestDst,
|
||||
Amount: tlb.FromNanoTONU(nano),
|
||||
Body: body,
|
||||
}}
|
||||
|
||||
return tx
|
||||
}
|
||||
|
||||
func tonTestOrdinary(success bool) tlb.TransactionDescriptionOrdinary {
|
||||
return tlb.TransactionDescriptionOrdinary{
|
||||
ComputePhase: tlb.ComputePhase{Phase: tlb.ComputePhaseVM{Success: success}},
|
||||
ActionPhase: &tlb.ActionPhase{Success: success},
|
||||
}
|
||||
}
|
||||
|
||||
func tonTestJettonBody(op uint32, amount uint64) *cell.Cell {
|
||||
return cell.BeginCell().
|
||||
MustStoreUInt(uint64(op), 32).
|
||||
MustStoreUInt(1, 64).
|
||||
MustStoreCoins(amount).
|
||||
MustStoreAddr(tonTestSrc).
|
||||
EndCell()
|
||||
}
|
||||
|
||||
func TestParseTonTransfer(t *testing.T) {
|
||||
empty := cell.BeginCell().EndCell()
|
||||
skipped := tlb.TransactionDescriptionOrdinary{
|
||||
ComputePhase: tlb.ComputePhase{Phase: tlb.ComputePhaseSkipped{}},
|
||||
Aborted: true,
|
||||
}
|
||||
returned := skipped
|
||||
returned.BouncePhase = &tlb.BouncePhase{Phase: tlb.BouncePhaseOk{}}
|
||||
noFunds := skipped
|
||||
noFunds.BouncePhase = &tlb.BouncePhase{Phase: tlb.BouncePhaseNoFunds{}}
|
||||
|
||||
bouncedIn := tonTestTx(empty, 1e9, tonTestOrdinary(true))
|
||||
bouncedIn.IO.In.Msg.(*tlb.InternalMessage).Bounced = true
|
||||
external := tonTestTx(empty, 1e9, tonTestOrdinary(true))
|
||||
external.IO.In.Msg = &tlb.ExternalMessage{}
|
||||
noIn := tonTestTx(empty, 1e9, tonTestOrdinary(true))
|
||||
noIn.IO.In = nil
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
tx *tlb.Transaction
|
||||
ok bool
|
||||
}{
|
||||
{"plain", tonTestTx(empty, 1e9, tonTestOrdinary(true)), true},
|
||||
{"uninit account", tonTestTx(empty, 1e9, skipped), true},
|
||||
{"uninit account, bounce unpaid", tonTestTx(empty, 1e9, noFunds), true},
|
||||
{"returned to sender", tonTestTx(empty, 1e9, returned), false},
|
||||
{"zero amount", tonTestTx(empty, 0, tonTestOrdinary(true)), false},
|
||||
{"with body", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 1), 1e9, tonTestOrdinary(true)), false},
|
||||
{"bounced inbound", bouncedIn, false},
|
||||
{"external inbound", external, false},
|
||||
{"no inbound", noIn, false},
|
||||
{"tick tock", tonTestTx(empty, 1e9, tlb.TransactionDescriptionTickTock{}), false},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
got, ok := (&ton{}).parseTonTransfer(c.tx, 100)
|
||||
if ok != c.ok {
|
||||
t.Errorf("%s: ok = %v, want %v", c.name, ok, c.ok)
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if got.TradeType != model.TonGram || got.Amount.String() != "1" || got.BlockNum != 100 {
|
||||
t.Errorf("%s: unexpected transfer %+v", c.name, got)
|
||||
}
|
||||
if got.RecvAddress != tonTestDst.Bounce(false).String() || got.FromAddress != tonTestSrc.Bounce(false).String() {
|
||||
t.Errorf("%s: unexpected address %s <- %s", c.name, got.RecvAddress, got.FromAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTonInternalTransfer(t *testing.T) {
|
||||
shard := &tgo.BlockIDExt{Workchain: 0}
|
||||
cases := []struct {
|
||||
name string
|
||||
tx *tlb.Transaction
|
||||
ok bool
|
||||
}{
|
||||
{"jetton received", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 2_500_000), 1, tonTestOrdinary(true)), true},
|
||||
{"other op", tonTestTx(tonTestJettonBody(0x7362d09c, 2_500_000), 1, tonTestOrdinary(true)), false},
|
||||
{"execution failed", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 2_500_000), 1, tonTestOrdinary(false)), false},
|
||||
{"zero amount", tonTestTx(tonTestJettonBody(tonOpInternalTransfer, 0), 1, tonTestOrdinary(true)), false},
|
||||
{"empty body", tonTestTx(cell.BeginCell().EndCell(), 1, tonTestOrdinary(true)), false},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
got, ok := (&ton{}).parseInternalTransfer(shard, c.tx, 100)
|
||||
if ok != c.ok {
|
||||
t.Errorf("%s: ok = %v, want %v", c.name, ok, c.ok)
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if got.TradeType != model.UsdtTon || got.Amount.String() != "2.5" || got.RecvAddress != tonTestDst.Bounce(false).String() {
|
||||
t.Errorf("%s: unexpected transfer %+v", c.name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-7
@@ -3,7 +3,6 @@ package task
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -293,6 +292,22 @@ func hasLookbackOrders(tradeType []model.TradeType) bool {
|
||||
return count > 0
|
||||
}
|
||||
|
||||
// lookbackOrdersPending 判断这些订单中是否还有需要回溯的,条件与 hasLookbackOrders 相同
|
||||
func lookbackOrdersPending(orderIDs []int64) (bool, error) {
|
||||
if len(orderIDs) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := model.Db.Model(&model.Order{}).
|
||||
Where("id in (?)", orderIDs).
|
||||
Where("status in (?)", receivableOrderStatuses()).
|
||||
Where("expired_at > ?", time.Now().Add(model.GetLookbackHour())).
|
||||
Count(&count).Error
|
||||
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func getLookbackUnix(network model.Network) (startAt, endAt int64, ok bool) {
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(network)
|
||||
if ok {
|
||||
@@ -401,16 +416,21 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
|
||||
case model.Classic:
|
||||
return amount.String() == target
|
||||
case model.HasPrefix:
|
||||
s := amount.String()
|
||||
if !strings.HasPrefix(s, target) {
|
||||
t, err := decimal.NewFromString(target)
|
||||
if err != nil {
|
||||
log.Warn(err.Error())
|
||||
|
||||
return false
|
||||
}
|
||||
rest := s[len(target):]
|
||||
if rest == "" {
|
||||
return true
|
||||
|
||||
// 订单金额去掉了末尾的 0(1.50 存为 1.5),直接按字符串比前缀会让 1.5 的订单吃掉 1.51 的付款;
|
||||
// 按原子精度和订单金额小数位中的较大者截断实付金额再精确比较,只容忍精度以下的多付
|
||||
_, precision := model.GetAtomicity(model.TradeType(tradeType))
|
||||
if p := abs(t.Exponent()); p > precision {
|
||||
precision = p
|
||||
}
|
||||
|
||||
return strings.Contains(target, ".") || strings.HasPrefix(rest, ".")
|
||||
return amount.Truncate(precision).Equal(t)
|
||||
case model.RoundOff:
|
||||
t, err := decimal.NewFromString(target)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# BEpusdt(SQLite 版)—— 单机最简部署
|
||||
#
|
||||
# 用法:
|
||||
# 1) docker login git.viaeon.com # 私有镜像仓库,用 Gitea 账号/token
|
||||
# 2) docker compose up -d
|
||||
# 3) 浏览器打开 http://服务器IP:8080 走安装向导(记下「安全入口」和后台账号)
|
||||
#
|
||||
# 关键点:
|
||||
# - SQLite 数据库在容器内 /var/lib/bepusdt/sqlite.db,必须挂出来,否则删容器=丢单
|
||||
# - 日志在 /var/log/bepusdt/,也挂出来,排查掉单要靠它
|
||||
# - 默认 LISTEN 就是 :8080(0.0.0.0),容器内不用改;要只让反代访问就绑 127.0.0.1
|
||||
|
||||
services:
|
||||
bepusdt:
|
||||
image: git.viaeon.com/admin/bepusdt:latest # 想用官方镜像就换成 v03413/bepusdt:latest
|
||||
container_name: bepusdt
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
# 前面有 Nginx/Caddy 反代时绑本机,别把后台裸奔在公网
|
||||
- "127.0.0.1:8080:8080"
|
||||
# 没有反代、想直接 IP:端口 访问,就用下面这行替换上面那行:
|
||||
# - "8080:8080"
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
LISTEN: ":8080"
|
||||
SQLITE: /var/lib/bepusdt/sqlite.db
|
||||
LOG: /var/log/bepusdt/
|
||||
volumes:
|
||||
- ./data:/var/lib/bepusdt # sqlite.db 就在这里
|
||||
- ./logs:/var/log/bepusdt
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -0,0 +1,60 @@
|
||||
# BEpusdt + MySQL 8 —— 需要 MySQL 的场景
|
||||
#
|
||||
# 注意:这是**本仓库(admin/BEPUSDT)加了 MySQL 支持之后**才能用的写法。
|
||||
# 上游 v03413/bepusdt 的代码只有 SQLite 和 PostgreSQL,文档里那段 MYSQL_DSN 是过期内容。
|
||||
# 镜像:git.viaeon.com/admin/bepusdt:latest(>= e7a8dd9)
|
||||
#
|
||||
# 用法:
|
||||
# echo "DB_ROOT_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" > .env
|
||||
# echo "DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" >> .env
|
||||
# docker login git.viaeon.com
|
||||
# docker compose -f docker-compose.mysql.yml up -d
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mysql:8.0
|
||||
container_name: bepusdt-db
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_unicode_ci
|
||||
- --default-time-zone=+08:00
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?先把 DB_ROOT_PASSWORD 写进 .env}
|
||||
MYSQL_DATABASE: bepusdt
|
||||
MYSQL_USER: bepusdt
|
||||
MYSQL_PASSWORD: ${DB_PASSWORD:?先把 DB_PASSWORD 写进 .env}
|
||||
TZ: Asia/Shanghai
|
||||
volumes:
|
||||
- ./mysqldata:/var/lib/mysql
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-p$${DB_ROOT_PASSWORD}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 40s
|
||||
expose:
|
||||
- "3306"
|
||||
|
||||
bepusdt:
|
||||
image: git.viaeon.com/admin/bepusdt:latest
|
||||
container_name: bepusdt
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
LISTEN: ":8080"
|
||||
LOG: /var/log/bepusdt/
|
||||
# DSN 三个参数别省:charset=utf8mb4(中文)、parseTime=True(时间列)、loc=Local(时区)
|
||||
MYSQL_DSN: bepusdt:${DB_PASSWORD}@tcp(db:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s&readTimeout=10s&writeTimeout=10s
|
||||
volumes:
|
||||
- ./logs:/var/log/bepusdt
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -0,0 +1,52 @@
|
||||
# BEpusdt + PostgreSQL —— 生产推荐
|
||||
#
|
||||
# 说明:官方文档里那套 MySQL 写法是**过期的**(代码里已经没有任何 MySQL 分支),
|
||||
# 现在只支持 SQLite 和 PostgreSQL 两种。数据量大/要多实例就看这份。
|
||||
#
|
||||
# 用法:
|
||||
# echo "DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')" > .env
|
||||
# docker login git.viaeon.com
|
||||
# docker compose -f docker-compose.postgres.yml up -d
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:18-alpine
|
||||
container_name: bepusdt-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: bepusdt
|
||||
POSTGRES_USER: bepusdt
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:?先把 DB_PASSWORD 写进 .env}
|
||||
TZ: Asia/Shanghai
|
||||
volumes:
|
||||
- ./pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U bepusdt -d bepusdt"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
# 数据库不要暴露到公网
|
||||
expose:
|
||||
- "5432"
|
||||
|
||||
bepusdt:
|
||||
image: git.viaeon.com/admin/bepusdt:latest
|
||||
container_name: bepusdt
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
LISTEN: ":8080"
|
||||
LOG: /var/log/bepusdt/
|
||||
POSTGRESQL_DSN: postgres://bepusdt:${DB_PASSWORD}@db:5432/bepusdt?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
|
||||
volumes:
|
||||
- ./logs:/var/log/bepusdt
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -212,7 +212,8 @@ key := t.Address + string(t.TradeType)
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式二:HasPrefix(前缀匹配 / 允许多付) │
|
||||
│ │
|
||||
│ 规则:实际到账金额以订单金额为前缀,允许多付小数 │
|
||||
│ 规则:订单金额按原子精度补齐小数位后,作为实际到账金额的前缀 │
|
||||
│ (1.5 补成 1.50),只容忍原子精度以下的多付 │
|
||||
│ │
|
||||
│ 订单金额:10.01 │
|
||||
│ 到账金额:10.01 ✅ 匹配(完全等于) │
|
||||
|
||||
+30
-11
@@ -78,11 +78,14 @@ docker run -d \
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>MySQL 数据库(已弃用)</strong></summary>
|
||||
<summary><strong>MySQL 数据库(本仓库已支持)</strong></summary>
|
||||
|
||||
> **注意:** MySQL 支持将逐步弃用,建议使用 PostgreSQL 替代。
|
||||
|
||||
系统仍支持使用 MySQL 作为数据存储方案,但不再推荐用于新部署。
|
||||
> **上游 `v03413/bepusdt` 不支持 MySQL**(代码里只有 SQLite / PostgreSQL 两条分支,
|
||||
> 文末那段 `MYSQL_DSN` 曾长期是「文档先行、代码没有」的状态)。
|
||||
> **本仓库 `admin/BEPUSDT` 已实现**(自 `e7a8dd9` 起):启动时按
|
||||
> `MYSQL_DSN` > `POSTGRESQL_DSN` > SQLite 的优先级选择后端。
|
||||
>
|
||||
> 新部署仍建议 PostgreSQL;如果你已经有 MySQL 实例、或要和别的业务共用一个库,就用这条。
|
||||
|
||||
**部署命令:**
|
||||
|
||||
@@ -90,16 +93,32 @@ docker run -d \
|
||||
docker run -d \
|
||||
--restart unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s \
|
||||
v03413/bepusdt:latest
|
||||
-e MYSQL_DSN='user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s&readTimeout=10s&writeTimeout=10s' \
|
||||
git.viaeon.com/admin/bepusdt:latest
|
||||
```
|
||||
|
||||
**配置说明:**
|
||||
**建库(表结构由程序启动时自动迁移,不用手工建表):**
|
||||
|
||||
- 将 `user` 替换为 MySQL 用户名
|
||||
- 将 `password` 替换为 MySQL 密码
|
||||
- 将 `127.0.0.1:3306` 替换为 MySQL 服务器地址和端口
|
||||
- 将 `bepusdt` 替换为实际数据库名称(如需要)
|
||||
```sql
|
||||
CREATE DATABASE bepusdt CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
CREATE USER 'bepusdt'@'%' IDENTIFIED BY '你的密码';
|
||||
GRANT ALL ON bepusdt.* TO 'bepusdt'@'%';
|
||||
```
|
||||
|
||||
**DSN 里这三个参数一个都不能省**(省掉不报错,但会出问题):
|
||||
|
||||
| 参数 | 省掉的后果 |
|
||||
|---|---|
|
||||
| `charset=utf8mb4` | 中文写进去变成 `?`,后台文案/商品名乱码 |
|
||||
| `parseTime=True` | `datetime` 列读不出,时间显示 1970 或直接报错 |
|
||||
| `loc=Local` | 时间按 UTC 存,订单超时、汇率有效期整体偏移 8 小时 |
|
||||
|
||||
**注意事项:**
|
||||
|
||||
- 建议 MySQL **8.0**;5.7 的 utf8mb4 索引长度上限(767 字节)可能让 `varchar(1024)` 相关的唯一索引建不出来
|
||||
- 本仓库把 `return_url` / `notify_url` 从 `TEXT` 改成了 `VARCHAR(1024)` —— MySQL 8 不允许 TEXT 列带 `DEFAULT ''`(`Error 1101`)
|
||||
- 老库(之前用 SQLite/PG 的)切到 MySQL 不会自动搬数据,需要自己导出导入
|
||||
- 完整的 compose 示例见仓库根目录 `docker-compose.mysql.example.yml`
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -25,25 +25,33 @@
|
||||
|
||||
## 前缀匹配
|
||||
|
||||
如同名字一般,前缀匹配模式会将两个交易金额转换成字符串,然后从左到右逐位进行对比。
|
||||
如果订单金额字符串是实际交易金额字符串的前缀,则认为是匹配成功。
|
||||
订单金额按原子精度补齐小数位(如 `atom_usdt = 0.01` 时 1.5 写成 1.50),如果它是实际交易金额的前缀,则认为是匹配成功。
|
||||
实现上等价于:把实际交易金额按原子精度直接截断(不四舍五入),再与订单金额精确比较。
|
||||
只容忍原子精度以下的多付;少付、或多付达到一个原子精度,都会匹配失败。
|
||||
|
||||
**适用场景:**
|
||||
|
||||
- 某些支付渠道可能会在金额末尾添加额外的小数位
|
||||
- 用户可能因为汇率波动或手续费问题支付了稍多的金额
|
||||
- 需要更灵活的金额匹配策略
|
||||
- 用户转账时在原子精度以下多带了几位小数(如应付 1.50,实付 1.50123)
|
||||
- 同一地址同时有多笔等待支付的订单:系统按原子精度递增订单金额(1.50、1.51 …),
|
||||
每笔付款只会匹配其中一笔,不会把 1.51 的付款匹配给 1.50 的订单
|
||||
|
||||
**举例:**
|
||||
**举例(原子精度 0.01):**
|
||||
|
||||
| 订单金额 | 实际交易金额 | 匹配结果 | 说明 |
|
||||
|--------|------------|--------|-----------------------------|
|
||||
| 100 | 100.5 | ✅ 匹配成功 | "100" 是 "100.5" 的前缀 |
|
||||
| 100.5 | 100.56 | ✅ 匹配成功 | "100.5" 是 "100.56" 的前缀 |
|
||||
| 99.9 | 99.99 | ✅ 匹配成功 | "99.9" 是 "99.99" 的前缀 |
|
||||
| 100 | 99.99 | ❌ 匹配失败 | "100" 不是 "99.99" 的前缀 |
|
||||
| 100.5 | 100.4 | ❌ 匹配失败 | "100.5" 不是 "100.4" 的前缀 |
|
||||
| 123.45 | 123.456789 | ✅ 匹配成功 | "123.45" 是 "123.456789" 的前缀 |
|
||||
| 订单金额 | 实际交易金额 | 匹配结果 | 说明 |
|
||||
|--------|------------|--------|-------------------------------|
|
||||
| 1.50 | 1.50 | ✅ 匹配成功 | 金额一致 |
|
||||
| 1.50 | 1.50123 | ✅ 匹配成功 | "1.50" 是 "1.50123" 的前缀 |
|
||||
| 1.50 | 1.509 | ✅ 匹配成功 | 截断不进位,第三位起的多付被忽略 |
|
||||
| 1.50 | 1.51 | ❌ 匹配失败 | 属于 1.51 的订单 |
|
||||
| 1.50 | 1.4999 | ❌ 匹配失败 | 少付 |
|
||||
| 100.00 | 100.5 | ❌ 匹配失败 | 多付达到原子精度,"100.00" 不是 "100.50" 的前缀 |
|
||||
| 123.45 | 123.456789 | ✅ 匹配成功 | "123.45" 是 "123.456789" 的前缀 |
|
||||
|
||||
订单金额小数位多于当前原子精度时(例如修改原子精度前创建的订单),按订单金额自己的小数位补齐和截断。
|
||||
|
||||
> 早期版本直接拿订单金额字符串做前缀比较。订单金额保存时会去掉末尾的 0(1.50 存为 `"1.5"`,2.00 存为 `"2"`),
|
||||
> 而 `"1.5"` 是 `"1.51"` 的前缀、`"2"` 是 `"2.01"` 的前缀,同一地址有多笔订单时,后建订单的付款会被先建的订单匹配走。
|
||||
> 现在改为按原子精度补齐后比较,多付达到一个原子精度(如订单 100,实付 100.5)不再匹配。
|
||||
|
||||
---
|
||||
|
||||
@@ -81,7 +89,7 @@
|
||||
## 选择建议
|
||||
|
||||
- **传统模式**:适合金额固定、对准确性要求高的场景
|
||||
- **前缀匹配**:适合仅允许用户多付、可能添加额外精度的场景
|
||||
- **前缀匹配**:适合只容忍原子精度以下多付、同一地址可能同时有多笔订单的场景
|
||||
- **修约匹配**:适合允许用户多付或者少付,容忍度更高的场景
|
||||
|
||||
根据实际业务需求选择合适的匹配模式,可以在保证安全性的同时提升用户体验。
|
||||
|
||||
@@ -27,6 +27,7 @@ require (
|
||||
github.com/xssnick/tonutils-go v1.17.2
|
||||
golang.org/x/crypto v0.51.0
|
||||
google.golang.org/grpc v1.81.0
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
@@ -44,6 +45,7 @@ require (
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.2 // indirect
|
||||
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||
github.com/goccy/go-json v0.10.6 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
|
||||
@@ -78,6 +78,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=
|
||||
github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-telegram/bot v1.20.0 h1:4Pea/qTidSspr4WBJw9FbHUMNhYeqszBqQUfsQEyFbc=
|
||||
github.com/go-telegram/bot v1.20.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
|
||||
@@ -315,6 +317,8 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
|
||||
Reference in New Issue
Block a user