Compare commits
16 Commits
v0.0.4-rc3
...
v0.0.6
| Author | SHA1 | Date | |
|---|---|---|---|
| 5168beda00 | |||
| 5e4d5dfae4 | |||
| 32ca778735 | |||
| 730ff983f8 | |||
| 93b32d38d9 | |||
| 3f071e6c01 | |||
| a7963b335b | |||
| d7fa90112d | |||
| 5a607aa347 | |||
| b91d8b819c | |||
| f87a131d7f | |||
| 258d239831 | |||
| 5a960d3eec | |||
| 2d673493cf | |||
| 537168008c | |||
| 99c4e5e072 |
@@ -1,26 +1,24 @@
|
||||
FROM golang:alpine AS builder
|
||||
|
||||
RUN apk add --no-cache --update git build-base
|
||||
ENV CGO_ENABLED=1
|
||||
ARG VERSION=0.0.0-dev
|
||||
ARG COMMIT=none
|
||||
ARG DATE=unknown
|
||||
WORKDIR /app
|
||||
COPY ./src/go.mod ./src/go.sum ./
|
||||
RUN go mod download
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
COPY ./src .
|
||||
RUN go build -ldflags "-s -w -X github.com/assimon/luuu/config.BuildVersion=${VERSION} -X github.com/assimon/luuu/config.BuildCommit=${COMMIT} -X github.com/assimon/luuu/config.BuildDate=${DATE}" \
|
||||
-o epusdt .
|
||||
WORKDIR /app
|
||||
|
||||
RUN git clone https://github.com/GMwalletApp/epusdt.git .
|
||||
|
||||
WORKDIR /app/src
|
||||
RUN go mod download
|
||||
RUN go build -o /app/epusdt .
|
||||
|
||||
FROM alpine:latest AS runner
|
||||
ENV TZ=Asia/Shanghai
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/static /app/static
|
||||
COPY --from=builder /app/static /static
|
||||
COPY --from=builder /app/src/static /app/static
|
||||
COPY --from=builder /app/src/static /static
|
||||
COPY --from=builder /app/epusdt .
|
||||
VOLUME /app/conf
|
||||
|
||||
ENTRYPOINT ["./epusdt" ,"http","start"]
|
||||
VOLUME /app/conf
|
||||
ENTRYPOINT ["./epusdt", "http", "start"]
|
||||
|
||||
@@ -38,6 +38,8 @@ Epusdt
|
||||
```
|
||||
|
||||
## 教程:
|
||||
- docker 运行教程 [docker-RUN](wiki/docker-RUN.md)
|
||||
- API 文档( 自定义汇率接口 ) [API](wiki/LEGACY_API_MIGRATION.md)
|
||||
- 宝塔运行`epusdt`教程👉🏻[宝塔运行epusdt](wiki/BT_RUN.md)
|
||||
- 不好意思我有洁癖,手动运行`epusdt`教程👉🏻[手动运行epusdt](wiki/manual_RUN.md)
|
||||
- 开发者接入`epusdt`文档👉🏻[开发者接入epusdt](wiki/API.md)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
version: "3"
|
||||
services:
|
||||
epusdt:
|
||||
image: annona/epusdt:alpine
|
||||
image: gmwallet/epusdt:alpine
|
||||
restart: always
|
||||
build:
|
||||
context: .
|
||||
@@ -9,4 +8,4 @@ services:
|
||||
volumes:
|
||||
- ./env:/app/.env
|
||||
ports:
|
||||
- "8088:8000"
|
||||
- "8000:8000"
|
||||
|
||||
@@ -61,3 +61,11 @@ order_notice_max_retry=0
|
||||
forced_usdt_rate=
|
||||
api_rate_url=
|
||||
tron_grid_api_key=
|
||||
solana_rpc_url=
|
||||
|
||||
ethereum_ws_url=wss://ethereum.publicnode.com
|
||||
|
||||
|
||||
# epay
|
||||
epay_pid=
|
||||
epay_key=
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
.DS_Store
|
||||
dist/
|
||||
*.log
|
||||
@@ -328,3 +328,23 @@ func GetCallbackRetryBaseDuration() time.Duration {
|
||||
}
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func GetSolanaRpcUrl() string {
|
||||
rpcUrl := viper.GetString("solana_rpc_url")
|
||||
if rpcUrl == "" {
|
||||
return "https://api.mainnet-beta.solana.com"
|
||||
}
|
||||
return rpcUrl
|
||||
}
|
||||
|
||||
func GetEthereumWsUrl() string {
|
||||
return strings.TrimSpace(viper.GetString("ethereum_ws_url"))
|
||||
}
|
||||
|
||||
func GetEpayPid() int {
|
||||
return viper.GetInt("epay_pid")
|
||||
}
|
||||
|
||||
func GetEpayKey() string {
|
||||
return viper.GetString("epay_key")
|
||||
}
|
||||
|
||||
@@ -67,8 +67,27 @@ func TestResolveConfigFilePathUsesCurrentDirectoryByDefault(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("resolve config path: %v", err)
|
||||
}
|
||||
if got != configPath {
|
||||
t.Fatalf("config path = %s, want %s", got, configPath)
|
||||
|
||||
gotAbs, err := filepath.Abs(got)
|
||||
if err != nil {
|
||||
t.Fatalf("abs got: %v", err)
|
||||
}
|
||||
wantAbs, err := filepath.Abs(configPath)
|
||||
if err != nil {
|
||||
t.Fatalf("abs want: %v", err)
|
||||
}
|
||||
|
||||
gotReal, err := filepath.EvalSymlinks(gotAbs)
|
||||
if err != nil {
|
||||
t.Fatalf("eval symlinks got: %v", err)
|
||||
}
|
||||
wantReal, err := filepath.EvalSymlinks(wantAbs)
|
||||
if err != nil {
|
||||
t.Fatalf("eval symlinks want: %v", err)
|
||||
}
|
||||
|
||||
if gotReal != wantReal {
|
||||
t.Fatalf("config path = %s, want %s", gotReal, wantReal)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package comm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/assimon/luuu/model/request"
|
||||
"github.com/assimon/luuu/model/service"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
@@ -22,3 +26,53 @@ func (c *BaseCommController) CreateTransaction(ctx echo.Context) (err error) {
|
||||
}
|
||||
return c.SucJson(ctx, resp)
|
||||
}
|
||||
|
||||
// SwitchNetwork 切换支付网络,创建或返回子订单
|
||||
func (c *BaseCommController) SwitchNetwork(ctx echo.Context) (err error) {
|
||||
req := new(request.SwitchNetworkRequest)
|
||||
if err = ctx.Bind(req); err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
if err = c.ValidateStruct(ctx, req); err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
resp, err := service.SwitchNetwork(req)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(resp, "", " ")
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
|
||||
fmt.Printf("switch network response: \n%s", string(jsonBytes))
|
||||
|
||||
return c.SucJson(ctx, resp)
|
||||
}
|
||||
|
||||
func (c *BaseCommController) CreateTransactionAndRedirect(ctx echo.Context) (err error) {
|
||||
req := new(request.CreateTransactionRequest)
|
||||
if err = ctx.Bind(req); err != nil {
|
||||
log.Println("bind request error:", err)
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
if err = c.ValidateStruct(ctx, req); err != nil {
|
||||
log.Println("validate request error:", err)
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
resp, err := service.CreateTransaction(req)
|
||||
if err != nil {
|
||||
log.Println("create transaction error:", err)
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
|
||||
fmt.Printf("create transaction response: %+v\n", resp)
|
||||
|
||||
tradeID := resp.TradeId
|
||||
|
||||
ctx.Redirect(302, "/pay/checkout-counter/"+tradeID)
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package comm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/assimon/luuu/config"
|
||||
"github.com/assimon/luuu/model/response"
|
||||
"github.com/assimon/luuu/model/service"
|
||||
"github.com/labstack/echo/v4"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// CheckoutCounter 收银台
|
||||
@@ -15,12 +18,27 @@ func (c *BaseCommController) CheckoutCounter(ctx echo.Context) (err error) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
resp, err := service.GetCheckoutCounterByTradeId(tradeId)
|
||||
if err != nil {
|
||||
if err == service.ErrOrder {
|
||||
tmpl, err := template.ParseFiles(filepath.Join(config.StaticFilePath, "index.html"))
|
||||
if err != nil {
|
||||
return ctx.String(http.StatusOK, err.Error())
|
||||
}
|
||||
emptyResp := response.CheckoutCounterResponse{}
|
||||
return tmpl.Execute(ctx.Response(), emptyResp)
|
||||
}
|
||||
return ctx.String(http.StatusOK, err.Error())
|
||||
}
|
||||
tmpl, err := template.ParseFiles(filepath.Join(config.StaticFilePath, "index.html"))
|
||||
if err != nil {
|
||||
return ctx.String(http.StatusOK, err.Error())
|
||||
}
|
||||
|
||||
jsonByte, err := json.MarshalIndent(resp, "", " ")
|
||||
if err != nil {
|
||||
return ctx.String(http.StatusOK, err.Error())
|
||||
}
|
||||
fmt.Printf("%v\n", string(jsonByte))
|
||||
|
||||
return tmpl.Execute(ctx.Response(), resp)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package comm
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/assimon/luuu/model/data"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type addWalletRequest struct {
|
||||
Network string `json:"network" validate:"required"`
|
||||
Address string `json:"address" validate:"required"`
|
||||
}
|
||||
|
||||
type changeStatusRequest struct {
|
||||
Status int `json:"status" validate:"required|in:1,2"`
|
||||
}
|
||||
|
||||
// AddWallet 添加钱包地址
|
||||
func (c *BaseCommController) AddWallet(ctx echo.Context) error {
|
||||
req := new(addWalletRequest)
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
if err := c.ValidateStruct(ctx, req); err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
wallet, err := data.AddWalletAddressWithNetwork(req.Network, req.Address)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
return c.SucJson(ctx, wallet)
|
||||
}
|
||||
|
||||
// ListWallets 获取钱包列表
|
||||
func (c *BaseCommController) ListWallets(ctx echo.Context) error {
|
||||
network := ctx.QueryParam("network")
|
||||
var wallets []mdb.WalletAddress
|
||||
var err error
|
||||
if network != "" {
|
||||
wallets, err = data.GetAllWalletAddressByNetwork(network)
|
||||
} else {
|
||||
wallets, err = data.GetAllWalletAddress()
|
||||
}
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
return c.SucJson(ctx, wallets)
|
||||
}
|
||||
|
||||
// GetWallet 获取单个钱包
|
||||
func (c *BaseCommController) GetWallet(ctx echo.Context) error {
|
||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
wallet, err := data.GetWalletAddressById(id)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
if wallet.ID <= 0 {
|
||||
return c.FailJson(ctx, constant.NotAvailableWalletAddress)
|
||||
}
|
||||
return c.SucJson(ctx, wallet)
|
||||
}
|
||||
|
||||
// ChangeWalletStatus 启用/禁用钱包
|
||||
func (c *BaseCommController) ChangeWalletStatus(ctx echo.Context) error {
|
||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
req := new(changeStatusRequest)
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
if err := c.ValidateStruct(ctx, req); err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
if err := data.ChangeWalletAddressStatus(id, req.Status); err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
return c.SucJson(ctx, nil)
|
||||
}
|
||||
|
||||
// DeleteWallet 删除钱包
|
||||
func (c *BaseCommController) DeleteWallet(ctx echo.Context) error {
|
||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
return c.FailJson(ctx, constant.ParamsMarshalErr)
|
||||
}
|
||||
if err := data.DeleteWalletAddressById(id); err != nil {
|
||||
return c.FailJson(ctx, err)
|
||||
}
|
||||
return c.SucJson(ctx, nil)
|
||||
}
|
||||
@@ -5,6 +5,8 @@ go 1.25.0
|
||||
require (
|
||||
github.com/btcsuite/btcutil v1.0.2
|
||||
github.com/dromara/carbon/v2 v2.6.15
|
||||
github.com/ethereum/go-ethereum v1.15.11
|
||||
github.com/gagliardetto/solana-go v1.16.0
|
||||
github.com/go-resty/resty/v2 v2.11.0
|
||||
github.com/gookit/color v1.5.0
|
||||
github.com/gookit/goutil v0.4.6
|
||||
@@ -17,10 +19,10 @@ require (
|
||||
github.com/satori/go.uuid v1.2.0
|
||||
github.com/shengdoushi/base58 v1.0.0
|
||||
github.com/shopspring/decimal v1.3.1
|
||||
github.com/spf13/cobra v1.2.1
|
||||
github.com/spf13/viper v1.9.0
|
||||
github.com/spf13/cobra v1.9.1
|
||||
github.com/spf13/viper v1.20.1
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
go.uber.org/zap v1.17.0
|
||||
go.uber.org/zap v1.27.0
|
||||
gopkg.in/telebot.v3 v3.0.0
|
||||
gorm.io/driver/mysql v1.5.1
|
||||
gorm.io/driver/postgres v1.5.2
|
||||
@@ -29,54 +31,85 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/StackExchange/wmi v1.2.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.20.0 // indirect
|
||||
github.com/blendle/zapdriver v1.3.1 // indirect
|
||||
github.com/consensys/bavard v0.1.27 // indirect
|
||||
github.com/consensys/gnark-crypto v0.16.0 // indirect
|
||||
github.com/crate-crypto/go-eth-kzg v1.3.0 // indirect
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.5.1 // indirect
|
||||
github.com/ethereum/c-kzg-4844/v2 v2.1.0 // indirect
|
||||
github.com/ethereum/go-verkle v0.2.2 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gagliardetto/binary v0.8.0 // indirect
|
||||
github.com/gagliardetto/treeout v0.1.4 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gookit/filter v1.1.2 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/holiman/uint256 v1.3.2 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.3.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/labstack/gommon v0.3.0 // indirect
|
||||
github.com/magiconair/properties v1.8.5 // indirect
|
||||
github.com/mattn/go-colorable v0.1.12 // indirect
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/mitchellh/mapstructure v1.4.2 // indirect
|
||||
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
|
||||
github.com/mmcloughlin/addchain v0.4.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mostynb/zstdpool-freelist v0.0.0-20201229113212-927304c0c3b1 // indirect
|
||||
github.com/mr-tron/base58 v1.2.0 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pelletier/go-toml v1.9.4 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/spf13/afero v1.6.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.9.0 // indirect
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.14.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.2.0 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/streamingfast/logging v0.0.0-20250404134358-92b15d2fbd2e // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/supranational/blst v0.3.14 // indirect
|
||||
github.com/tidwall/match v1.2.0 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.1 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
go.uber.org/multierr v1.6.0 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/net v0.17.0 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.3 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/crypto v0.47.0 // indirect
|
||||
golang.org/x/net v0.49.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
golang.org/x/term v0.39.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
gopkg.in/ini.v1 v1.63.2 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.70.0 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.47.0 // indirect
|
||||
rsc.io/tmplfunc v0.0.3 // indirect
|
||||
)
|
||||
|
||||
@@ -2,12 +2,13 @@ package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/assimon/luuu/config"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
"github.com/assimon/luuu/util/json"
|
||||
"github.com/assimon/luuu/util/sign"
|
||||
"github.com/labstack/echo/v4"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func CheckApiSign() echo.MiddlewareFunc {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/assimon/luuu/config"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// CheckApiToken validates the Authorization header against the configured api_auth_token.
|
||||
// Use this for management APIs (GET/POST) where body-based signature is not practical.
|
||||
func CheckApiToken() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(ctx echo.Context) error {
|
||||
token := ctx.Request().Header.Get("Authorization")
|
||||
if token == "" {
|
||||
token = ctx.QueryParam("api_token")
|
||||
}
|
||||
if token == "" || token != config.GetApiAuthToken() {
|
||||
return constant.SignatureErr
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ func RuntimeInit() error {
|
||||
if err = RuntimeDB.Exec("DROP INDEX IF EXISTS transaction_lock_token_amount_uindex").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = RuntimeDB.Exec("DROP INDEX IF EXISTS transaction_lock_address_token_amount_uindex").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = RuntimeDB.AutoMigrate(&mdb.TransactionLock{}); err != nil {
|
||||
color.Red.Printf("[runtime_db] sqlite migrate DB(TransactionLock),err=%s\n", err)
|
||||
return err
|
||||
|
||||
@@ -108,11 +108,103 @@ func UpdateOrderIsExpirationById(id uint64, expirationCutoff time.Time) (bool, e
|
||||
return result.RowsAffected > 0, result.Error
|
||||
}
|
||||
|
||||
// GetTradeIdByWalletAddressAndAmountAndToken resolves the reserved trade id by address, token and amount.
|
||||
func GetTradeIdByWalletAddressAndAmountAndToken(address string, token string, amount float64) (string, error) {
|
||||
// CountActiveSubOrders counts sub-orders with status=WaitPay under a parent.
|
||||
func CountActiveSubOrders(parentTradeId string) (int64, error) {
|
||||
var count int64
|
||||
err := dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("parent_trade_id = ?", parentTradeId).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetSubOrderByTokenNetwork finds an existing active sub-order matching token+network under a parent.
|
||||
func GetSubOrderByTokenNetwork(parentTradeId string, token string, network string) (*mdb.Orders, error) {
|
||||
order := new(mdb.Orders)
|
||||
err := dao.Mdb.Model(order).
|
||||
Where("parent_trade_id = ?", parentTradeId).
|
||||
Where("token = ?", token).
|
||||
Where("network = ?", network).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Limit(1).
|
||||
Find(order).Error
|
||||
return order, err
|
||||
}
|
||||
|
||||
// GetSiblingSubOrders returns active sub-orders under the same parent, excluding the given trade_id.
|
||||
func GetSiblingSubOrders(parentTradeId string, excludeTradeId string) ([]mdb.Orders, error) {
|
||||
var orders []mdb.Orders
|
||||
err := dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("parent_trade_id = ?", parentTradeId).
|
||||
Where("trade_id != ?", excludeTradeId).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Find(&orders).Error
|
||||
return orders, err
|
||||
}
|
||||
|
||||
// MarkParentOrderSuccess updates the parent order with the sub-order's payment details.
|
||||
// Token and network are NOT overwritten — the parent keeps its original values.
|
||||
func MarkParentOrderSuccess(parentTradeId string, sub *mdb.Orders) (bool, error) {
|
||||
result := dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("trade_id = ?", parentTradeId).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Updates(map[string]interface{}{
|
||||
"status": mdb.StatusPaySuccess,
|
||||
"block_transaction_id": sub.BlockTransactionId,
|
||||
"callback_confirm": mdb.CallBackConfirmNo,
|
||||
"actual_amount": sub.ActualAmount,
|
||||
"receive_address": sub.ReceiveAddress,
|
||||
})
|
||||
return result.RowsAffected > 0, result.Error
|
||||
}
|
||||
|
||||
// MarkOrderSelected sets is_selected=true for the given trade_id.
|
||||
func MarkOrderSelected(tradeId string) error {
|
||||
return dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("trade_id = ?", tradeId).
|
||||
Update("is_selected", true).Error
|
||||
}
|
||||
|
||||
// RefreshOrderExpiration resets created_at to now so the expiration timer restarts.
|
||||
// Called on the parent order when a sub-order is created or returned.
|
||||
func RefreshOrderExpiration(tradeId string) error {
|
||||
return dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("trade_id = ?", tradeId).
|
||||
Update("created_at", time.Now()).Error
|
||||
}
|
||||
|
||||
// ResetCallbackConfirmOk sets callback_confirm back to Ok.
|
||||
// Prevents the callback worker from retrying a sub-order with an empty notify_url.
|
||||
func ResetCallbackConfirmOk(tradeId string) error {
|
||||
return dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("trade_id = ?", tradeId).
|
||||
Update("callback_confirm", mdb.CallBackConfirmOk).Error
|
||||
}
|
||||
|
||||
// GetActiveSubOrders returns all active sub-orders under a parent.
|
||||
func GetActiveSubOrders(parentTradeId string) ([]mdb.Orders, error) {
|
||||
var orders []mdb.Orders
|
||||
err := dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("parent_trade_id = ?", parentTradeId).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Find(&orders).Error
|
||||
return orders, err
|
||||
}
|
||||
|
||||
// ExpireOrderByTradeId marks a single order as expired if still waiting.
|
||||
func ExpireOrderByTradeId(tradeId string) error {
|
||||
return dao.Mdb.Model(&mdb.Orders{}).
|
||||
Where("trade_id = ?", tradeId).
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Update("status", mdb.StatusExpired).Error
|
||||
}
|
||||
|
||||
// GetTradeIdByWalletAddressAndAmountAndToken resolves the reserved trade id by network, address, token and amount.
|
||||
func GetTradeIdByWalletAddressAndAmountAndToken(network string, address string, token string, amount float64) (string, error) {
|
||||
scaledAmount, _ := normalizeLockAmount(amount)
|
||||
var lock mdb.TransactionLock
|
||||
err := dao.RuntimeDB.Model(&mdb.TransactionLock{}).
|
||||
Where("network = ?", network).
|
||||
Where("address = ?", address).
|
||||
Where("token = ?", normalizeLockToken(token)).
|
||||
Where("amount_scaled = ?", scaledAmount).
|
||||
@@ -128,12 +220,13 @@ func GetTradeIdByWalletAddressAndAmountAndToken(address string, token string, am
|
||||
return lock.TradeId, nil
|
||||
}
|
||||
|
||||
// LockTransaction reserves an address+token+amount pair in sqlite until expiration.
|
||||
func LockTransaction(address, token, tradeID string, amount float64, expirationTime time.Duration) error {
|
||||
// LockTransaction reserves a network+address+token+amount pair in sqlite until expiration.
|
||||
func LockTransaction(network, address, token, tradeID string, amount float64, expirationTime time.Duration) error {
|
||||
scaledAmount, amountText := normalizeLockAmount(amount)
|
||||
normalizedToken := normalizeLockToken(token)
|
||||
now := time.Now()
|
||||
lock := &mdb.TransactionLock{
|
||||
Network: network,
|
||||
Address: address,
|
||||
Token: normalizedToken,
|
||||
AmountScaled: scaledAmount,
|
||||
@@ -143,7 +236,8 @@ func LockTransaction(address, token, tradeID string, amount float64, expirationT
|
||||
}
|
||||
|
||||
return dao.RuntimeDB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("address = ?", address).
|
||||
if err := tx.Where("network = ?", network).
|
||||
Where("address = ?", address).
|
||||
Where("token = ?", normalizedToken).
|
||||
Where("amount_scaled = ?", scaledAmount).
|
||||
Where("expires_at <= ?", now).
|
||||
@@ -165,10 +259,11 @@ func LockTransaction(address, token, tradeID string, amount float64, expirationT
|
||||
})
|
||||
}
|
||||
|
||||
// UnLockTransaction releases the reservation for address+token+amount.
|
||||
func UnLockTransaction(address string, token string, amount float64) error {
|
||||
// UnLockTransaction releases the reservation for network+address+token+amount.
|
||||
func UnLockTransaction(network string, address string, token string, amount float64) error {
|
||||
scaledAmount, _ := normalizeLockAmount(amount)
|
||||
return dao.RuntimeDB.
|
||||
Where("network = ?", network).
|
||||
Where("address = ?", address).
|
||||
Where("token = ?", normalizeLockToken(token)).
|
||||
Where("amount_scaled = ?", scaledAmount).
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/assimon/luuu/model/dao"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
)
|
||||
|
||||
// AddWalletAddress 创建钱包
|
||||
// AddWalletAddress 创建钱包 (默认 tron 网络,用于 Telegram 添加)
|
||||
func AddWalletAddress(address string) (*mdb.WalletAddress, error) {
|
||||
exist, err := GetWalletAddressByToken(address)
|
||||
return AddWalletAddressWithNetwork(mdb.NetworkTron, address)
|
||||
}
|
||||
|
||||
// AddWalletAddressWithNetwork 创建指定网络的钱包地址
|
||||
func AddWalletAddressWithNetwork(network, address string) (*mdb.WalletAddress, error) {
|
||||
network = strings.ToLower(strings.TrimSpace(network))
|
||||
address = strings.TrimSpace(address)
|
||||
exist, err := GetWalletAddressByNetworkAndAddress(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -16,6 +25,7 @@ func AddWalletAddress(address string) (*mdb.WalletAddress, error) {
|
||||
return nil, constant.WalletAddressAlreadyExists
|
||||
}
|
||||
walletAddress := &mdb.WalletAddress{
|
||||
Network: network,
|
||||
Address: address,
|
||||
Status: mdb.TokenStatusEnable,
|
||||
}
|
||||
@@ -23,7 +33,17 @@ func AddWalletAddress(address string) (*mdb.WalletAddress, error) {
|
||||
return walletAddress, err
|
||||
}
|
||||
|
||||
// GetWalletAddressByToken 通过钱包地址获取address
|
||||
// GetWalletAddressByNetworkAndAddress 通过网络和地址查询
|
||||
func GetWalletAddressByNetworkAndAddress(network, address string) (*mdb.WalletAddress, error) {
|
||||
walletAddress := new(mdb.WalletAddress)
|
||||
err := dao.Mdb.Model(walletAddress).
|
||||
Where("network = ?", network).
|
||||
Where("address = ?", address).
|
||||
Limit(1).Find(walletAddress).Error
|
||||
return walletAddress, err
|
||||
}
|
||||
|
||||
// GetWalletAddressByToken 通过钱包地址获取address (兼容旧接口)
|
||||
func GetWalletAddressByToken(address string) (*mdb.WalletAddress, error) {
|
||||
walletAddress := new(mdb.WalletAddress)
|
||||
err := dao.Mdb.Model(walletAddress).Limit(1).Find(walletAddress, "address = ?", address).Error
|
||||
@@ -50,6 +70,16 @@ func GetAvailableWalletAddress() ([]mdb.WalletAddress, error) {
|
||||
return WalletAddressList, err
|
||||
}
|
||||
|
||||
// GetAvailableWalletAddressByNetwork 获得指定网络的所有可用钱包地址
|
||||
func GetAvailableWalletAddressByNetwork(network string) ([]mdb.WalletAddress, error) {
|
||||
var list []mdb.WalletAddress
|
||||
err := dao.Mdb.Model(list).
|
||||
Where("status = ?", mdb.TokenStatusEnable).
|
||||
Where("network = ?", network).
|
||||
Find(&list).Error
|
||||
return list, err
|
||||
}
|
||||
|
||||
// GetAllWalletAddress 获得所有钱包地址
|
||||
func GetAllWalletAddress() ([]mdb.WalletAddress, error) {
|
||||
var WalletAddressList []mdb.WalletAddress
|
||||
@@ -57,6 +87,13 @@ func GetAllWalletAddress() ([]mdb.WalletAddress, error) {
|
||||
return WalletAddressList, err
|
||||
}
|
||||
|
||||
// GetAllWalletAddressByNetwork 获得指定网络的所有钱包地址
|
||||
func GetAllWalletAddressByNetwork(network string) ([]mdb.WalletAddress, error) {
|
||||
var list []mdb.WalletAddress
|
||||
err := dao.Mdb.Model(list).Where("network = ?", network).Find(&list).Error
|
||||
return list, err
|
||||
}
|
||||
|
||||
// ChangeWalletAddressStatus 启用禁用钱包
|
||||
func ChangeWalletAddressStatus(id uint64, status int) error {
|
||||
err := dao.Mdb.Model(&mdb.WalletAddress{}).Where("id = ?", id).Update("status", status).Error
|
||||
|
||||
@@ -8,20 +8,29 @@ const (
|
||||
CallBackConfirmNo = 2
|
||||
)
|
||||
|
||||
const (
|
||||
PaymentTypeEpay = "Epay"
|
||||
)
|
||||
|
||||
type Orders struct {
|
||||
TradeId string `gorm:"column:trade_id;uniqueIndex:orders_trade_id_uindex" json:"trade_id"`
|
||||
OrderId string `gorm:"column:order_id;uniqueIndex:orders_order_id_uindex" json:"order_id"`
|
||||
OrderId string `gorm:"column:order_id;uniqueIndex:orders_order_id_uindex" json:"order_id"` // the order id is generated by client, and will notify client when order is paid
|
||||
ParentTradeId string `gorm:"column:parent_trade_id;index:idx_orders_parent_trade_id;default:''" json:"parent_trade_id"`
|
||||
BlockTransactionId string `gorm:"index:orders_block_transaction_id_index;column:block_transaction_id" json:"block_transaction_id"`
|
||||
Amount float64 `gorm:"column:amount" json:"amount"`
|
||||
Currency string `gorm:"column:currency" json:"currency"`
|
||||
ActualAmount float64 `gorm:"column:actual_amount" json:"actual_amount"`
|
||||
ReceiveAddress string `gorm:"column:receive_address" json:"receive_address"`
|
||||
Token string `gorm:"column:token" json:"token"`
|
||||
Network string `gorm:"column:network" json:"network"`
|
||||
Status int `gorm:"column:status;default:1" json:"status"`
|
||||
NotifyUrl string `gorm:"column:notify_url" json:"notify_url"`
|
||||
RedirectUrl string `gorm:"column:redirect_url" json:"redirect_url"`
|
||||
Name string `gorm:"column:name" json:"name"`
|
||||
CallbackNum int `gorm:"column:callback_num;default:0" json:"callback_num"`
|
||||
CallBackConfirm int `gorm:"column:callback_confirm;default:2" json:"callback_confirm"`
|
||||
IsSelected bool `gorm:"column:is_selected;default:false" json:"is_selected"`
|
||||
PaymentType string `gorm:"column:payment_type" json:"payment_type"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@ import "time"
|
||||
|
||||
type TransactionLock struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
|
||||
Address string `gorm:"column:address;uniqueIndex:transaction_lock_address_token_amount_uindex,priority:1" json:"address"`
|
||||
Token string `gorm:"column:token;uniqueIndex:transaction_lock_address_token_amount_uindex,priority:2" json:"token"`
|
||||
AmountScaled int64 `gorm:"column:amount_scaled;uniqueIndex:transaction_lock_address_token_amount_uindex,priority:3" json:"amount_scaled"`
|
||||
Network string `gorm:"column:network;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:1" json:"network"`
|
||||
Address string `gorm:"column:address;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:2" json:"address"`
|
||||
Token string `gorm:"column:token;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:3" json:"token"`
|
||||
AmountScaled int64 `gorm:"column:amount_scaled;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:4" json:"amount_scaled"`
|
||||
AmountText string `gorm:"column:amount_text" json:"amount_text"`
|
||||
TradeId string `gorm:"column:trade_id;index:transaction_lock_trade_id_index" json:"trade_id"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at;index:transaction_lock_expires_at_index" json:"expires_at"`
|
||||
|
||||
@@ -5,8 +5,15 @@ const (
|
||||
TokenStatusDisable = 2
|
||||
)
|
||||
|
||||
const (
|
||||
NetworkTron = "tron"
|
||||
NetworkSolana = "solana"
|
||||
NetworkEthereum = "ethereum"
|
||||
)
|
||||
|
||||
type WalletAddress struct {
|
||||
Address string `gorm:"column:address;uniqueIndex:wallet_address_address_uindex" json:"address"`
|
||||
Network string `gorm:"column:network;uniqueIndex:wallet_address_network_address_uindex" json:"network"`
|
||||
Address string `gorm:"column:address;uniqueIndex:wallet_address_network_address_uindex" json:"address"`
|
||||
Status int64 `gorm:"column:status;default:1" json:"status"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
@@ -5,12 +5,15 @@ import "github.com/gookit/validate"
|
||||
// CreateTransactionRequest 创建交易请求
|
||||
type CreateTransactionRequest struct {
|
||||
OrderId string `json:"order_id" validate:"required|maxLen:32"`
|
||||
Currency string `json:"currency" validate:"required"`
|
||||
Token string `json:"token" validate:"required"`
|
||||
Currency string `json:"currency" validate:"required"` // 法币 如:cny
|
||||
Token string `json:"token" validate:"required"` // 币种 如:usdt
|
||||
Network string `json:"network" validate:"required"` // 网络 如:TRON
|
||||
Amount float64 `json:"amount" validate:"required|isFloat|gt:0.01"`
|
||||
NotifyUrl string `json:"notify_url" validate:"required"`
|
||||
Signature string `json:"signature" validate:"required"`
|
||||
RedirectUrl string `json:"redirect_url"`
|
||||
Name string `json:"name"`
|
||||
PaymentType string `json:"payment_type"`
|
||||
}
|
||||
|
||||
func (r CreateTransactionRequest) Translates() map[string]string {
|
||||
@@ -18,6 +21,7 @@ func (r CreateTransactionRequest) Translates() map[string]string {
|
||||
"OrderId": "订单号",
|
||||
"Currency": "货币",
|
||||
"Token": "币种",
|
||||
"Network": "网络",
|
||||
"Amount": "支付金额",
|
||||
"NotifyUrl": "异步回调网址",
|
||||
"Signature": "签名",
|
||||
@@ -29,7 +33,23 @@ type OrderProcessingRequest struct {
|
||||
ReceiveAddress string
|
||||
Currency string
|
||||
Token string
|
||||
Network string
|
||||
Amount float64
|
||||
TradeId string
|
||||
BlockTransactionId string
|
||||
}
|
||||
|
||||
// SwitchNetworkRequest 切换支付网络
|
||||
type SwitchNetworkRequest struct {
|
||||
TradeId string `json:"trade_id" validate:"required"`
|
||||
Token string `json:"token" validate:"required"`
|
||||
Network string `json:"network" validate:"required"`
|
||||
}
|
||||
|
||||
func (r SwitchNetworkRequest) Translates() map[string]string {
|
||||
return validate.MS{
|
||||
"TradeId": "订单号",
|
||||
"Token": "币种",
|
||||
"Network": "网络",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,3 +25,16 @@ type OrderNotifyResponse struct {
|
||||
Signature string `json:"signature"` // 签名
|
||||
Status int `json:"status"` // 1:等待支付,2:支付成功,3:已过期
|
||||
}
|
||||
|
||||
// OrderNotifyResponseEpay epay订单异步回调结构体
|
||||
type OrderNotifyResponseEpay struct {
|
||||
PID int `json:"pid"` // 商户ID
|
||||
TradeNo string `json:"trade_no"` // 平台订单号
|
||||
OutTradeNo string `json:"out_trade_no"` // 商户订单号
|
||||
Type string `json:"type"` // 订单类型
|
||||
Name string `json:"name"` // 商品名称
|
||||
Money string `json:"money"` // 订单金额,保留4位小数
|
||||
Sign string `json:"sign"` // 签名
|
||||
SignType string `json:"sign_type"` // 签名类型 // MD5
|
||||
TradeStatus string `json:"trade_status"` // 订单状态 // only has "TRADE_SUCCESS" for now
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@ package response
|
||||
|
||||
type CheckoutCounterResponse struct {
|
||||
TradeId string `json:"trade_id"` // epusdt订单号
|
||||
ActualAmount float64 `json:"actual_amount"` // 订单实际需要支付的金额,保留4位小数
|
||||
ReceiveAddress string `json:"receive_address"` // 收款钱包地址
|
||||
Amount float64 `json:"amount"` // 订单金额,保留4位小数 法币金额
|
||||
ActualAmount float64 `json:"actual_amount"` // 订单实际需要支付的金额,保留4位小数 加密货币金额
|
||||
Token string `json:"token"` // 所属币种 TRX USDT......
|
||||
Currency string `json:"currency"` // 法币币种 CNY USD ...
|
||||
ReceiveAddress string `json:"receive_address"` // 收款钱包地址
|
||||
Network string `json:"network"` // 网络 TRON ETH ...
|
||||
ExpirationTime int64 `json:"expiration_time"` // 过期时间 时间戳
|
||||
RedirectUrl string `json:"redirect_url"`
|
||||
CreatedAt int64 `json:"created_at"` // 订单创建时间 时间戳
|
||||
IsSelected bool `json:"is_selected"`
|
||||
}
|
||||
|
||||
type CheckStatusResponse struct {
|
||||
|
||||
@@ -28,8 +28,10 @@ const (
|
||||
IncrementalMaximumNumber = 100
|
||||
)
|
||||
|
||||
var gCreateTransactionLock sync.Mutex
|
||||
var gOrderProcessingLock sync.Mutex
|
||||
var (
|
||||
gCreateTransactionLock sync.Mutex
|
||||
gOrderProcessingLock sync.Mutex
|
||||
)
|
||||
|
||||
// CreateTransaction creates a new payment order.
|
||||
func CreateTransaction(req *request.CreateTransactionRequest) (*response.CreateTransactionResponse, error) {
|
||||
@@ -38,6 +40,7 @@ func CreateTransaction(req *request.CreateTransactionRequest) (*response.CreateT
|
||||
|
||||
token := strings.ToUpper(strings.TrimSpace(req.Token))
|
||||
currency := strings.ToUpper(strings.TrimSpace(req.Currency))
|
||||
network := strings.ToLower(strings.TrimSpace(req.Network))
|
||||
payAmount := math.MustParsePrecFloat64(req.Amount, 2)
|
||||
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(currency))
|
||||
if rate <= 0 {
|
||||
@@ -61,7 +64,7 @@ func CreateTransaction(req *request.CreateTransactionRequest) (*response.CreateT
|
||||
return nil, constant.OrderAlreadyExists
|
||||
}
|
||||
|
||||
walletAddress, err := data.GetAvailableWalletAddress()
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(network)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,7 +74,7 @@ func CreateTransaction(req *request.CreateTransactionRequest) (*response.CreateT
|
||||
|
||||
tradeID := GenerateCode()
|
||||
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), 2)
|
||||
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(tradeID, token, amount, walletAddress)
|
||||
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(tradeID, network, token, amount, walletAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -88,9 +91,12 @@ func CreateTransaction(req *request.CreateTransactionRequest) (*response.CreateT
|
||||
ActualAmount: availableAmount,
|
||||
ReceiveAddress: availableAddress,
|
||||
Token: token,
|
||||
Network: network,
|
||||
Status: mdb.StatusWaitPay,
|
||||
NotifyUrl: req.NotifyUrl,
|
||||
RedirectUrl: req.RedirectUrl,
|
||||
Name: req.Name,
|
||||
PaymentType: req.PaymentType,
|
||||
}
|
||||
if err = data.CreateOrderWithTransaction(tx, order); err != nil {
|
||||
tx.Rollback()
|
||||
@@ -148,20 +154,83 @@ func OrderProcessing(req *request.OrderProcessingRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = data.UnLockTransaction(req.ReceiveAddress, req.Token, req.Amount); err != nil {
|
||||
if err = data.UnLockTransaction(req.Network, req.ReceiveAddress, req.Token, req.Amount); err != nil {
|
||||
log.Sugar.Warnf("[order] unlock transaction after pay success failed, trade_id=%s, err=%v", req.TradeId, err)
|
||||
}
|
||||
|
||||
// Load order to check parent-child relationship
|
||||
order, err := data.GetOrderInfoByTradeId(req.TradeId)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parent order paid directly: expire all sub-orders and release their locks
|
||||
if order.ParentTradeId == "" {
|
||||
subs, subErr := data.GetActiveSubOrders(order.TradeId)
|
||||
if subErr != nil {
|
||||
log.Sugar.Errorf("[order] get sub-orders for parent failed, trade_id=%s, err=%v", order.TradeId, subErr)
|
||||
return nil
|
||||
}
|
||||
for _, sub := range subs {
|
||||
if err = data.ExpireOrderByTradeId(sub.TradeId); err != nil {
|
||||
log.Sugar.Warnf("[order] expire sub-order failed, trade_id=%s, err=%v", sub.TradeId, err)
|
||||
}
|
||||
if err = data.UnLockTransaction(sub.Network, sub.ReceiveAddress, sub.Token, sub.ActualAmount); err != nil {
|
||||
log.Sugar.Warnf("[order] unlock sub-order transaction failed, trade_id=%s, err=%v", sub.TradeId, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sub-order should not trigger its own callback (notify_url is empty).
|
||||
// OrderSuccessWithTransaction unconditionally sets callback_confirm=No,
|
||||
// reset it here to prevent the callback worker from retrying an empty URL.
|
||||
if err = data.ResetCallbackConfirmOk(order.TradeId); err != nil {
|
||||
log.Sugar.Warnf("[order] reset sub-order callback_confirm failed, trade_id=%s, err=%v", order.TradeId, err)
|
||||
}
|
||||
|
||||
parent, err := data.GetOrderInfoByTradeId(order.ParentTradeId)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[order] load parent order failed, parent_trade_id=%s, err=%v", order.ParentTradeId, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Mark parent as paid with sub-order's payment details
|
||||
if _, err = data.MarkParentOrderSuccess(parent.TradeId, order); err != nil {
|
||||
log.Sugar.Errorf("[order] mark parent success failed, parent_trade_id=%s, err=%v", parent.TradeId, err)
|
||||
}
|
||||
|
||||
// Release parent's own wallet lock
|
||||
if err = data.UnLockTransaction(parent.Network, parent.ReceiveAddress, parent.Token, parent.ActualAmount); err != nil {
|
||||
log.Sugar.Warnf("[order] unlock parent transaction failed, parent_trade_id=%s, err=%v", parent.TradeId, err)
|
||||
}
|
||||
|
||||
// Expire sibling sub-orders and release their locks
|
||||
siblings, err := data.GetSiblingSubOrders(parent.TradeId, order.TradeId)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[order] get sibling sub-orders failed, parent_trade_id=%s, err=%v", parent.TradeId, err)
|
||||
return nil
|
||||
}
|
||||
for _, sib := range siblings {
|
||||
if err = data.ExpireOrderByTradeId(sib.TradeId); err != nil {
|
||||
log.Sugar.Warnf("[order] expire sibling failed, trade_id=%s, err=%v", sib.TradeId, err)
|
||||
}
|
||||
if err = data.UnLockTransaction(sib.Network, sib.ReceiveAddress, sib.Token, sib.ActualAmount); err != nil {
|
||||
log.Sugar.Warnf("[order] unlock sibling transaction failed, trade_id=%s, err=%v", sib.TradeId, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReserveAvailableWalletAndAmount finds and locks an address+token+amount pair.
|
||||
func ReserveAvailableWalletAndAmount(tradeID string, token string, amount float64, walletAddress []mdb.WalletAddress) (string, float64, error) {
|
||||
// ReserveAvailableWalletAndAmount finds and locks a network+address+token+amount pair.
|
||||
func ReserveAvailableWalletAndAmount(tradeID string, network string, token string, amount float64, walletAddress []mdb.WalletAddress) (string, float64, error) {
|
||||
availableAddress := ""
|
||||
availableAmount := amount
|
||||
|
||||
tryLockWalletFunc := func(targetAmount float64) (string, error) {
|
||||
for _, address := range walletAddress {
|
||||
err := data.LockTransaction(address.Address, token, tradeID, targetAmount, config.GetOrderExpirationTimeDuration())
|
||||
err := data.LockTransaction(network, address.Address, token, tradeID, targetAmount, config.GetOrderExpirationTimeDuration())
|
||||
if err == nil {
|
||||
return address.Address, nil
|
||||
}
|
||||
@@ -208,3 +277,141 @@ func GetOrderInfoByTradeId(tradeId string) (*mdb.Orders, error) {
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
const MaxSubOrders = 2
|
||||
|
||||
// SwitchNetwork creates or returns an existing sub-order for a different token+network.
|
||||
func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounterResponse, error) {
|
||||
gCreateTransactionLock.Lock()
|
||||
defer gCreateTransactionLock.Unlock()
|
||||
|
||||
token := strings.ToUpper(strings.TrimSpace(req.Token))
|
||||
network := strings.ToLower(strings.TrimSpace(req.Network))
|
||||
|
||||
// 1. Load parent order
|
||||
parent, err := data.GetOrderInfoByTradeId(req.TradeId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parent.ID <= 0 {
|
||||
return nil, constant.OrderNotExists
|
||||
}
|
||||
if parent.ParentTradeId != "" {
|
||||
return nil, constant.CannotSwitchSubOrder
|
||||
}
|
||||
if parent.Status != mdb.StatusWaitPay {
|
||||
return nil, constant.OrderNotWaitPay
|
||||
}
|
||||
|
||||
// 2. Same token+network as parent → mark selected and return
|
||||
if strings.EqualFold(parent.Token, token) && strings.EqualFold(parent.Network, network) {
|
||||
_ = data.MarkOrderSelected(parent.TradeId)
|
||||
parent.IsSelected = true
|
||||
return buildCheckoutResponse(parent), nil
|
||||
}
|
||||
|
||||
// 3. Existing active sub-order for this token+network → return it
|
||||
existing, err := data.GetSubOrderByTokenNetwork(parent.TradeId, token, network)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing.ID > 0 {
|
||||
_ = data.MarkOrderSelected(parent.TradeId)
|
||||
_ = data.MarkOrderSelected(existing.TradeId)
|
||||
_ = data.RefreshOrderExpiration(parent.TradeId)
|
||||
existing.IsSelected = true
|
||||
return buildCheckoutResponse(existing), nil
|
||||
}
|
||||
|
||||
// 4. Check sub-order limit
|
||||
count, err := data.CountActiveSubOrders(parent.TradeId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count >= MaxSubOrders {
|
||||
return nil, constant.SubOrderLimitExceeded
|
||||
}
|
||||
|
||||
// 5. Calculate amount for the new network
|
||||
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(parent.Currency))
|
||||
if rate <= 0 {
|
||||
return nil, constant.RateAmountErr
|
||||
}
|
||||
decimalPayAmount := decimal.NewFromFloat(parent.Amount)
|
||||
decimalTokenAmount := decimalPayAmount.Mul(decimal.NewFromFloat(rate))
|
||||
if decimalTokenAmount.Cmp(decimal.NewFromFloat(UsdtMinimumPaymentAmount)) == -1 {
|
||||
return nil, constant.PayAmountErr
|
||||
}
|
||||
|
||||
// 6. Find and lock wallet
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(network)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(walletAddress) <= 0 {
|
||||
return nil, constant.NotAvailableWalletAddress
|
||||
}
|
||||
|
||||
subTradeID := GenerateCode()
|
||||
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), 2)
|
||||
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(subTradeID, network, token, amount, walletAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if availableAddress == "" {
|
||||
return nil, constant.NotAvailableAmountErr
|
||||
}
|
||||
|
||||
// 7. Create sub-order
|
||||
tx := dao.Mdb.Begin()
|
||||
subOrder := &mdb.Orders{
|
||||
TradeId: subTradeID,
|
||||
OrderId: subTradeID, // sub-order uses its own trade_id as order_id (unique constraint)
|
||||
ParentTradeId: parent.TradeId,
|
||||
Amount: parent.Amount,
|
||||
Currency: parent.Currency,
|
||||
ActualAmount: availableAmount,
|
||||
ReceiveAddress: availableAddress,
|
||||
Token: token,
|
||||
Network: network,
|
||||
Status: mdb.StatusWaitPay,
|
||||
IsSelected: true,
|
||||
NotifyUrl: "",
|
||||
RedirectUrl: parent.RedirectUrl,
|
||||
Name: parent.Name,
|
||||
CallBackConfirm: mdb.CallBackConfirmOk, // don't trigger callback on sub-order
|
||||
PaymentType: parent.PaymentType,
|
||||
}
|
||||
if err = data.CreateOrderWithTransaction(tx, subOrder); err != nil {
|
||||
tx.Rollback()
|
||||
_ = data.UnLockTransactionByTradeId(subTradeID)
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
_ = data.UnLockTransactionByTradeId(subTradeID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Mark parent as selected and refresh its expiration to match the sub-order
|
||||
_ = data.MarkOrderSelected(parent.TradeId)
|
||||
_ = data.RefreshOrderExpiration(parent.TradeId)
|
||||
|
||||
return buildCheckoutResponse(subOrder), nil
|
||||
}
|
||||
|
||||
func buildCheckoutResponse(order *mdb.Orders) *response.CheckoutCounterResponse {
|
||||
return &response.CheckoutCounterResponse{
|
||||
TradeId: order.TradeId,
|
||||
Amount: order.Amount,
|
||||
ActualAmount: order.ActualAmount,
|
||||
Token: order.Token,
|
||||
Currency: order.Currency,
|
||||
ReceiveAddress: order.ReceiveAddress,
|
||||
Network: order.Network,
|
||||
ExpirationTime: order.CreatedAt.AddMinutes(config.GetOrderExpirationTime()).TimestampMilli(),
|
||||
RedirectUrl: order.RedirectUrl,
|
||||
CreatedAt: order.CreatedAt.TimestampMilli(),
|
||||
IsSelected: order.IsSelected,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ func newCreateTransactionRequest(orderID string, amount float64) *request.Create
|
||||
OrderId: orderID,
|
||||
Currency: "CNY",
|
||||
Token: "USDT",
|
||||
Network: "tron",
|
||||
Amount: amount,
|
||||
NotifyUrl: "https://merchant.example/callback",
|
||||
}
|
||||
@@ -53,7 +54,7 @@ func TestCreateTransactionAssignsIncrementedAmountsAndLocks(t *testing.T) {
|
||||
t.Fatalf("unexpected tokens: %s, %s", resp1.Token, resp2.Token)
|
||||
}
|
||||
|
||||
tradeID1, err := data.GetTradeIdByWalletAddressAndAmountAndToken(resp1.ReceiveAddress, resp1.Token, resp1.ActualAmount)
|
||||
tradeID1, err := data.GetTradeIdByWalletAddressAndAmountAndToken("tron", resp1.ReceiveAddress, resp1.Token, resp1.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("get first runtime lock: %v", err)
|
||||
}
|
||||
@@ -61,7 +62,7 @@ func TestCreateTransactionAssignsIncrementedAmountsAndLocks(t *testing.T) {
|
||||
t.Fatalf("first runtime lock = %s, want %s", tradeID1, resp1.TradeId)
|
||||
}
|
||||
|
||||
tradeID2, err := data.GetTradeIdByWalletAddressAndAmountAndToken(resp2.ReceiveAddress, resp2.Token, resp2.ActualAmount)
|
||||
tradeID2, err := data.GetTradeIdByWalletAddressAndAmountAndToken("tron", resp2.ReceiveAddress, resp2.Token, resp2.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("get second runtime lock: %v", err)
|
||||
}
|
||||
@@ -86,6 +87,7 @@ func TestOrderProcessingMarksPaidAndReleasesLock(t *testing.T) {
|
||||
err = OrderProcessing(&request.OrderProcessingRequest{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: resp.Token,
|
||||
Network: "tron",
|
||||
TradeId: resp.TradeId,
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTransactionId: "block_1",
|
||||
@@ -108,7 +110,7 @@ func TestOrderProcessingMarksPaidAndReleasesLock(t *testing.T) {
|
||||
t.Fatalf("block transaction id = %s, want block_1", order.BlockTransactionId)
|
||||
}
|
||||
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(resp.ReceiveAddress, resp.Token, resp.ActualAmount)
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken("tron", resp.ReceiveAddress, resp.Token, resp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("get runtime lock after processing: %v", err)
|
||||
}
|
||||
@@ -133,6 +135,7 @@ func TestOrderProcessingRejectsDuplicateBlockForSameOrder(t *testing.T) {
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: resp.Token,
|
||||
Network: "tron",
|
||||
TradeId: resp.TradeId,
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTransactionId: "block_1",
|
||||
@@ -180,6 +183,7 @@ func TestOrderProcessingDoesNotReviveExpiredOrder(t *testing.T) {
|
||||
err = OrderProcessing(&request.OrderProcessingRequest{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: resp.Token,
|
||||
Network: "tron",
|
||||
TradeId: resp.TradeId,
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTransactionId: "block_expired",
|
||||
@@ -239,6 +243,7 @@ func TestOrderProcessingOnlyOneOrderClaimsABlockTransaction(t *testing.T) {
|
||||
errs <- OrderProcessing(&request.OrderProcessingRequest{
|
||||
ReceiveAddress: address,
|
||||
Token: token,
|
||||
Network: "tron",
|
||||
TradeId: tradeID,
|
||||
Amount: amount,
|
||||
BlockTransactionId: "shared_block",
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"github.com/assimon/luuu/model/response"
|
||||
)
|
||||
|
||||
var ErrOrder = errors.New("不存在待支付订单或已过期")
|
||||
|
||||
// GetCheckoutCounterByTradeId returns checkout info for a pending order.
|
||||
func GetCheckoutCounterByTradeId(tradeId string) (*response.CheckoutCounterResponse, error) {
|
||||
orderInfo, err := data.GetOrderInfoByTradeId(tradeId)
|
||||
@@ -16,16 +18,21 @@ func GetCheckoutCounterByTradeId(tradeId string) (*response.CheckoutCounterRespo
|
||||
return nil, err
|
||||
}
|
||||
if orderInfo.ID <= 0 || orderInfo.Status != mdb.StatusWaitPay {
|
||||
return nil, errors.New("不存在待支付订单或已过期")
|
||||
return nil, ErrOrder
|
||||
}
|
||||
|
||||
resp := &response.CheckoutCounterResponse{
|
||||
TradeId: orderInfo.TradeId,
|
||||
Amount: orderInfo.Amount,
|
||||
ActualAmount: orderInfo.ActualAmount,
|
||||
ReceiveAddress: orderInfo.ReceiveAddress,
|
||||
Token: orderInfo.Token,
|
||||
Currency: orderInfo.Currency,
|
||||
ReceiveAddress: orderInfo.ReceiveAddress,
|
||||
Network: orderInfo.Network,
|
||||
ExpirationTime: orderInfo.CreatedAt.AddMinutes(config.GetOrderExpirationTime()).TimestampMilli(),
|
||||
RedirectUrl: orderInfo.RedirectUrl,
|
||||
CreatedAt: orderInfo.CreatedAt.TimestampMilli(),
|
||||
IsSelected: orderInfo.IsSelected,
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/assimon/luuu/config"
|
||||
"github.com/assimon/luuu/model/data"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/model/request"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
"github.com/assimon/luuu/util/log"
|
||||
"github.com/assimon/luuu/util/math"
|
||||
"github.com/gagliardetto/solana-go"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// gProcessedSignatures 已处理签名缓存,避免重复调用 getTransaction
|
||||
var gProcessedSignatures sync.Map // sig -> unix timestamp
|
||||
|
||||
type TransferInfo struct {
|
||||
Source string // Source address (for SOL) or source ATA (for SPL tokens)
|
||||
Destination string // Destination address (for SOL) or destination ATA (for SPL tokens)
|
||||
Mint string // Token mint (e.g. USDT mint, USDC mint, or "SOL" for native transfers)
|
||||
Amount float64 // Human-readable amount (adjusted for decimals)
|
||||
RawAmount uint64 // Raw amount from the transaction (before adjusting for decimals)
|
||||
Decimals *int // Optional decimals from the transaction, if available
|
||||
BlockTime int64 // Block time of the transfer unit is seconds since epoch
|
||||
}
|
||||
|
||||
// SolCallBack 扫描指定钱包地址的 Solana 链上交易,匹配待支付订单并确认收款。
|
||||
func SolCallBack(address string, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Sugar.Errorf("[SOL][%s] panic recovered: %v", address, err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Clean up old entries from processed cache (older than 1 hour)
|
||||
cleanupCutoff := time.Now().Add(-1 * time.Hour).Unix()
|
||||
gProcessedSignatures.Range(func(key, value interface{}) bool {
|
||||
if ts, ok := value.(int64); ok && ts < cleanupCutoff {
|
||||
gProcessedSignatures.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
limit := 1000
|
||||
|
||||
// 查询钱包地址 + USDT ATA + USDC ATA 三个地址的签名
|
||||
queryAddrs := []string{address}
|
||||
if usdtAta, err := FindATAAddress(address, USDT_Mint); err == nil {
|
||||
queryAddrs = append(queryAddrs, usdtAta)
|
||||
} else {
|
||||
log.Sugar.Errorf("[SOL][%s] failed to derive USDT ATA: %v", address, err)
|
||||
}
|
||||
if usdcAta, err := FindATAAddress(address, USDC_Mint); err == nil {
|
||||
queryAddrs = append(queryAddrs, usdcAta)
|
||||
} else {
|
||||
log.Sugar.Errorf("[SOL][%s] failed to derive USDC ATA: %v", address, err)
|
||||
}
|
||||
|
||||
// 拉取签名并去重
|
||||
seen := make(map[string]bool)
|
||||
var result []solSignatureResult
|
||||
for _, queryAddr := range queryAddrs {
|
||||
respBody, err := SolGetSignaturesForAddress(queryAddr, limit, "", "")
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[SOL][%s] SolGetSignaturesForAddress(%s) failed: %v", address, queryAddr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
resultBody := gjson.GetBytes(respBody, "result")
|
||||
if !resultBody.Exists() || !resultBody.IsArray() {
|
||||
log.Sugar.Errorf("[SOL][%s] unexpected response format for %s: %s", address, queryAddr, string(respBody))
|
||||
continue
|
||||
}
|
||||
|
||||
var batch []solSignatureResult
|
||||
err = json.Unmarshal([]byte(resultBody.Raw), &batch)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[SOL][%s] failed to unmarshal signatures for %s: %v", address, queryAddr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, sig := range batch {
|
||||
if !seen[sig.Signature] {
|
||||
seen[sig.Signature] = true
|
||||
result = append(result, sig)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(result) == 0 {
|
||||
log.Sugar.Debugf("[SOL][%s] no transaction signatures found", address)
|
||||
return
|
||||
}
|
||||
|
||||
// 按 blockTime 降序排列
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].BlockTime == nil {
|
||||
return false
|
||||
}
|
||||
if result[j].BlockTime == nil {
|
||||
return true
|
||||
}
|
||||
return *result[i].BlockTime > *result[j].BlockTime
|
||||
})
|
||||
|
||||
// 时间截止线:订单过期时间 + 5 分钟
|
||||
cutoffTime := time.Now().Add(-config.GetOrderExpirationTimeDuration() - 5*time.Minute).Unix()
|
||||
|
||||
log.Sugar.Debugf("[SOL][%s] fetched %d unique signatures from %d addresses, cutoff=%d",
|
||||
address, len(result), len(queryAddrs), cutoffTime)
|
||||
|
||||
// Process each transaction signature
|
||||
for sigIdx, txSig := range result {
|
||||
sig := txSig.Signature
|
||||
|
||||
// Skip failed transactions
|
||||
if txSig.Err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// 超过截止时间的旧签名不再处理
|
||||
if txSig.BlockTime != nil && *txSig.BlockTime < cutoffTime {
|
||||
log.Sugar.Debugf("[SOL][%s] [%d/%d] sig=%s blockTime=%d before cutoff=%d, stopping scan",
|
||||
address, sigIdx+1, len(result), sig, *txSig.BlockTime, cutoffTime)
|
||||
break
|
||||
}
|
||||
|
||||
// 跳过已处理的签名
|
||||
if _, ok := gProcessedSignatures.Load(sig); ok {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Sugar.Debugf("[SOL][%s] [%d/%d] processing sig=%s slot=%d", address, sigIdx+1, len(result), sig, txSig.Slot)
|
||||
|
||||
txData, err := SolGetTransaction(sig)
|
||||
if err != nil {
|
||||
log.Sugar.Debugf("[SOL][%s] sig=%s fetch failed: %v", address, sig, err)
|
||||
continue
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(txData, "result.transaction.message.instructions").Array()
|
||||
log.Sugar.Debugf("[SOL][%s] sig=%s has %d instructions", address, sig, len(instructions))
|
||||
|
||||
for instrIdx, instruction := range instructions {
|
||||
programID := instruction.Get("programId").String()
|
||||
parsedType := instruction.Get("parsed.type").String()
|
||||
log.Sugar.Debugf("[SOL][%s] sig=%s instr[%d] programId=%s parsedType=%s", address, sig, instrIdx, programID, parsedType)
|
||||
|
||||
transferInfo, err := ParseTransferInfoFromInstruction(instruction, txData)
|
||||
if err != nil {
|
||||
log.Sugar.Debugf("[SOL][%s] sig=%s instr[%d] parse error: %v", address, sig, instrIdx, err)
|
||||
continue
|
||||
}
|
||||
if transferInfo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Sugar.Debugf("[SOL][%s] sig=%s instr[%d] transfer: src=%s dst=%s mint=%s rawAmount=%d amount=%.6f blockTime=%d",
|
||||
address, sig, instrIdx,
|
||||
transferInfo.Source, transferInfo.Destination, transferInfo.Mint,
|
||||
transferInfo.RawAmount, transferInfo.Amount, transferInfo.BlockTime)
|
||||
|
||||
if !isTransferToAddress(transferInfo, address) {
|
||||
continue
|
||||
}
|
||||
|
||||
token, amount := getTokenTypeAndAmount(transferInfo)
|
||||
if token == "" || amount <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Sugar.Infof("[SOL][%s] sig=%s instr[%d] incoming transfer confirmed: token=%s amount=%.2f -> querying transaction_lock network=solana address=%s token=%s amount=%.2f",
|
||||
address, sig, instrIdx, token, amount, address, token, amount)
|
||||
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkSolana, address, token, amount)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[SOL][%s] sig=%s query transaction_lock failed: %v", address, sig, err)
|
||||
continue
|
||||
}
|
||||
if tradeID == "" {
|
||||
log.Sugar.Infof("[SOL][%s] sig=%s no active transaction_lock matched: network=solana address=%s token=%s amount=%.2f (no order or expired)",
|
||||
address, sig, address, token, amount)
|
||||
continue
|
||||
}
|
||||
log.Sugar.Infof("[SOL][%s] transaction_lock matched: trade_id=%s sig=%s token=%s amount=%.2f",
|
||||
address, tradeID, sig, token, amount)
|
||||
|
||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[SOL][%s] sig=%s load order failed for trade_id=%s: %v", address, sig, tradeID, err)
|
||||
continue
|
||||
}
|
||||
log.Sugar.Infof("[SOL][%s] order loaded: trade_id=%s order_id=%s status=%d created_at_ms=%d",
|
||||
address, tradeID, order.OrderId, order.Status, order.CreatedAt.TimestampMilli())
|
||||
|
||||
// blockTime 秒 → 毫秒,与订单创建时间对齐
|
||||
blockTimestamp := transferInfo.BlockTime * 1000
|
||||
createTime := order.CreatedAt.TimestampMilli()
|
||||
log.Sugar.Infof("[SOL][%s] time check: sig=%s block_time_ms=%d order_created_ms=%d diff_ms=%d",
|
||||
address, sig, blockTimestamp, createTime, blockTimestamp-createTime)
|
||||
if blockTimestamp < createTime {
|
||||
log.Sugar.Warnf("[SOL][%s] sig=%s skipped: block_time_ms=%d is %d ms before order created_ms=%d (transaction predates the order)",
|
||||
address, sig, blockTimestamp, createTime-blockTimestamp, createTime)
|
||||
continue
|
||||
}
|
||||
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: address,
|
||||
Token: token,
|
||||
Network: mdb.NetworkSolana,
|
||||
TradeId: tradeID,
|
||||
Amount: amount,
|
||||
BlockTransactionId: sig,
|
||||
}
|
||||
log.Sugar.Infof("[SOL][%s] calling OrderProcessing: trade_id=%s sig=%s token=%s amount=%.2f",
|
||||
address, tradeID, sig, token, amount)
|
||||
err = OrderProcessing(req)
|
||||
if err != nil {
|
||||
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
||||
log.Sugar.Infof("[SOL][%s] sig=%s already resolved: trade_id=%s reason=%v", address, sig, tradeID, err)
|
||||
continue
|
||||
}
|
||||
log.Sugar.Errorf("[SOL][%s] sig=%s OrderProcessing failed for trade_id=%s: %v", address, sig, tradeID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Sugar.Infof("[SOL][%s] order marked paid: trade_id=%s sig=%s token=%s amount=%.2f, sending telegram notification",
|
||||
address, tradeID, sig, token, amount)
|
||||
sendPaymentNotification(order)
|
||||
log.Sugar.Infof("[SOL][%s] payment fully processed: trade_id=%s sig=%s", address, tradeID, sig)
|
||||
}
|
||||
|
||||
// 标记已处理
|
||||
gProcessedSignatures.Store(sig, time.Now().Unix())
|
||||
}
|
||||
}
|
||||
|
||||
// solSignatureResult getSignaturesForAddress 返回结构
|
||||
type solSignatureResult struct {
|
||||
Signature string `json:"signature"`
|
||||
Slot uint64 `json:"slot"`
|
||||
Err interface{} `json:"err"`
|
||||
BlockTime *int64 `json:"blockTime"`
|
||||
}
|
||||
|
||||
// SolRetryClient 发送 Solana JSON-RPC 请求,自动重试
|
||||
func SolRetryClient(method string, params []interface{}) ([]byte, error) {
|
||||
client := resty.New()
|
||||
client.SetRetryCount(5)
|
||||
client.SetRetryWaitTime(2 * time.Second)
|
||||
client.SetRetryMaxWaitTime(10 * time.Second)
|
||||
client.AddRetryCondition(func(r *resty.Response, err error) bool {
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if r.StatusCode() >= 429 || r.StatusCode() >= 500 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
rpcUrl := config.GetSolanaRpcUrl()
|
||||
|
||||
resp, err := client.R().
|
||||
SetHeader("Content-Type", "application/json").
|
||||
SetBody(map[string]interface{}{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": method,
|
||||
"params": params,
|
||||
}).
|
||||
Post(rpcUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
respBody := resp.Body()
|
||||
|
||||
return respBody, nil
|
||||
}
|
||||
|
||||
func SolGetSignaturesForAddress(address string, limit int, untilSig string, beforeSig string) ([]byte, error) {
|
||||
opts := map[string]interface{}{
|
||||
"commitment": "finalized",
|
||||
"limit": limit,
|
||||
}
|
||||
if untilSig != "" {
|
||||
opts["until"] = untilSig
|
||||
}
|
||||
if beforeSig != "" {
|
||||
opts["before"] = beforeSig
|
||||
}
|
||||
|
||||
bodyData, err := SolRetryClient("getSignaturesForAddress",
|
||||
[]interface{}{address, opts})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
err = json.Unmarshal(bodyData, &result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, ok := result["result"].([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected response format: %v", result)
|
||||
}
|
||||
|
||||
return bodyData, nil
|
||||
}
|
||||
|
||||
func SolGetTransaction(sig string) ([]byte, error) {
|
||||
txData, err := SolRetryClient("getTransaction", []interface{}{
|
||||
sig,
|
||||
map[string]interface{}{
|
||||
"encoding": "jsonParsed",
|
||||
"commitment": "confirmed",
|
||||
"maxSupportedTransactionVersion": 0, // suport
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("SolRetryClient failed: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
errField := gjson.GetBytes(txData, "result.meta.err")
|
||||
if errField.Exists() && errField.Type != gjson.Null {
|
||||
log.Sugar.Warnf("Transaction failed: %v", errField.String())
|
||||
return nil, fmt.Errorf("transaction failed: %s", errField.String())
|
||||
}
|
||||
|
||||
return txData, nil
|
||||
}
|
||||
|
||||
// isTransferToAddress 判断转账目标是否为指定钱包地址
|
||||
func isTransferToAddress(transfer *TransferInfo, targetAddress string) bool {
|
||||
// Native SOL transfer - check destination directly
|
||||
if transfer.Mint == "SOL" {
|
||||
return strings.EqualFold(transfer.Destination, targetAddress)
|
||||
}
|
||||
|
||||
// Skip Transfer instruction without mint info (use TransferChecked instead)
|
||||
if transfer.Mint == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// SPL Token transfer - check if destination ATA matches
|
||||
return MatchAtaAddress(targetAddress, transfer.Mint, transfer.Destination)
|
||||
}
|
||||
|
||||
// getTokenTypeAndAmount 根据 mint 识别代币类型并计算可读金额
|
||||
func getTokenTypeAndAmount(transfer *TransferInfo) (string, float64) {
|
||||
mint := transfer.Mint
|
||||
|
||||
// Native SOL
|
||||
if mint == "SOL" {
|
||||
return "SOL", transfer.Amount
|
||||
}
|
||||
|
||||
// SPL Tokens
|
||||
switch mint {
|
||||
case USDT_Mint:
|
||||
decimals := USDT_Decimals
|
||||
if transfer.Decimals != nil {
|
||||
decimals = int(*transfer.Decimals)
|
||||
}
|
||||
return "USDT", ADJustAmount(transfer.RawAmount, decimals)
|
||||
|
||||
case USDC_Mint:
|
||||
decimals := USDC_Decimals
|
||||
if transfer.Decimals != nil {
|
||||
decimals = int(*transfer.Decimals)
|
||||
}
|
||||
return "USDC", ADJustAmount(transfer.RawAmount, decimals)
|
||||
|
||||
default:
|
||||
// Unsupported token
|
||||
return "", 0
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
// Mint token
|
||||
USDT_Mint = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
|
||||
USDC_Mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
|
||||
|
||||
USDT_Decimals = 6
|
||||
USDC_Decimals = 6
|
||||
SOL_Decimals = 9
|
||||
)
|
||||
|
||||
const (
|
||||
// SPL Token instructions
|
||||
InstructionTransfer = 3
|
||||
InstructionTransferChecked = 12
|
||||
)
|
||||
|
||||
const (
|
||||
// System Program
|
||||
SystemProgramID = "11111111111111111111111111111111"
|
||||
InstructionSystemTransfer = 2
|
||||
)
|
||||
|
||||
const (
|
||||
TokenProgramID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
|
||||
Token2022ProgramID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
|
||||
)
|
||||
|
||||
// ADJustAmount 将链上原始金额转为可读金额(除以 10^decimals,保留 2 位小数)
|
||||
func ADJustAmount(amount uint64, decimals int) float64 {
|
||||
if amount == 0 {
|
||||
return 0
|
||||
}
|
||||
decimalAmount := decimal.NewFromBigInt(new(big.Int).SetUint64(amount), 0)
|
||||
// 10^decimals
|
||||
decimalDivisor := decimal.New(1, int32(decimals))
|
||||
adjustedAmount := decimalAmount.Div(decimalDivisor)
|
||||
// Round to 2 decimal places
|
||||
return math.MustParsePrecFloat64(adjustedAmount.InexactFloat64(), 2)
|
||||
}
|
||||
|
||||
func MatchUsdtAtaAddress(address string, ataTo string) bool {
|
||||
ata, err := FindATAAddress(address, USDT_Mint)
|
||||
if err != nil {
|
||||
fmt.Printf("FindATAAddress failed: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.EqualFold(ata, ataTo)
|
||||
}
|
||||
|
||||
func MatchUsdcAtaAddress(address string, ataTo string) bool {
|
||||
ata, err := FindATAAddress(address, USDC_Mint)
|
||||
if err != nil {
|
||||
fmt.Printf("FindATAAddress failed: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.EqualFold(ata, ataTo)
|
||||
}
|
||||
|
||||
func MatchAtaAddress(address string, mint string, ataTo string) bool {
|
||||
ata, err := FindATAAddress(address, mint)
|
||||
if err != nil {
|
||||
fmt.Printf("FindATAAddress failed: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
return strings.EqualFold(ata, ataTo)
|
||||
}
|
||||
|
||||
func FindATAAddress(owner, mint string) (string, error) {
|
||||
ownerPubKey, err := solana.PublicKeyFromBase58(owner)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid owner public key: %w", err)
|
||||
}
|
||||
|
||||
mintPubKey, err := solana.PublicKeyFromBase58(mint)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid mint public key: %w", err)
|
||||
}
|
||||
|
||||
ata, _, err := solana.FindAssociatedTokenAddress(ownerPubKey, mintPubKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find associated token address failed: %w", err)
|
||||
}
|
||||
|
||||
return ata.String(), nil
|
||||
}
|
||||
|
||||
// ParseTransferInfoFromInstruction 从单条指令中解析转账信息,非转账指令返回 nil
|
||||
func ParseTransferInfoFromInstruction(instruction gjson.Result, txData []byte) (*TransferInfo, error) {
|
||||
programID := instruction.Get("programId").String()
|
||||
parsedType := instruction.Get("parsed.type").String()
|
||||
|
||||
if programID == SystemProgramID && parsedType == "transfer" {
|
||||
return parseSystemTransfer(instruction, txData)
|
||||
}
|
||||
|
||||
if programID == TokenProgramID || programID == Token2022ProgramID {
|
||||
switch parsedType {
|
||||
case "transfer":
|
||||
return parseSplTransfer(instruction, txData)
|
||||
case "transferChecked":
|
||||
return parseSplTransferChecked(instruction, txData)
|
||||
}
|
||||
}
|
||||
|
||||
// Skip non-transfer instructions (ComputeBudget, AToken create, etc.)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func parseSystemTransfer(instruction gjson.Result, txData []byte) (*TransferInfo, error) {
|
||||
info := instruction.Get("parsed.info")
|
||||
source := info.Get("source").String()
|
||||
destination := info.Get("destination").String()
|
||||
lamports := info.Get("lamports").Uint()
|
||||
blockTime := gjson.GetBytes(txData, "result.blockTime").Int()
|
||||
|
||||
return &TransferInfo{
|
||||
Source: source,
|
||||
Destination: destination,
|
||||
Mint: "SOL",
|
||||
Amount: ADJustAmount(lamports, SOL_Decimals),
|
||||
RawAmount: lamports,
|
||||
BlockTime: blockTime,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseSplTransfer 解析 SPL Token "transfer" 指令,mint 从 postTokenBalances 中查找
|
||||
func parseSplTransfer(instruction gjson.Result, txData []byte) (*TransferInfo, error) {
|
||||
info := instruction.Get("parsed.info")
|
||||
source := info.Get("source").String()
|
||||
destination := info.Get("destination").String()
|
||||
amountStr := info.Get("amount").String()
|
||||
blockTime := gjson.GetBytes(txData, "result.blockTime").Int()
|
||||
|
||||
rawAmount, ok := new(big.Int).SetString(amountStr, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid amount: %s", amountStr)
|
||||
}
|
||||
|
||||
// Look up mint and decimals from postTokenBalances using the destination ATA
|
||||
mint, decimals, found := findMintFromTokenBalances(destination, txData)
|
||||
if !found {
|
||||
// Try source ATA as fallback
|
||||
mint, decimals, found = findMintFromTokenBalances(source, txData)
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("could not determine mint for transfer: source=%s dest=%s", source, destination)
|
||||
}
|
||||
|
||||
d := decimals
|
||||
return &TransferInfo{
|
||||
Source: source,
|
||||
Destination: destination,
|
||||
Mint: mint,
|
||||
Amount: ADJustAmount(rawAmount.Uint64(), decimals),
|
||||
RawAmount: rawAmount.Uint64(),
|
||||
Decimals: &d,
|
||||
BlockTime: blockTime,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseSplTransferChecked 解析 SPL Token "transferChecked" 指令
|
||||
func parseSplTransferChecked(instruction gjson.Result, txData []byte) (*TransferInfo, error) {
|
||||
info := instruction.Get("parsed.info")
|
||||
source := info.Get("source").String()
|
||||
destination := info.Get("destination").String()
|
||||
mint := info.Get("mint").String()
|
||||
amountStr := info.Get("tokenAmount.amount").String()
|
||||
decimals := int(info.Get("tokenAmount.decimals").Int())
|
||||
blockTime := gjson.GetBytes(txData, "result.blockTime").Int()
|
||||
|
||||
rawAmount, ok := new(big.Int).SetString(amountStr, 10)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid amount: %s", amountStr)
|
||||
}
|
||||
|
||||
return &TransferInfo{
|
||||
Source: source,
|
||||
Destination: destination,
|
||||
Mint: mint,
|
||||
Amount: ADJustAmount(rawAmount.Uint64(), decimals),
|
||||
RawAmount: rawAmount.Uint64(),
|
||||
Decimals: &decimals,
|
||||
BlockTime: blockTime,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// findMintFromTokenBalances 从 postTokenBalances 中查找 ATA 对应的 mint 和 decimals
|
||||
func findMintFromTokenBalances(ataAddress string, txData []byte) (string, int, bool) {
|
||||
accountKeys := gjson.GetBytes(txData, "result.transaction.message.accountKeys").Array()
|
||||
accountIndex := -1
|
||||
for i, key := range accountKeys {
|
||||
if key.Get("pubkey").String() == ataAddress {
|
||||
accountIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if accountIndex == -1 {
|
||||
return "", 0, false
|
||||
}
|
||||
|
||||
balances := gjson.GetBytes(txData, "result.meta.postTokenBalances").Array()
|
||||
for _, balance := range balances {
|
||||
if int(balance.Get("accountIndex").Int()) == accountIndex {
|
||||
mint := balance.Get("mint").String()
|
||||
decimals := int(balance.Get("uiTokenAmount.decimals").Int())
|
||||
return mint, decimals, true
|
||||
}
|
||||
}
|
||||
return "", 0, false
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestSolClientHealthy(t *testing.T) {
|
||||
bodyData, err := SolRetryClient("getHealth", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("SolRetryClient failed: %v", err)
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
err = json.Unmarshal(bodyData, &result)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal response: %v", err)
|
||||
}
|
||||
|
||||
status, ok := result["result"].(string)
|
||||
if !ok {
|
||||
t.Fatalf("Unexpected response format: %v", result)
|
||||
}
|
||||
|
||||
t.Logf("RPC Health Status: %s", status)
|
||||
|
||||
if status != "ok" {
|
||||
t.Errorf("Expected health status 'ok', got '%s'", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolClientGetSignaturesForAddress(t *testing.T) {
|
||||
// Example wallet address (replace with actual test address)
|
||||
address := "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu"
|
||||
|
||||
bodyData, err := SolRetryClient("getSignaturesForAddress", []interface{}{address, map[string]interface{}{"commitment": "finalized", "limit": 100}})
|
||||
if err != nil {
|
||||
t.Fatalf("SolRetryClient failed: %v", err)
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
err = json.Unmarshal(bodyData, &result)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal response: %v", err)
|
||||
}
|
||||
|
||||
signatures, ok := result["result"].([]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Unexpected response format: %v", result)
|
||||
}
|
||||
|
||||
t.Logf("Found %d signatures for address %s", len(signatures), address)
|
||||
|
||||
}
|
||||
|
||||
func TestSolClientGetTransaction(t *testing.T) {
|
||||
// Example transaction signature (replace with actual test signature)
|
||||
sig := "2aEoNykk4ZJ27C3y7EDJiQUc7GFnnsMe7ofFzB73swGL8kTxSBFCnwzWw3jzr3BND7k8hx15fZHUUAbG1XemNFe5"
|
||||
|
||||
txData, err := SolRetryClient("getTransaction", []interface{}{sig, map[string]interface{}{"encoding": "jsonParsed", "commitment": "finalized"}})
|
||||
if err != nil {
|
||||
t.Fatalf("SolRetryClient failed: %v", err)
|
||||
}
|
||||
fmt.Printf("%v\n", string(txData))
|
||||
|
||||
var result map[string]interface{}
|
||||
err = json.Unmarshal(txData, &result)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal response: %v", err)
|
||||
}
|
||||
|
||||
txInfo, ok := result["result"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("Unexpected response format: %v", result)
|
||||
}
|
||||
|
||||
t.Logf("Transaction Info for signature %s: %v", sig, txInfo)
|
||||
}
|
||||
|
||||
func TestFindATAAddress(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
owner string
|
||||
mint string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "RAY token ATA",
|
||||
owner: "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu",
|
||||
mint: "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R",
|
||||
want: "GgmJrwuP946uV8qAwsnXxzYrJqEwW6eGnsVnQZFS5rp4",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ata, err := FindATAAddress(tt.owner, tt.mint)
|
||||
if err != nil {
|
||||
t.Fatalf("FindATAAddress failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Owner: %s", tt.owner)
|
||||
t.Logf("Mint: %s", tt.mint)
|
||||
t.Logf("ATA: %s", ata)
|
||||
|
||||
if tt.want != "" && ata != tt.want {
|
||||
t.Errorf("Expected ATA %s, got %s", tt.want, ata)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchATAAddress(t *testing.T) {
|
||||
owner := "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu"
|
||||
mint := "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R" // ray token
|
||||
expectedATA := "GgmJrwuP946uV8qAwsnXxzYrJqEwW6eGnsVnQZFS5rp4"
|
||||
|
||||
ok := MatchAtaAddress(owner, mint, expectedATA)
|
||||
t.Logf("Owner: %s", owner)
|
||||
t.Logf("Mint: %s", mint)
|
||||
t.Logf("Expected ATA: %s", expectedATA)
|
||||
t.Logf("Match result: %v", ok)
|
||||
|
||||
if !ok {
|
||||
t.Error("Expected ATA to match, but it didn't")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchUsdtAtaAddress(t *testing.T) {
|
||||
// Example wallet address (replace with actual test address)
|
||||
owner := "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu"
|
||||
|
||||
ata, err := FindATAAddress(owner, USDT_Mint)
|
||||
if err != nil {
|
||||
t.Fatalf("FindATAAddress failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Owner: %s", owner)
|
||||
t.Logf("USDT Mint: %s", USDT_Mint)
|
||||
t.Logf("USDT ATA: %s", ata)
|
||||
|
||||
ok := MatchUsdtAtaAddress(owner, ata)
|
||||
if !ok {
|
||||
t.Error("Expected USDT ATA to match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchUsdcAtaAddress(t *testing.T) {
|
||||
// Example wallet address (replace with actual test address)
|
||||
owner := "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu"
|
||||
|
||||
ata, err := FindATAAddress(owner, USDC_Mint)
|
||||
if err != nil {
|
||||
t.Fatalf("FindATAAddress failed: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Owner: %s", owner)
|
||||
t.Logf("USDC Mint: %s", USDC_Mint)
|
||||
t.Logf("USDC ATA: %s", ata)
|
||||
|
||||
ok := MatchUsdcAtaAddress(owner, ata)
|
||||
if !ok {
|
||||
t.Error("Expected USDC ATA to match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustAmount(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
amount uint64
|
||||
decimals int
|
||||
want float64
|
||||
}{
|
||||
{
|
||||
name: "USDT amount (6 decimals)",
|
||||
amount: 123456789,
|
||||
decimals: 6,
|
||||
want: 123.46,
|
||||
},
|
||||
{
|
||||
name: "USDC amount (6 decimals)",
|
||||
amount: 1000000,
|
||||
decimals: 6,
|
||||
want: 1.0,
|
||||
},
|
||||
{
|
||||
name: "SOL amount (9 decimals)",
|
||||
amount: 1000000000,
|
||||
decimals: 9,
|
||||
want: 1.0,
|
||||
},
|
||||
{
|
||||
name: "Zero amount",
|
||||
amount: 0,
|
||||
decimals: 6,
|
||||
want: 0,
|
||||
},
|
||||
{
|
||||
name: "Small amount",
|
||||
amount: 1,
|
||||
decimals: 6,
|
||||
want: 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
adjusted := ADJustAmount(tt.amount, tt.decimals)
|
||||
t.Logf("Raw amount: %d, Decimals: %d, Adjusted: %.2f", tt.amount, tt.decimals, adjusted)
|
||||
|
||||
if adjusted != tt.want {
|
||||
t.Errorf("Expected %.2f, got %.2f", tt.want, adjusted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTransferInfoFromInstruction_SplTransfer(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test")
|
||||
}
|
||||
|
||||
// SPL Token "transfer" (no mint in instruction, must look up from postTokenBalances)
|
||||
sig := "3tZTwLrvmiZ59h4UzyMHPd7DPux7t9eXZgkUvEfquaoSuERrPSRNzWuSHKQM2fbiCWFDGNqoLpu2kLZnfoegVpqN"
|
||||
txData, err := SolGetTransaction(sig)
|
||||
if err != nil {
|
||||
t.Fatalf("SolGetTransaction failed: %v", err)
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(txData, "result.transaction.message.instructions").Array()
|
||||
var found bool
|
||||
for _, inst := range instructions {
|
||||
info, err := ParseTransferInfoFromInstruction(inst, txData)
|
||||
if err != nil {
|
||||
t.Logf("parse error (ok to skip): %v", err)
|
||||
continue
|
||||
}
|
||||
if info == nil {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
t.Logf("SPL transfer: source=%s dest=%s mint=%s amount=%.6f raw=%d blockTime=%d",
|
||||
info.Source, info.Destination, info.Mint, info.Amount, info.RawAmount, info.BlockTime)
|
||||
|
||||
if info.Mint == "" {
|
||||
t.Error("Expected mint to be resolved from postTokenBalances")
|
||||
}
|
||||
if info.RawAmount != 50000 {
|
||||
t.Errorf("Expected raw amount 50000, got %d", info.RawAmount)
|
||||
}
|
||||
if info.BlockTime == 0 {
|
||||
t.Error("Expected non-zero blockTime")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("No transfer instruction found in transaction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTransferInfoFromInstruction_TransferChecked(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test")
|
||||
}
|
||||
|
||||
// SPL Token "transferChecked" (has mint and tokenAmount in instruction)
|
||||
sig := "2aEoNykk4ZJ27C3y7EDJiQUc7GFnnsMe7ofFzB73swGL8kTxSBFCnwzWw3jzr3BND7k8hx15fZHUUAbG1XemNFe5"
|
||||
txData, err := SolGetTransaction(sig)
|
||||
if err != nil {
|
||||
t.Fatalf("SolGetTransaction failed: %v", err)
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(txData, "result.transaction.message.instructions").Array()
|
||||
var found bool
|
||||
for _, inst := range instructions {
|
||||
info, err := ParseTransferInfoFromInstruction(inst, txData)
|
||||
if err != nil {
|
||||
t.Logf("parse error (ok to skip): %v", err)
|
||||
continue
|
||||
}
|
||||
if info == nil {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
t.Logf("TransferChecked: source=%s dest=%s mint=%s amount=%.6f raw=%d blockTime=%d",
|
||||
info.Source, info.Destination, info.Mint, info.Amount, info.RawAmount, info.BlockTime)
|
||||
|
||||
if info.Mint != USDT_Mint {
|
||||
t.Errorf("Expected USDT mint %s, got %s", USDT_Mint, info.Mint)
|
||||
}
|
||||
if info.RawAmount != 300000 {
|
||||
t.Errorf("Expected raw amount 300000, got %d", info.RawAmount)
|
||||
}
|
||||
if info.Amount != 0.3 {
|
||||
t.Errorf("Expected amount 0.3, got %f", info.Amount)
|
||||
}
|
||||
if info.BlockTime == 0 {
|
||||
t.Error("Expected non-zero blockTime")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("No transferChecked instruction found in transaction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTransferInfoFromInstruction_SystemTransfer(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test")
|
||||
}
|
||||
|
||||
// System program SOL transfer
|
||||
sig := "5pNMonUBvLVpxXTmyd5CGVBs49W6781g2ACnrCXhbmtz58KENYA7HSqu6hQkQweg3qQboRd8WAscphNAtiq9UtZZ"
|
||||
txData, err := SolGetTransaction(sig)
|
||||
if err != nil {
|
||||
t.Fatalf("SolGetTransaction failed: %v", err)
|
||||
}
|
||||
|
||||
instructions := gjson.GetBytes(txData, "result.transaction.message.instructions").Array()
|
||||
transferCount := 0
|
||||
for _, inst := range instructions {
|
||||
info, err := ParseTransferInfoFromInstruction(inst, txData)
|
||||
if err != nil {
|
||||
t.Logf("parse error (ok to skip): %v", err)
|
||||
continue
|
||||
}
|
||||
if info == nil {
|
||||
continue
|
||||
}
|
||||
transferCount++
|
||||
t.Logf("System transfer #%d: source=%s dest=%s mint=%s amount=%.9f raw=%d blockTime=%d",
|
||||
transferCount, info.Source, info.Destination, info.Mint, info.Amount, info.RawAmount, info.BlockTime)
|
||||
|
||||
if info.Mint != "SOL" {
|
||||
t.Errorf("Expected mint SOL, got %s", info.Mint)
|
||||
}
|
||||
if info.RawAmount == 0 {
|
||||
t.Error("Expected non-zero raw amount")
|
||||
}
|
||||
if info.BlockTime == 0 {
|
||||
t.Error("Expected non-zero blockTime")
|
||||
}
|
||||
}
|
||||
if transferCount == 0 {
|
||||
t.Error("No system transfer instruction found")
|
||||
}
|
||||
t.Logf("Found %d system transfers", transferCount)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"github.com/assimon/luuu/util/log"
|
||||
"github.com/assimon/luuu/util/math"
|
||||
"github.com/dromara/carbon/v2"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/gookit/goutil/stdutil"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -110,7 +112,7 @@ func checkTrxTransfers(address string, wg *sync.WaitGroup) {
|
||||
}
|
||||
|
||||
txID := transfer.Get("txID").String()
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(address, "TRX", amount)
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, address, "TRX", amount)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -134,6 +136,7 @@ func checkTrxTransfers(address string, wg *sync.WaitGroup) {
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: address,
|
||||
Token: "TRX",
|
||||
Network: mdb.NetworkTron,
|
||||
TradeId: tradeID,
|
||||
Amount: amount,
|
||||
BlockTransactionId: txID,
|
||||
@@ -212,7 +215,7 @@ func checkTrc20Transfers(address string, wg *sync.WaitGroup) {
|
||||
}
|
||||
|
||||
txID := transfer.Get("transaction_id").String()
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(address, "USDT", amount)
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, address, "USDT", amount)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -236,6 +239,7 @@ func checkTrc20Transfers(address string, wg *sync.WaitGroup) {
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: address,
|
||||
Token: "USDT",
|
||||
Network: mdb.NetworkTron,
|
||||
TradeId: tradeID,
|
||||
Amount: amount,
|
||||
BlockTransactionId: txID,
|
||||
@@ -254,6 +258,84 @@ func checkTrc20Transfers(address string, wg *sync.WaitGroup) {
|
||||
}
|
||||
}
|
||||
|
||||
func TryProcessEthereumERC20Transfer(contract common.Address, toAddr common.Address, rawValue *big.Int, txHash string, blockTsMs int64) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Sugar.Errorf("[ETH-WS] TryProcessEthereumERC20Transfer panic: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
usdt := common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7")
|
||||
usdc := common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
|
||||
var tokenSym string
|
||||
switch contract {
|
||||
case usdt:
|
||||
tokenSym = "USDT"
|
||||
case usdc:
|
||||
tokenSym = "USDC"
|
||||
default:
|
||||
log.Sugar.Warnf("[ETH-WS] skip unsupported contract %s", contract.Hex())
|
||||
return
|
||||
}
|
||||
|
||||
walletAddr := strings.ToLower(toAddr.Hex())
|
||||
if rawValue == nil || rawValue.Sign() <= 0 {
|
||||
log.Sugar.Infof("[ETH-%s][%s] skip non-positive or nil amount", tokenSym, walletAddr)
|
||||
return
|
||||
}
|
||||
decimalQuant := decimal.NewFromBigInt(rawValue, 0)
|
||||
amount := math.MustParsePrecFloat64(decimalQuant.Div(decimal.NewFromInt(1_000_000)).InexactFloat64(), 2)
|
||||
if amount <= 0 {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] skip non-positive amount %.2f", tokenSym, walletAddr, amount)
|
||||
return
|
||||
}
|
||||
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkEthereum, walletAddr, tokenSym, amount)
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] lock lookup: %v", tokenSym, walletAddr, err)
|
||||
return
|
||||
}
|
||||
if tradeID == "" {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] skip unmatched tx hash=%s amount=%.2f", tokenSym, walletAddr, txHash, amount)
|
||||
return
|
||||
}
|
||||
|
||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] load order: %v", tokenSym, walletAddr, err)
|
||||
return
|
||||
}
|
||||
if strings.ToLower(strings.TrimSpace(order.Network)) != mdb.NetworkEthereum {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] skip trade_id=%s network=%q", tokenSym, walletAddr, tradeID, order.Network)
|
||||
return
|
||||
}
|
||||
if strings.ToUpper(strings.TrimSpace(order.Token)) != tokenSym {
|
||||
log.Sugar.Warnf("[ETH-%s][%s] skip trade_id=%s token mismatch order=%s", tokenSym, walletAddr, tradeID, order.Token)
|
||||
return
|
||||
}
|
||||
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: walletAddr,
|
||||
Token: tokenSym,
|
||||
Network: mdb.NetworkEthereum,
|
||||
TradeId: tradeID,
|
||||
Amount: amount,
|
||||
BlockTransactionId: txHash,
|
||||
}
|
||||
err = OrderProcessing(req)
|
||||
if err != nil {
|
||||
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
||||
log.Sugar.Infof("[ETH-%s][%s] skip resolved trade_id=%s hash=%s err=%v", tokenSym, walletAddr, tradeID, txHash, err)
|
||||
return
|
||||
}
|
||||
log.Sugar.Errorf("[ETH-%s][%s] OrderProcessing: %v", tokenSym, walletAddr, err)
|
||||
return
|
||||
}
|
||||
|
||||
sendPaymentNotification(order)
|
||||
log.Sugar.Infof("[ETH-%s][%s] payment processed trade_id=%s hash=%s", tokenSym, walletAddr, tradeID, txHash)
|
||||
}
|
||||
|
||||
func sendPaymentNotification(order *mdb.Orders) {
|
||||
msg := fmt.Sprintf(
|
||||
"🎉 <b>收款成功通知</b>\n\n"+
|
||||
@@ -263,6 +345,7 @@ func sendPaymentNotification(order *mdb.Orders) {
|
||||
"📋 <b>订单信息</b>\n"+
|
||||
"├ 交易号:<code>%s</code>\n"+
|
||||
"├ 订单号:<code>%s</code>\n"+
|
||||
"├ 网络:<code>%s</code>\n"+
|
||||
"└ 钱包地址:<code>%s</code>\n\n"+
|
||||
"⏰ <b>时间信息</b>\n"+
|
||||
"├ 创建时间:%s\n"+
|
||||
@@ -273,9 +356,26 @@ func sendPaymentNotification(order *mdb.Orders) {
|
||||
strings.ToUpper(order.Token),
|
||||
order.TradeId,
|
||||
order.OrderId,
|
||||
networkDisplay(order.Network),
|
||||
order.ReceiveAddress,
|
||||
order.CreatedAt.ToDateTimeString(),
|
||||
carbon.Now().ToDateTimeString(),
|
||||
)
|
||||
telegram.SendToBot(msg)
|
||||
}
|
||||
|
||||
func networkDisplay(n string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(n)) {
|
||||
case mdb.NetworkTron:
|
||||
return "Tron"
|
||||
case mdb.NetworkSolana:
|
||||
return "Solana"
|
||||
case mdb.NetworkEthereum:
|
||||
return "Ethereum"
|
||||
default:
|
||||
if n == "" {
|
||||
return "Tron"
|
||||
}
|
||||
return strings.ToUpper(n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ package mq
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -23,6 +26,7 @@ const sqliteBusyRetryAttempts = 3
|
||||
type expirableOrder struct {
|
||||
ID uint64 `gorm:"column:id"`
|
||||
TradeId string `gorm:"column:trade_id"`
|
||||
Network string `gorm:"column:network"`
|
||||
ReceiveAddress string `gorm:"column:receive_address"`
|
||||
Token string `gorm:"column:token"`
|
||||
ActualAmount float64 `gorm:"column:actual_amount"`
|
||||
@@ -65,7 +69,7 @@ func processExpiredOrders() {
|
||||
var orders []expirableOrder
|
||||
err := withSQLiteBusyRetry(func() error {
|
||||
return dao.Mdb.Model(&mdb.Orders{}).
|
||||
Select("id", "trade_id", "receive_address", "token", "actual_amount").
|
||||
Select("id", "trade_id", "network", "receive_address", "token", "actual_amount").
|
||||
Where("status = ?", mdb.StatusWaitPay).
|
||||
Where("created_at <= ?", expirationCutoff).
|
||||
Order("id asc").
|
||||
@@ -89,7 +93,7 @@ func processExpiredOrders() {
|
||||
if !expired {
|
||||
continue
|
||||
}
|
||||
if err = data.UnLockTransaction(order.ReceiveAddress, order.Token, order.ActualAmount); err != nil {
|
||||
if err = data.UnLockTransaction(order.Network, order.ReceiveAddress, order.Token, order.ActualAmount); err != nil {
|
||||
log.Sugar.Warnf("[mq] release expired transaction lock failed, trade_id=%s, err=%v", order.TradeId, err)
|
||||
}
|
||||
}
|
||||
@@ -161,6 +165,54 @@ func processCallback(tradeID string) {
|
||||
}
|
||||
|
||||
func sendOrderCallback(order *mdb.Orders) error {
|
||||
|
||||
switch order.PaymentType {
|
||||
case mdb.PaymentTypeEpay:
|
||||
// 构造 EPay 标准回调参数
|
||||
notifyData := response.OrderNotifyResponseEpay{
|
||||
PID: config.GetEpayPid(),
|
||||
TradeNo: order.TradeId, // epusdt 订单号作为 EPay 平台订单号
|
||||
OutTradeNo: order.OrderId, // 注意:EPay 回调要求商户订单号使用 out_trade_no 参数
|
||||
|
||||
Type: "alipay",
|
||||
Name: order.Name,
|
||||
Money: fmt.Sprintf("%.4f", order.Amount),
|
||||
TradeStatus: "TRADE_SUCCESS",
|
||||
}
|
||||
|
||||
signstr2, err := sign.Get(notifyData, config.GetEpayKey())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 使用 form-encoded POST(EPay 标准协议格式)
|
||||
formData := url.Values{
|
||||
"pid": {fmt.Sprintf("%d", notifyData.PID)},
|
||||
"trade_no": {notifyData.TradeNo},
|
||||
"out_trade_no": {notifyData.OutTradeNo},
|
||||
"type": {notifyData.Type},
|
||||
"name": {notifyData.Name},
|
||||
"money": {notifyData.Money},
|
||||
"trade_status": {notifyData.TradeStatus},
|
||||
"sign": {signstr2},
|
||||
"sign_type": {"MD5"},
|
||||
}
|
||||
|
||||
resp, err := http.PostForm(order.NotifyUrl, formData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
responseBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("notify_url response status: %d, body: %s\n", resp.StatusCode, string(responseBody))
|
||||
|
||||
default:
|
||||
|
||||
client := http_client.GetHttpClient()
|
||||
orderResp := response.OrderNotifyResponse{
|
||||
TradeId: order.TradeId,
|
||||
@@ -191,6 +243,8 @@ func sendOrderCallback(order *mdb.Orders) error {
|
||||
if string(resp.Body()) != "ok" {
|
||||
return errors.New("not ok")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ func TestProcessExpiredOrdersExpiresWaitingOrdersAndReleasesLocks(t *testing.T)
|
||||
ActualAmount: 1,
|
||||
ReceiveAddress: "wallet_1",
|
||||
Token: "USDT",
|
||||
Network: "tron",
|
||||
Status: mdb.StatusWaitPay,
|
||||
NotifyUrl: "https://merchant.example/callback",
|
||||
}
|
||||
@@ -36,7 +37,7 @@ func TestProcessExpiredOrdersExpiresWaitingOrdersAndReleasesLocks(t *testing.T)
|
||||
if err := dao.Mdb.Model(order).UpdateColumn("created_at", time.Now().Add(-20*time.Minute)).Error; err != nil {
|
||||
t.Fatalf("age expired order: %v", err)
|
||||
}
|
||||
if err := data.LockTransaction(order.ReceiveAddress, order.Token, order.TradeId, order.ActualAmount, time.Hour); err != nil {
|
||||
if err := data.LockTransaction("tron", order.ReceiveAddress, order.Token, order.TradeId, order.ActualAmount, time.Hour); err != nil {
|
||||
t.Fatalf("lock expired order: %v", err)
|
||||
}
|
||||
|
||||
@@ -48,13 +49,14 @@ func TestProcessExpiredOrdersExpiresWaitingOrdersAndReleasesLocks(t *testing.T)
|
||||
ActualAmount: 1.01,
|
||||
ReceiveAddress: "wallet_1",
|
||||
Token: "USDT",
|
||||
Network: "tron",
|
||||
Status: mdb.StatusWaitPay,
|
||||
NotifyUrl: "https://merchant.example/callback",
|
||||
}
|
||||
if err := dao.Mdb.Create(recentOrder).Error; err != nil {
|
||||
t.Fatalf("create recent order: %v", err)
|
||||
}
|
||||
if err := data.LockTransaction(recentOrder.ReceiveAddress, recentOrder.Token, recentOrder.TradeId, recentOrder.ActualAmount, time.Hour); err != nil {
|
||||
if err := data.LockTransaction("tron", recentOrder.ReceiveAddress, recentOrder.Token, recentOrder.TradeId, recentOrder.ActualAmount, time.Hour); err != nil {
|
||||
t.Fatalf("lock recent order: %v", err)
|
||||
}
|
||||
|
||||
@@ -67,7 +69,7 @@ func TestProcessExpiredOrdersExpiresWaitingOrdersAndReleasesLocks(t *testing.T)
|
||||
if expired.Status != mdb.StatusExpired {
|
||||
t.Fatalf("expired order status = %d, want %d", expired.Status, mdb.StatusExpired)
|
||||
}
|
||||
lockTradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(order.ReceiveAddress, order.Token, order.ActualAmount)
|
||||
lockTradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken("tron", order.ReceiveAddress, order.Token, order.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("expired order lock lookup: %v", err)
|
||||
}
|
||||
@@ -82,7 +84,7 @@ func TestProcessExpiredOrdersExpiresWaitingOrdersAndReleasesLocks(t *testing.T)
|
||||
if recent.Status != mdb.StatusWaitPay {
|
||||
t.Fatalf("recent order status = %d, want %d", recent.Status, mdb.StatusWaitPay)
|
||||
}
|
||||
lockTradeID, err = data.GetTradeIdByWalletAddressAndAmountAndToken(recentOrder.ReceiveAddress, recentOrder.Token, recentOrder.ActualAmount)
|
||||
lockTradeID, err = data.GetTradeIdByWalletAddressAndAmountAndToken("tron", recentOrder.ReceiveAddress, recentOrder.Token, recentOrder.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("recent order lock lookup: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/assimon/luuu/config"
|
||||
"github.com/assimon/luuu/controller/comm"
|
||||
"github.com/assimon/luuu/middleware"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/util/constant"
|
||||
"github.com/assimon/luuu/util/sign"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
@@ -13,16 +22,116 @@ func RegisterRoute(e *echo.Echo) {
|
||||
e.Any("/", func(c echo.Context) error {
|
||||
return c.String(http.StatusOK, "hello epusdt, https://github.com/GMwalletApp/epusdt")
|
||||
})
|
||||
// ==== 支付相关=====
|
||||
payRoute := e.Group("/pay")
|
||||
// 收银台
|
||||
payRoute.GET("/checkout-counter/:trade_id", comm.Ctrl.CheckoutCounter)
|
||||
// 状态检测
|
||||
payRoute.GET("/check-status/:trade_id", comm.Ctrl.CheckStatus)
|
||||
|
||||
apiV1Route := e.Group("/api/v1")
|
||||
// ====订单相关====
|
||||
orderRoute := apiV1Route.Group("/order", middleware.CheckApiSign())
|
||||
// 创建订单
|
||||
orderRoute.POST("/create-transaction", comm.Ctrl.CreateTransaction)
|
||||
payRoute := e.Group("/pay")
|
||||
payRoute.GET("/checkout-counter/:trade_id", comm.Ctrl.CheckoutCounter)
|
||||
payRoute.GET("/check-status/:trade_id", comm.Ctrl.CheckStatus)
|
||||
payRoute.POST("/switch-network", comm.Ctrl.SwitchNetwork)
|
||||
|
||||
// payment routes
|
||||
paymentRoute := e.Group("/payments")
|
||||
|
||||
// for epusdt
|
||||
epusdtV1 := paymentRoute.Group("/epusdt/v1")
|
||||
epusdtV1.POST("/order/create-transaction", func(ctx echo.Context) error {
|
||||
// add default token and currency for old plugin
|
||||
|
||||
body := make(map[string]interface{})
|
||||
if err := ctx.Bind(&body); err != nil {
|
||||
return comm.Ctrl.FailJson(ctx, err)
|
||||
}
|
||||
if _, ok := body["token"]; !ok {
|
||||
body["token"] = "usdt"
|
||||
}
|
||||
if _, ok := body["currency"]; !ok {
|
||||
body["currency"] = "cny"
|
||||
}
|
||||
if _, ok := body["network"]; !ok {
|
||||
body["network"] = "tron"
|
||||
}
|
||||
ctx.Set("request_body", body)
|
||||
|
||||
jsonBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return comm.Ctrl.FailJson(ctx, err)
|
||||
}
|
||||
ctx.Request().Body = io.NopCloser(bytes.NewBuffer(jsonBytes))
|
||||
ctx.Request().ContentLength = int64(len(jsonBytes))
|
||||
|
||||
return comm.Ctrl.CreateTransaction(ctx)
|
||||
}, middleware.CheckApiSign())
|
||||
|
||||
// gmpay v1 routes
|
||||
gmpayV1 := paymentRoute.Group("/gmpay/v1")
|
||||
gmpayV1.POST("/order/create-transaction", comm.Ctrl.CreateTransaction, middleware.CheckApiSign())
|
||||
|
||||
// wallet management routes
|
||||
walletV1 := gmpayV1.Group("/wallet", middleware.CheckApiToken())
|
||||
walletV1.POST("/add", comm.Ctrl.AddWallet)
|
||||
walletV1.GET("/list", comm.Ctrl.ListWallets)
|
||||
walletV1.GET("/:id", comm.Ctrl.GetWallet)
|
||||
walletV1.POST("/:id/status", comm.Ctrl.ChangeWalletStatus)
|
||||
walletV1.POST("/:id/delete", comm.Ctrl.DeleteWallet)
|
||||
|
||||
// epay v1 routes
|
||||
epayV1 := paymentRoute.Group("/epay/v1")
|
||||
epayV1.GET("/order/create-transaction/submit.php", func(ctx echo.Context) error {
|
||||
money := ctx.QueryParam("money")
|
||||
name := ctx.QueryParam("name")
|
||||
notifyURL := ctx.QueryParam("notify_url")
|
||||
outTradeNo := ctx.QueryParam("out_trade_no")
|
||||
returnURL := ctx.QueryParam("return_url")
|
||||
signstr := ctx.QueryParam("sign")
|
||||
// signType := ctx.QueryParam("sign_type")
|
||||
|
||||
m := map[string]interface{}{
|
||||
"money": money,
|
||||
"name": name,
|
||||
"notify_url": notifyURL,
|
||||
"out_trade_no": outTradeNo,
|
||||
"pid": config.GetEpayPid(), // 注意:验签时需要包含 pid 参数
|
||||
"return_url": returnURL,
|
||||
}
|
||||
|
||||
checkSignature, err := sign.Get(m, config.GetApiAuthToken())
|
||||
if err != nil {
|
||||
return constant.SignatureErr
|
||||
}
|
||||
if checkSignature != signstr {
|
||||
return constant.SignatureErr
|
||||
}
|
||||
|
||||
amountFloat, err := strconv.ParseFloat(money, 64)
|
||||
if err != nil {
|
||||
return comm.Ctrl.FailJson(ctx, fmt.Errorf("invalid money value: %s", money))
|
||||
}
|
||||
|
||||
body := map[string]interface{}{
|
||||
"token": "usdt",
|
||||
"currency": "cny",
|
||||
"network": "tron",
|
||||
"amount": amountFloat,
|
||||
"notify_url": notifyURL,
|
||||
"order_id": outTradeNo,
|
||||
"redirect_url": returnURL,
|
||||
"signature": signstr,
|
||||
"name": name,
|
||||
"payment_type": mdb.PaymentTypeEpay,
|
||||
}
|
||||
|
||||
ctx.Set("request_body", body)
|
||||
|
||||
jsonBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return comm.Ctrl.FailJson(ctx, err)
|
||||
}
|
||||
|
||||
ctx.Request().Body = io.NopCloser(bytes.NewBuffer(jsonBytes))
|
||||
ctx.Request().ContentLength = int64(len(jsonBytes))
|
||||
ctx.Request().Method = http.MethodPost
|
||||
ctx.Request().Header.Set("Content-Type", "application/json")
|
||||
|
||||
return comm.Ctrl.CreateTransactionAndRedirect(ctx)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/assimon/luuu/model/dao"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/util/log"
|
||||
"github.com/assimon/luuu/util/sign"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const testAPIToken = "test-secret-token"
|
||||
|
||||
func setupTestEnv(t *testing.T) *echo.Echo {
|
||||
t.Helper()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// minimal viper config
|
||||
viper.Reset()
|
||||
viper.Set("db_type", "sqlite")
|
||||
viper.Set("api_auth_token", testAPIToken)
|
||||
viper.Set("app_uri", "http://localhost:8080")
|
||||
viper.Set("order_expiration_time", 10)
|
||||
viper.Set("api_rate_url", "")
|
||||
viper.Set("forced_usdt_rate", 7.0)
|
||||
viper.Set("runtime_root_path", tmpDir)
|
||||
viper.Set("log_save_path", tmpDir)
|
||||
viper.Set("sqlite_database_filename", tmpDir+"/test.db")
|
||||
viper.Set("runtime_sqlite_filename", tmpDir+"/runtime.db")
|
||||
|
||||
log.Init()
|
||||
|
||||
// init config paths
|
||||
os.Setenv("EPUSDT_CONFIG", tmpDir)
|
||||
defer os.Unsetenv("EPUSDT_CONFIG")
|
||||
|
||||
// init DB
|
||||
if err := dao.DBInit(); err != nil {
|
||||
t.Fatalf("DBInit: %v", err)
|
||||
}
|
||||
if err := dao.RuntimeInit(); err != nil {
|
||||
t.Fatalf("RuntimeInit: %v", err)
|
||||
}
|
||||
|
||||
// ensure tables exist (MdbTableInit uses sync.Once, so migrate directly)
|
||||
dao.Mdb.AutoMigrate(&mdb.Orders{}, &mdb.WalletAddress{})
|
||||
|
||||
// seed wallet addresses
|
||||
dao.Mdb.Create(&mdb.WalletAddress{Network: mdb.NetworkTron, Address: "TTestTronAddress001", Status: mdb.TokenStatusEnable})
|
||||
dao.Mdb.Create(&mdb.WalletAddress{Network: mdb.NetworkSolana, Address: "SolTestAddress001", Status: mdb.TokenStatusEnable})
|
||||
|
||||
e := echo.New()
|
||||
RegisterRoute(e)
|
||||
return e
|
||||
}
|
||||
|
||||
func signBody(body map[string]interface{}) map[string]interface{} {
|
||||
sig, _ := sign.Get(body, testAPIToken)
|
||||
body["signature"] = sig
|
||||
return body
|
||||
}
|
||||
|
||||
func doPost(e *echo.Echo, path string, body map[string]interface{}) *httptest.ResponseRecorder {
|
||||
jsonBytes, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(jsonBytes)))
|
||||
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// TestCreateOrderEpusdtDefaultTron tests the epusdt compatibility route defaults to tron network.
|
||||
func TestCreateOrderEpusdtDefaultTron(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
body := signBody(map[string]interface{}{
|
||||
"order_id": "test-tron-001",
|
||||
"amount": 1.00,
|
||||
"notify_url": "http://localhost/notify",
|
||||
})
|
||||
|
||||
rec := doPost(e, "/payments/epusdt/v1/order/create-transaction", body)
|
||||
t.Logf("Status: %d, Body: %s", rec.Code, rec.Body.String())
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", rec.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
data, ok := resp["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected data in response, got: %v", resp)
|
||||
}
|
||||
|
||||
if data["trade_id"] == nil || data["trade_id"] == "" {
|
||||
t.Error("expected trade_id in response")
|
||||
}
|
||||
if data["receive_address"] != "TTestTronAddress001" {
|
||||
t.Errorf("expected tron address, got: %v", data["receive_address"])
|
||||
}
|
||||
t.Logf("Order created: trade_id=%v address=%v amount=%v", data["trade_id"], data["receive_address"], data["actual_amount"])
|
||||
}
|
||||
|
||||
// TestCreateOrderGmpayV1Solana tests the gmpay route with solana network.
|
||||
func TestCreateOrderGmpayV1Solana(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
body := signBody(map[string]interface{}{
|
||||
"order_id": "test-sol-001",
|
||||
"amount": 1.00,
|
||||
"token": "usdt",
|
||||
"currency": "cny",
|
||||
"network": "solana",
|
||||
"notify_url": "http://localhost/notify",
|
||||
})
|
||||
|
||||
rec := doPost(e, "/payments/gmpay/v1/order/create-transaction", body)
|
||||
t.Logf("Status: %d, Body: %s", rec.Code, rec.Body.String())
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", rec.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
data, ok := resp["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected data in response, got: %v", resp)
|
||||
}
|
||||
|
||||
if data["trade_id"] == nil || data["trade_id"] == "" {
|
||||
t.Error("expected trade_id in response")
|
||||
}
|
||||
if data["receive_address"] != "SolTestAddress001" {
|
||||
t.Errorf("expected solana address, got: %v", data["receive_address"])
|
||||
}
|
||||
t.Logf("Order created: trade_id=%v address=%v amount=%v", data["trade_id"], data["receive_address"], data["actual_amount"])
|
||||
}
|
||||
|
||||
// TestCreateOrderGmpayV1SolNative tests creating an order for native SOL token.
|
||||
func TestCreateOrderGmpayV1SolNative(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
body := signBody(map[string]interface{}{
|
||||
"order_id": "test-sol-native-001",
|
||||
"amount": 0.05,
|
||||
"token": "sol",
|
||||
"currency": "usd",
|
||||
"network": "solana",
|
||||
"notify_url": "http://localhost/notify",
|
||||
})
|
||||
|
||||
rec := doPost(e, "/payments/gmpay/v1/order/create-transaction", body)
|
||||
t.Logf("Status: %d, Body: %s", rec.Code, rec.Body.String())
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(rec.Body.Bytes(), &resp)
|
||||
t.Logf("Response: %v", resp)
|
||||
|
||||
// This may fail if rate API is not configured, which is expected in test
|
||||
// The important thing is the route accepts the request with network=solana token=sol
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Logf("Note: non-200 may be expected if rate API is not configured for SOL")
|
||||
}
|
||||
}
|
||||
|
||||
func doGet(e *echo.Echo, path string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Header.Set("Authorization", testAPIToken)
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func doPostWithToken(e *echo.Echo, path string, body map[string]interface{}) *httptest.ResponseRecorder {
|
||||
jsonBytes, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(jsonBytes)))
|
||||
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
|
||||
req.Header.Set("Authorization", testAPIToken)
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func parseResp(t *testing.T, rec *httptest.ResponseRecorder) map[string]interface{} {
|
||||
t.Helper()
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
// TestWalletAddAndList tests adding wallets via API and listing them.
|
||||
func TestWalletAddAndList(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
// Add a solana wallet
|
||||
rec := doPostWithToken(e, "/payments/gmpay/v1/wallet/add", map[string]interface{}{
|
||||
"network": "solana",
|
||||
"address": "NewSolWallet001",
|
||||
})
|
||||
t.Logf("Add: %s", rec.Body.String())
|
||||
resp := parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("add wallet failed: %v", resp)
|
||||
}
|
||||
|
||||
// Add a tron wallet
|
||||
rec = doPostWithToken(e, "/payments/gmpay/v1/wallet/add", map[string]interface{}{
|
||||
"network": "tron",
|
||||
"address": "NewTronWallet001",
|
||||
})
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("add tron wallet failed: %v", resp)
|
||||
}
|
||||
|
||||
// List all wallets
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/list")
|
||||
resp = parseResp(t, rec)
|
||||
wallets := resp["data"].([]interface{})
|
||||
// 2 seeded + 2 added = 4
|
||||
if len(wallets) != 4 {
|
||||
t.Fatalf("expected 4 wallets, got %d: %v", len(wallets), wallets)
|
||||
}
|
||||
|
||||
// List by network
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/list?network=solana")
|
||||
resp = parseResp(t, rec)
|
||||
wallets = resp["data"].([]interface{})
|
||||
if len(wallets) != 2 {
|
||||
t.Fatalf("expected 2 solana wallets, got %d", len(wallets))
|
||||
}
|
||||
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/list?network=tron")
|
||||
resp = parseResp(t, rec)
|
||||
wallets = resp["data"].([]interface{})
|
||||
if len(wallets) != 2 {
|
||||
t.Fatalf("expected 2 tron wallets, got %d", len(wallets))
|
||||
}
|
||||
}
|
||||
|
||||
// TestWalletDuplicateRejected tests that adding the same network+address twice fails.
|
||||
func TestWalletDuplicateRejected(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
body := map[string]interface{}{"network": "solana", "address": "DupWallet001"}
|
||||
rec := doPostWithToken(e, "/payments/gmpay/v1/wallet/add", body)
|
||||
resp := parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("first add failed: %v", resp)
|
||||
}
|
||||
|
||||
// Same network+address should fail
|
||||
rec = doPostWithToken(e, "/payments/gmpay/v1/wallet/add", body)
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) == 200 {
|
||||
t.Fatal("expected duplicate to be rejected")
|
||||
}
|
||||
t.Logf("Duplicate rejected: %v", resp["message"])
|
||||
|
||||
// Same address, different network should succeed
|
||||
rec = doPostWithToken(e, "/payments/gmpay/v1/wallet/add", map[string]interface{}{
|
||||
"network": "tron",
|
||||
"address": "DupWallet001",
|
||||
})
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("same address on different network should succeed: %v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWalletStatusAndDelete tests enable/disable/delete operations.
|
||||
func TestWalletStatusAndDelete(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
// Add a wallet
|
||||
rec := doPostWithToken(e, "/payments/gmpay/v1/wallet/add", map[string]interface{}{
|
||||
"network": "solana",
|
||||
"address": "StatusTestWallet",
|
||||
})
|
||||
resp := parseResp(t, rec)
|
||||
wallet := resp["data"].(map[string]interface{})
|
||||
walletID := fmt.Sprintf("%.0f", wallet["id"].(float64))
|
||||
|
||||
// Get wallet
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/"+walletID)
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("get wallet failed: %v", resp)
|
||||
}
|
||||
|
||||
// Disable wallet
|
||||
rec = doPostWithToken(e, "/payments/gmpay/v1/wallet/"+walletID+"/status", map[string]interface{}{
|
||||
"status": 2,
|
||||
})
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("disable wallet failed: %v", resp)
|
||||
}
|
||||
|
||||
// Verify disabled — should not appear in available list
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/list?network=solana")
|
||||
resp = parseResp(t, rec)
|
||||
wallets := resp["data"].([]interface{})
|
||||
for _, w := range wallets {
|
||||
wm := w.(map[string]interface{})
|
||||
if wm["address"] == "StatusTestWallet" && wm["status"].(float64) != 2 {
|
||||
t.Error("wallet should be disabled")
|
||||
}
|
||||
}
|
||||
|
||||
// Delete wallet
|
||||
rec = doPostWithToken(e, "/payments/gmpay/v1/wallet/"+walletID+"/delete", nil)
|
||||
resp = parseResp(t, rec)
|
||||
if resp["status_code"].(float64) != 200 {
|
||||
t.Fatalf("delete wallet failed: %v", resp)
|
||||
}
|
||||
|
||||
// Verify deleted
|
||||
rec = doGet(e, "/payments/gmpay/v1/wallet/"+walletID)
|
||||
resp = parseResp(t, rec)
|
||||
// Should return not found
|
||||
if resp["status_code"].(float64) == 200 {
|
||||
data := resp["data"].(map[string]interface{})
|
||||
if data["id"].(float64) > 0 {
|
||||
t.Error("wallet should be deleted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWalletAuthRequired tests that wallet APIs require auth token.
|
||||
func TestWalletAuthRequired(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
// No auth header — should not return success
|
||||
req := httptest.NewRequest(http.MethodGet, "/payments/gmpay/v1/wallet/list", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
|
||||
// The response should indicate auth failure (not 200 success)
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
// echo may return plain text error
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Error("expected auth failure without token")
|
||||
}
|
||||
t.Logf("Auth rejected (non-JSON): status=%d body=%s", rec.Code, rec.Body.String())
|
||||
return
|
||||
}
|
||||
statusCode, _ := resp["status_code"].(float64)
|
||||
if statusCode == 200 {
|
||||
t.Error("expected auth failure without token")
|
||||
}
|
||||
t.Logf("Auth rejected: %v", resp)
|
||||
}
|
||||
|
||||
// TestCreateOrderNetworkIsolation verifies tron and solana wallets don't mix.
|
||||
func TestCreateOrderNetworkIsolation(t *testing.T) {
|
||||
e := setupTestEnv(t)
|
||||
|
||||
// Try to create a solana order — should get solana address, not tron
|
||||
body := signBody(map[string]interface{}{
|
||||
"order_id": fmt.Sprintf("test-isolation-%d", 1),
|
||||
"amount": 1.00,
|
||||
"token": "usdt",
|
||||
"currency": "cny",
|
||||
"network": "solana",
|
||||
"notify_url": "http://localhost/notify",
|
||||
})
|
||||
rec := doPost(e, "/payments/gmpay/v1/order/create-transaction", body)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(rec.Body.Bytes(), &resp)
|
||||
|
||||
data, ok := resp["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected data, got: %v", resp)
|
||||
}
|
||||
if data["receive_address"] == "TTestTronAddress001" {
|
||||
t.Error("solana order should NOT get a tron address")
|
||||
}
|
||||
if data["receive_address"] != "SolTestAddress001" {
|
||||
t.Errorf("expected SolTestAddress001, got %v", data["receive_address"])
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 597 B |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 952 B |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,972 @@
|
||||
/* =============================================================
|
||||
* GM Pay — payment.js
|
||||
* 后端对接只需关注:
|
||||
* 1. CONFIG.api.selectMethod — Step 1 确认接口(POST 币种/网络,返回收款地址)
|
||||
* 2. CONFIG.api.checkStatus — 轮询接口 URL
|
||||
* 3. CONFIG.api.statusMap — 状态码映射
|
||||
* 4. index.html 底部 <script> 中 ORDER / PAYMENT_OPTIONS 变量
|
||||
* ============================================================= */
|
||||
|
||||
'use strict';
|
||||
|
||||
// ── DOM helpers ───────────────────────────────────────────────
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const $$ = (sel) => document.querySelectorAll(sel);
|
||||
const setText = (id, value) => {
|
||||
const el = $(id);
|
||||
if (el) el.textContent = value;
|
||||
return el;
|
||||
};
|
||||
const setHtml = (id, value) => {
|
||||
const el = $(id);
|
||||
if (el) el.innerHTML = value;
|
||||
return el;
|
||||
};
|
||||
|
||||
// ── 全局配置(可按项目调整)─────────────────────────────────
|
||||
const CONFIG = {
|
||||
poll: {
|
||||
interval: 5000, // 轮询间隔(毫秒)
|
||||
maxErrors: 5, // 最多连续错误次数,超出进入 timeout 状态
|
||||
timeout: 8000, // 单次请求超时(毫秒)
|
||||
},
|
||||
redirect: {
|
||||
delay: 3000, // 支付成功后自动跳转延迟(毫秒)
|
||||
},
|
||||
// ---- 后端接口 ----
|
||||
api: {
|
||||
// 切换网络接口:POST { trade_id, token, network },返回完整订单对象
|
||||
selectMethod: () => '/pay/switch-network',
|
||||
// 轮询接口:GET,返回 { data: { status: number } }
|
||||
checkStatus: (tradeId) => `/pay/check-status/${encodeURIComponent(tradeId)}`,
|
||||
// status 状态码映射
|
||||
statusMap: {
|
||||
paid: 2, // 支付成功
|
||||
expired: 3, // 已过期
|
||||
},
|
||||
},
|
||||
// ---- 连接钱包 ----
|
||||
wallet: {
|
||||
enabled: false, // false = 隐藏「连接钱包支付」按钮
|
||||
// TronLink deeplink,如需支持其他钱包替换此处
|
||||
deeplink: (currentUrl) => {
|
||||
const param = JSON.stringify({
|
||||
url: currentUrl,
|
||||
action: 'open',
|
||||
dapp_name: 'GM Pay',
|
||||
dapp_icon: 'https://www.gmwallet.app/favicon.png',
|
||||
});
|
||||
return 'tronlinkoutside://pull.activity?param=' + encodeURIComponent(param);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 1 — 链图标 / 网络渲染
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
const _CHAIN_PRESETS = {
|
||||
Ethereum: { bg: 'hsla(0,0%,55%,0.25)', color: 'hsla(0,0%,55%,1)', icon: 'ethereum' },
|
||||
Solana: { bg: 'hsla(256,85%,65%,0.25)', color: 'hsla(256,85%,65%,1)', icon: 'solana' },
|
||||
BSC: { bg: 'hsla(46,91%,49%,0.25)', color: 'hsla(46,91%,49%,1)', icon: 'bsc' },
|
||||
Arbitrum: { bg: 'hsla(202,100%,54%,0.25)', color: 'hsla(202,100%,54%,1)', icon: 'arbitrum' },
|
||||
TRON: { bg: 'hsla(350,100%,47%,0.20)', color: 'hsla(350,100%,47%,1)', icon: 'tron' },
|
||||
Polygon: { bg: 'hsla(263,73%,56%,0.25)', color: 'hsla(263,73%,56%,1)', icon: 'polygon' },
|
||||
Base: { bg: 'hsla(240,100%,61%,0.25)', color: 'hsla(240,100%,61%,1)', icon: 'base' },
|
||||
OP: { bg: 'hsla(353,99%,51%,0.25)', color: 'hsla(353,99%,51%,1)', icon: 'op' },
|
||||
HyperEVM: { bg: 'hsla(166,94%,79%,0.20)', color: 'hsla(166,94%,79%,1)', icon: 'hyperevm' },
|
||||
Plasma: { bg: 'hsla(166,64%,32%,0.25)', color: 'hsla(166,64%,32%,1)', icon: 'plasma' },
|
||||
Bitcoin: { bg: 'hsla(33,93%,54%,0.20)', color: 'hsla(33,93%,54%,1)', icon: 'bitcoin' },
|
||||
Binance: { bg: 'hsla(46,91%,49%,0.24)', color: 'hsla(46,91%,49%,1)', icon: 'binance' },
|
||||
};
|
||||
|
||||
const _CHAIN_ALIASES = {
|
||||
evm:'Ethereum', eth:'Ethereum', ethereum:'Ethereum',
|
||||
bsc:'BSC', bnb:'BSC',
|
||||
arbitrum:'Arbitrum', arb:'Arbitrum',
|
||||
sol:'Solana', solana:'Solana',
|
||||
tron:'TRON', trx:'TRON',
|
||||
polygon:'Polygon', matic:'Polygon', pol:'Polygon',
|
||||
base:'Base',
|
||||
op:'OP', optimism:'OP',
|
||||
hyperevm:'HyperEVM', hyperliquid:'HyperEVM', hype:'HyperEVM',
|
||||
plasma:'Plasma', xpl:'Plasma',
|
||||
bitcoin:'Bitcoin', btc:'Bitcoin',
|
||||
binance:'Binance', bnb_chain:'Binance',
|
||||
};
|
||||
|
||||
const IMAGE_PREFIX = {
|
||||
chain: '/static/images/',
|
||||
tokenTrigger: 'https://cdn.jsdmirror.com/gh/atomiclabs/cryptocurrency-icons@1a63530/128/color/',
|
||||
tokenMenu: 'https://cdn.jsdmirror.com/gh/atomiclabs/cryptocurrency-icons@1a63530/128/color/',
|
||||
};
|
||||
|
||||
function _resolveChain(name) {
|
||||
if (!name) return null;
|
||||
const k = name.trim().toLowerCase();
|
||||
const canonical = _CHAIN_ALIASES[k] || Object.keys(_CHAIN_PRESETS).find(c => c.toLowerCase() === k);
|
||||
return canonical ? { label: canonical, ..._CHAIN_PRESETS[canonical] } : null;
|
||||
}
|
||||
|
||||
/** 用于 order-info 顶部的网络 tag badge */
|
||||
function networkTag(network) {
|
||||
const chain = _resolveChain(network);
|
||||
if (!chain) return `<span style="font-weight:600;color:var(--card-foreground)">${network}</span>`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:4px;padding:2px 8px 2px 4px;border-radius:99px;background:${chain.bg};color:${chain.color};font-size:12px;font-weight:600;line-height:1.6">
|
||||
<img src="${IMAGE_PREFIX.chain}${chain.icon}.png" width="14" height="14" style="width:14px;height:14px;border-radius:50%;object-fit:cover;flex-shrink:0" />
|
||||
${chain.label}
|
||||
</span>`;
|
||||
}
|
||||
|
||||
/** 选择器触发器显示:网络 */
|
||||
function _networkTriggerHtml(network) {
|
||||
const chain = _resolveChain(network);
|
||||
if (!chain) return `<span class="text-sm font-semibold" style="color:var(--card-foreground)">${network || '--'}</span>`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:7px">
|
||||
<img src="${IMAGE_PREFIX.chain}${chain.icon}.png" width="18" height="18" style="width:18px;height:18px;border-radius:50%;object-fit:cover;flex-shrink:0" />
|
||||
<span class="text-sm font-semibold" style="color:var(--card-foreground)">${chain.label}</span>
|
||||
</span>`;
|
||||
}
|
||||
|
||||
/** 选择器触发器显示:Token */
|
||||
function _tokenTriggerHtml(token) {
|
||||
if (!token) return `<span class="text-sm font-semibold" style="color:var(--card-foreground)">--</span>`;
|
||||
const src = `${IMAGE_PREFIX.tokenTrigger}${token.toLowerCase()}.png`;
|
||||
return `<span style="display:inline-flex;align-items:center;gap:7px">
|
||||
<img src="${src}" width="18" height="18" style="width:18px;height:18px;border-radius:50%;object-fit:cover;flex-shrink:0" onerror="this.style.display='none'" />
|
||||
<span class="text-sm font-semibold" style="color:var(--card-foreground)">${token}</span>
|
||||
</span>`;
|
||||
}
|
||||
|
||||
/** 下拉菜单中的网络选项 */
|
||||
function _networkMenuItemHtml(opt, selected) {
|
||||
const chain = _resolveChain(opt.network);
|
||||
const icon = chain
|
||||
? `<img src="${IMAGE_PREFIX.chain}${chain.icon}.png" width="16" height="16" style="width:16px;height:16px;border-radius:50%;object-fit:cover;flex-shrink:0" />`
|
||||
: '';
|
||||
return `<div class="select-option menu-item${selected ? ' is-selected' : ''}"
|
||||
onclick="step1SetNetwork('${opt.network}')"
|
||||
style="display:flex;align-items:center;gap:8px">${icon}${chain ? chain.label : opt.network}</div>`;
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 2 — 主题 & Lucide 图标
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
if (typeof lucide !== 'undefined') lucide.createIcons();
|
||||
|
||||
let currentTheme = localStorage.getItem('theme') || 'dark';
|
||||
applyTheme(currentTheme);
|
||||
|
||||
function applyTheme(t) {
|
||||
currentTheme = t;
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
localStorage.setItem('theme', t);
|
||||
$('icon-moon').style.display = t === 'light' ? 'block' : 'none';
|
||||
$('icon-sun').style.display = t === 'dark' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function toggleTheme(e) {
|
||||
const next = currentTheme === 'light' ? 'dark' : 'light';
|
||||
if (!document.startViewTransition) { applyTheme(next); return; }
|
||||
const x = e ? e.clientX : window.innerWidth / 2;
|
||||
const y = e ? e.clientY : window.innerHeight / 2;
|
||||
const r = Math.hypot(Math.max(x, window.innerWidth - x), Math.max(y, window.innerHeight - y));
|
||||
document.startViewTransition(() => applyTheme(next)).ready.then(() => {
|
||||
document.documentElement.animate(
|
||||
{ clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${r}px at ${x}px ${y}px)`] },
|
||||
{ duration: 420, easing: 'ease-in-out', pseudoElement: '::view-transition-new(root)' }
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 3 — 国际化 (i18n)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
const LANGS = {
|
||||
en: {
|
||||
scan_title: 'Scan or copy address to pay',
|
||||
amount_to_pay: 'Amount to pay',
|
||||
payment_address: 'Payment address',
|
||||
i_have_transferred: 'I have transferred',
|
||||
checking_blockchain: 'Checking blockchain…',
|
||||
expires: 'Expires',
|
||||
copied: 'Copied to clipboard',
|
||||
verifying: 'Verifying…',
|
||||
payment_success: 'Payment Successful',
|
||||
redirecting: 'Redirecting…',
|
||||
payment_expired: 'Payment Expired',
|
||||
expired_sub: 'Please initiate a new payment',
|
||||
order_id: 'Order ID',
|
||||
order_amount: 'Order amount',
|
||||
network_timeout: 'Connection Timeout',
|
||||
timeout_sub: 'Unable to connect to the payment server',
|
||||
retry: 'Retry',
|
||||
back: 'Back',
|
||||
order_not_found: 'Order Not Found',
|
||||
not_found_sub: 'The order does not exist or has already expired',
|
||||
select_method: 'Select payment method',
|
||||
currency_label: 'Currency',
|
||||
network_label: 'Network',
|
||||
confirm: 'Confirm',
|
||||
connect_wallet: 'Connect Wallet to Pay',
|
||||
},
|
||||
zh: {
|
||||
scan_title: '扫码或复制地址付款',
|
||||
amount_to_pay: '付款金额',
|
||||
payment_address: '付款地址',
|
||||
i_have_transferred: '我已转账',
|
||||
checking_blockchain: '链上核验中…',
|
||||
expires: '到期时间',
|
||||
copied: '已复制到剪贴板',
|
||||
verifying: '核验中…',
|
||||
payment_success: '支付成功',
|
||||
redirecting: '正在跳转…',
|
||||
payment_expired: '支付已过期',
|
||||
expired_sub: '请重新发起支付',
|
||||
order_id: '订单 ID',
|
||||
order_amount: '订单金额',
|
||||
network_timeout: '连接超时',
|
||||
timeout_sub: '无法连接至支付服务器',
|
||||
retry: '重试',
|
||||
back: '返回',
|
||||
order_not_found: '订单不存在',
|
||||
not_found_sub: '待支付订单不存在或已过期',
|
||||
select_method: '选择支付方式',
|
||||
currency_label: '币种',
|
||||
network_label: '网络',
|
||||
confirm: '确认',
|
||||
connect_wallet: '连接钱包支付',
|
||||
},
|
||||
ja: {
|
||||
scan_title: 'アドレスをスキャンまたはコピーして支払う',
|
||||
amount_to_pay: '支払い金額',
|
||||
payment_address: '支払いアドレス',
|
||||
i_have_transferred: '送金しました',
|
||||
checking_blockchain: 'ブロックチェーン確認中…',
|
||||
expires: '有効期限',
|
||||
copied: 'コピーしました',
|
||||
verifying: '確認中…',
|
||||
payment_success: '支払い完了',
|
||||
redirecting: 'リダイレクト中…',
|
||||
payment_expired: '支払い期限切れ',
|
||||
expired_sub: '新しい支払いを開始してください',
|
||||
order_id: '注文 ID',
|
||||
order_amount: '注文金額',
|
||||
network_timeout: '接続タイムアウト',
|
||||
timeout_sub: '支払いサーバーに接続できません',
|
||||
retry: '再試行',
|
||||
back: '戻る',
|
||||
order_not_found: '注文が見つかりません',
|
||||
not_found_sub: '注文が存在しないか、すでに期限切れです',
|
||||
select_method: '支払い方法を選択',
|
||||
currency_label: '通貨',
|
||||
network_label: 'ネットワーク',
|
||||
confirm: '確認',
|
||||
connect_wallet: 'ウォレットで支払う',
|
||||
},
|
||||
ko: {
|
||||
scan_title: '주소를 스캔하거나 복사하여 결제',
|
||||
amount_to_pay: '결제 금액',
|
||||
payment_address: '결제 주소',
|
||||
i_have_transferred: '이체 완료',
|
||||
checking_blockchain: '블록체인 확인 중…',
|
||||
expires: '만료 시간',
|
||||
copied: '복사됨',
|
||||
verifying: '확인 중…',
|
||||
payment_success: '결제 성공',
|
||||
redirecting: '리다이렉트 중…',
|
||||
payment_expired: '결제 만료',
|
||||
expired_sub: '새로운 결제를 시작하세요',
|
||||
order_id: '주문 ID',
|
||||
order_amount: '주문 금액',
|
||||
network_timeout: '연결 시간 초과',
|
||||
timeout_sub: '결제 서버에 연결할 수 없습니다',
|
||||
retry: '다시 시도',
|
||||
back: '돌아가기',
|
||||
order_not_found: '주문 없음',
|
||||
not_found_sub: '주문이 존재하지 않거나 이미 만료되었습니다',
|
||||
select_method: '결제 수단 선택',
|
||||
currency_label: '통화',
|
||||
network_label: '네트워크',
|
||||
confirm: '확인',
|
||||
connect_wallet: '지갑으로 결제',
|
||||
},
|
||||
'zh-hk': {
|
||||
scan_title: '掃碼或複製地址付款',
|
||||
amount_to_pay: '付款金額',
|
||||
payment_address: '付款地址',
|
||||
i_have_transferred: '我已轉帳',
|
||||
checking_blockchain: '鏈上核驗中…',
|
||||
expires: '到期時間',
|
||||
copied: '已複製到剪貼簿',
|
||||
verifying: '核驗中…',
|
||||
payment_success: '支付成功',
|
||||
redirecting: '正在跳轉…',
|
||||
payment_expired: '支付已過期',
|
||||
expired_sub: '請重新發起支付',
|
||||
order_id: '訂單 ID',
|
||||
order_amount: '訂單金額',
|
||||
network_timeout: '連線逾時',
|
||||
timeout_sub: '無法連線至支付伺服器',
|
||||
retry: '重試',
|
||||
back: '返回',
|
||||
order_not_found: '訂單不存在',
|
||||
not_found_sub: '待支付訂單不存在或已過期',
|
||||
select_method: '選擇支付方式',
|
||||
currency_label: '幣種',
|
||||
network_label: '網絡',
|
||||
confirm: '確認',
|
||||
connect_wallet: '連接錢包支付',
|
||||
},
|
||||
ru: {
|
||||
scan_title: 'Отсканируйте или скопируйте адрес для оплаты',
|
||||
amount_to_pay: 'Сумма к оплате',
|
||||
payment_address: 'Адрес для оплаты',
|
||||
i_have_transferred: 'Я перевёл',
|
||||
checking_blockchain: 'Проверка блокчейна…',
|
||||
expires: 'Истекает',
|
||||
copied: 'Скопировано',
|
||||
verifying: 'Проверка…',
|
||||
payment_success: 'Оплата прошла успешно',
|
||||
redirecting: 'Перенаправление…',
|
||||
payment_expired: 'Срок оплаты истёк',
|
||||
expired_sub: 'Пожалуйста, создайте новый платёж',
|
||||
order_id: 'Заказ ID',
|
||||
order_amount: 'Сумма заказа',
|
||||
network_timeout: 'Тайм-аут подключения',
|
||||
timeout_sub: 'Не удалось подключиться к серверу',
|
||||
retry: 'Повторить',
|
||||
back: 'Назад',
|
||||
order_not_found: 'Заказ не найден',
|
||||
not_found_sub: 'Заказ не существует или уже истёк',
|
||||
select_method: 'Выберите способ оплаты',
|
||||
currency_label: 'Валюта',
|
||||
network_label: 'Сеть',
|
||||
confirm: 'Подтвердить',
|
||||
connect_wallet: 'Оплатить через кошелёк',
|
||||
},
|
||||
};
|
||||
|
||||
const LANG_LABELS = { en: 'EN', zh: '中文', 'zh-hk': '繁體', ja: '日本語', ko: '한국어', ru: 'RU' };
|
||||
const SUPPORTED_LANGS = Object.keys(LANGS);
|
||||
let currentLang = 'en';
|
||||
|
||||
const t = (key) => LANGS[currentLang]?.[key] ?? key;
|
||||
|
||||
function detectLang() {
|
||||
const saved = localStorage.getItem('lang');
|
||||
if (saved && SUPPORTED_LANGS.includes(saved)) return saved;
|
||||
for (const nav of (navigator.languages || [navigator.language])) {
|
||||
const lc = nav.toLowerCase();
|
||||
if (lc.startsWith('zh-hk') || lc.startsWith('zh-tw') || lc.startsWith('zh-mo')) return 'zh-hk';
|
||||
if (lc.startsWith('zh')) return 'zh';
|
||||
if (lc.startsWith('ja')) return 'ja';
|
||||
if (lc.startsWith('ko')) return 'ko';
|
||||
if (lc.startsWith('ru')) return 'ru';
|
||||
if (lc.startsWith('en')) return 'en';
|
||||
}
|
||||
return 'en';
|
||||
}
|
||||
|
||||
function setLang(lang) {
|
||||
currentLang = lang;
|
||||
localStorage.setItem('lang', lang);
|
||||
$$('[data-i18n]').forEach(el => {
|
||||
const v = t(el.dataset.i18n);
|
||||
if (v) el.textContent = v;
|
||||
});
|
||||
setText('lang-label', LANG_LABELS[lang]);
|
||||
$$('#dd-lang-menu .select-option').forEach(o =>
|
||||
o.classList.toggle('is-selected', o.dataset.lang === lang));
|
||||
closeAllSelects();
|
||||
// 重新渲染含翻译文案的动态行
|
||||
if (ORDER?.tradeId) renderOrderId();
|
||||
if (ORDER?.amount && !ORDER.amount.startsWith('{{')) {
|
||||
renderRow('display-fiat', t('order_amount'), `${ORDER.amount} ${ORDER.currency || ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 4 — 下拉选择器
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
function toggleSelect(id) {
|
||||
const wrap = $(id);
|
||||
const trigger = wrap.querySelector('.select-trigger');
|
||||
const menu = wrap.querySelector('.select-menu');
|
||||
const wasOpen = menu.classList.contains('is-open');
|
||||
closeAllSelects();
|
||||
if (!wasOpen) {
|
||||
menu.classList.add('is-open');
|
||||
trigger?.classList.add('is-open');
|
||||
}
|
||||
}
|
||||
|
||||
function closeAllSelects() {
|
||||
$$('.select-menu.is-open').forEach(m => {
|
||||
m.classList.remove('is-open');
|
||||
m.closest('.select-wrap')?.querySelector('.select-trigger')?.classList.remove('is-open');
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!e.target.closest('.select-wrap')) closeAllSelects();
|
||||
});
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 5 — Toast & Clipboard
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
const CHECK_ICON = '<i data-lucide="check" width="15" height="15" stroke-width="2.5" color="#22c55e"></i>';
|
||||
|
||||
function showToast(msg) {
|
||||
const el = $('toast');
|
||||
if (!el) return;
|
||||
el.textContent = msg || t('copied');
|
||||
el.style.opacity = '1';
|
||||
el.style.transform = 'translateX(-50%) translateY(0)';
|
||||
clearTimeout(el._tid);
|
||||
el._tid = setTimeout(() => {
|
||||
el.style.opacity = '0';
|
||||
el.style.transform = 'translateX(-50%) translateY(10px)';
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function flashCheck(btnId) {
|
||||
const btn = $(btnId);
|
||||
if (!btn) return;
|
||||
const orig = btn.innerHTML;
|
||||
btn.innerHTML = CHECK_ICON;
|
||||
lucide.createIcons({ nodes: [btn] });
|
||||
setTimeout(() => { btn.innerHTML = orig; lucide.createIcons({ nodes: [btn] }); }, 1800);
|
||||
}
|
||||
|
||||
let _clipboard = null;
|
||||
|
||||
function initClipboard() {
|
||||
const targets = [
|
||||
{ id: 'copy-addr-box', text: ORDER.receiveAddress, iconId: 'btn-copy-addr' },
|
||||
{ id: 'btn-copy-amount', text: ORDER.actualAmount, iconId: 'btn-copy-amount' },
|
||||
];
|
||||
targets.forEach(({ id, text }) => $(id)?.setAttribute('data-clipboard-text', text));
|
||||
|
||||
if (typeof ClipboardJS !== 'undefined') {
|
||||
_clipboard?.destroy();
|
||||
_clipboard = new ClipboardJS(targets.map(c => '#' + c.id).join(', '));
|
||||
_clipboard.on('success', e => {
|
||||
e.clearSelection();
|
||||
const tgt = targets.find(c => c.id === e.trigger.id);
|
||||
showToast();
|
||||
if (tgt) flashCheck(tgt.iconId);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 6 — 面板切换 & 导航
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
const PANEL_IDS = {
|
||||
step1: 'step1-panel',
|
||||
payment: 'payment-panel',
|
||||
success: 'screen-success',
|
||||
expired: 'screen-expired',
|
||||
timeout: 'screen-timeout',
|
||||
'not-found': 'screen-not-found',
|
||||
};
|
||||
const PANEL_ORDER = ['step1', 'payment', 'success', 'expired', 'timeout', 'not-found'];
|
||||
let _currentPanel = 'step1';
|
||||
|
||||
function slideTo(name, dir) {
|
||||
const fromEl = $(PANEL_IDS[_currentPanel]);
|
||||
const toEl = $(PANEL_IDS[name]);
|
||||
const viewport = $('panel-viewport');
|
||||
if (!toEl || name === _currentPanel) return;
|
||||
|
||||
const d = dir ?? (PANEL_ORDER.indexOf(name) >= PANEL_ORDER.indexOf(_currentPanel) ? 1 : -1);
|
||||
_currentPanel = name;
|
||||
|
||||
if (viewport) viewport.style.overflowX = 'hidden'; // 动画期间裁剪
|
||||
|
||||
if (fromEl) {
|
||||
Object.assign(fromEl.style, { position: 'absolute', top: '0', left: '0', width: '100%' });
|
||||
fromEl.style.animation = `${d > 0 ? 'slide-out-l' : 'slide-out-r'} 0.38s cubic-bezier(.4,0,.2,1) forwards`;
|
||||
fromEl.addEventListener('animationend', () => {
|
||||
fromEl.style.cssText = 'display:none';
|
||||
if (viewport) viewport.style.overflowX = '';
|
||||
}, { once: true });
|
||||
} else if (viewport) {
|
||||
setTimeout(() => { viewport.style.overflowX = ''; }, 420);
|
||||
}
|
||||
|
||||
toEl.style.display = '';
|
||||
toEl.style.animation = `${d > 0 ? 'slide-in-r' : 'slide-in-l'} 0.38s cubic-bezier(.4,0,.2,1) forwards`;
|
||||
}
|
||||
|
||||
function showStatePanel(state) {
|
||||
const isNotFound = state === 'not-found';
|
||||
const orderInfo = $('order-info');
|
||||
const stepProgress = $('step-progress');
|
||||
if (orderInfo) orderInfo.style.display = isNotFound ? 'none' : '';
|
||||
if (stepProgress) stepProgress.style.display = isNotFound ? 'none' : '';
|
||||
slideTo(state);
|
||||
}
|
||||
|
||||
function hideStatePanel() {
|
||||
const orderInfo = $('order-info');
|
||||
const stepProgress = $('step-progress');
|
||||
if (orderInfo) orderInfo.style.display = '';
|
||||
if (stepProgress) stepProgress.style.display = '';
|
||||
slideTo('payment', -1);
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (ORDER?.redirectUrl && !ORDER.redirectUrl.startsWith('{{')) {
|
||||
window.location.href = ORDER.redirectUrl;
|
||||
} else if (document.referrer) {
|
||||
window.location.href = document.referrer;
|
||||
} else {
|
||||
history.back();
|
||||
}
|
||||
}
|
||||
|
||||
function syncStatusCardHeight() {} // 兼容旧调用,保留空桩
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 7 — 步骤进度条
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
function setStepBar(step) {
|
||||
const f1 = $('step-fill-1');
|
||||
const f2 = $('step-fill-2');
|
||||
if (!f1) return;
|
||||
const BASE = 'height:100%;border-radius:9999px;background:var(--foreground);';
|
||||
if (step === 1) {
|
||||
f1.style.cssText = BASE + 'animation:fill-bar 0.9s ease-out forwards';
|
||||
f2.style.cssText = BASE + 'width:0%';
|
||||
} else {
|
||||
f1.style.cssText = BASE + 'width:100%';
|
||||
f2.style.cssText = BASE + 'animation:fill-bar 0.9s ease-out forwards';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 8 — Step 1 — 币种 & 网络选择
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
let _step1Token = null;
|
||||
let _step1Opt = null;
|
||||
|
||||
// 内置优先网络,按顺序匹配第一个可用选项
|
||||
const _PREFERRED_NETWORKS = ['TRON', 'Solana'];
|
||||
|
||||
function initStep1() {
|
||||
// 按内置优先顺序找到首个可用选项
|
||||
_step1Opt = null;
|
||||
for (const net of _PREFERRED_NETWORKS) {
|
||||
_step1Opt = PAYMENT_OPTIONS.find(
|
||||
o => (_resolveChain(o.network)?.label ?? o.network) === net
|
||||
);
|
||||
if (_step1Opt) break;
|
||||
}
|
||||
_step1Opt = _step1Opt ?? PAYMENT_OPTIONS[0];
|
||||
_step1Token = _step1Opt.token;
|
||||
_renderNetworkMenu();
|
||||
_renderTokenMenu();
|
||||
}
|
||||
|
||||
function _renderTokenMenu() {
|
||||
// 按当前选中网络过滤可用币种
|
||||
const opts = PAYMENT_OPTIONS.filter(o => o.network === _step1Opt?.network);
|
||||
const tokens = [...new Set(opts.map(o => o.token))];
|
||||
// 若当前 token 在新网络下不存在则重置为第一个
|
||||
if (!tokens.includes(_step1Token)) {
|
||||
_step1Token = tokens[0] ?? null;
|
||||
_step1Opt = opts[0] ?? _step1Opt;
|
||||
}
|
||||
const menu = $('dd-token-menu');
|
||||
if (!menu) return;
|
||||
menu.innerHTML = tokens.map(tok => {
|
||||
const src = `${IMAGE_PREFIX.tokenMenu}${tok.toLowerCase()}.png`;
|
||||
return `<div class="select-option menu-item${tok === _step1Token ? ' is-selected' : ''}"
|
||||
onclick="step1SetToken('${tok}')"
|
||||
style="display:flex;align-items:center;gap:8px">
|
||||
<img src="${src}" width="16" height="16" style="width:16px;height:16px;border-radius:50%;object-fit:cover;flex-shrink:0" onerror="this.style.display='none'" />
|
||||
${tok}
|
||||
</div>`;
|
||||
}).join('');
|
||||
setHtml('token-label', _tokenTriggerHtml(_step1Token));
|
||||
}
|
||||
|
||||
function _renderNetworkMenu() {
|
||||
// 去重,每个网络只显示一项
|
||||
const seen = new Set();
|
||||
const networkOpts = PAYMENT_OPTIONS.filter(o => {
|
||||
if (seen.has(o.network)) return false;
|
||||
seen.add(o.network);
|
||||
return true;
|
||||
});
|
||||
const menu = $('dd-network-menu');
|
||||
if (menu) menu.innerHTML = networkOpts.map(opt => _networkMenuItemHtml(opt, opt.network === _step1Opt?.network)).join('');
|
||||
setHtml('network-label', _networkTriggerHtml(_step1Opt?.network || '--'));
|
||||
}
|
||||
|
||||
function step1SetToken(tok) {
|
||||
_step1Token = tok;
|
||||
// 在当前网络下找对应 opt
|
||||
_step1Opt = PAYMENT_OPTIONS.find(o => o.network === _step1Opt?.network && o.token === tok) ?? _step1Opt;
|
||||
setHtml('token-label', _tokenTriggerHtml(tok));
|
||||
$$('#dd-token-menu .select-option').forEach(o =>
|
||||
o.classList.toggle('is-selected', o.textContent.trim() === tok));
|
||||
closeAllSelects();
|
||||
}
|
||||
|
||||
function step1SetNetwork(networkName) {
|
||||
// 找该网络下第一个 opt 作为默认
|
||||
_step1Opt = PAYMENT_OPTIONS.find(o => o.network === networkName) ?? _step1Opt;
|
||||
const chain = _resolveChain(networkName);
|
||||
const label = chain ? chain.label : networkName;
|
||||
$$('#dd-network-menu .select-option').forEach(o =>
|
||||
o.classList.toggle('is-selected', o.textContent.trim() === label));
|
||||
setHtml('network-label', _networkTriggerHtml(_step1Opt.network));
|
||||
_renderTokenMenu();
|
||||
closeAllSelects();
|
||||
}
|
||||
|
||||
async function confirmStep1() {
|
||||
const opt = _step1Opt || PAYMENT_OPTIONS[0];
|
||||
const btn = $('btn-confirm-step1');
|
||||
const span = btn?.querySelector('span') ?? btn;
|
||||
const origText = span?.textContent;
|
||||
|
||||
// 1. 乐观 UI:禁用按钮防止重复提交
|
||||
if (btn) { btn.disabled = true; if (span) span.textContent = '…'; }
|
||||
|
||||
try {
|
||||
const res = await fetch(CONFIG.api.selectMethod(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({
|
||||
trade_id: ORDER.tradeId,
|
||||
token: opt.token.toLowerCase(),
|
||||
network: opt.network.toLowerCase(),
|
||||
}),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const resp = await res.json();
|
||||
const data = resp?.data ?? resp;
|
||||
|
||||
// 2. 用后端返回的完整订单字段更新 ORDER,本地选项作为兜底
|
||||
ORDER.tradeId = data?.trade_id ?? ORDER.tradeId;
|
||||
// 同步新 trade_id 到 URL(路径末段),轮询将自动使用最新值
|
||||
if (data?.trade_id) {
|
||||
const _url = new URL(window.location.href);
|
||||
_url.pathname = _url.pathname.replace(/\/[^/]+$/, '/' + encodeURIComponent(data.trade_id));
|
||||
history.replaceState(null, '', _url.toString());
|
||||
renderOrderId();
|
||||
}
|
||||
ORDER.token = data?.token ?? opt.token;
|
||||
ORDER.network = data?.network ?? opt.network;
|
||||
ORDER.actualAmount = data?.actual_amount != null ? String(data.actual_amount) : opt.actualAmount;
|
||||
ORDER.amount = data?.amount != null ? String(data.amount) : ORDER.amount;
|
||||
ORDER.currency = data?.currency ?? ORDER.currency;
|
||||
ORDER.receiveAddress = data?.receive_address ?? opt.receiveAddress;
|
||||
if (data?.expiration_time != null) ORDER.expirationTime = String(data.expiration_time);
|
||||
if (data?.created_at != null) ORDER.createdAt = String(data.created_at);
|
||||
if (data?.redirect_url) ORDER.redirectUrl = data.redirect_url;
|
||||
|
||||
setStepBar(2);
|
||||
slideTo('payment');
|
||||
initOrder();
|
||||
} catch (err) {
|
||||
console.error('[confirmStep1]', err);
|
||||
showToast('⚠ ' + (err.message || 'Request failed'));
|
||||
} finally {
|
||||
if (btn) { btn.disabled = false; if (span && origText) span.textContent = origText; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 9 — 订单渲染 & 倒计时
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
function truncateAddr(addr) {
|
||||
return addr && addr.length > 10 ? `${addr.slice(0, 4)}...${addr.slice(-6)}` : addr;
|
||||
}
|
||||
|
||||
function formatAddr(addr) {
|
||||
if (!addr || addr.length <= 10) return addr;
|
||||
return `<span style="font-weight:800;color:var(--primary)">${addr.slice(0, 4)}</span>`
|
||||
+ `<span style="color:var(--muted-foreground)">${addr.slice(4, -6)}</span>`
|
||||
+ `<span style="font-weight:800;color:var(--primary)">${addr.slice(-6)}</span>`;
|
||||
}
|
||||
|
||||
function renderRow(id, label, value) {
|
||||
const el = $(id);
|
||||
if (el) el.innerHTML = `
|
||||
<td style="width:1%;white-space:nowrap;padding-right:0.75em">${label}</td>
|
||||
<td style="color:var(--card-foreground);font-weight:500;word-break:break-all">${value}</td>`;
|
||||
}
|
||||
|
||||
function renderOrderId() {
|
||||
if (ORDER?.tradeId && !ORDER.tradeId.startsWith('{{')) {
|
||||
renderRow('display-order-id', t('order_id'), ORDER.tradeId);
|
||||
}
|
||||
}
|
||||
|
||||
function initOrder() {
|
||||
if (!ORDER?.tradeId || ORDER.tradeId.startsWith('{{')) { showNotFound(); return; }
|
||||
|
||||
setText('display-amount', `${ORDER.actualAmount} ${ORDER.token}`);
|
||||
setHtml('field-address', formatAddr(ORDER.receiveAddress));
|
||||
setHtml('display-network', networkTag(ORDER.network));
|
||||
|
||||
if (ORDER.amount && !ORDER.amount.startsWith('{{')) {
|
||||
renderRow('display-fiat', t('order_amount'), `${ORDER.amount} ${ORDER.currency || ''}`);
|
||||
}
|
||||
renderOrderId();
|
||||
|
||||
const qrcodeEl = $('qrcode');
|
||||
if (qrcodeEl) {
|
||||
new QRCode(qrcodeEl, {
|
||||
text: ORDER.receiveAddress,
|
||||
width: 176,
|
||||
height: 176,
|
||||
colorDark: '#111111',
|
||||
colorLight: '#ffffff',
|
||||
correctLevel: QRCode.CorrectLevel.M,
|
||||
});
|
||||
}
|
||||
|
||||
initCountdown();
|
||||
checkOrderStatus();
|
||||
initClipboard();
|
||||
}
|
||||
|
||||
// 倒计时内部状态
|
||||
const CIRCUMFERENCE = 2 * Math.PI * 20;
|
||||
const _pad = (n) => String(n).padStart(2, '0');
|
||||
let _countdownInterval = null;
|
||||
let _totalSeconds = 0;
|
||||
let _expiresAt = null;
|
||||
|
||||
function _lerpColor(a, b, ratio) {
|
||||
return `rgb(${[0,1,2].map(i => Math.round(a[i] + (b[i] - a[i]) * ratio)).join(',')})`;
|
||||
}
|
||||
function _ratioColor(ratio) {
|
||||
if (ratio >= 0.5) return '#22c55e';
|
||||
if (ratio >= 0.2) return _lerpColor([34,197,94], [249,115,22], (0.5 - ratio) / 0.3);
|
||||
return _lerpColor([249,115,22], [239,68,68], (0.2 - ratio) / 0.2);
|
||||
}
|
||||
|
||||
function initCountdown() {
|
||||
const parseTime = (raw) => new Date(/^\d+$/.test(String(raw)) ? Number(raw) : raw);
|
||||
_expiresAt = parseTime(ORDER.expirationTime);
|
||||
const remaining = Math.max(0, Math.round((_expiresAt - Date.now()) / 1000));
|
||||
if (remaining <= 0) { showExpired(); return; }
|
||||
|
||||
const created = parseTime(ORDER.createdAt);
|
||||
_totalSeconds = (!isNaN(created) && !isNaN(_expiresAt))
|
||||
? Math.max(1, Math.round((_expiresAt - created) / 1000))
|
||||
: 600;
|
||||
|
||||
$('ring').style.strokeDasharray = CIRCUMFERENCE;
|
||||
_expiresAt = new Date(_expiresAt.getTime() - 1000); // 避免初始渲染停顿
|
||||
_tickCountdown();
|
||||
_countdownInterval = setInterval(_tickCountdown, 1000);
|
||||
}
|
||||
|
||||
function _tickCountdown() {
|
||||
const remaining = Math.max(0, Math.round((_expiresAt - Date.now()) / 1000));
|
||||
const h = Math.floor(remaining / 3600);
|
||||
const m = Math.floor((remaining % 3600) / 60);
|
||||
const s = remaining % 60;
|
||||
const timeStr = h > 0 ? `${_pad(h)}:${_pad(m)}:${_pad(s)}` : `${_pad(m)}:${_pad(s)}`;
|
||||
const color = _ratioColor(_totalSeconds > 0 ? remaining / _totalSeconds : 0);
|
||||
const offset = CIRCUMFERENCE * (1 - (_totalSeconds > 0 ? remaining / _totalSeconds : 0));
|
||||
|
||||
$('countdown').textContent = timeStr;
|
||||
$('countdown').style.color = color;
|
||||
$('ring').style.stroke = color;
|
||||
$('ring').style.strokeDashoffset = offset;
|
||||
|
||||
const inlineEl = $('countdown-inline');
|
||||
if (inlineEl) { inlineEl.textContent = timeStr; inlineEl.style.color = color; }
|
||||
|
||||
if (remaining <= 0) { clearInterval(_countdownInterval); showExpired(); }
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 10 — API 轮询
|
||||
// 后端对接:修改 CONFIG.api.checkStatus 与 CONFIG.api.statusMap
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
let _pollTimer = null;
|
||||
let _pollStopped = false;
|
||||
let _pollErrors = 0;
|
||||
|
||||
function checkOrderStatus() {
|
||||
if (_pollStopped || !ORDER?.tradeId || ORDER.tradeId.startsWith('{{')) return;
|
||||
|
||||
fetch(CONFIG.api.checkStatus(ORDER.tradeId), {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(CONFIG.poll.timeout),
|
||||
})
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json();
|
||||
})
|
||||
.then(({ data }) => {
|
||||
_pollErrors = 0;
|
||||
const { paid, expired } = CONFIG.api.statusMap;
|
||||
if (data?.status === paid) onPaymentSuccess();
|
||||
else if (data?.status === expired) showExpired();
|
||||
else _scheduleNextPoll();
|
||||
})
|
||||
.catch(() => {
|
||||
if (++_pollErrors >= CONFIG.poll.maxErrors) showTimeout();
|
||||
else _scheduleNextPoll();
|
||||
});
|
||||
}
|
||||
|
||||
function _scheduleNextPoll() {
|
||||
if (!_pollStopped) _pollTimer = setTimeout(checkOrderStatus, CONFIG.poll.interval);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
_pollStopped = true;
|
||||
clearTimeout(_pollTimer);
|
||||
}
|
||||
|
||||
function retryPolling() {
|
||||
_pollErrors = 0;
|
||||
_pollStopped = false;
|
||||
hideStatePanel();
|
||||
checkOrderStatus();
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 11 — 支付状态处理
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
function onPaymentSuccess() {
|
||||
stopPolling();
|
||||
clearInterval(_countdownInterval);
|
||||
showStatePanel('success');
|
||||
if (ORDER?.redirectUrl && !ORDER.redirectUrl.startsWith('{{')) {
|
||||
setTimeout(() => { window.location.href = ORDER.redirectUrl; }, CONFIG.redirect.delay);
|
||||
}
|
||||
}
|
||||
|
||||
function showExpired() {
|
||||
stopPolling();
|
||||
clearInterval(_countdownInterval);
|
||||
const btn = $('btn-transferred');
|
||||
if (btn) btn.disabled = true;
|
||||
showStatePanel('expired');
|
||||
}
|
||||
|
||||
function showTimeout() {
|
||||
stopPolling();
|
||||
showStatePanel('timeout');
|
||||
}
|
||||
|
||||
function showNotFound() {
|
||||
stopPolling();
|
||||
clearInterval(_countdownInterval);
|
||||
const btn = $('btn-transferred');
|
||||
if (btn) btn.disabled = true;
|
||||
showStatePanel('not-found');
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 12 — 转账按钮 & 连接钱包
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
function handleTransfer() {
|
||||
const btn = $('btn-transferred');
|
||||
if (!btn) return;
|
||||
const span = btn.querySelector('span');
|
||||
if (!span) return;
|
||||
span.textContent = t('verifying');
|
||||
btn.disabled = true;
|
||||
_pollErrors = 0;
|
||||
_pollStopped = false;
|
||||
clearTimeout(_pollTimer);
|
||||
checkOrderStatus();
|
||||
setTimeout(() => {
|
||||
span.textContent = t('i_have_transferred');
|
||||
btn.disabled = false;
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
function connectWallet() {
|
||||
window.location.href = CONFIG.wallet.deeplink(window.location.href);
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SECTION 13 — 初始化入口
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
setLang(detectLang());
|
||||
|
||||
if (!ORDER?.tradeId || ORDER.tradeId.startsWith('{{')) {
|
||||
showNotFound();
|
||||
return;
|
||||
}
|
||||
|
||||
// 在 Step 1 阶段就填充订单信息卡片
|
||||
if (ORDER.amount && !ORDER.amount.startsWith('{{')) {
|
||||
renderRow('display-fiat', t('order_amount'), `${ORDER.amount} ${ORDER.currency || ''}`);
|
||||
setText('display-amount', `${ORDER.amount} ${ORDER.currency || ''}`);
|
||||
}
|
||||
renderOrderId();
|
||||
|
||||
// 确保 PAYMENT_OPTIONS 存在(服务端未注入时降级为内置默认选项)
|
||||
if (typeof PAYMENT_OPTIONS === 'undefined' || !Array.isArray(PAYMENT_OPTIONS) || !PAYMENT_OPTIONS.length) {
|
||||
window.PAYMENT_OPTIONS = [
|
||||
{ token: 'USDT', network: 'TRON', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
{ token: 'TRX', network: 'TRON', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
{ token: 'USDT', network: 'Solana', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
{ token: 'USDC', network: 'Solana', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
{ token: 'USDT', network: 'Ethereum', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
{ token: 'USDC', network: 'Ethereum', actualAmount: ORDER.actualAmount, receiveAddress: ORDER.receiveAddress },
|
||||
];
|
||||
}
|
||||
|
||||
// isselect=true 时跳过 Step 1,直接进入支付面板
|
||||
const _isSelect = ORDER.is_selected && ORDER.is_selected !== 'false' && !ORDER.is_selected.startsWith('{{');
|
||||
if (_isSelect) {
|
||||
$('step1-panel').style.display = 'none';
|
||||
$('payment-panel').style.display = '';
|
||||
_currentPanel = 'payment';
|
||||
setStepBar(2);
|
||||
initOrder();
|
||||
} else {
|
||||
initStep1();
|
||||
setStepBar(1);
|
||||
}
|
||||
|
||||
// 连接钱包按钮开关
|
||||
const walletBtn = $('btn-connect-wallet');
|
||||
if (walletBtn) walletBtn.style.display = CONFIG.wallet.enabled ? '' : 'none';
|
||||
});
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
html, body, div, span, applet, object, iframe,
|
||||
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
|
||||
a, abbr, acronym, address, big, cite, code,
|
||||
del, dfn, em, img, ins, kbd, q, s, samp,
|
||||
small, strike, strong, sub, sup, tt, var,
|
||||
b, u, i, center,
|
||||
dl, dt, dd, ol, ul, li,
|
||||
fieldset, form, label, legend,
|
||||
table, caption, tbody, tfoot, thead, tr, th, td,
|
||||
article, aside, canvas, details, embed,
|
||||
figure, figcaption, footer, header, hgroup,
|
||||
menu, nav, output, ruby, section, summary,
|
||||
time, mark, audio, video {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
font-size: 100%;
|
||||
font: inherit;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
/* HTML5 display-role reset for older browsers */
|
||||
article, aside, details, figcaption, figure,
|
||||
footer, header, hgroup, menu, nav, section {
|
||||
display: block;
|
||||
}
|
||||
body {
|
||||
line-height: 1;
|
||||
background-color: #fafbfc;
|
||||
}
|
||||
ol, ul {
|
||||
list-style: none;
|
||||
}
|
||||
blockquote, q {
|
||||
quotes: none;
|
||||
}
|
||||
blockquote:before, blockquote:after,
|
||||
q:before, q:after {
|
||||
content: '';
|
||||
content: none;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
border-spacing: 0;
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
|
||||
func Start() {
|
||||
log.Sugar.Info("[task] Starting task scheduler...")
|
||||
go StartEthereumWebSocketListener()
|
||||
|
||||
c := cron.New()
|
||||
// trc20钱包监听
|
||||
_, err := c.AddJob("@every 5s", ListenTrc20Job{})
|
||||
@@ -15,6 +17,13 @@ func Start() {
|
||||
return
|
||||
}
|
||||
log.Sugar.Info("[task] ListenTrc20Job scheduled successfully (@every 5s)")
|
||||
// solana钱包监听
|
||||
_, err = c.AddJob("@every 5s", ListenSolJob{})
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[task] Failed to add ListenSolJob: %v", err)
|
||||
return
|
||||
}
|
||||
log.Sugar.Info("[task] ListenSolJob scheduled successfully (@every 5s)")
|
||||
c.Start()
|
||||
log.Sugar.Info("[task] Task scheduler started")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/assimon/luuu/model/data"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/model/service"
|
||||
"github.com/assimon/luuu/util/log"
|
||||
|
||||
"github.com/ethereum/go-ethereum"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/ethclient"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
// USDT / USDC 合约地址(ETH 主网)
|
||||
usdtContract = common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7")
|
||||
usdcContract = common.HexToAddress("0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
|
||||
|
||||
// Transfer 事件签名
|
||||
transferEventHash = common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")
|
||||
)
|
||||
|
||||
type ethRecipientSnapshot struct {
|
||||
addrs map[string]struct{}
|
||||
}
|
||||
|
||||
var ethWatchedRecipients atomic.Pointer[ethRecipientSnapshot]
|
||||
|
||||
func StartEthereumWebSocketListener() {
|
||||
wallets, err := data.GetAvailableWalletAddressByNetwork(mdb.NetworkEthereum)
|
||||
if err != nil {
|
||||
log.Sugar.Fatalf("Failed to get wallet addresses: %v", err)
|
||||
return
|
||||
}
|
||||
StoreEthRecipientsFromWallets(wallets)
|
||||
go func() {
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
w, err := data.GetAvailableWalletAddressByNetwork(mdb.NetworkEthereum)
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[ETH-WS] refresh wallet addresses: %v", err)
|
||||
continue
|
||||
}
|
||||
StoreEthRecipientsFromWallets(w)
|
||||
}
|
||||
}()
|
||||
wsURL := "wss://ethereum.publicnode.com"
|
||||
|
||||
client, err := ethclient.Dial(wsURL)
|
||||
if err != nil {
|
||||
log.Sugar.Fatal("连接失败:", err)
|
||||
}
|
||||
|
||||
// 创建日志通道
|
||||
logsCh := make(chan types.Log)
|
||||
|
||||
// 订阅条件
|
||||
query := ethereum.FilterQuery{
|
||||
Addresses: []common.Address{
|
||||
usdtContract,
|
||||
usdcContract,
|
||||
},
|
||||
Topics: [][]common.Hash{},
|
||||
}
|
||||
|
||||
// 订阅日志(核心)
|
||||
sub, err := client.SubscribeFilterLogs(context.Background(), query, logsCh)
|
||||
if err != nil {
|
||||
log.Sugar.Fatal("订阅失败:", err)
|
||||
}
|
||||
|
||||
fmt.Println("🚀 开始监听 USDT / USDC 收款...")
|
||||
|
||||
for {
|
||||
select {
|
||||
case err := <-sub.Err():
|
||||
log.Sugar.Fatal("订阅错误:", err)
|
||||
|
||||
case vLog := <-logsCh:
|
||||
|
||||
// topics:
|
||||
// [0] Transfer event
|
||||
// [1] from
|
||||
// [2] to
|
||||
if len(vLog.Topics) < 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
event := vLog.Topics[0].String()
|
||||
if event != transferEventHash.String() {
|
||||
continue
|
||||
}
|
||||
|
||||
// value from data
|
||||
amount := new(big.Int).SetBytes(vLog.Data)
|
||||
|
||||
|
||||
if event != transferEventHash.String() {
|
||||
continue
|
||||
}
|
||||
toAddr := common.HexToAddress(vLog.Topics[2].Hex())
|
||||
|
||||
if !isWatchedEthRecipient(toAddr) {
|
||||
continue
|
||||
}
|
||||
|
||||
var blockTsMs int64
|
||||
header, err := client.HeaderByNumber(context.Background(), big.NewInt(int64(vLog.BlockNumber)))
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[ETH-WS] HeaderByNumber block=%d: %v, using local time", vLog.BlockNumber, err)
|
||||
blockTsMs = time.Now().UnixMilli()
|
||||
} else {
|
||||
blockTsMs = int64(header.Time) * 1000
|
||||
}
|
||||
|
||||
service.TryProcessEthereumERC20Transfer(vLog.Address, toAddr, amount, vLog.TxHash.Hex(), blockTsMs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StoreEthRecipientsFromWallets(wallets []mdb.WalletAddress) int {
|
||||
m := make(map[string]struct{})
|
||||
for _, w := range wallets {
|
||||
a := strings.TrimSpace(w.Address)
|
||||
if !common.IsHexAddress(a) {
|
||||
continue
|
||||
}
|
||||
m[strings.ToLower(common.HexToAddress(a).Hex())] = struct{}{}
|
||||
}
|
||||
ethWatchedRecipients.Store(ðRecipientSnapshot{addrs: m})
|
||||
return len(m)
|
||||
}
|
||||
|
||||
func isWatchedEthRecipient(to common.Address) bool {
|
||||
snap := ethWatchedRecipients.Load()
|
||||
if snap == nil || len(snap.addrs) == 0 {
|
||||
return false
|
||||
}
|
||||
_, ok := snap.addrs[strings.ToLower(to.Hex())]
|
||||
return ok
|
||||
}
|
||||
|
||||
func formatAmount(amount *big.Int, decimals int) string {
|
||||
f := new(big.Float).SetInt(amount)
|
||||
divisor := new(big.Float).SetFloat64(float64Pow(10, decimals))
|
||||
result := new(big.Float).Quo(f, divisor)
|
||||
|
||||
return result.Text('f', 6)
|
||||
}
|
||||
|
||||
func float64Pow(a, b int) float64 {
|
||||
result := 1.0
|
||||
for i := 0; i < b; i++ {
|
||||
result *= float64(a)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/assimon/luuu/model/data"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/model/service"
|
||||
"github.com/assimon/luuu/util/log"
|
||||
)
|
||||
|
||||
type ListenSolJob struct{}
|
||||
|
||||
var gListenSolJobLock sync.Mutex
|
||||
|
||||
func (r ListenSolJob) Run() {
|
||||
gListenSolJobLock.Lock()
|
||||
defer gListenSolJobLock.Unlock()
|
||||
log.Sugar.Debug("[ListenSolJob] Job triggered")
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(mdb.NetworkSolana)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[ListenSolJob] Failed to get wallet addresses: %v", err)
|
||||
return
|
||||
}
|
||||
if len(walletAddress) <= 0 {
|
||||
log.Sugar.Debug("[ListenSolJob] No available wallet addresses")
|
||||
return
|
||||
}
|
||||
log.Sugar.Infof("[ListenSolJob] Found %d wallet addresses to monitor", len(walletAddress))
|
||||
var wg sync.WaitGroup
|
||||
for _, address := range walletAddress {
|
||||
log.Sugar.Infof("[ListenSolJob] Listening to address: %s", address.Address)
|
||||
wg.Add(1)
|
||||
go service.SolCallBack(address.Address, &wg)
|
||||
}
|
||||
wg.Wait()
|
||||
log.Sugar.Debug("[ListenSolJob] Job completed")
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/assimon/luuu/model/data"
|
||||
"github.com/assimon/luuu/model/mdb"
|
||||
"github.com/assimon/luuu/model/service"
|
||||
"github.com/assimon/luuu/util/log"
|
||||
)
|
||||
|
||||
type ListenTrc20Job struct {
|
||||
}
|
||||
type ListenTrc20Job struct{}
|
||||
|
||||
var gListenTrc20JobLock sync.Mutex
|
||||
|
||||
@@ -17,7 +17,7 @@ func (r ListenTrc20Job) Run() {
|
||||
gListenTrc20JobLock.Lock()
|
||||
defer gListenTrc20JobLock.Unlock()
|
||||
log.Sugar.Debug("[ListenTrc20Job] Job triggered")
|
||||
walletAddress, err := data.GetAvailableWalletAddress()
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(mdb.NetworkTron)
|
||||
if err != nil {
|
||||
log.Sugar.Errorf("[ListenTrc20Job] Failed to get wallet addresses: %v", err)
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -13,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
ReplayAddWallet = "请发给我一个合法的钱包地址"
|
||||
ReplayAddWallet = "请发给我 TRON(T 开头)、以太坊主网(0x 开头)或 Solana 收款地址"
|
||||
pendingWalletAddressTTL = 5 * time.Minute
|
||||
)
|
||||
|
||||
@@ -45,13 +46,19 @@ func OnTextMessageHandle(c tb.Context) error {
|
||||
defer bots.Delete(msg.ReplyTo)
|
||||
}
|
||||
|
||||
msgText := msg.Text
|
||||
if !isValidTronAddress(msgText) {
|
||||
_ = c.Send(fmt.Sprintf("钱包 [%s] 添加失败:不是合法的 TRON 地址", msgText))
|
||||
msgText := strings.TrimSpace(msg.Text)
|
||||
var err error
|
||||
switch {
|
||||
case isValidTronAddress(msgText):
|
||||
_, err = data.AddWalletAddress(msgText)
|
||||
case isValidEthereumAddress(msgText):
|
||||
_, err = data.AddWalletAddressWithNetwork(mdb.NetworkEthereum, strings.ToLower(msgText))
|
||||
case isValidSolanaAddress(msgText):
|
||||
_, err = data.AddWalletAddressWithNetwork(mdb.NetworkSolana, msgText)
|
||||
default:
|
||||
_ = c.Send(fmt.Sprintf("钱包 [%s] 添加失败:不是合法的 TRON、以太坊或 Solana 地址", msgText))
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err := data.AddWalletAddress(msgText)
|
||||
if err != nil {
|
||||
return c.Send(err.Error())
|
||||
}
|
||||
@@ -73,10 +80,14 @@ func WalletList(c tb.Context) error {
|
||||
if wallet.Status == mdb.TokenStatusDisable {
|
||||
status = "已禁用🚫"
|
||||
}
|
||||
net := wallet.Network
|
||||
if net == "" {
|
||||
net = mdb.NetworkTron
|
||||
}
|
||||
|
||||
btnInfo := tb.InlineButton{
|
||||
Unique: wallet.Address,
|
||||
Text: fmt.Sprintf("%s [%s]", wallet.Address, status),
|
||||
Text: fmt.Sprintf("[%s] %s [%s]", net, wallet.Address, status),
|
||||
Data: strutil.MustString(wallet.ID),
|
||||
}
|
||||
bots.Handle(&btnInfo, WalletInfo)
|
||||
@@ -131,7 +142,12 @@ func WalletInfo(c tb.Context) error {
|
||||
bots.Handle(&delBtn, DelWallet)
|
||||
bots.Handle(&backBtn, WalletList)
|
||||
|
||||
return c.EditOrReply(tokenInfo.Address, &tb.ReplyMarkup{InlineKeyboard: [][]tb.InlineButton{
|
||||
net := tokenInfo.Network
|
||||
if net == "" {
|
||||
net = mdb.NetworkTron
|
||||
}
|
||||
detail := fmt.Sprintf("网络:%s\n地址:%s", net, tokenInfo.Address)
|
||||
return c.EditOrReply(detail, &tb.ReplyMarkup{InlineKeyboard: [][]tb.InlineButton{
|
||||
{
|
||||
enableBtn,
|
||||
disableBtn,
|
||||
|
||||
@@ -2,10 +2,23 @@ package telegram
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"github.com/btcsuite/btcutil/base58"
|
||||
"github.com/gagliardetto/solana-go"
|
||||
)
|
||||
|
||||
// isValidEthereumAddress 校验 0x + 20 字节十六进制(主网收款)。
|
||||
func isValidEthereumAddress(addr string) bool {
|
||||
addr = strings.TrimSpace(addr)
|
||||
if len(addr) != 42 || !strings.HasPrefix(addr, "0x") {
|
||||
return false
|
||||
}
|
||||
_, err := hex.DecodeString(addr[2:])
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// isValidTronAddress 校验 Tron Base58Check 地址是否合法
|
||||
func isValidTronAddress(addr string) bool {
|
||||
// 基本过滤
|
||||
@@ -32,3 +45,13 @@ func isValidTronAddress(addr string) bool {
|
||||
|
||||
return string(checksum) == string(hash2[:4])
|
||||
}
|
||||
|
||||
// isValidSolanaAddress 校验 Solana Base58 地址是否合法(32 字节公钥)。
|
||||
func isValidSolanaAddress(addr string) bool {
|
||||
addr = strings.TrimSpace(addr)
|
||||
if len(addr) < 32 || len(addr) > 44 {
|
||||
return false
|
||||
}
|
||||
_, err := solana.PublicKeyFromBase58(addr)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ var Errno = map[int]string{
|
||||
10008: "order does not exist",
|
||||
10009: "failed to parse request params",
|
||||
10010: "order status already changed",
|
||||
10011: "exceeded maximum sub-order limit",
|
||||
10012: "cannot switch network on a sub-order",
|
||||
10013: "order is not awaiting payment",
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -28,6 +31,9 @@ var (
|
||||
OrderNotExists = Err(10008)
|
||||
ParamsMarshalErr = Err(10009)
|
||||
OrderStatusConflict = Err(10010)
|
||||
SubOrderLimitExceeded = Err(10011)
|
||||
CannotSwitchSubOrder = Err(10012)
|
||||
OrderNotWaitPay = Err(10013)
|
||||
)
|
||||
|
||||
type RspError struct {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# API 变更文档
|
||||
|
||||
## 概述
|
||||
|
||||
## 后台配置说明(重要)
|
||||
|
||||
### 对于 dujiaoka 用户
|
||||
|
||||
**只需要修改一个地方**:在 dujiaoka 后台支付插件配置中,将 API 地址前缀从 `/api` 改为 `/payments/epusdt` 即可。
|
||||
|
||||
**示例**:
|
||||
|
||||
```
|
||||
旧配置:https://your-domain.com/api/v1/order/create-transaction
|
||||
新配置:https://your-domain.com/payments/epusdt/v1/order/create-transaction
|
||||
```
|
||||
|
||||
**就这么简单!** 其他配置(密钥、回调地址等)完全不需要修改。
|
||||
|
||||
---
|
||||
|
||||
## 路由变更对照表
|
||||
|
||||
### API 路由
|
||||
|
||||
| 原路由 | 新路由 | 说明 |
|
||||
|--------|--------|------|
|
||||
| `POST /api/v1/order/create-transaction` | `POST /payments/epusdt/v1/order/create-transaction` | 创建交易订单 |
|
||||
|
||||
|
||||
## 新增配置项说明
|
||||
|
||||
本次更新新增了以下配置项(位于 `src/.env.example` 文件):
|
||||
|
||||
### 1. `api_rate_url` - 汇率接口 URL
|
||||
|
||||
用于获取实时汇率的 API 地址。系统会根据此接口动态获取不同币种的汇率。
|
||||
|
||||
```bash
|
||||
# 汇率接口url
|
||||
api_rate_url=https://your-rate-api.com/
|
||||
```
|
||||
|
||||
**API 格式要求**:
|
||||
|
||||
系统会请求 `{api_rate_url}/{currency}.json`,例如:
|
||||
- `https://your-rate-api.com/cny.json`
|
||||
- `https://your-rate-api.com/usd.json`
|
||||
|
||||
**返回格式示例**:
|
||||
|
||||
```json
|
||||
{
|
||||
"cny": {
|
||||
"usdt": 0.1389,
|
||||
"trx": 0.0123
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
其中 `0.1389` 表示 1 CNY = 0.1389 USDT(即 1 USDT ≈ 7.2 CNY)
|
||||
|
||||
**说明**:
|
||||
- 支持自建汇率 API,只需按照上述格式返回数据即可
|
||||
|
||||
### 2. `tron_grid_api_key` - TRON Grid API Key
|
||||
|
||||
TRON Grid API 密钥,用于提高 API 请求限制和稳定性。
|
||||
|
||||
```bash
|
||||
tron_grid_api_key=
|
||||
```
|
||||
|
||||
**如何获取 API Key**:
|
||||
|
||||
1. 访问 [https://www.trongrid.io/](https://www.trongrid.io/)
|
||||
2. 注册账号并登录
|
||||
3. 在控制台创建 API Key
|
||||
4. 将 API Key 填入配置文件
|
||||
|
||||
**为什么需要 API Key**:
|
||||
|
||||
- ✅ **提高请求限制**:免费账号有更高的 API 调用配额
|
||||
- ✅ **更好的稳定性**:避免公共 API 的限流问题
|
||||
- ✅ **支持更多功能**:为后续支持 TRX 等其他代币做准备
|
||||
|
||||
### 配置示例
|
||||
|
||||
`.env` 配置示例:
|
||||
|
||||
```bash
|
||||
# 订单过期时间(分钟)
|
||||
order_expiration_time=15
|
||||
|
||||
# 订单回调失败最大重试次数
|
||||
order_notice_max_retry=0
|
||||
|
||||
# 汇率接口url(动态获取汇率)
|
||||
api_rate_url=
|
||||
|
||||
# TRON Grid API Key(推荐配置)
|
||||
tron_grid_api_key=your-api-key-here
|
||||
```
|
||||
@@ -0,0 +1,104 @@
|
||||
1. 创建和进去这个目录
|
||||
```shell
|
||||
mkdir epusdt && cd epusdt
|
||||
```
|
||||
|
||||
2. 把配置文件放进去这个目录,只需要改
|
||||
|
||||
app_url
|
||||
|
||||
tron_grid_api_key
|
||||
|
||||
api_rate_url
|
||||
|
||||
```shell
|
||||
cat <<EOF > env
|
||||
app_name=epusdt
|
||||
app_uri=https://dujiaoka.com
|
||||
log_level=info
|
||||
http_access_log=false
|
||||
sql_debug=false
|
||||
http_listen=:8000
|
||||
|
||||
static_path=/static
|
||||
runtime_root_path=/runtime
|
||||
|
||||
log_save_path=/logs
|
||||
log_max_size=32
|
||||
log_max_age=7
|
||||
max_backups=3
|
||||
|
||||
# supported values: postgres,mysql,sqlite
|
||||
db_type=sqlite
|
||||
|
||||
# sqlite primary database config
|
||||
sqlite_database_filename=
|
||||
sqlite_table_prefix=
|
||||
|
||||
# postgres config
|
||||
postgres_host=127.0.0.1
|
||||
postgres_port=3306
|
||||
postgres_user=mysql_user
|
||||
postgres_passwd=mysql_password
|
||||
postgres_database=database_name
|
||||
postgres_table_prefix=
|
||||
postgres_max_idle_conns=10
|
||||
postgres_max_open_conns=100
|
||||
postgres_max_life_time=6
|
||||
|
||||
# mysql config
|
||||
mysql_host=127.0.0.1
|
||||
mysql_port=3306
|
||||
mysql_user=mysql_user
|
||||
mysql_passwd=mysql_password
|
||||
mysql_database=database_name
|
||||
mysql_table_prefix=
|
||||
mysql_max_idle_conns=10
|
||||
mysql_max_open_conns=100
|
||||
mysql_max_life_time=6
|
||||
|
||||
# sqlite runtime store config
|
||||
runtime_sqlite_filename=epusdt-runtime.db
|
||||
|
||||
# background scheduler config
|
||||
queue_concurrency=10
|
||||
queue_poll_interval_ms=1000
|
||||
callback_retry_base_seconds=5
|
||||
|
||||
tg_bot_token=
|
||||
tg_proxy=
|
||||
tg_manage=
|
||||
|
||||
api_auth_token=
|
||||
|
||||
order_expiration_time=10
|
||||
order_notice_max_retry=0
|
||||
forced_usdt_rate=
|
||||
api_rate_url=https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/
|
||||
tron_grid_api_key=
|
||||
EOF
|
||||
```
|
||||
3. docker compose 创建
|
||||
```shell
|
||||
cat <<EOF > docker-compose.yaml
|
||||
services:
|
||||
epusdt:
|
||||
image: gmwallet/epusdt:alpine
|
||||
restart: always
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
volumes:
|
||||
- ./env:/app/.env
|
||||
ports:
|
||||
- "8000:8000"
|
||||
EOF
|
||||
```
|
||||
4. 运行
|
||||
```shell
|
||||
docker compose up -d
|
||||
```
|
||||
5. 配置独角兽后台
|
||||
|
||||
商户密钥: http://your_domain/payments/epusdt/v1/order/create-transaction
|
||||
|
||||