Compare commits

..
41 Commits
Author SHA1 Message Date
v03413 8a91be6a15 chore: .gitignore update 2026-11-13 09:38:22 +08:00
v03413 8ff1bce889 docs: 更新安全问题反馈联系邮箱 2026-11-13 09:37:06 +08:00
v03413 5791328de4 refactor: 合并 TON 转账解析的入站消息处理并补充单元测试 2026-11-13 09:20:39 +08:00
v03413 566aa5a486 fix: 修正 stale issue 提示信息中的天数为 3 天 2026-11-10 14:37:55 +08:00
莫名 78db081b35 Merge pull request #248 from sylearn/feat/truncate-match-mode
fix: 前缀匹配按原子精度补齐后比较,并发订单不互相抢付款
2026-11-01 22:10:19 +08:00
sylearn c592d3fb7a fix: fold truncate matching into has_prefix
Per review, drop the separate truncate mode and use its logic for
has_prefix instead. Order amounts are stored without trailing zeros
(1.50 as "1.5"), so the plain string prefix check let the 1.5 order
claim a 1.51 payment meant for a concurrent order on the same address.
Truncate the received amount to the larger of the atom precision and
the order's own decimals, then compare exactly: overpayment below the
atom precision still matches, underpayment and overpayment of a full
atom no longer do.
2026-11-01 22:49:44 +09:00
sylearn 5cb1d6f099 feat: add truncate amount match mode
Truncate the received amount to the atom precision before an exact comparison, so overpayment below the atom precision still matches while concurrent orders on one address (1.50, 1.51, ...) never claim each other's payments.
2026-10-31 23:45:49 +09:00
莫名 ebff24a190 Merge pull request #246 from sylearn/fix/solana-forward-tolerates-slot-retries
fix(solana): keep scanning forward while a few slots retry
2026-10-29 17:33:31 +08:00
莫名 5a1f9def13 Merge pull request #244 from sylearn/fix/solana-pruned-slot-no-retry
fix(solana): give up on slots the node has cleaned up
2026-10-29 17:33:22 +08:00
莫名 448cda9022 Merge pull request #243 from sylearn/fix/solana-drop-stale-lookback
fix(solana): drop lookback ranges of finished orders
2026-10-29 17:33:12 +08:00
sylearn 6784a98c8e test(solana): cover backpressure threshold and recovery 2026-10-29 00:46:44 +08:00
sylearn d54669a8aa fix(solana): keep cleaned slots terminal under concurrency 2026-10-29 00:46:26 +08:00
sylearn 5b3a1ded6d fix(solana): keep lookback progress when the order query fails
lookbackOrdersPending ignored the query error, so a failed read counted
as "no order needs a lookback" and dropped the progress of a range that
was still needed. Return the error and keep the progress until the next
tick can check again.
2026-10-28 13:27:18 +08:00
sylearn 144cdb8c40 fix(solana): keep scanning forward while a few slots retry
syncSlotForward stops fetching the head slot as soon as any slot waits
for a retry. One slot that keeps failing with a timeout, 429 or -32004
therefore holds back every later payment until it succeeds or is given
up after about 7 minutes, although the following slots can be fetched
normally.

Pause forward scanning only when solanaForwardPauseRetries (10) slots
wait for a retry. That still stops new slots from piling into the retry
set during a node outage, while a single failing slot no longer delays
new payments.
2026-10-28 13:24:12 +08:00
sylearn 9131b9d5c4 fix(solana): give up on slots the node has cleaned up
getBlock returns -32001 (BlockCleanedUp) for a slot older than the
node's first available block. Retrying cannot succeed, yet the slot was
retried 10 times over about 7 minutes, and forward scanning stays paused
while any retry is pending.

In production a lookback range from a week earlier hit this for 627
slots at once: forward scanning stopped for about 10 minutes and the
node started to answer 429, which delayed a real payment by four
minutes.

Treat -32001 as final: log an ERROR with the slot number, clear any
retry left from an earlier failure of the same slot, and do not schedule
another one. Other errors keep the bounded retry. The existing retry
test now uses -32004 (block not available), a transient error.
2026-10-28 12:59:38 +08:00
sylearn 2fdb6e81d3 fix(solana): drop lookback ranges of finished orders
lookbackSlots keeps its progress (lookbackNext/lookbackEnd) across ticks,
but returns early through syncBreak once no order needs scanning. When an
order is paid, canceled or expires before its range is fully queued, the
remainder stays in memory. The next Solana order, possibly days later,
resumes that old range first.

