Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1cd01f7c8 | ||
|
|
507f201bd6 | ||
|
|
a7c6618437 | ||
|
|
0b8adb2ab4 | ||
|
|
0ef12745ea | ||
|
|
2988a6f1f4 | ||
|
|
ecd3a3983c | ||
|
|
34c005a3ab | ||
|
|
bfcfcc2f3c | ||
|
|
9d65fceaa9 | ||
|
|
bf5ff0fc5c | ||
|
|
98eedf378d | ||
|
|
99c9557ab3 | ||
|
|
a2b072d4be | ||
|
|
866d4ce193 | ||
|
|
b2d97b09a1 | ||
|
|
0680a3829a | ||
|
|
9aed022d43 | ||
|
|
dc4ef18526 | ||
|
|
a45f51be6f | ||
|
|
b098246a6f |
@@ -1,37 +0,0 @@
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = ["-conf", "/usr/local/bepusdt/conf.toml"]
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main -trimpath -ldflags \"-s -w -buildid=\" ./main"
|
||||
delay = 3000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
send_interrupt = false
|
||||
stop_on_error = true
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
@@ -6,52 +6,25 @@ on:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
BUILD_DIR: build_assets
|
||||
jobs:
|
||||
build-release:
|
||||
strategy:
|
||||
matrix:
|
||||
goos: [ linux ]
|
||||
goarch: [ amd64,arm64 ]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- name: Show workflow information
|
||||
id: get_filename
|
||||
run: |
|
||||
export _NAME=$GOOS-$GOARCH
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
|
||||
echo "OS_ARCH=$_NAME" >> $GITHUB_ENV
|
||||
fetch-depth: 0
|
||||
- name: Git Fetch Tags
|
||||
run: git fetch --force --tags
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.24.3
|
||||
- name: Get project dependencies
|
||||
run: go mod download
|
||||
- name: Build
|
||||
run: |
|
||||
export CGO_ENABLED=0
|
||||
mkdir -p ${{ env.BUILD_DIR }}
|
||||
go build -v -o ${{ env.BUILD_DIR }}/${{ env.APP_NAME }} -trimpath -ldflags "-s -w -buildid=" ./main
|
||||
- name: Prepare package
|
||||
run: |
|
||||
cp -v ./docs/${{ env.APP_NAME }}.service ./${{ env.BUILD_DIR }}
|
||||
cp -v ./conf.example.toml ./${{ env.BUILD_DIR }}
|
||||
mv -v ./${{ env.BUILD_DIR }} ./${{ env.APP_NAME }}
|
||||
- name: Archive
|
||||
run: zip -9vr ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip ./${{ env.APP_NAME }}
|
||||
- name: Upload files to GitHub release
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
go-version: '1.24.3'
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip
|
||||
tag: ${{ github.ref }}
|
||||
distribution: goreleaser
|
||||
version: latest
|
||||
args: release --clean --verbose
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,4 +1,7 @@
|
||||
tmp
|
||||
.air.toml
|
||||
.DS_Store
|
||||
.idea
|
||||
conf.toml
|
||||
conf.toml
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
version: 2
|
||||
project_name: BEpusdt
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
main: ./main
|
||||
binary: bepusdt
|
||||
ldflags:
|
||||
- s -w -buildid=
|
||||
goos:
|
||||
- windows
|
||||
- linux
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
archives:
|
||||
- formats: [ tar.gz ]
|
||||
name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats: [ zip ]
|
||||
files:
|
||||
- conf.example.toml
|
||||
- conf.simple.toml
|
||||
- src: docs/bepusdt.service
|
||||
dst: .
|
||||
strip_parent: true
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^docs:"
|
||||
- "^test:"
|
||||
release:
|
||||
footer: >-
|
||||
|
||||
---
|
||||
|
||||
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
|
||||
@@ -23,7 +23,10 @@
|
||||
|
||||
## 🎉 新特性
|
||||
|
||||
**🌟 目前支持收款类型:trx usdt.trc20 usdt.bep20(币安) usdt.erc20(以太) usdt.polygon usdt.xlayer(OKX)**
|
||||
### 🌟 目前支持收款类型
|
||||
|
||||
🔥 主流网络:TRON(`trx` `usdt.trc20`) Ethereum(`usdt.erc20`) BSC(`usdt.bep20`)
|
||||
⚡ 其他网络:Polygon(`usdt.polygon`) X-Layer(`usdt.xlayer`) Solana(`usdt.solana`) Aptos(`usdt.aptos`)
|
||||
|
||||
- ✅ 完全兼容 `Epusdt`,插件可无缝替换
|
||||
- ✅ 实时同步 USDT 汇率,支持自定义浮动
|
||||
@@ -39,17 +42,10 @@
|
||||
|
||||
## 🚀 安装部署
|
||||
|
||||
- [Docker 安装教程(推荐🔥)](./docs/docker.md)
|
||||
- [异次元发卡对接教程 🌟](./docs/acg-faka.md)
|
||||
- [萌次元商城系统对接 🌟](./docs/mcy-shop.md)
|
||||
- [独角数卡对接教程 🌟](./docs/dujiaoka.md)
|
||||
- [https 配置教程](./docs/ssl.md)
|
||||
- [Linux 手动安装教程](./docs/systemd.md)
|
||||
- [Linux 时钟同步配置](./docs/systemd-timesyncd.md)
|
||||
- [彩虹易支付对接教程](./docs/epay.md)
|
||||
- [API 对接开发签名算法](./docs/sign.md)
|
||||
- [对接 回调通知说明](./docs/notify-epusdt.md)
|
||||
- [Webhook 事件回调](./docs/webhook.md)
|
||||
- 安装:[Docker](./docs/docker.md)・[Linux](./docs/systemd.md)・1Panel・宝塔
|
||||
- 对接:[独角数卡](./docs/dujiaoka.md)・[异次元](./docs/acg-faka.md)・[萌次元](./docs/mcy-shop.md)・[彩虹易支付](https://github.com/v03413/Epay-BEpusdt)
|
||||
- 开发:[API对接](./docs/api.md)・[订单回调](./docs/notify-epusdt.md)・[Webhook 事件](./docs/webhook.md)
|
||||
- 其它:[https 配置](./docs/ssl.md)・[Linux 时钟同步](./docs/systemd-timesyncd.md)
|
||||
|
||||
## 🖼 功能截图
|
||||
|
||||
@@ -66,107 +62,6 @@ Telegram 搜索加入群`@BEpusdtChat`,随后发送命令`/info`,返回的`I
|
||||
- 订单交易强依赖时间,请确保服务器时间准确性,否则可能导致订单异常!
|
||||
- 部分功能依赖网络,请确保服务器网络纯洁性,否则可能导致功能异常!
|
||||
|
||||
## 📚 接口文档
|
||||
|
||||
<details>
|
||||
<summary>创建订单</summary>
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/create-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 可根据实际情况传入收款地址,亦可留空
|
||||
"trade_type": "usdt.trc20", // usdt.trc20(默认) tron.trx 可选列表 https://github.com/v03413/bepusdt/blob/16d8df2cc5acc3d41c1c014ecb5370bd97f7e955/app/model/orders.go#L25:L30
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": 28.88, // 请求支付金额,CNY
|
||||
"signature":"123456abcd", // 签名
|
||||
"notify_url": "https://example.com/callback", // 回调地址
|
||||
"redirect_url": "https://example.com/callback", // 支付成功跳转地址
|
||||
"timeout": 1200 // 超时时间(秒) 最低60;留空则取配置文件 expire_time,还是没有取默认600
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415", // 本地交易ID
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": "28.88", // 请求支付金额,CNY
|
||||
"actual_amount": "10", // 实际支付数额 usdt or trx
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 收款地址
|
||||
"expiration_time": 1200, // 订单有效期,秒
|
||||
"payment_url": "https://example.com//pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415" // 收银台地址
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>取消订单</summary>
|
||||
|
||||
商户端系统可以通过此接口取消订单,取消后,系统将不再监控此订单,同时释放对应金额占用。
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/cancel-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ", // 交易ID
|
||||
"signature":"123456abcd" // 签名内容
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ"
|
||||
},
|
||||
"message": "success",
|
||||
"request_id": "",
|
||||
"status_code": 200
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>回调通知</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415",
|
||||
"order_id": "787240927112940881",
|
||||
"amount": 28.88,
|
||||
"actual_amount": 10,
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"block_transaction_id": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"signature": "123456abcd",
|
||||
"status": 2 // 1:等待支付 2:支付成功 3:支付超时
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 🏝️ 交流反馈
|
||||
|
||||
- Telegram 群组:[https://t.me/BEpusdtChat](https://t.me/BEpusdtChat)
|
||||
|
||||
@@ -55,7 +55,8 @@ func Start() {
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressDisable, bot.MatchTypePrefix, cbAddressDisableAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressOtherNotify, bot.MatchTypePrefix, cbAddressOtherNotifyAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbMarkNotifySucc, bot.MatchTypePrefix, cbMarkNotifySuccAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, dbOrderNotifyRetry, bot.MatchTypePrefix, dbOrderNotifyRetryAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbOrderNotifyRetry, bot.MatchTypePrefix, dbOrderNotifyRetryAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbOrderList, bot.MatchTypePrefix, cbOrderListAction)
|
||||
}
|
||||
|
||||
_, err = api.SetMyCommands(ctx, &bot.SetMyCommandsParams{
|
||||
@@ -63,7 +64,7 @@ func Start() {
|
||||
{Command: cmdGetId, Description: "获取ID"},
|
||||
{Command: cmdStart, Description: "开始使用"},
|
||||
{Command: cmdState, Description: "收款状态"},
|
||||
{Command: cmdOrder, Description: "最近订单"},
|
||||
{Command: cmdOrder, Description: "订单列表"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
@@ -116,3 +117,11 @@ func EditMessageText(ctx context.Context, b *bot.Bot, p *bot.EditMessageTextPara
|
||||
log.Warn("BotEditMessageText Error:", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func EditMessageReplyMarkup(ctx context.Context, b *bot.Bot, p *bot.EditMessageReplyMarkupParams) {
|
||||
_, err := b.EditMessageReplyMarkup(ctx, p)
|
||||
if err != nil {
|
||||
|
||||
log.Warn("BotEditMessageReplyMarkup Error:", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,8 +32,9 @@ const cbAddressDelete = "address_del"
|
||||
const cbAddressBack = "address_back"
|
||||
const cbAddressOtherNotify = "address_other_notify"
|
||||
const cbOrderDetail = "order_detail"
|
||||
const cbOrderList = "order_list"
|
||||
const cbMarkNotifySucc = "mark_notify_succ"
|
||||
const dbOrderNotifyRetry = "order_notify_retry"
|
||||
const cbOrderNotifyRetry = "order_notify_retry"
|
||||
|
||||
func cbWalletAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var address = ctx.Value("args").([]string)[1]
|
||||
@@ -214,74 +215,112 @@ func cbAddressOtherNotifyAction(ctx context.Context, b *bot.Bot, u *models.Updat
|
||||
}
|
||||
|
||||
func cbOrderDetailAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var args = ctx.Value("args").([]string)
|
||||
|
||||
var o model.TradeOrders
|
||||
|
||||
if model.DB.Where("trade_id = ?", args[1]).First(&o).Error != nil {
|
||||
args := ctx.Value("args").([]string)
|
||||
if len(args) < 2 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var urlInfo, er2 = url.Parse(o.NotifyUrl)
|
||||
if er2 != nil {
|
||||
log.Error("商户网站地址解析错误:" + er2.Error())
|
||||
var order model.TradeOrders
|
||||
if err := model.DB.Where("trade_id = ?", args[1]).First(&order).Error; err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var notifyStateLabel = "✅回调成功"
|
||||
if o.NotifyState != model.OrderNotifyStateSucc {
|
||||
urlInfo, err := url.Parse(order.NotifyUrl)
|
||||
if err != nil {
|
||||
log.Error("商户网站地址解析错误:" + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 确定回调状态标签
|
||||
var notifyStateLabel string
|
||||
switch {
|
||||
case order.Status == model.OrderStatusWaiting:
|
||||
notifyStateLabel = order.GetStatusLabel()
|
||||
case order.Status == model.OrderStatusExpired:
|
||||
notifyStateLabel = "🈚️没有回调"
|
||||
case order.NotifyState == model.OrderNotifyStateSucc:
|
||||
notifyStateLabel = "✅回调成功"
|
||||
default:
|
||||
notifyStateLabel = "❌回调失败"
|
||||
}
|
||||
if model.OrderStatusWaiting == o.Status {
|
||||
notifyStateLabel = o.GetStatusLabel()
|
||||
}
|
||||
if model.OrderStatusExpired == o.Status {
|
||||
notifyStateLabel = "🈚️没有回调"
|
||||
}
|
||||
|
||||
var site = &url.URL{Scheme: urlInfo.Scheme, Host: urlInfo.Host}
|
||||
var markup = models.InlineKeyboardMarkup{
|
||||
site := &url.URL{Scheme: urlInfo.Scheme, Host: urlInfo.Host}
|
||||
markup := models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "🌏商户网站", URL: site.String()},
|
||||
models.InlineKeyboardButton{Text: "📝交易明细", URL: o.GetDetailUrl()},
|
||||
{Text: "🌏商户网站", URL: site.String()},
|
||||
{Text: "📝交易明细", URL: order.GetDetailUrl()},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if o.Status == model.OrderStatusSuccess && o.NotifyState == model.OrderNotifyStateFail {
|
||||
if order.Status == model.OrderStatusSuccess && order.NotifyState == model.OrderNotifyStateFail {
|
||||
markup.InlineKeyboard = append(markup.InlineKeyboard, []models.InlineKeyboardButton{
|
||||
{Text: "✅标记回调成功", CallbackData: cbMarkNotifySucc + "|" + o.TradeId},
|
||||
{Text: "⚡️立刻回调重试", CallbackData: dbOrderNotifyRetry + "|" + o.TradeId},
|
||||
{Text: "✅标记回调成功", CallbackData: cbMarkNotifySucc + "|" + order.TradeId},
|
||||
{Text: "⚡️立刻回调重试", CallbackData: cbOrderNotifyRetry + "|" + order.TradeId},
|
||||
})
|
||||
}
|
||||
|
||||
var text = "```" + `
|
||||
⛵️系统订单:` + o.TradeId + `
|
||||
📌商户订单:` + o.OrderId + `
|
||||
📊交易汇率:` + o.TradeRate + `(` + conf.GetUsdtRate() + `)
|
||||
💲交易数额:` + o.Amount + `
|
||||
💰交易金额:` + fmt.Sprintf("%.2f", o.Money) + ` CNY
|
||||
💍交易类别:` + strings.ToUpper(o.TradeType) + `
|
||||
🌏商户网站:` + site.String() + `
|
||||
🔋收款状态:` + o.GetStatusLabel() + `
|
||||
🍀回调状态:` + notifyStateLabel + `
|
||||
💎️收款地址:` + help.MaskAddress(o.Address) + `
|
||||
🕒创建时间:` + o.CreatedAt.Format(time.DateTime) + `
|
||||
🕒失效时间:` + o.ExpiredAt.Format(time.DateTime) + `
|
||||
⚖️️确认时间:` + o.ConfirmedAt.Format(time.DateTime) + `
|
||||
` + "\n```"
|
||||
if len(args) == 3 {
|
||||
markup.InlineKeyboard = append(markup.InlineKeyboard, []models.InlineKeyboardButton{
|
||||
{Text: "📦返回订单列表", CallbackData: fmt.Sprintf("%s|%s", cbOrderList, args[2])},
|
||||
})
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: conf.BotAdminID(),
|
||||
text := fmt.Sprintf("```\n"+
|
||||
"⛵️系统订单:%s\n"+
|
||||
"📌商户订单:%s\n"+
|
||||
"📊交易汇率:%s(%s)\n"+
|
||||
"💲交易数额:%s\n"+
|
||||
"💰交易金额:%.2f CNY\n"+
|
||||
"💍交易类别:%s\n"+
|
||||
"🌏商户网站:%s\n"+
|
||||
"🔋收款状态:%s\n"+
|
||||
"🍀回调状态:%s\n"+
|
||||
"💎️收款地址:%s\n"+
|
||||
"🕒创建时间:%s\n"+
|
||||
"🕒失效时间:%s\n"+
|
||||
"⚖️️确认时间:%s\n"+
|
||||
"```",
|
||||
order.TradeId,
|
||||
order.OrderId,
|
||||
order.TradeRate, conf.GetUsdtRate(),
|
||||
order.Amount,
|
||||
order.Money,
|
||||
strings.ToUpper(order.TradeType),
|
||||
site.String(),
|
||||
order.GetStatusLabel(),
|
||||
notifyStateLabel,
|
||||
help.MaskAddress(order.Address),
|
||||
order.CreatedAt.Format(time.DateTime),
|
||||
order.ExpiredAt.Format(time.DateTime),
|
||||
order.ConfirmedAt.Format(time.DateTime))
|
||||
|
||||
EditMessageText(ctx, b, &bot.EditMessageTextParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: markup,
|
||||
})
|
||||
}
|
||||
|
||||
func cbOrderListAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
page := cast.ToInt(ctx.Value("args").([]string)[1])
|
||||
buttons := buildOrderListWithNavigation(page)
|
||||
|
||||
EditMessageText(ctx, b, &bot.EditMessageTextParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
Text: orderListText,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: buttons},
|
||||
})
|
||||
}
|
||||
|
||||
func cbMarkNotifySuccAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var tradeId = ctx.Value("args").([]string)[1]
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/task/rate"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -19,6 +20,8 @@ const cmdState = "state"
|
||||
const cmdOrder = "order"
|
||||
|
||||
const replayAddressText = "🚚 请发送需要添加的钱包地址"
|
||||
const orderListText = "*现有订单列表,点击可查看详细信息,不同颜色对应着不同支付状态!*\n>🟢收款成功 🔴交易过期 🟡等待支付 ⚪️订单取消\n>🌟按钮内容 订单创建时间 订单号末八位 交易金额"
|
||||
const orderPageSize = 8
|
||||
|
||||
func cmdGetIdHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
|
||||
@@ -70,7 +73,7 @@ func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var rows []model.TradeOrders
|
||||
model.DB.Where("created_at > ?", time.Now().Format(time.DateOnly)).Find(&rows)
|
||||
var succ uint64
|
||||
var money, trx, uTrc20, uErc20, uBep20, uXlayer, uPol float64
|
||||
var money, trx, uTrc20, uErc20, uBep20, uXlayer, uSolana, uPol, uAptos float64
|
||||
for _, o := range rows {
|
||||
if o.Status != model.OrderStatusSuccess {
|
||||
|
||||
@@ -99,6 +102,12 @@ func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
if o.TradeType == model.OrderTradeTypeUsdtXlayer {
|
||||
uXlayer += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtSolana {
|
||||
uSolana += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtAptos {
|
||||
uAptos += amount
|
||||
}
|
||||
}
|
||||
|
||||
var base = "```" + `
|
||||
@@ -110,12 +119,16 @@ func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
- %.2f USDT.Trc20
|
||||
- %.2f USDT.Erc20
|
||||
- %.2f USDT.Bep20
|
||||
- %.2f USDT.Aptos
|
||||
- %.2f USDT.Xlayer
|
||||
- %.2f USDT.Solana
|
||||
- %.2f USDT.Polygon
|
||||
🌟扫块成功数据
|
||||
- Bsc %s
|
||||
- Tron %s
|
||||
- Aptos %s
|
||||
- Xlayer %s
|
||||
- Solana %s
|
||||
- Polygon %s
|
||||
- Ethereum %s
|
||||
-----------------------
|
||||
@@ -138,11 +151,15 @@ func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
uTrc20,
|
||||
uErc20,
|
||||
uBep20,
|
||||
uAptos,
|
||||
uXlayer,
|
||||
uSolana,
|
||||
uPol,
|
||||
conf.GetBlockSuccRate(conf.Bsc),
|
||||
conf.GetBlockSuccRate(conf.Tron),
|
||||
conf.GetBlockSuccRate(conf.Aptos),
|
||||
conf.GetBlockSuccRate(conf.Xlayer),
|
||||
conf.GetBlockSuccRate(conf.Solana),
|
||||
conf.GetBlockSuccRate(conf.Polygon),
|
||||
conf.GetBlockSuccRate(conf.Ethereum),
|
||||
cast.ToString(rate.GetOkxTrxRawRate()),
|
||||
@@ -159,23 +176,73 @@ func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
}
|
||||
|
||||
func cmdOrderHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var orders []model.TradeOrders
|
||||
var btn [][]models.InlineKeyboardButton
|
||||
if model.DB.Order("id desc").Limit(8).Find(&orders).Error == nil {
|
||||
for _, o := range orders {
|
||||
btn = append(btn, []models.InlineKeyboardButton{
|
||||
{
|
||||
Text: fmt.Sprintf("%s %s 💰%.2f", o.GetStatusEmoji(), o.OrderId, o.Money),
|
||||
CallbackData: fmt.Sprintf("%s|%v", cbOrderDetail, o.TradeId),
|
||||
},
|
||||
})
|
||||
}
|
||||
buttons := buildOrderListWithNavigation(1)
|
||||
if buttons == nil {
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: "*订单列表暂时为空!*",
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: "*下面是最近的8个订单,点击可查看详细信息*\n```\n🟢 收款成功 🔴 交易过期 \n🟡 等待支付 ⚪️ 订单取消\n```",
|
||||
Text: orderListText,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: btn},
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: buttons},
|
||||
})
|
||||
}
|
||||
|
||||
func buildOrderListWithNavigation(page int) [][]models.InlineKeyboardButton {
|
||||
buttons, total := buildOrderButtons(page, orderPageSize)
|
||||
if buttons == nil {
|
||||
return nil
|
||||
}
|
||||
return append(buttons, buildPageNavigation(page, total, orderPageSize)...)
|
||||
}
|
||||
|
||||
func buildOrderButtons(page, size int) ([][]models.InlineKeyboardButton, int) {
|
||||
var total int64
|
||||
model.DB.Model(&model.TradeOrders{}).Count(&total)
|
||||
if total == 0 {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
var orders []model.TradeOrders
|
||||
model.DB.Order("id desc").Offset((page - 1) * size).Limit(size).Find(&orders)
|
||||
|
||||
buttons := make([][]models.InlineKeyboardButton, 0, len(orders))
|
||||
for _, o := range orders {
|
||||
orderId := o.OrderId
|
||||
if len(orderId) > 8 {
|
||||
orderId = orderId[len(orderId)-8:]
|
||||
}
|
||||
buttons = append(buttons, []models.InlineKeyboardButton{{
|
||||
Text: fmt.Sprintf("%s〚%s〛%s 💰%.2f", o.GetStatusEmoji(), o.CreatedAt.Format("1/2 15:04"), orderId, o.Money),
|
||||
CallbackData: fmt.Sprintf("%s|%v|%d", cbOrderDetail, o.TradeId, page),
|
||||
}})
|
||||
}
|
||||
|
||||
return buttons, int(total)
|
||||
}
|
||||
|
||||
func buildPageNavigation(page, total, size int) [][]models.InlineKeyboardButton {
|
||||
totalPage := int(math.Ceil(float64(total) / float64(size)))
|
||||
|
||||
prevBtn := models.InlineKeyboardButton{Text: "🏠首页", CallbackData: "-"}
|
||||
if page > 1 {
|
||||
prevBtn = models.InlineKeyboardButton{Text: "⬅️上一页", CallbackData: fmt.Sprintf("%s|%d", cbOrderList, page-1)}
|
||||
}
|
||||
|
||||
nextBtn := models.InlineKeyboardButton{Text: "🔙末页", CallbackData: "-"}
|
||||
if page < totalPage {
|
||||
nextBtn = models.InlineKeyboardButton{Text: "➡️下一页", CallbackData: fmt.Sprintf("%s|%d", cbOrderList, page+1)}
|
||||
}
|
||||
|
||||
return [][]models.InlineKeyboardButton{{
|
||||
prevBtn,
|
||||
{Text: fmt.Sprintf("📄第[%d/%d]页", page, totalPage), CallbackData: "-"},
|
||||
nextBtn,
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
func defaultHandle(ctx context.Context, bot *bot.Bot, u *models.Update) {
|
||||
if u.Message.ReplyToMessage != nil && u.Message.ReplyToMessage.Text == replayAddressText {
|
||||
if u.Message != nil && u.Message.ReplyToMessage != nil && u.Message.ReplyToMessage.Text == replayAddressText {
|
||||
addWalletAddress(u)
|
||||
|
||||
return
|
||||
@@ -29,7 +29,7 @@ func defaultHandle(ctx context.Context, bot *bot.Bot, u *models.Update) {
|
||||
|
||||
func addWalletAddress(u *models.Update) {
|
||||
var address = strings.TrimSpace(u.Message.Text)
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidEvmAddress(address) {
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidEvmAddress(address) && !help.IsValidSolanaAddress(address) && !help.IsValidAptosAddress(address) {
|
||||
SendMessage(&bot.SendMessageParams{Text: "钱包地址不合法"})
|
||||
|
||||
return
|
||||
@@ -42,7 +42,7 @@ func addWalletAddress(u *models.Update) {
|
||||
|
||||
var tradeType, _ = cache.Get(fmt.Sprintf("%s_%d_trade_type", cbAddressAdd, u.Message.Chat.ID))
|
||||
|
||||
var wa = model.WalletAddress{TradeType: tradeType.(string), Address: address, Status: model.StatusEnable, OtherNotify: model.OtherNotifyEnable}
|
||||
var wa = model.WalletAddress{TradeType: tradeType.(string), Address: address, Status: model.StatusEnable, OtherNotify: model.OtherNotifyDisable}
|
||||
var r = model.DB.Create(&wa)
|
||||
if r.Error != nil {
|
||||
SendMessage(&bot.SendMessageParams{Text: "❌地址添加失败," + r.Error.Error()})
|
||||
|
||||
@@ -8,6 +8,7 @@ type Conf struct {
|
||||
StaticPath string `toml:"static_path"`
|
||||
SqlitePath string `toml:"sqlite_path"`
|
||||
TronGrpcNode string `toml:"tron_grpc_node"`
|
||||
AptosRpcNode string `toml:"aptos_rpc_node"`
|
||||
WebhookUrl string `toml:"webhook_url"`
|
||||
Pay struct {
|
||||
TrxAtom float64 `toml:"trx_atom"`
|
||||
@@ -22,6 +23,7 @@ type Conf struct {
|
||||
} `toml:"pay"`
|
||||
EvmRpc struct {
|
||||
Bsc string `toml:"bsc"`
|
||||
Solana string `toml:"solana"`
|
||||
Xlayer string `toml:"xlayer"`
|
||||
Polygon string `toml:"polygon"`
|
||||
Ethereum string `toml:"ethereum"`
|
||||
|
||||
@@ -1,29 +1,35 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
defaultExpireTime = 600 // 订单默认有效期 10分钟
|
||||
DefaultUsdtCnyRate = 6.4 // 默认USDT基准汇率
|
||||
DefaultTrxCnyRate = 0.95 // 默认TRX基准汇率
|
||||
defaultAuthToken = "123234" // 默认授权码
|
||||
defaultListen = ":8080" // 默认监听地址
|
||||
defaultPaymentMinAmount = 0.01
|
||||
defaultPaymentMaxAmount = 99999
|
||||
defaultUsdtAtomicity = 0.01 // 原子精度
|
||||
defaultTrxAtomicity = 0.01
|
||||
defaultExpireTime = 600 // 订单默认有效期 10分钟
|
||||
DefaultUsdtCnyRate = 6.4 // 默认USDT基准汇率
|
||||
DefaultTrxCnyRate = 0.95 // 默认TRX基准汇率
|
||||
defaultAuthToken = "123234" // 默认授权码
|
||||
defaultListen = ":8080" // 默认监听地址
|
||||
defaultPaymentMinAmount = 0.01
|
||||
defaultPaymentMaxAmount = 99999
|
||||
defaultUsdtAtomicity = 0.01 // 原子精度
|
||||
defaultTrxAtomicity = 0.01
|
||||
|
||||
defaultTronGrpcNode = "18.141.79.38:50051" // 默认GRPC节点
|
||||
defaultBscRpcEndpoint = "https://bsc-dataseed.bnbchain.org/" // 默认BSC RPC节点
|
||||
defaultSolanaRpcEndpoint = "https://solana-rpc.publicnode.com/" // 默认Solana RPC节点 官方是 https://api.mainnet-beta.solana.com/ 但存在速率限制
|
||||
defaultXlayerRpcEndpoint = "https://xlayerrpc.okx.com/" // 默认Xlayer RPC节点
|
||||
defaultPolygonRpcEndpoint = "https://polygon-rpc.com/" // 默认Polygon RPC节点
|
||||
defaultEthereumRpcEndpoint = "https://ethereum.publicnode.com/" // 默认Ethereum RPC节点
|
||||
defaultAptosRpcEndpoint = "https://aptos-rest.publicnode.com/" // 默认Aptos RPC节点
|
||||
defaultOutputLog = "/var/log/bepusdt.log" // 默认日志输出文件
|
||||
defaultSqlitePath = "/var/lib/bepusdt/sqlite.db" // 默认数据库文件
|
||||
)
|
||||
|
||||
const (
|
||||
UsdtErc20 = "0xdac17f958d2ee523a2206206994597c13d831ec7" // Eth USDT合约地址
|
||||
UsdtBep20 = "0x55d398326f99059ff775485246999027b3197955" // BSC USDT合约地址
|
||||
UsdtXlayer = "0x1e4a5963abfd975d8c9021ce480b42188849d41d" // Xlayer USDT合约地址
|
||||
UsdtPolygon = "0xc2132d05d31c914a87c6611c10748aeb04b58e8f" // Polygon USDT合约地址
|
||||
UsdtErc20 = "0xdac17f958d2ee523a2206206994597c13d831ec7" // Eth USDT合约地址
|
||||
UsdtBep20 = "0x55d398326f99059ff775485246999027b3197955" // BSC USDT合约地址
|
||||
UsdtXlayer = "0x1e4a5963abfd975d8c9021ce480b42188849d41d" // Xlayer USDT合约地址
|
||||
UsdtPolygon = "0xc2132d05d31c914a87c6611c10748aeb04b58e8f" // Polygon USDT合约地址
|
||||
UsdtSolana = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" // Solana USDT合约地址
|
||||
SolSplToken = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" // Solana SPL Token合约地址
|
||||
UsdtAptos = "0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b" // Aptos USDT合约地址
|
||||
)
|
||||
|
||||
// UsdtDecimals USDT合约小数位数
|
||||
@@ -32,6 +38,10 @@ const (
|
||||
UsdtEthDecimals = -6 // USDT ERC20小数位数
|
||||
UsdtXlayerDecimals = -6 // USDT Xlayer小数位数
|
||||
UsdtPolygonDecimals = -6 // USDT Polygon小数位数
|
||||
UsdtAptosDecimals = -6 // USDT Aptos小数位数
|
||||
)
|
||||
|
||||
const NotifyMaxRetry = 10 // 最大重试次数,订单回调失败、Webhook失败
|
||||
const (
|
||||
NotifyMaxRetry = 10 // 最大重试次数,订单回调失败、Webhook失败
|
||||
BlockHeightMaxDiff = 1000 // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
)
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
const (
|
||||
Bsc = "bsc" // Binance Smart Chain
|
||||
Tron = "tron"
|
||||
Aptos = "aptos"
|
||||
Solana = "solana"
|
||||
Xlayer = "xlayer"
|
||||
Polygon = "polygon"
|
||||
Ethereum = "ethereum"
|
||||
|
||||
@@ -9,6 +9,23 @@ func GetTronGrpcNode() string {
|
||||
return defaultTronGrpcNode
|
||||
}
|
||||
|
||||
func GetAptosRpcNode() string {
|
||||
if cfg.AptosRpcNode != "" {
|
||||
return cfg.AptosRpcNode
|
||||
}
|
||||
|
||||
return defaultAptosRpcEndpoint
|
||||
}
|
||||
|
||||
func GetSolanaRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Solana != "" {
|
||||
|
||||
return cfg.EvmRpc.Solana
|
||||
}
|
||||
|
||||
return defaultSolanaRpcEndpoint
|
||||
}
|
||||
|
||||
func GetXlayerRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Xlayer != "" {
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
"math"
|
||||
"math/big"
|
||||
@@ -114,6 +115,28 @@ func IsValidEvmAddress(address string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func IsValidSolanaAddress(address string) bool {
|
||||
data := base58.Decode(address)
|
||||
|
||||
return len(data) == 32
|
||||
}
|
||||
|
||||
func IsValidAptosAddress(address string) bool {
|
||||
if strings.HasPrefix(address, "0x") || strings.HasPrefix(address, "0X") {
|
||||
|
||||
address = address[2:]
|
||||
}
|
||||
|
||||
if len(address) != 64 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
matched, _ := regexp.MatchString("^[0-9a-fA-F]{64}$", address)
|
||||
|
||||
return matched
|
||||
}
|
||||
|
||||
func MaskAddress(address string) string {
|
||||
if len(address) <= 20 {
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ var SupportTradeTypes = []string{
|
||||
OrderTradeTypeUsdtTrc20,
|
||||
OrderTradeTypeUsdtErc20,
|
||||
OrderTradeTypeUsdtBep20,
|
||||
OrderTradeTypeUsdtAptos,
|
||||
OrderTradeTypeUsdtXlayer,
|
||||
OrderTradeTypeUsdtSolana,
|
||||
OrderTradeTypeUsdtPolygon,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"strconv"
|
||||
@@ -28,6 +29,8 @@ const (
|
||||
OrderTradeTypeUsdtErc20 = "usdt.erc20"
|
||||
OrderTradeTypeUsdtBep20 = "usdt.bep20"
|
||||
OrderTradeTypeUsdtXlayer = "usdt.xlayer"
|
||||
OrderTradeTypeUsdtSolana = "usdt.solana"
|
||||
OrderTradeTypeUsdtAptos = "usdt.aptos"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -139,24 +142,23 @@ func (o *TradeOrders) GetDetailUrl() string {
|
||||
|
||||
func GetDetailUrl(tradeType, hash string) string {
|
||||
if tradeType == OrderTradeTypeUsdtErc20 {
|
||||
|
||||
return "https://etherscan.io/tx/" + hash
|
||||
}
|
||||
|
||||
if tradeType == OrderTradeTypeUsdtBep20 {
|
||||
|
||||
return "https://bscscan.com/tx/" + hash
|
||||
}
|
||||
|
||||
if tradeType == OrderTradeTypeUsdtXlayer {
|
||||
|
||||
return "https://web3.okx.com/zh-hans/explorer/x-layer/tx/" + hash
|
||||
}
|
||||
|
||||
if tradeType == OrderTradeTypeUsdtPolygon {
|
||||
|
||||
return "https://polygonscan.com/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtSolana {
|
||||
return "https://solscan.io/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtAptos {
|
||||
return fmt.Sprintf("https://explorer.aptoslabs.com/txn/%s?network=mainnet", hash)
|
||||
}
|
||||
|
||||
return "https://tronscan.org/#/transaction/" + hash
|
||||
}
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
aptosPayloadType = "entry_function_payload"
|
||||
)
|
||||
|
||||
type aptos struct {
|
||||
versionChunkSize int64
|
||||
versionConfirmedOffset int64
|
||||
versionInitStartOffset int64
|
||||
lastVersion int64
|
||||
versionQueue *chanx.UnboundedChan[version]
|
||||
}
|
||||
|
||||
type version struct {
|
||||
Start int64
|
||||
Limit int64
|
||||
}
|
||||
|
||||
var apt aptos
|
||||
|
||||
func init() {
|
||||
apt = newAptos()
|
||||
register(task{callback: apt.versionDispatch})
|
||||
register(task{callback: apt.versionRoll, duration: time.Second * 3})
|
||||
}
|
||||
|
||||
func newAptos() aptos {
|
||||
return aptos{
|
||||
versionChunkSize: 100, // 目前好像最大就只能100
|
||||
versionConfirmedOffset: 1000,
|
||||
versionInitStartOffset: -100 * 500,
|
||||
lastVersion: 0,
|
||||
versionQueue: chanx.NewUnboundedChan[version](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionRoll(context.Context) {
|
||||
if rollBreak(conf.Aptos) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.Get(conf.GetAptosRpcNode() + "/v1")
|
||||
if err != nil {
|
||||
log.Warn("aptos versionRoll Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Warn("aptos versionRoll Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("aptos versionRoll Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "ledger_version").Int()
|
||||
if now <= 0 {
|
||||
log.Warn("versionRoll Error: invalid ledger_version:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - a.versionConfirmedOffset
|
||||
}
|
||||
|
||||
if now-a.lastVersion > 10000 {
|
||||
a.versionInitOffset(now)
|
||||
a.lastVersion = now - a.versionChunkSize
|
||||
}
|
||||
|
||||
var sub = now - a.lastVersion
|
||||
if now == 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if sub <= a.versionChunkSize {
|
||||
a.versionQueue.In <- version{Start: a.lastVersion, Limit: sub}
|
||||
} else {
|
||||
chunks := (sub + a.versionChunkSize - 1) / a.versionChunkSize
|
||||
for i := int64(0); i < chunks; i++ {
|
||||
limit := a.versionChunkSize
|
||||
start := a.lastVersion + a.versionChunkSize*i
|
||||
if i == chunks-1 {
|
||||
limit = sub % a.versionChunkSize
|
||||
if limit == 0 {
|
||||
limit = a.versionChunkSize
|
||||
}
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{Start: start, Limit: limit}
|
||||
}
|
||||
}
|
||||
|
||||
a.lastVersion = now
|
||||
}
|
||||
|
||||
func (a *aptos) versionDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, a.versionParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case n := <-a.versionQueue.Out:
|
||||
if err := p.Invoke(n); err != nil {
|
||||
a.versionQueue.In <- n
|
||||
log.Warn("versionDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Warn("versionDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionInitOffset(now int64) {
|
||||
if now == 0 || a.lastVersion != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
var end = now + a.versionInitStartOffset
|
||||
for s := now - a.versionChunkSize; s >= end; s = s - a.versionChunkSize {
|
||||
if rollBreak(conf.Aptos) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{Start: s, Limit: a.versionChunkSize}
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *aptos) versionParse(n any) {
|
||||
p := n.(version)
|
||||
|
||||
var network = conf.Aptos
|
||||
var url = fmt.Sprintf("%sv1/transactions?start=%d&limit=%d", conf.GetAptosRpcNode(), p.Start, p.Limit)
|
||||
|
||||
conf.SetBlockTotal(network)
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("versionParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("versionParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
a.versionQueue.In <- p
|
||||
log.Warn("versionParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !gjson.ValidBytes(body) {
|
||||
conf.SetBlockFail(network)
|
||||
a.versionQueue.In <- p
|
||||
log.Warn("versionParse Error: invalid JSON response body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, trans := range gjson.ParseBytes(body).Array() {
|
||||
tsNano := trans.Get("timestamp").Int() * 1000
|
||||
timestamp := time.Unix(tsNano/1e9, tsNano%1e9)
|
||||
function := trans.Get("payload.function").String()
|
||||
typeName := trans.Get("payload.type").String()
|
||||
if typeName != aptosPayloadType {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
hash := trans.Get("hash").String()
|
||||
sender := trans.Get("sender").String()
|
||||
ver := trans.Get("version").Int()
|
||||
args := trans.Get("payload.arguments").Array()
|
||||
|
||||
switch function {
|
||||
case "0x1::primary_fungible_store::transfer":
|
||||
a.parsePrimaryFungibleStoreTransfer(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::aptos_account::batch_transfer_fungible_assets":
|
||||
a.parseAptosAccountBatchTransferFungibleAssets(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::aptos_account::transfer_fungible_assets":
|
||||
a.parseAptosAccountTransferFungibleAssets(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::fungible_asset::transfer":
|
||||
// 待定
|
||||
case "0x1::coin::transfer":
|
||||
// 待定
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", fmt.Sprintf("%d.%d", p.Start, p.Limit), conf.GetBlockSuccRate(network), network)
|
||||
}
|
||||
|
||||
func (a *aptos) parsePrimaryFungibleStoreTransfer(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].String(), 10)
|
||||
|
||||
transferQueue.In <- []transfer{{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: args[1].String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *aptos) parseAptosAccountBatchTransferFungibleAssets(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var result = make([]transfer, 0)
|
||||
for i, recv := range args[1].Array() {
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].Get(fmt.Sprintf("%d", i)).String(), 10)
|
||||
if rawAmount == nil || rawAmount.Sign() <= 0 {
|
||||
log.Warn("parseAptosAccountBatchTransferFungibleAssets Error: invalid amount for receiver", recv.String(), "in transaction", hash)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
result = append(result, transfer{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: recv.String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
})
|
||||
}
|
||||
|
||||
if len(result) > 0 {
|
||||
transferQueue.In <- result
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) parseAptosAccountTransferFungibleAssets(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].String(), 10)
|
||||
|
||||
transferQueue.In <- []transfer{
|
||||
{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: args[1].String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
blockParseMaxNum = 10 // 每次解析区块的最大数量
|
||||
|
||||
usdtTransfer = "0xa9059cbb" // Tether transfer function ID
|
||||
contentType = "application/json"
|
||||
|
||||
@@ -42,9 +44,17 @@ var contractMap = map[string]string{
|
||||
conf.UsdtPolygon: model.OrderTradeTypeUsdtPolygon,
|
||||
conf.UsdtErc20: model.OrderTradeTypeUsdtErc20,
|
||||
}
|
||||
var chainUsdtMap = map[string]string{
|
||||
conf.Bsc: model.OrderTradeTypeUsdtBep20,
|
||||
conf.Xlayer: model.OrderTradeTypeUsdtXlayer,
|
||||
conf.Polygon: model.OrderTradeTypeUsdtPolygon,
|
||||
conf.Ethereum: model.OrderTradeTypeUsdtErc20,
|
||||
conf.Solana: model.OrderTradeTypeUsdtSolana,
|
||||
conf.Aptos: model.OrderTradeTypeUsdtAptos,
|
||||
}
|
||||
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
var chainScanQueue = chanx.NewUnboundedChan[evmBlock](context.Background(), 30)
|
||||
var client = &http.Client{Timeout: time.Second * 30}
|
||||
var chainScanQueue = chanx.NewUnboundedChan[[]evmBlock](context.Background(), 30)
|
||||
|
||||
type decimals struct {
|
||||
Usdt int32 // USDT小数位数
|
||||
@@ -73,44 +83,28 @@ func init() {
|
||||
register(task{callback: evmBlockDispatch})
|
||||
}
|
||||
|
||||
func evmBlockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, evmBlockParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range chainScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
chainScanQueue.In <- n
|
||||
|
||||
log.Warn("evmBlockDispatch Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func evmBlockRoll(ctx context.Context) {
|
||||
var val = ctx.Value("cfg")
|
||||
val := ctx.Value("cfg")
|
||||
if val == nil {
|
||||
log.Warn("evmBlockRoll: context value 'cfg' is nil")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var cfg, ok = val.(evmCfg)
|
||||
cfg, ok := val.(evmCfg)
|
||||
if !ok {
|
||||
log.Warn("evmBlockRoll: context value 'cfg' is not of type evmCfg")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var url = cfg.Endpoint
|
||||
var jsonData = []byte(`{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}`)
|
||||
if rollBreak(cfg.Type) {
|
||||
|
||||
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonData))
|
||||
return
|
||||
}
|
||||
|
||||
post := []byte(`{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}`)
|
||||
resp, err := client.Post(cfg.Endpoint, contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
@@ -144,42 +138,98 @@ func evmBlockRoll(ctx context.Context) {
|
||||
lastBlockNumber = v.(int64)
|
||||
}
|
||||
|
||||
// 首次启动
|
||||
if lastBlockNumber == 0 {
|
||||
if now-lastBlockNumber > conf.BlockHeightMaxDiff {
|
||||
|
||||
lastBlockNumber = now + cfg.Block.InitStartOffset
|
||||
lastBlockNumber = evmBlockInitOffset(now, cfg.Block.InitStartOffset, cfg) - 1
|
||||
}
|
||||
|
||||
// 区块高度没有变化
|
||||
if now <= lastBlockNumber {
|
||||
chainBlockNum.Store(cfg.Type, now)
|
||||
if now <= lastBlockNumber { // 区块高度没有变化
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
blocks := make([]evmBlock, 0)
|
||||
for n := lastBlockNumber + 1; n <= now; n++ {
|
||||
|
||||
chainScanQueue.In <- evmBlock{Num: n, Network: cfg}
|
||||
blocks = append(blocks, evmBlock{Num: n, Network: cfg})
|
||||
if len(blocks) >= blockParseMaxNum {
|
||||
chainScanQueue.In <- blocks
|
||||
blocks = make([]evmBlock, 0)
|
||||
}
|
||||
}
|
||||
|
||||
chainBlockNum.Store(cfg.Type, now)
|
||||
if len(blocks) > 0 {
|
||||
chainScanQueue.In <- blocks
|
||||
}
|
||||
}
|
||||
|
||||
func evmBlockInitOffset(now, offset int64, cfg evmCfg) int64 {
|
||||
go func() {
|
||||
var blocks []evmBlock
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for b := now; b >= now+offset; b-- {
|
||||
if rollBreak(cfg.Type) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
blocks = append(blocks, evmBlock{Num: b, Network: cfg})
|
||||
if len(blocks) >= blockParseMaxNum {
|
||||
chainScanQueue.In <- blocks
|
||||
blocks = blocks[:0]
|
||||
}
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
if len(blocks) > 0 {
|
||||
chainScanQueue.In <- blocks
|
||||
}
|
||||
}()
|
||||
|
||||
return now
|
||||
}
|
||||
|
||||
func evmBlockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, evmBlockParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range chainScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
chainScanQueue.In <- n
|
||||
|
||||
log.Warn("evmBlockDispatch Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func evmBlockParse(b any) {
|
||||
var n, ok = b.(evmBlock)
|
||||
var blocks, ok = b.([]evmBlock)
|
||||
if !ok {
|
||||
log.Warn("evmBlockParse: received non-evmBlock type")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var post = []byte(fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x%x",true],"id":1}`, n.Num))
|
||||
first := blocks[0]
|
||||
items := make([]string, 0)
|
||||
for _, v := range blocks {
|
||||
conf.SetBlockTotal(v.Network.Type)
|
||||
items = append(items, fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x%x",true],"id":%d}`, v.Num, v.Num))
|
||||
}
|
||||
|
||||
conf.SetBlockTotal(n.Network.Type)
|
||||
|
||||
resp, err := client.Post(n.Network.Endpoint, contentType, bytes.NewBuffer(post))
|
||||
post := []byte(fmt.Sprintf(`[%s]`, strings.Join(items, ",")))
|
||||
resp, err := client.Post(first.Network.Endpoint, contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.SetBlockFail(n.Network.Type)
|
||||
chainScanQueue.In <- n
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- blocks
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
return
|
||||
@@ -189,76 +239,79 @@ func evmBlockParse(b any) {
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(n.Network.Type)
|
||||
chainScanQueue.In <- n
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- blocks
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var data = gjson.ParseBytes(body)
|
||||
if data.Get("error").Exists() {
|
||||
conf.SetBlockFail(n.Network.Type)
|
||||
chainScanQueue.In <- n
|
||||
log.Warn(fmt.Sprintf("%s getBlockByNumber response error %s %v", n.Network.Type, data.Get("error").String(), n))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var result = data.Get("result")
|
||||
var timestamp = help.HexStr2Int(result.Get("timestamp").String())
|
||||
var transfers = make([]transfer, 0)
|
||||
for _, v := range result.Get("transactions").Array() {
|
||||
var recv = v.Get("to").String()
|
||||
var input = v.Get("input").String()
|
||||
var rawValue = v.Get("value").String()
|
||||
var rawAmount, ok = new(big.Int).SetString(rawValue, 0)
|
||||
if !ok {
|
||||
log.Warn("Error converting value to integer:" + " " + rawValue)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var amount = decimal.NewFromBigInt(rawAmount, n.Network.Decimals.Native)
|
||||
var tradeType = getTradeType(n.Network.Type, recv, input, rawAmount)
|
||||
if tradeType == nil {
|
||||
var list = gjson.ParseBytes(body).Array()
|
||||
for _, data := range list {
|
||||
if !data.Get("result").Exists() {
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- []evmBlock{{Network: first.Network, Num: data.Get("id").Int()}}
|
||||
log.Warn(fmt.Sprintf("%s getBlockByNumber response error %s", first.Network.Type, data.String()))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !tradeType.Native && len(input) == inputAddressTotal { // usdt transfer
|
||||
rawAmount, ok = new(big.Int).SetString(input[inputAddressEnd:], 16)
|
||||
num := data.Get("id").Int()
|
||||
result := data.Get("result")
|
||||
timestamp := time.Unix(help.HexStr2Int(result.Get("timestamp").String()).Int64(), 0)
|
||||
transfers := make([]transfer, 0)
|
||||
for _, v := range result.Get("transactions").Array() {
|
||||
recv := v.Get("to").String()
|
||||
input := v.Get("input").String()
|
||||
rawValue := v.Get("value").String()
|
||||
rawAmount, ok := new(big.Int).SetString(rawValue, 0)
|
||||
if !ok {
|
||||
log.Warn("Error converting amount(value):" + input[inputAddressEnd:])
|
||||
log.Warn("Error converting value to integer:" + " " + rawValue)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount = decimal.NewFromBigInt(rawAmount, n.Network.Decimals.Usdt)
|
||||
recv = "0x" + input[inputAddressStart:inputAddressEnd] // USDT转账接收地址
|
||||
amount := decimal.NewFromBigInt(rawAmount, first.Network.Decimals.Native)
|
||||
tradeType := evmParseTradeType(first.Network.Type, recv, input, rawAmount)
|
||||
if tradeType == nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !tradeType.Native && len(input) == inputAddressTotal { // usdt transfer
|
||||
rawAmount, ok = new(big.Int).SetString(input[inputAddressEnd:], 16)
|
||||
if !ok {
|
||||
log.Warn("Error converting amount(value):" + input[inputAddressEnd:])
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount = decimal.NewFromBigInt(rawAmount, first.Network.Decimals.Usdt)
|
||||
recv = "0x" + input[inputAddressStart:inputAddressEnd] // USDT转账接收地址
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: first.Network.Type,
|
||||
FromAddress: v.Get("from").String(),
|
||||
RecvAddress: recv,
|
||||
Amount: amount,
|
||||
TxHash: v.Get("hash").String(),
|
||||
BlockNum: num,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType.Type,
|
||||
})
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: n.Network.Type,
|
||||
FromAddress: v.Get("from").String(),
|
||||
RecvAddress: recv,
|
||||
Amount: amount,
|
||||
TxHash: v.Get("hash").String(),
|
||||
BlockNum: n.Num,
|
||||
Timestamp: time.Unix(timestamp.Int64(), 0),
|
||||
TradeType: tradeType.Type,
|
||||
})
|
||||
}
|
||||
if len(transfers) > 0 {
|
||||
|
||||
log.Info("区块扫描完成", n.Num, conf.GetBlockSuccRate(n.Network.Type), n.Network.Type)
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
|
||||
transferQueue.In <- transfers
|
||||
log.Info("区块扫描完成", num, conf.GetBlockSuccRate(first.Network.Type), first.Network.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func getTradeType(net, to, input string, value *big.Int) *model.TradeType {
|
||||
func evmParseTradeType(net, to, input string, value *big.Int) *model.TradeType {
|
||||
var tradeType, ok = nativeToken[net]
|
||||
if ok && input == "0x" && value.Sign() == 1 { // 原生代币
|
||||
|
||||
@@ -275,3 +328,26 @@ func getTradeType(net, to, input string, value *big.Int) *model.TradeType {
|
||||
// 其他合约数据
|
||||
return nil
|
||||
}
|
||||
|
||||
func rollBreak(network string) bool {
|
||||
usdt, ok := chainUsdtMap[network]
|
||||
if !ok {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var count int64 = 0
|
||||
model.DB.Model(&model.TradeOrders{}).Where("status = ? and trade_type = ?", model.OrderStatusWaiting, usdt).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
model.DB.Model(&model.WalletAddress{}).Where("other_notify = ? and trade_type = ?", model.OtherNotifyEnable, usdt).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -39,16 +39,16 @@ func GetOkxTrxRawRate() float64 {
|
||||
func SetOkxTrxCnyRate(syntax string, rawRate float64) {
|
||||
rawRate = round(rawRate, okxRatePrecision)
|
||||
okxTrxCnyRawRate = rawRate
|
||||
okxTrxCnyCalcRate = parseFloatRate(syntax, rawRate)
|
||||
okxTrxCnyCalcRate = ParseFloatRate(syntax, rawRate)
|
||||
}
|
||||
|
||||
func SetOkxUsdtCnyRate(syntax string, rawRate float64) {
|
||||
rawRate = round(rawRate, okxRatePrecision)
|
||||
okxUsdtCnyRawRate = rawRate
|
||||
okxUsdtCnyCalcRate = parseFloatRate(syntax, rawRate)
|
||||
okxUsdtCnyCalcRate = ParseFloatRate(syntax, rawRate)
|
||||
}
|
||||
|
||||
func parseFloatRate(syntax string, rawVal float64) float64 {
|
||||
func ParseFloatRate(syntax string, rawVal float64) float64 {
|
||||
if syntax == "" {
|
||||
|
||||
return rawVal
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 参考文档
|
||||
// - https://solana.com/zh/docs/rpc
|
||||
// - https://github.com/solana-program/token/blob/main/program/src/instruction.rs
|
||||
|
||||
type solana struct {
|
||||
slotConfirmedOffset int64
|
||||
slotInitStartOffset int64
|
||||
lastSlotNum int64
|
||||
slotQueue *chanx.UnboundedChan[int64]
|
||||
}
|
||||
|
||||
var sol solana
|
||||
|
||||
func init() {
|
||||
sol = newSolana()
|
||||
register(task{callback: sol.slotDispatch})
|
||||
register(task{callback: sol.slotRoll, duration: time.Second * 5})
|
||||
}
|
||||
|
||||
func newSolana() solana {
|
||||
return solana{
|
||||
slotConfirmedOffset: 60,
|
||||
slotInitStartOffset: -600,
|
||||
lastSlotNum: 0,
|
||||
slotQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) slotRoll(context.Context) {
|
||||
if rollBreak(conf.Solana) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
post := []byte(`{"jsonrpc":"2.0","id":1,"method":"getSlot"}`)
|
||||
|
||||
resp, err := client.Post(conf.GetSolanaRpcEndpoint(), contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Warn("slotRoll Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Warn("slotRoll Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("slotRoll Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "result").Int()
|
||||
if now <= 0 {
|
||||
log.Warn("slotRoll Error: invalid slot number:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - s.slotConfirmedOffset
|
||||
}
|
||||
|
||||
if now-s.lastSlotNum > conf.BlockHeightMaxDiff { // 区块高度变化过大,强制丢块重扫
|
||||
s.lastSlotNum = now
|
||||
s.slotInitOffset(now)
|
||||
}
|
||||
|
||||
if now == s.lastSlotNum { // 区块高度没有变化
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for n := s.lastSlotNum + 1; n <= now; n++ {
|
||||
// 待扫描区块入列
|
||||
|
||||
s.slotQueue.In <- n
|
||||
}
|
||||
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
func (s *solana) slotDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, s.slotParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case slot := <-s.slotQueue.Out:
|
||||
if err := p.Invoke(slot); err != nil {
|
||||
s.slotQueue.In <- slot
|
||||
log.Warn("slotDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Warn("slotDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// slotInitOffset 初始化区块高度偏移,往回扫一定数量的区块
|
||||
func (s *solana) slotInitOffset(now int64) {
|
||||
if now == 0 || s.lastSlotNum != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Millisecond * 300)
|
||||
defer ticker.Stop()
|
||||
|
||||
for num := now; num >= now+s.slotInitStartOffset; num-- {
|
||||
if rollBreak(conf.Solana) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
s.slotQueue.In <- num
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *solana) slotParse(n any) {
|
||||
slot := n.(int64)
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":0,"transactionDetails":"full","rewards":false}]}`, slot))
|
||||
network := conf.Solana
|
||||
|
||||
conf.SetBlockTotal(network)
|
||||
resp, err := client.Post(conf.GetSolanaRpcEndpoint(), contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("slotParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("slotParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
s.slotQueue.In <- slot
|
||||
log.Warn("slotParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Unix(gjson.GetBytes(body, "result.blockTime").Int(), 0)
|
||||
|
||||
for _, trans := range gjson.GetBytes(body, "result.transactions").Array() {
|
||||
hash := trans.Get("transaction.signatures.0").String()
|
||||
|
||||
// 解析账号索引
|
||||
accountKeys := make([]string, 0)
|
||||
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
for _, v := range []string{"readonly", "writable"} {
|
||||
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
|
||||
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 查找SPL Token索引
|
||||
splTokenIndex := int64(-1)
|
||||
for i, v := range accountKeys {
|
||||
if v == conf.SolSplToken {
|
||||
splTokenIndex = int64(i)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// SPL Token的Mint地址,即不包含USDT交易信息
|
||||
if splTokenIndex == -1 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析 USDT Token 账户 【Token Address => Owner Address】
|
||||
usdtTokenAccountMap := make(map[string]string)
|
||||
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
|
||||
for _, itm := range trans.Get("meta." + v).Array() {
|
||||
if itm.Get("mint").String() != conf.UsdtSolana || itm.Get("programId").String() != conf.SolSplToken {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
usdtTokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = itm.Get("owner").String()
|
||||
}
|
||||
}
|
||||
|
||||
transArr := make([]transfer, 0)
|
||||
|
||||
// 解析外部指令
|
||||
for _, instr := range trans.Get("transaction.message.instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, usdtTokenAccountMap))
|
||||
}
|
||||
|
||||
// 解析内部指令
|
||||
innerInstructions := trans.Get("meta.innerInstructions").Array()
|
||||
if len(innerInstructions) == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, itm := range innerInstructions {
|
||||
for _, instr := range itm.Get("instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
// 不是SPL Token的指令,即不会包含合约代表 transfer 的指令
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, usdtTokenAccountMap))
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤无关交易
|
||||
result := make([]transfer, 0)
|
||||
for _, t := range transArr {
|
||||
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
t.TxHash = hash
|
||||
t.Network = conf.Solana
|
||||
t.BlockNum = slot
|
||||
t.Timestamp = timestamp
|
||||
t.TradeType = model.OrderTradeTypeUsdtSolana
|
||||
|
||||
result = append(result, t)
|
||||
}
|
||||
|
||||
if len(result) > 0 {
|
||||
transferQueue.In <- result
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", slot, conf.GetBlockSuccRate(network), network)
|
||||
}
|
||||
|
||||
func (s *solana) parseTransfer(instr gjson.Result, accountKeys []string, usdtTokenAccountMap map[string]string) transfer {
|
||||
accounts := instr.Get("accounts").Array()
|
||||
trans := transfer{}
|
||||
if len(accounts) < 3 { // from to singer,至少存在3个账户索引,如果是多签则 > 3
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
data := base58.Decode(instr.Get("data").String())
|
||||
dLen := len(data)
|
||||
isTransfer := data[0] == 3 && dLen == 9
|
||||
isTransferChecked := data[0] == 12 && dLen == 10
|
||||
if !isTransfer && !isTransferChecked {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
var exp int32 = -6
|
||||
if isTransferChecked {
|
||||
exp = int32(data[9]) * -1
|
||||
}
|
||||
|
||||
from, ok := usdtTokenAccountMap[accountKeys[accounts[0].Int()]]
|
||||
if !ok {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
trans.FromAddress = from
|
||||
trans.RecvAddress = usdtTokenAccountMap[accountKeys[accounts[1].Int()]]
|
||||
if isTransferChecked {
|
||||
trans.RecvAddress = usdtTokenAccountMap[accountKeys[accounts[2].Int()]]
|
||||
}
|
||||
|
||||
buf := make([]byte, 8)
|
||||
copy(buf[:], data[1:9])
|
||||
number := binary.LittleEndian.Uint64(buf)
|
||||
b := new(big.Int)
|
||||
b.SetUint64(number)
|
||||
trans.Amount = decimal.NewFromBigInt(b, exp) // USDT的精度是6位小数
|
||||
|
||||
return trans
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func orderTransferHandle(context.Context) {
|
||||
var orders = getAllWaitingOrders()
|
||||
for _, t := range transfers {
|
||||
// debug
|
||||
//if t.Network == conf.Xlayer {
|
||||
//if t.Network == conf.Aptos {
|
||||
// fmt.Println(t.Network, t.TradeType, t.TxHash, t.Amount.String(), t.RecvAddress)
|
||||
//}
|
||||
|
||||
@@ -83,7 +83,7 @@ func orderTransferHandle(context.Context) {
|
||||
o.MarkSuccess(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp)
|
||||
|
||||
model.PushWebhookEvent(model.WebhookEventOrderPaid, o)
|
||||
|
||||
|
||||
go notify.Handle(o) // 通知订单支付成功
|
||||
go bot2.SendTradeSuccMsg(o) // TG发送订单信息
|
||||
}
|
||||
|
||||
@@ -23,31 +23,41 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Tron区块确认偏移量
|
||||
const tronBlockConfirmedOffset = 30
|
||||
const tronBlockInitStartOffset = -400 // 大概为过去20分钟的区块高度
|
||||
|
||||
// usdt trc20 contract address 41a614f803b6fd780986a42c78ec9c7f77e6ded13c TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
|
||||
var gasFreeUsdtTokenAddress = []byte{0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd, 0x78, 0x09, 0x86, 0xa4, 0x2c, 0x78, 0xec, 0x9c, 0x7f, 0x77, 0xe6, 0xde, 0xd1, 0x3c}
|
||||
var gasFreeOwnerAddress = []byte{0x41, 0x3b, 0x41, 0x50, 0x50, 0xb1, 0xe7, 0x9e, 0x38, 0x50, 0x7c, 0xb6, 0xe4, 0x8d, 0xac, 0xc2, 0x27, 0xaf, 0xfd, 0xd5, 0x0c}
|
||||
var gasFreeContractAddress = []byte{0x41, 0x39, 0xdd, 0x12, 0xa5, 0x4e, 0x2b, 0xab, 0x7c, 0x82, 0xaa, 0x14, 0xa1, 0xe1, 0x58, 0xb3, 0x42, 0x63, 0xd2, 0xd5, 0x10}
|
||||
var usdtTrc20ContractAddress = []byte{0x41, 0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd, 0x78, 0x09, 0x86, 0xa4, 0x2c, 0x78, 0xec, 0x9c, 0x7f, 0x77, 0xe6, 0xde, 0xd1, 0x3c}
|
||||
var tronLastBlockNum int64
|
||||
var tronBlockScanQueue = chanx.NewUnboundedChan[int64](context.Background(), 30)
|
||||
var params = grpc.ConnectParams{
|
||||
var grpcParams = grpc.ConnectParams{
|
||||
Backoff: backoff.Config{BaseDelay: 1 * time.Second, MaxDelay: 30 * time.Second, Multiplier: 1.5},
|
||||
MinConnectTimeout: 1 * time.Minute,
|
||||
}
|
||||
|
||||
type usdtTrc20TransferRaw struct {
|
||||
RecvAddress string
|
||||
Amount int64
|
||||
type tron struct {
|
||||
blockConfirmedOffset int64
|
||||
blockInitStartOffset int64
|
||||
lastBlockNum int64
|
||||
blockScanQueue *chanx.UnboundedChan[int64]
|
||||
}
|
||||
|
||||
var tr tron
|
||||
|
||||
func init() {
|
||||
register(task{duration: time.Second * 3, callback: tronBlockRoll}) // 大概3秒产生一个区块
|
||||
register(task{duration: time.Second, callback: tronBlockDispatch})
|
||||
tr = newTron()
|
||||
register(task{duration: time.Second * 3, callback: tr.blockRoll}) // 大概3秒产生一个区块
|
||||
register(task{duration: time.Second, callback: tr.blockDispatch})
|
||||
}
|
||||
|
||||
func tronBlockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, tronBlockParse)
|
||||
func newTron() tron {
|
||||
return tron{
|
||||
blockConfirmedOffset: 30, // 区块确认偏移量
|
||||
blockInitStartOffset: -400, // 大概为过去20分钟的区块高度
|
||||
lastBlockNum: 0,
|
||||
blockScanQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tron) blockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, t.blockParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -56,19 +66,19 @@ func tronBlockDispatch(context.Context) {
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range tronBlockScanQueue.Out {
|
||||
for n := range t.blockScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
tronBlockScanQueue.In <- n
|
||||
t.blockScanQueue.In <- n
|
||||
|
||||
log.Warn("Tron Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tronBlockRoll(context.Context) {
|
||||
func (t *tron) blockRoll(context.Context) {
|
||||
var node = conf.GetTronGrpcNode()
|
||||
|
||||
conn, err := grpc.NewClient(node, grpc.WithConnectParams(params), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
conn, err := grpc.NewClient(node, grpc.WithConnectParams(grpcParams), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
|
||||
log.Error("grpc.NewClient", err)
|
||||
@@ -91,36 +101,36 @@ func tronBlockRoll(context.Context) {
|
||||
var now = block.BlockHeader.RawData.Number
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - tronBlockConfirmedOffset
|
||||
now = now - t.blockConfirmedOffset
|
||||
}
|
||||
|
||||
// 首次启动
|
||||
if tronLastBlockNum == 0 {
|
||||
if t.lastBlockNum == 0 {
|
||||
|
||||
tronLastBlockNum = now + tronBlockInitStartOffset
|
||||
t.lastBlockNum = now + t.blockInitStartOffset
|
||||
}
|
||||
|
||||
// 区块高度没有变化
|
||||
if now <= tronLastBlockNum {
|
||||
if now <= t.lastBlockNum {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 待扫描区块入列
|
||||
for n := tronLastBlockNum + 1; n <= now; n++ {
|
||||
for n := t.lastBlockNum + 1; n <= now; n++ {
|
||||
|
||||
tronBlockScanQueue.In <- n
|
||||
t.blockScanQueue.In <- n
|
||||
}
|
||||
|
||||
tronLastBlockNum = now
|
||||
t.lastBlockNum = now
|
||||
}
|
||||
|
||||
func tronBlockParse(n any) {
|
||||
func (t *tron) blockParse(n any) {
|
||||
var num = n.(int64)
|
||||
var node = conf.GetTronGrpcNode()
|
||||
var conn *grpc.ClientConn
|
||||
var err error
|
||||
if conn, err = grpc.NewClient(node, grpc.WithConnectParams(params), grpc.WithTransportCredentials(insecure.NewCredentials())); err != nil {
|
||||
if conn, err = grpc.NewClient(node, grpc.WithConnectParams(grpcParams), grpc.WithTransportCredentials(insecure.NewCredentials())); err != nil {
|
||||
|
||||
log.Error("grpc.NewClient", err)
|
||||
}
|
||||
@@ -131,27 +141,27 @@ func tronBlockParse(n any) {
|
||||
conf.SetBlockTotal(conf.Tron)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*3)
|
||||
block, err1 := client.GetBlockByNum2(ctx, &api.NumberMessage{Num: num})
|
||||
bok, err2 := client.GetBlockByNum2(ctx, &api.NumberMessage{Num: num})
|
||||
cancel()
|
||||
if err1 != nil {
|
||||
if err2 != nil {
|
||||
conf.SetBlockFail(conf.Tron)
|
||||
tronBlockScanQueue.In <- num
|
||||
log.Warn("GetBlockByNum Error", err1)
|
||||
t.blockScanQueue.In <- num
|
||||
log.Warn("GetBlockByNum2 Error", err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var resources = make([]resource, 0)
|
||||
var transfers = make([]transfer, 0)
|
||||
var timestamp = time.UnixMilli(block.GetBlockHeader().GetRawData().GetTimestamp())
|
||||
for _, v := range block.GetTransactions() {
|
||||
if !v.Result.Result {
|
||||
var timestamp = time.UnixMilli(bok.GetBlockHeader().GetRawData().GetTimestamp())
|
||||
for _, trans := range bok.GetTransactions() {
|
||||
if !trans.Result.Result {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var itm = v.GetTransaction()
|
||||
var id = hex.EncodeToString(v.Txid)
|
||||
var itm = trans.GetTransaction()
|
||||
var id = hex.EncodeToString(trans.Txid)
|
||||
for _, contract := range itm.GetRawData().GetContract() {
|
||||
// 资源代理 DelegateResourceContract
|
||||
if contract.GetType() == core.Transaction_Contract_DelegateResourceContract {
|
||||
@@ -167,8 +177,8 @@ func tronBlockParse(n any) {
|
||||
Type: core.Transaction_Contract_DelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ReceiverAddress),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
@@ -187,8 +197,8 @@ func tronBlockParse(n any) {
|
||||
Type: core.Transaction_Contract_UnDelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ReceiverAddress),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
@@ -206,8 +216,8 @@ func tronBlockParse(n any) {
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(foo.Amount), -6),
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ToAddress),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ToAddress),
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeTronTrx,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
@@ -219,33 +229,58 @@ func tronBlockParse(n any) {
|
||||
// 触发智能合约
|
||||
if contract.GetType() == core.Transaction_Contract_TriggerSmartContract {
|
||||
var foo = &core.TriggerSmartContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
if err := contract.GetParameter().UnmarshalTo(foo); err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var transItem = transfer{Timestamp: timestamp, TxHash: id, FromAddress: base58CheckEncode(foo.OwnerAddress)}
|
||||
var reader = bytes.NewReader(foo.GetData())
|
||||
if !bytes.Equal(foo.GetContractAddress(), usdtTrc20ContractAddress) { // usdt trc20 contract
|
||||
// Gas Free 钱包 合约授权转账
|
||||
if bytes.Equal(foo.OwnerAddress, gasFreeOwnerAddress) && bytes.Equal(foo.ContractAddress, gasFreeContractAddress) {
|
||||
from, receiver, amount := t.gasFreePermitTransfer(foo.GetData())
|
||||
if from == "" || receiver == "" || amount == nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(amount.Int64()), -6),
|
||||
FromAddress: from,
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeUsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析合约数据
|
||||
var trc20Contract = parseUsdtTrc20Contract(reader)
|
||||
if trc20Contract.Amount == 0 {
|
||||
{
|
||||
var reader = bytes.NewReader(foo.GetData())
|
||||
if !bytes.Equal(foo.GetContractAddress(), usdtTrc20ContractAddress) { // usdt trc20 contract
|
||||
|
||||
continue
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析合约数据
|
||||
var recvAddress, amount = t.parseUsdtTrc20Contract(reader)
|
||||
if amount == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(amount), -6),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: recvAddress,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeUsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
})
|
||||
}
|
||||
|
||||
transItem.Network = conf.Tron
|
||||
transItem.TradeType = model.OrderTradeTypeUsdtTrc20
|
||||
transItem.Amount = decimal.NewFromBigInt(new(big.Int).SetInt64(trc20Contract.Amount), -6)
|
||||
transItem.RecvAddress = trc20Contract.RecvAddress
|
||||
transItem.BlockNum = cast.ToInt64(num)
|
||||
|
||||
transfers = append(transfers, transItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,18 +296,18 @@ func tronBlockParse(n any) {
|
||||
log.Info("区块扫描完成", num, conf.GetBlockSuccRate(conf.Tron), conf.Tron)
|
||||
}
|
||||
|
||||
func parseUsdtTrc20Contract(reader *bytes.Reader) usdtTrc20TransferRaw {
|
||||
func (t *tron) parseUsdtTrc20Contract(reader *bytes.Reader) (string, int64) {
|
||||
var funcName = make([]byte, 4)
|
||||
_, err = reader.Read(funcName)
|
||||
if err != nil {
|
||||
// 读取funcName失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
return "", 0
|
||||
}
|
||||
if !bytes.Equal(funcName, []byte{0xa9, 0x05, 0x9c, 0xbb}) { // a9059cbb transfer(address,uint256)
|
||||
// funcName不匹配transfer
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var addressBytes = make([]byte, 20)
|
||||
@@ -280,24 +315,50 @@ func parseUsdtTrc20Contract(reader *bytes.Reader) usdtTrc20TransferRaw {
|
||||
if err != nil {
|
||||
// 读取toAddress失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var toAddress = base58CheckEncode(append([]byte{0x41}, addressBytes...))
|
||||
var toAddress = t.base58CheckEncode(append([]byte{0x41}, addressBytes...))
|
||||
var value = make([]byte, 32)
|
||||
_, err = reader.ReadAt(value, 36)
|
||||
if err != nil {
|
||||
// 读取value失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var amount, _ = strconv.ParseInt(hex.EncodeToString(value), 16, 64)
|
||||
|
||||
return usdtTrc20TransferRaw{RecvAddress: toAddress, Amount: amount}
|
||||
return toAddress, amount
|
||||
}
|
||||
|
||||
func base58CheckEncode(input []byte) string {
|
||||
func (t *tron) gasFreePermitTransfer(data []byte) (string, string, *big.Int) {
|
||||
// https://tronscan.org/#/contract/TFFAMQLZybALaLb4uxHA9RBE7pxhUAjF3U/code?func=Tab-proxywrite-F3proxyNonePayable
|
||||
if len(data) != 420 {
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[:4], []byte{0x6f, 0x21, 0xb8, 0x98}) {
|
||||
// not permitTransfer (6f21b898) function
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[16:36], gasFreeUsdtTokenAddress) {
|
||||
// not gas free usdt token address
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
user := t.base58CheckEncode(append([]byte{0x41}, data[48:68]...))
|
||||
receiver := t.base58CheckEncode(append([]byte{0x41}, data[80:100]...))
|
||||
amount := big.NewInt(0).SetBytes(data[100:132])
|
||||
|
||||
return user, receiver, amount
|
||||
}
|
||||
|
||||
func (t *tron) base58CheckEncode(input []byte) string {
|
||||
checksum := chainhash.DoubleHashB(input)
|
||||
checksum = checksum[:4]
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package app
|
||||
|
||||
// Version 版本号说明 1.0.0 代表主版本号.功能版本号.修订号
|
||||
const Version = "1.20.6"
|
||||
const Version = "1.21.1"
|
||||
|
||||
@@ -3,6 +3,9 @@ package web
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
@@ -10,8 +13,6 @@ import (
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/web/epay"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
func signVerify(ctx *gin.Context) {
|
||||
@@ -24,7 +25,7 @@ func signVerify(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var m = make(map[string]any)
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
log.Error(err.Error())
|
||||
ctx.JSON(400, gin.H{"error": err.Error()})
|
||||
@@ -55,7 +56,7 @@ func signVerify(ctx *gin.Context) {
|
||||
|
||||
func createTransaction(ctx *gin.Context) {
|
||||
var address string
|
||||
var data = ctx.GetStringMap("data")
|
||||
data := ctx.GetStringMap("data")
|
||||
var timeout uint64 = 0
|
||||
for _, key := range []string{"order_id", "amount", "notify_url", "redirect_url"} {
|
||||
if _, ok := data[key]; !ok {
|
||||
@@ -66,7 +67,7 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
var tradeType, ok = data["trade_type"]
|
||||
tradeType, ok := data["trade_type"]
|
||||
if !ok {
|
||||
tradeType = model.OrderTradeTypeUsdtTrc20 // 默认 USDT TRC20
|
||||
}
|
||||
@@ -78,7 +79,6 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
if v, ok := data["timeout"]; ok {
|
||||
|
||||
timeout = cast.ToUint64(v)
|
||||
}
|
||||
if v, ok := data["address"]; ok && cast.ToString(v) != "" {
|
||||
@@ -91,14 +91,13 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
var host = "http://" + ctx.Request.Host
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
var orderId = cast.ToString(data["order_id"])
|
||||
var params = orderParams{
|
||||
orderId := cast.ToString(data["order_id"])
|
||||
params := orderParams{
|
||||
Money: cast.ToFloat64(data["amount"]),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
PayAddress: address,
|
||||
@@ -108,9 +107,10 @@ func createTransaction(ctx *gin.Context) {
|
||||
NotifyUrl: cast.ToString(data["notify_url"]),
|
||||
Name: orderId,
|
||||
Timeout: timeout,
|
||||
Rate: cast.ToString(data["rate"]),
|
||||
}
|
||||
|
||||
var order, err = buildOrder(params)
|
||||
order, err := buildOrder(params)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
|
||||
@@ -132,7 +132,7 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func cancelTransaction(ctx *gin.Context) {
|
||||
var data = ctx.GetStringMap("data")
|
||||
data := ctx.GetStringMap("data")
|
||||
tradeId, ok := data["trade_id"].(string)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("参数 trade_id 不存在"))
|
||||
@@ -140,7 +140,7 @@ func cancelTransaction(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var order, ok2 = model.GetTradeOrder(tradeId)
|
||||
order, ok2 := model.GetTradeOrder(tradeId)
|
||||
if !ok2 {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
@@ -165,8 +165,8 @@ func cancelTransaction(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func checkoutCounter(ctx *gin.Context) {
|
||||
var tradeId = ctx.Param("trade_id")
|
||||
var order, ok = model.GetTradeOrder(tradeId)
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.String(200, "订单不存在")
|
||||
|
||||
@@ -195,8 +195,8 @@ func checkoutCounter(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func checkStatus(ctx *gin.Context) {
|
||||
var tradeId = ctx.Param("trade_id")
|
||||
var order, ok = model.GetTradeOrder(tradeId)
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
|
||||
@@ -2,13 +2,14 @@ package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/task/rate"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type orderParams struct {
|
||||
@@ -21,6 +22,7 @@ type orderParams struct {
|
||||
NotifyUrl string `json:"notify_url"` // 异步通知地址
|
||||
Name string `json:"name"` // 商品名称
|
||||
Timeout uint64 `json:"timeout"` // 订单超时时间(秒)
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
}
|
||||
|
||||
func buildOrder(p orderParams) (model.TradeOrders, error) {
|
||||
@@ -29,7 +31,6 @@ func buildOrder(p orderParams) (model.TradeOrders, error) {
|
||||
|
||||
model.DB.Where("order_id = ?", p.OrderId).Find(&order)
|
||||
if order.Status == model.OrderStatusWaiting || order.Status == model.OrderStatusSuccess {
|
||||
|
||||
return order, nil
|
||||
}
|
||||
|
||||
@@ -38,16 +39,23 @@ func buildOrder(p orderParams) (model.TradeOrders, error) {
|
||||
defer lock.Unlock()
|
||||
|
||||
// 获取兑换汇率
|
||||
var calcRate = rate.GetUsdtCalcRate()
|
||||
if p.TradeType == model.OrderTradeTypeTronTrx {
|
||||
|
||||
calcRate = rate.GetTrxCalcRate()
|
||||
var calcRate float64
|
||||
if p.Rate != "" {
|
||||
rawRate := rate.GetOkxUsdtRawRate()
|
||||
if p.TradeType == model.OrderTradeTypeTronTrx {
|
||||
rawRate = rate.GetOkxTrxRawRate()
|
||||
}
|
||||
calcRate = rate.ParseFloatRate(p.Rate, rawRate)
|
||||
} else {
|
||||
calcRate = rate.GetUsdtCalcRate()
|
||||
if p.TradeType == model.OrderTradeTypeTronTrx {
|
||||
calcRate = rate.GetTrxCalcRate()
|
||||
}
|
||||
}
|
||||
|
||||
// 获取钱包地址
|
||||
var wallet = model.GetAvailableAddress(p.PayAddress, p.TradeType)
|
||||
wallet := model.GetAvailableAddress(p.PayAddress, p.TradeType)
|
||||
if len(wallet) == 0 {
|
||||
|
||||
return order, fmt.Errorf(fmt.Sprintf("类型(%s)没检测到可用收款地址", p.TradeType))
|
||||
}
|
||||
|
||||
@@ -55,20 +63,19 @@ func buildOrder(p orderParams) (model.TradeOrders, error) {
|
||||
address, amount := model.CalcTradeAmount(wallet, calcRate, p.Money, p.TradeType)
|
||||
tradeId, err := help.GenerateTradeId()
|
||||
if err != nil {
|
||||
|
||||
return order, err
|
||||
}
|
||||
|
||||
// 超时处理
|
||||
var timeout = conf.GetExpireTime() * time.Second
|
||||
timeout := conf.GetExpireTime() * time.Second
|
||||
if p.Timeout >= 60 { // 至少60秒
|
||||
|
||||
timeout = time.Duration(p.Timeout) * time.Second
|
||||
}
|
||||
|
||||
// 创建交易订单
|
||||
var expiredAt = time.Now().Add(timeout)
|
||||
var tradeOrder = model.TradeOrders{
|
||||
expiredAt := time.Now().Add(timeout)
|
||||
tradeOrder := model.TradeOrders{
|
||||
OrderId: p.OrderId,
|
||||
TradeId: tradeId,
|
||||
TradeHash: tradeId, // 这里默认填充一个本地交易ID,等支付成功后再更新为实际交易哈希
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
## 📚 接口文档
|
||||
|
||||
<details>
|
||||
<summary>创建订单</summary>
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/create-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 可根据实际情况传入收款地址,亦可留空
|
||||
"trade_type": "usdt.trc20", // usdt.trc20(默认) tron.trx 可选列表 https://github.com/v03413/bepusdt/blob/16d8df2cc5acc3d41c1c014ecb5370bd97f7e955/app/model/orders.go#L25:L30
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": 28.88, // 请求支付金额,CNY
|
||||
"signature":"123456abcd", // 签名
|
||||
"notify_url": "https://example.com/callback", // 回调地址
|
||||
"redirect_url": "https://example.com/callback", // 支付成功跳转地址
|
||||
"timeout": 1200, // 超时时间(秒) 最低60;留空则取配置文件 expire_time,还是没有取默认600
|
||||
"rate": 7.4 // 强制指定汇率,留空则取配置汇率;支持多种写法,如:7.4表示固定7.4、~1.02表示最新汇率上浮2%、~0.97表示最新汇率下浮3%、+0.3表示最新加0.3、-0.2表示最新减0.2
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415", // 本地交易ID
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": "28.88", // 请求支付金额,CNY
|
||||
"actual_amount": "10", // 实际支付数额 usdt or trx
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 收款地址
|
||||
"expiration_time": 1200, // 订单有效期,秒
|
||||
"payment_url": "https://example.com//pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415" // 收银台地址
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>取消订单</summary>
|
||||
|
||||
商户端系统可以通过此接口取消订单,取消后,系统将不再监控此订单,同时释放对应金额占用。
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/cancel-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ", // 交易ID
|
||||
"signature":"123456abcd" // 签名内容
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ"
|
||||
},
|
||||
"message": "success",
|
||||
"request_id": "",
|
||||
"status_code": 200
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>回调通知</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415",
|
||||
"order_id": "787240927112940881",
|
||||
"amount": 28.88,
|
||||
"actual_amount": 10,
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"block_transaction_id": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"signature": "123456abcd",
|
||||
"status": 2 // 1:等待支付 2:支付成功 3:支付超时
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 签名算法
|
||||
|
||||
签名生成的通用步骤如下:
|
||||
|
||||
第一步,将所有非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成
|
||||
`待加密参数`。
|
||||
|
||||
重要规则:
|
||||
◆ 参数名ASCII码从小到大排序(字典序);
|
||||
◆ 如果参数的值为空不参与签名;
|
||||
◆ 参数名区分大小写;
|
||||
第二步,`待加密参数`最后拼接上`api接口认证token`得到`待签名字符串`,并对`待签名字符串`进行MD5运算,再将得到的`MD5字符串`
|
||||
所有字符转换为`小写`,得到签名`signature`。 注意:`signature`的长度为32个字节。
|
||||
|
||||
举例:
|
||||
|
||||
假设传送的参数如下:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
```
|
||||
|
||||
假设api接口认证token为:`epusdt_password_xasddawqe`(api接口认证token可以在`conf.toml`文件设置)
|
||||
|
||||
第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:
|
||||
|
||||
```
|
||||
amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirect
|
||||
```
|
||||
|
||||
第二步:拼接API密钥并加密:
|
||||
|
||||
```
|
||||
MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirectepusdt_password_xasddawqe)
|
||||
```
|
||||
|
||||
最终得到最终发送的数据:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
signature : 1cd4b52df5587cfb1968b0c0c6e156cd
|
||||
```
|
||||
|
||||
## 参考引用
|
||||
|
||||
- https://github.com/assimon/epusdt/blob/master/wiki/API.md
|
||||
@@ -1,44 +0,0 @@
|
||||
# 彩虹易支付对接教程
|
||||
|
||||
从版本号`v1.14.0`开始,Bepusdt开始原生支持易支付对接,没有三方插件依赖,可直接对接使用;目前网上流传的易支付改版很多,可能做不到100%兼容,有问题可以issue反馈。
|
||||
|
||||
本教程测试的易支付版本号,如下:
|
||||
|
||||

|
||||
|
||||
其它版本的易支付,可能会有一些不同,但是大体上是一样。
|
||||
|
||||
## 对接教程
|
||||
|
||||
### 1. 增加支付方式
|
||||
|
||||
找到易支付自带的原生插件文件,增加两种支付方式 `tron.trx`和`usdt.trc20`,照着下图改。
|
||||
|
||||

|
||||
|
||||
改外后回到后台,支付插件刷新,找到易支付插件,确保支付方式添加成功,如图:
|
||||

|
||||
|
||||
增加支付方式:`后台` -> `支付方式` -> `新增`,必须确保`调用值`与下图完全一致:
|
||||
|
||||

|
||||
|
||||
如果保存提示`调用值不符合规则`,请找到下图文件的两行代码临时注释掉,保存后再取消注释即可。
|
||||
|
||||

|
||||
|
||||
### 2. 增加支付通道
|
||||
|
||||
`后台` -> `支付通道` -> `新增`,参考如图:
|
||||
|
||||

|
||||
|
||||
支付方式选择刚才添加的其中一种,插件选择彩虹易支付,其它参数自行调整,最后保存。
|
||||
|
||||
配置密钥,如图,按照自己的情况填写:
|
||||
|
||||

|
||||
|
||||
最后保存,然后就可以开始测试是否可以正常支付了。
|
||||
|
||||
---
|
||||
|
Before Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 326 KiB |
|
Before Width: | Height: | Size: 143 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 83 KiB |
|
Before Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 108 KiB |
@@ -1,52 +0,0 @@
|
||||
# 签名算法
|
||||
|
||||
签名生成的通用步骤如下:
|
||||
|
||||
第一步,将所有非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成
|
||||
`待加密参数`。
|
||||
|
||||
重要规则:
|
||||
◆ 参数名ASCII码从小到大排序(字典序);
|
||||
◆ 如果参数的值为空不参与签名;
|
||||
◆ 参数名区分大小写;
|
||||
第二步,`待加密参数`最后拼接上`api接口认证token`得到`待签名字符串`,并对`待签名字符串`进行MD5运算,再将得到的`MD5字符串`
|
||||
所有字符转换为`小写`,得到签名`signature`。 注意:`signature`的长度为32个字节。
|
||||
|
||||
举例:
|
||||
|
||||
假设传送的参数如下:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
```
|
||||
|
||||
假设api接口认证token为:`epusdt_password_xasddawqe`(api接口认证token可以在`conf.toml`文件设置)
|
||||
|
||||
第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:
|
||||
|
||||
```
|
||||
amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirect
|
||||
```
|
||||
|
||||
第二步:拼接API密钥并加密:
|
||||
|
||||
```
|
||||
MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirectepusdt_password_xasddawqe)
|
||||
```
|
||||
|
||||
最终得到最终发送的数据:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
signature : 1cd4b52df5587cfb1968b0c0c6e156cd
|
||||
```
|
||||
|
||||
## 参考引用
|
||||
|
||||
- https://github.com/assimon/epusdt/blob/master/wiki/API.md
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・Aptos 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Aptos</strong> 区块网络进行转账
|
||||
<span class="network-badge">Aptos</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Aptos 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Aptos 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・Solana 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Solana</strong> 区块网络进行转账
|
||||
<span class="network-badge">Solana</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Solana 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Solana 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||