Merge pull request #242 from sylearn/feat/solana-reconcile-expired-orders

feat(solana): reconcile expired orders against token account history
This commit is contained in:
莫名
2026-10-19 17:17:48 +08:00
committed by GitHub
5 changed files with 511 additions and 1 deletions
+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 {
+1
View File
@@ -56,6 +56,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 {
+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")
}
}
+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