In production the remainder was 627 slots from a week earlier. The RPC
node had already pruned them (-32001), every slot was retried, forward
scanning paused while retries were pending, and the node started to
answer 429. A payment made 90 seconds after the order was created was
seen four minutes late.

Before resuming, check that at least one order of the range still needs
a lookback (same condition as hasLookbackOrders); otherwise drop the
remaining range. The check runs before syncBreak so the state is also
cleared while scanning is idle.
2026-10-28 12:58:19 +08:00
莫名 07164853c3 Merge pull request #242 from sylearn/feat/solana-reconcile-expired-orders
feat(solana): reconcile expired orders against token account history
2026-10-19 17:17:48 +08:00
莫名 3a1201e485 Merge branch 'main' into feat/solana-reconcile-expired-orders 2026-10-19 17:14:33 +08:00
莫名 a88d36918a Merge pull request #238 from sylearn/fix/solana-no-skip-while-lagging
fix(solana): keep catching up instead of skipping slots
2026-10-19 17:12:43 +08:00
莫名 46665ce060 Merge pull request #237 from sylearn/fix/solana-slot-retry-limit
fix(solana): stop retrying permanently failing slots
2026-10-19 17:12:28 +08:00
莫名 a4ed778a94 Merge pull request #241 from sylearn/refactor/solana-parse-transaction
refactor(solana): extract transaction parsing with mainnet fixtures
2026-10-19 17:11:38 +08:00
莫名 03980768c7 Merge pull request #239 from sylearn/fix/solana-confirm-offset-from-status
fix(solana): check confirmations from the signature status
2026-10-19 17:11:17 +08:00
莫名 79a67fa942 Merge pull request #240 from sylearn/fix/lookback-window-end
fix(task): cover every pending order window in lookback
2026-10-19 17:10:52 +08:00
莫名 6f1b1ef6f6 Merge pull request #235 from sylearn/fix/solana-lookback-range
fix(solana): validate and resume lookback ranges
2026-10-19 17:09:02 +08:00
莫名 08bb49ea78 Merge pull request #236 from sylearn/fix/solana-skip-failed-transactions
fix(solana): skip transactions that failed on chain
2026-10-19 17:08:10 +08:00
sylearnandClaude Opus 5.5 014bb8e12b feat(solana): reconcile expired orders against token account history
Block scanning gives every slot one chance. A skipped or abandoned slot,
a restart, or an incomplete lookback range loses a payment for good, and
nothing finds it again.

Once a Solana order has been expired for a minute (up to two hours), look
it up once in the receiving token accounts' own history:

- token accounts: the wallet's associated token account, derived locally,
  plus any other account from getTokenAccountsByOwner when the node
  supports it (publicnode's free tier rejects that method);
- getSignaturesForAddress back to the order's creation time, keeping
  successful signatures inside the order window that no order has used;
- getTransaction, parsed with parseTransaction and checked with the
  existing orderTransferMatch. A match is marked confirming and then
  follows the normal confirm and callback flow.

RPC errors leave the order for the next round. Cost: a few RPC calls per
expired Solana order plus one getTransaction per candidate payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:41:36 +08:00
sylearnandClaude Opus 5.5 efe4a3873e refactor(solana): extract transaction parsing with mainnet fixtures
Move the per-transaction body of slotParse into parseTransaction so the
same parser can be used on getTransaction results. No behavior change:
`git diff -w` shows only the loop/return edits.

Add mainnet fixtures for legacy transfer (USDT), legacy transferChecked,
a transfer to a token account created in the same transaction, and a v1
transaction; expected transfers come from an independent decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:37:45 +08:00
sylearnandClaude Opus 5.5 f46b4b7f74 fix(task): cover every pending order window in lookback
pendingLookbackUnix ended the lookback range at the expiry of the last
expired order in created_at order. When a batch mixes expired and still
waiting orders (common after a restart), or an earlier order has a
longer timeout, part of the other orders' windows was outside the range
but they were still marked as looked back.

End the range at the latest min(expired_at, now) over the batch. Used by
every chain's lookback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:25:18 +08:00
sylearnandClaude Opus 5.5 e7f857d21e fix(solana): check confirmations from the signature status
With block_offset_confirm enabled, tradeConfirmHandle compared the
order's slot with lastSlotNum, the forward scan cursor. The cursor stops
moving once no unexpired order is pending and is 0 after a restart, so a
payment matched shortly before expiry stayed "confirming" forever.

Use result.context.slot from the same getSignatureStatuses response
instead. This also removes the unsynchronized read of lastSlotNum from
the confirm goroutines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:23:52 +08:00
sylearnandClaude Opus 5.5 b0292c87dc fix(solana): keep catching up instead of skipping slots
The jump to the latest slot when the scanner falls more than
block_height_max_diff behind is meant for resuming after an idle period
(no pending orders) or on startup. It also fired while orders were
active, e.g. after a retry pause, dropping every slot in between without
a log; payments in those slots were never matched.

Now the scanner jumps only on startup or after idling, and otherwise
logs a warning and keeps catching up within blockQueueLimit per round.
A full queue does not count as idle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:23:17 +08:00
sylearnandClaude Opus 5.5 0354e07232 fix(solana): stop retrying permanently failing slots
- Give up a slot after 10 failed scans (about 7 minutes with the
  existing backoff) and log an ERROR with the slot number. Before, a slot
  that can never be fetched (e.g. "Block cleaned up", -32001) was retried
  forever, and forward sync stayed paused the whole time.
- A retry is queued as soon as its timer fires instead of being
  postponed while the queue is full, so a busy queue is never counted as
  a failed attempt.
- Add shared task test helpers (temporary log dir and SQLite).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:22:59 +08:00
sylearnandClaude Opus 5.5 1f127e237b fix(solana): skip transactions that failed on chain
- slotParse ignores transactions whose meta.err is not null. Failed
  transactions are still included in blocks with their instructions and
  token balances, but every transfer in them was rolled back.
- tradeConfirmHandle only confirms a signature that is finalized and has
  err == null; getSignatureStatuses reports failed transactions as
  finalized too.
- Add mainnet fixtures (failed v1 top-level transfer, failed v0 inner
  transfer, succeeded v0 inner transfer) and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:22:43 +08:00
sylearn 6dcbc2ad00 fix(solana): validate and resume lookback ranges 2026-10-18 10:48:01 +08:00
v03413 d36d34fe04 fix: 订单 URL 字段改为 text
return_url/notify_url 原为 varchar(255),超长时 PostgreSQL 写入订单报错 (SQLSTATE 22001),由 AutoMigrate 自动变更列类型。

Fix #234
2026-10-15 18:07:53 +08:00
莫名 e769e32b1c Merge pull request #233 from sylearn/fix/solana-rpc-error-retry
fix(solana): retry failed block scans safely
2026-10-14 13:55:37 +08:00
sylearnandClaude Opus 5.5 16a46716c0 fix(solana): retry failed block scans safely
- Validate getBlock JSON, JSON-RPC error, result and result.transactions;
  record scan success only after a complete block is parsed.
- Treat skipped slots (result: null, -32007, -32009) as empty slots.
- Retry failed slots with bounded 2s/5s/15s/30s/60s backoff, one timer
  per slot; pause forward sync while retries are pending.
- Fill the slot queue only up to blockQueueLimit per round, keeping the
  existing BlockHeightMaxDiff jump-ahead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:50:23 +08:00
莫名 f2516d3212 Merge pull request #232 from sylearn/fix/solana-v1-transactions
fix(solana): support versioned v1 transactions
2026-10-14 10:11:25 +08:00
sylearn 3dafd2e7e1 fix(solana): support versioned v1 transactions 2026-10-14 02:54:37 +08:00
v03413 aa3bd5097f docs: update 2026-09-30 15:00:44 +08:00
v03413 50f7f16c28 docs: 更换 star 历史图表 2026-09-29 23:20:27 +08:00
v03413 9be43676aa docs: add pr submission guidance 2026-08-05 09:14:58 +08:00
37 changed files with 2163 additions and 223 deletions
+1 -1
View File
@@ -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
+2 -1
View File
@@ -9,4 +9,5 @@ dist/
static/web
static/secure
*.log
AGENTS.md
AGENTS.md
CLAUDE.md
+5 -4
View File
@@ -1,4 +1,4 @@
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务(谨防诈骗)
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务 (谨防诈骗)
,不鼓励任何衍生金融属性的交易行为,不负责任何使用本项目进行的三方行为;使用过程中遇见问题请提`issue`
或群里交流,开源项目请自重!**
@@ -66,8 +66,8 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
## 🖼 功能截图
| 前台收银 | 后台订单 | 订单通知 |
|--------------------------------------------------------|------------------------------------------------------|---------------------------------------------------------------|
| 前台收银 | 后台订单 | 订单通知 |
|-----------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------|
| <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> |
## ❓ 常见问题
@@ -82,6 +82,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)
## 🙏 致谢
@@ -97,4 +98,4 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
## 🌟 Star 历史
[![Stargazers over time](https://starchart.cc/v03413/bepusdt.svg)](https://starchart.cc/v03413/bepusdt)
[![Star History Chart](https://api.star-history.com/chart?repos=v03413/bepusdt&type=date&legend=top-left)](https://www.star-history.com/?repos=v03413%2Fbepusdt&type=date&legend=top-left)
+1 -1
View File
@@ -108,7 +108,7 @@ const (
)
const (
Classic MatchMode = "classic" // 经典模式,精确匹配
HasPrefix MatchMode = "has_prefix" // 前缀匹配,允许多付
HasPrefix MatchMode = "has_prefix" // 前缀匹配,按原子精度截断后比较,只容忍精度以下的多付
RoundOff MatchMode = "round_off" // 数值修约,四舍五入,允许容错
)
+2 -2
View File
@@ -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: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"`
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"`
+10
View File
@@ -396,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 {
+60
View File
@@ -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)
}
}
}
+351 -106
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
@@ -31,8 +32,17 @@ import (
type solana struct {
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
retryStopped map[int]struct{}
lookbackMu sync.Mutex
lookbackNext int
lookbackEnd int
lookbackOrderIDs []int64
}
type solanaTokenOwner struct {
@@ -48,6 +58,7 @@ func init() {
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 {
@@ -56,12 +67,25 @@ func newSolana() solana {
lastSlotNum: 0,
slotQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
client: utils.NewHttpClient(),
retryAttempts: make(map[int]int),
retryScheduled: make(map[int]*time.Timer),
retryStopped: make(map[int]struct{}),
}
}
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() >= solanaForwardPauseRetries {
return
}
@@ -97,22 +121,25 @@ func (s *solana) syncSlotForward(ctx context.Context) {
return
}
if now-s.lastSlotNum > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) { // 区块高度变化过大,强制丢块重扫
s.lastSlotNum = now
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 { // 区块高度没有变化
if now <= s.lastSlotNum { // 区块高度没有变化或节点返回旧高度
return
}
for n := s.lastSlotNum + 1; n <= now; n++ {
// 待扫描区块入列
// 只填充队列的可用容量;消费后由下一轮继续追赶,避免长时间故障恢复时瞬间过度扫描。
for n := s.lastSlotNum + 1; n <= now && s.slotQueue.Len() < blockQueueLimit; n++ {
s.slotQueue.In <- n
s.lastSlotNum = n
}
s.lastSlotNum = now
}
func (s *solana) slotDispatch(ctx context.Context) {
@@ -144,13 +171,13 @@ func (s *solana) slotDispatch(ctx context.Context) {
func (s *solana) slotParse(n any) {
slot := n.(int)
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":0,"transactionDetails":"full","rewards":false}]}`, slot))
post := solanaGetBlockPayload(slot)
network := conf.Solana
conf.RecordSuccess(network, cast.ToString(slot))
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
@@ -159,6 +186,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
@@ -167,65 +195,115 @@ 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 errors.Is(err, errSolanaBlockCleanedUp) { // 节点已清理该 slot,重试也拿不到;放弃,不暂停向前扫描
conf.RecordFailure(network)
s.stopSlotRetry(slot)
log.Task.Error(fmt.Sprintf("Solana slot %d 已被节点清理,无法扫描,该 slot 内的付款需要人工核对:%s", slot, err))
for _, trans := range gjson.GetBytes(body, "result.transactions").Array() {
hash := trans.Get("transaction.signatures.0").String()
return
}
if err != nil {
conf.RecordFailure(network)
s.scheduleSlotRetry(slot)
log.Task.Warn("slotParse Error JSON-RPC response:", err)
// 解析账号索引
accountKeys := make([]string, 0)
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
return
}
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
@@ -233,41 +311,169 @@ 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 (
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")
}
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
case solanaErrBlockCleanedUp:
return gjson.Result{}, fmt.Errorf("%w: %s", errSolanaBlockCleanedUp, rpcErr.Raw)
}
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 _, stopped := s.retryStopped[slot]; stopped {
s.retryMu.Unlock()
return
}
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) 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()
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
// 待重试的 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 {
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 {
@@ -325,15 +531,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)
@@ -365,7 +562,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)
}
@@ -384,26 +587,68 @@ 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
}
startAt, endAt, ok := getLookbackUnix(conf.Solana)
if !ok {
return
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
}
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Solana)
for i := int(start); i <= int(end); i++ {
for s.lookbackNext <= s.lookbackEnd && s.slotQueue.Len() < blockQueueLimit {
select {
case <-ctx.Done():
return
default:
}
if syncBreak(conf.Solana, s.slotQueue.Len()) {
return
}
s.slotQueue.In <- i
time.Sleep(time.Millisecond * 200)
s.slotQueue.In <- s.lookbackNext
s.lookbackNext++
}
if s.lookbackNext > s.lookbackEnd {
markLookbackDone(s.lookbackOrderIDs)
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
}
+65
View File
@@ -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)
}
})
}
}
+163
View File
@@ -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")
}
}
+72
View File
@@ -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)
}
}
+103
View File
@@ -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())
}
}
+101
View File
@@ -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)
}
}
+65
View File
@@ -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)
}
}
})
}
}
+98
View File
@@ -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")
}
}
+256
View File
@@ -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
}
+243
View File
@@ -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")
}
}
+60
View File
@@ -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":-32004,"message":"Block not available for slot 457000000"},"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")
}
}
+84
View File
@@ -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
+1
View File
@@ -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
+108
View File
@@ -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
}
+36 -28
View File
@@ -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,
+124
View File
@@ -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)
}
}
}
+36 -11
View File
@@ -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 {
@@ -334,11 +349,16 @@ func pendingLookbackUnix(network model.Network) (startAt, endAt int64, orderIDs
// 起点:最早的创建时间(已按 created_at asc 排序)
startAt = pending[0].CreatedAt.Time().Unix()
// 终点:最晚的已过期 expired_at;若全部尚未过期则用当前时间
endAt = time.Now().Unix()
// 终点:覆盖每个订单的有效期,取各订单 min(过期时间, 当前时间) 的最大值
now := time.Now()
endAt = startAt
for _, o := range pending {
if o.ExpiredAt.Before(time.Now()) && o.ExpiredAt.Unix() > startAt {
endAt = o.ExpiredAt.Unix()
end := o.ExpiredAt
if end.After(now) {
end = now
}
if end.Unix() > endAt {
endAt = end.Unix()
}
}
@@ -396,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 {
+72
View File
@@ -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)
}
})
}
}
Binary file not shown.
+2 -52
View File
@@ -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`,直接在商店搜索安装使用即可。
+2 -1
View File
@@ -212,7 +212,8 @@ key := t.Address + string(t.TradeType)
┌──────────────────────────────────────────────────────────────────┐
│ 模式二:HasPrefix(前缀匹配 / 允许多付) │
│ │
│ 规则:实际到账金额以订单金额为前缀,允许多付小数 │
│ 规则:订单金额按原子精度补齐小数位后,作为实际到账金额的前缀 │
│ (1.5 补成 1.50),只容忍原子精度以下的多付 │
│ │
│ 订单金额:10.01 │
│ 到账金额:10.01 ✅ 匹配(完全等于) │
+23 -15
View File
@@ -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 @@
## 选择建议
- **传统模式**:适合金额固定、对准确性要求高的场景
- **前缀匹配**:适合仅允许用户多付、可能添加额外精度的场景
- **前缀匹配**:适合只容忍原子精度以下多付、同一地址可能同时有多笔订单的场景
- **修约匹配**:适合允许用户多付或者少付,容忍度更高的场景
根据实际业务需求选择合适的匹配模式,可以在保证安全性的同时提升用户体验。
+1 -1
View File
@@ -3,6 +3,7 @@ module github.com/v03413/bepusdt
go 1.26.2
require (
filippo.io/edwards25519 v1.2.0
github.com/btcsuite/btcd/btcutil v1.1.6
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0
github.com/eclipse/paho.mqtt.golang v1.5.1
@@ -31,7 +32,6 @@ require (
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/bytedance/gopkg v0.1.4 // indirect
github.com/bytedance/sonic v1.15.1 // indirect
+10
View File
@@ -10,6 +10,16 @@ import (
"github.com/v03413/bepusdt/app/conf"
)
// PR 开发/贡献说明
//
// 个人精力有限,人脑也干不过 AI,为了保持项目的可维护性。
// 提交 PR 时,请确保一个 PR 只做一件事,并说明以下内容:
//
// - 这个 PR 做了什么
// - 为什么要这么做
// - Review 重点在哪
// - 自测 / 实测情况
func init() {
// 不推荐引导小白参与修改各种配置文件
_ = godotenv.Load()