mirror of
https://github.com/GMWalletApp/epusdt.git
synced 2026-07-07 10:16:15 +00:00
Compare commits
35 Commits
9c533a7ff8
...
v1.0.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 2a00a0332b | |||
| 8a48611625 | |||
| dec1b97b9e | |||
| 449d22a41b | |||
| 4b4701f5b9 | |||
| f4ef71b359 | |||
| c19a7e5f2c | |||
| 09642d4c2b | |||
| 9f9b258d59 | |||
| 85b81e661c | |||
| 049a15cb95 | |||
| 2a36a10e7f | |||
| 864eb5969c | |||
| b0093c48c7 | |||
| 4a69b7c863 | |||
| 52b171b49b | |||
| 4dc1ba88cd | |||
| 7a905ba307 | |||
| 07d1d8345f | |||
| 8d2ddbd045 | |||
| 1c805ed061 | |||
| 84972ea0f0 | |||
| 7c9e3e123e | |||
| 3e0be9bb20 | |||
| a8a3b8697f | |||
| 2d546e3478 | |||
| 1a35cab919 | |||
| ff157c33d9 | |||
| 51ad344b36 | |||
| 3623a543bb | |||
| 377176a0f2 | |||
| a4022df7b4 | |||
| 32aa1b66f5 | |||
| 53e66bad35 | |||
| ff68279b0f |
@@ -1,11 +1,7 @@
|
|||||||
name: docker-alpine-epusdt
|
name: docker-alpine-epusdt
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
push:
|
||||||
branches:
|
|
||||||
- "main"
|
|
||||||
- "master"
|
|
||||||
tags:
|
tags:
|
||||||
- "v*"
|
- "v*"
|
||||||
|
|
||||||
@@ -34,7 +30,6 @@ jobs:
|
|||||||
tags: |
|
tags: |
|
||||||
type=raw,value=alpine
|
type=raw,value=alpine
|
||||||
type=raw,value=latest
|
type=raw,value=latest
|
||||||
type=ref,event=branch,suffix=-alpine
|
|
||||||
type=ref,event=tag
|
type=ref,event=tag
|
||||||
type=sha,prefix=sha-,suffix=-alpine
|
type=sha,prefix=sha-,suffix=-alpine
|
||||||
|
|
||||||
@@ -53,5 +48,6 @@ jobs:
|
|||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
build-args: |
|
build-args: |
|
||||||
API_RATE_URL=${{ vars.API_RATE_URL }}
|
API_RATE_URL=${{ vars.API_RATE_URL }}
|
||||||
|
BUILD_VERSION=${{ github.ref_name }}
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|||||||
+2
-3
@@ -8,8 +8,9 @@ WORKDIR /app
|
|||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
WORKDIR /app/src
|
WORKDIR /app/src
|
||||||
|
ARG BUILD_VERSION=0.0.0-dev
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
RUN go build -o /app/epusdt .
|
RUN go build -trimpath -ldflags="-s -w -X github.com/GMWalletApp/epusdt/config.BuildVersion=${BUILD_VERSION}" -o /app/epusdt .
|
||||||
|
|
||||||
FROM alpine:latest AS runner
|
FROM alpine:latest AS runner
|
||||||
ENV TZ=Asia/Shanghai
|
ENV TZ=Asia/Shanghai
|
||||||
@@ -17,8 +18,6 @@ RUN apk --no-cache add ca-certificates tzdata
|
|||||||
ARG API_RATE_URL=""
|
ARG API_RATE_URL=""
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=builder /app/src/static /app/static
|
|
||||||
COPY --from=builder /app/src/static /static
|
|
||||||
COPY --from=builder /app/src/.env.example /app/.env
|
COPY --from=builder /app/src/.env.example /app/.env
|
||||||
RUN if [ -n "$API_RATE_URL" ]; then \
|
RUN if [ -n "$API_RATE_URL" ]; then \
|
||||||
sed -i "s|^api_rate_url=.*$|api_rate_url=${API_RATE_URL}|" /app/.env; \
|
sed -i "s|^api_rate_url=.*$|api_rate_url=${API_RATE_URL}|" /app/.env; \
|
||||||
|
|||||||
+176
@@ -0,0 +1,176 @@
|
|||||||
|
# Epusdt — Easy Payment USDT
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="https://gmwallet.app/favicon.png" alt="Epusdt Logo - Multi-chain Crypto Payment Gateway" width="120">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<strong>Open-source multi-chain crypto payment gateway · Top real-world adoption</strong>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./README.en.md">English</a> |
|
||||||
|
<a href="./README.zh-CN.md">简体中文</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://epusdt.com"><img src="https://img.shields.io/badge/Docs-epusdt.com-blue?style=for-the-badge" alt="Official Docs"></a>
|
||||||
|
<a href="https://t.me/epusdt"><img src="https://img.shields.io/badge/Telegram-Channel-26A5E4?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram Channel"></a>
|
||||||
|
<a href="https://t.me/epusdt_group"><img src="https://img.shields.io/badge/Telegram-Group-26A5E4?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram Group"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/GMWalletApp/epusdt/stargazers"><img src="https://img.shields.io/github/stars/GMWalletApp/epusdt?style=flat-square&color=f5c542" alt="GitHub Stars 3000+"></a>
|
||||||
|
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/badge/License-GPLv3-blue?style=flat-square" alt="GPLv3 License"></a>
|
||||||
|
<a href="https://golang.org"><img src="https://img.shields.io/badge/Go-1.16+-00ADD8?style=flat-square&logo=go&logoColor=white" alt="Go 1.16+"></a>
|
||||||
|
<a href="https://github.com/GMWalletApp/epusdt/releases"><img src="https://img.shields.io/github/v/release/GMWalletApp/epusdt?style=flat-square&color=green" alt="Latest Release"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What is Epusdt?
|
||||||
|
|
||||||
|
**Epusdt** (Easy Payment USDT) is a self-hosted **multi-chain, multi-token crypto payment gateway** built with Go. It started as a TRC20-only solution and evolved into a broader **multi-chain receiving platform**, allowing websites and applications to accept crypto payments across multiple networks and token types. No third-party custody, no platform fees — funds go directly into your wallet.
|
||||||
|
|
||||||
|
> **GitHub Star 3000+** · **10+ supported platform integrations** · **Top real-world adoption among crypto payment tools**
|
||||||
|
|
||||||
|
Deploy it privately, integrate with the HTTP API, and start receiving crypto payments in minutes.
|
||||||
|
|
||||||
|
### Supported Networks and Tokens
|
||||||
|
|
||||||
|
| Network | Tokens |
|
||||||
|
|---------|--------|
|
||||||
|
| **TRC20** (Tron) | USDT, TRX |
|
||||||
|
| **ERC20** (Ethereum) | USDT, USDC, ETH |
|
||||||
|
| **Solana** | USDT, USDC |
|
||||||
|
| **BEP20** (BSC) | USDT, USDC, BNB |
|
||||||
|
| **Polygon** | USDT, USDC |
|
||||||
|
| **More** | Expanding continuously |
|
||||||
|
|
||||||
|
> Actual support depends on the [latest release](https://github.com/GMWalletApp/epusdt/releases) and the [official docs](https://epusdt.com).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Broad Compatibility, Plug and Play
|
||||||
|
|
||||||
|
No matter what kind of platform you operate, Epusdt can fit into existing payment integration patterns with **minimal or no business logic refactor**, giving you a fast path to crypto payments for global use cases:
|
||||||
|
|
||||||
|
| Category | Supported Systems |
|
||||||
|
|----------|-------------------|
|
||||||
|
| **AI Distribution** | [OneAPI](https://github.com/songquanpeng/one-api), [NewAPI](https://github.com/QuantumNous/new-api) |
|
||||||
|
| **Card/Voucher Platforms** | [Dujiaoka](https://dujiao-next.com/), [ACG Faka](https://github.com/lizhipay/acg-faka) |
|
||||||
|
| **Proxy Panels** | [V2Board](https://github.com/v2board/v2board), [XBoard](https://github.com/cedar2025/Xboard), [xiaoV2board](https://github.com/wyx2685/v2board/), [SSPanel](https://github.com/anankke/sspanel-uim) |
|
||||||
|
| **Website Ecosystem** | [WordPress](https://wordpress.com/), [WHMCS](https://www.whmcs.com/) |
|
||||||
|
| **Epay-Compatible Flow** | Works with platforms already using Epay-style payment interfaces |
|
||||||
|
| **More** | Simple HTTP API, often integrated within 10 minutes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Features
|
||||||
|
|
||||||
|
- **Multi-chain and multi-token** — TRC20, ERC20, BEP20, Polygon, and more
|
||||||
|
- **Self-hosted** — full control of funds and wallet infrastructure
|
||||||
|
- **Low-dependency runtime** — a single binary can run the service; low-traffic setups do not require MySQL + Redis
|
||||||
|
- **Cross-platform** — supports x86 / ARM on Windows / Linux / Mac
|
||||||
|
- **Multi-wallet rotation** — rotates receiving addresses to improve concurrency handling
|
||||||
|
- **Async callback queue** — handles merchant notifications efficiently
|
||||||
|
- **HTTP API** — easy integration from any language or framework
|
||||||
|
- **Telegram Bot** — instant payment notifications and lightweight operations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation and Guides
|
||||||
|
|
||||||
|
Full documentation: **[epusdt.com](https://epusdt.com)**
|
||||||
|
|
||||||
|
Quick-start links:
|
||||||
|
|
||||||
|
| Guide | Description |
|
||||||
|
|-------|-------------|
|
||||||
|
| [Docker Deployment](https://epusdt.com/guide/installation/docker) | Recommended one-command setup |
|
||||||
|
| [aaPanel Deployment](https://epusdt.com/guide/installation/aapanel) | Great for aaPanel users |
|
||||||
|
| [Manual Deployment](https://epusdt.com/guide/installation/manual.html) | Full manual control |
|
||||||
|
| [Developer API Docs](https://epusdt.com) | Integration reference |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```text
|
||||||
|
Epusdt
|
||||||
|
├── src/ Core project source code
|
||||||
|
└── wiki/ Documentation assets and knowledge base
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
Epusdt listens to supported blockchain APIs or RPC nodes across multiple networks such as TRC20, ERC20, BEP20, and Polygon. It captures incoming token transfers in real time and matches ownership using **amount differentiation** and **time-bounded locks**:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Workflow:
|
||||||
|
1. A customer initiates payment and needs to send 20.05 USDT
|
||||||
|
2. The system searches for an available wallet-address + amount combination
|
||||||
|
3. If address_1:20.05 is free -> lock it for 10 minutes and return it
|
||||||
|
4. If already occupied -> add 0.0001 and try the next amount combination
|
||||||
|
5. Background listeners keep watching wallet deposits and mark the order paid once the amount matches
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Community and Support
|
||||||
|
|
||||||
|
If you hit an issue, please open a [GitHub Issue](https://github.com/GMWalletApp/epusdt/issues) first. That is the best way to get attention and help.
|
||||||
|
|
||||||
|
| Channel | Link |
|
||||||
|
|---------|------|
|
||||||
|
| Telegram Channel | [https://t.me/epusdt](https://t.me/epusdt) |
|
||||||
|
| Telegram Group | [https://t.me/epusdt_group](https://t.me/epusdt_group) |
|
||||||
|
| Official Docs | [https://epusdt.com](https://epusdt.com) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Star History
|
||||||
|
|
||||||
|
<a href="https://www.star-history.com/?type=date&repos=gmwalletapp%2Fepusdt">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=gmwalletapp/epusdt&type=date&theme=dark&legend=top-left" />
|
||||||
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=gmwalletapp/epusdt&type=date&legend=top-left" />
|
||||||
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=gmwalletapp/epusdt&type=date&legend=top-left" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Epusdt is released under the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) license.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Disclaimer and Terms of Use
|
||||||
|
|
||||||
|
EPusdt is developed and published by Good Morning Technology, LLC as free, open-source, non-profit, and non-custodial software for learning, research, and technical communication. Nothing in this project constitutes investment, financial, legal, tax, compliance, or any other professional advice, nor should it be interpreted as a guarantee regarding any asset, transaction outcome, revenue, fund safety, technical availability, or fitness for a particular purpose.
|
||||||
|
|
||||||
|
Good Morning Technology, LLC is an entity organized under United States law and will comply with applicable legal and regulatory obligations as required. Under U.S. regulatory frameworks, whether virtual currencies, digital assets, or related technical services constitute money transmission, a money services business (MSB), or another regulated activity generally depends on the specific business model, including whether the operator receives, holds, controls, or transmits funds or value, provides custody on behalf of users, or engages in exchange, payment, clearing, settlement, or other intermediary financial services.
|
||||||
|
|
||||||
|
As a free, open-source, non-profit, and non-custodial software project, the source code, documentation, technical communication, and related development activities of EPusdt should not be interpreted as authorization, endorsement, control, participation, warranty, or commitment by Good Morning Technology, LLC or its contributors regarding any user's downstream use, modification, deployment, integration, distribution, or secondary development.
|
||||||
|
|
||||||
|
Users independently determine how they use this project, for what purpose, and in what context. Good Morning Technology, LLC and its contributors cannot control, review, or restrict such conduct. Users are solely responsible for ensuring that their use, modification, deployment, integration, distribution, or derivative development complies with applicable laws, regulations, sanctions rules, and third-party rights in the relevant jurisdictions, and they bear all resulting risks, liabilities, and consequences.
|
||||||
|
|
||||||
|
Crypto assets are a high-risk emerging asset class. Stablecoins and other digital assets may experience sharp volatility, de-pegging, insufficient liquidity, technical failures, regulatory changes, or total loss of value. All code, documentation, and related materials in this project are provided on an "as is" and "as available" basis. Except where mandatory law provides otherwise, Good Morning Technology, LLC and its contributors are not liable for any direct or indirect loss resulting from use, inability to use, misuse, unlawful use, modification, deployment, integration, distribution, derivative development, or reliance on this project.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<sub>
|
||||||
|
<b>Keywords:</b> USDT Payment Gateway · Crypto Payment · Multi-chain Payment · TRC20 Payment · ERC20 Payment · BEP20 Payment ·
|
||||||
|
Self-hosted Crypto Gateway · OneAPI Payment · NewAPI Payment · Dujiaoka Payment · ACG Faka Payment ·
|
||||||
|
V2Board Payment · XBoard Payment · SSPanel Payment Interface ·
|
||||||
|
WordPress Crypto Payment · WHMCS USDT Payment · Polygon USDT ·
|
||||||
|
Epusdt · Easy Payment USDT · Open Source Payment Gateway · Multi-chain Collection
|
||||||
|
</sub>
|
||||||
|
</p>
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
# Epusdt — Easy Payment USDT
|
# Epusdt — Easy Payment USDT
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="wiki/img/usdtlogo.png" alt="Epusdt Logo - Multi-chain Crypto Payment Gateway" width="120">
|
<img src="https://gmwallet.app/favicon.png" alt="Epusdt Logo - Multi-chain Crypto Payment Gateway" width="120">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<strong>开源多链多币种 Crypto 支付网关 · 实际采用率 Top 1</strong>
|
<strong>开源多链多币种 Crypto 支付网关 · 实际采用率 Top 1</strong>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./README.en.md">English</a> |
|
||||||
|
<a href="./README.md">简体中文</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://epusdt.com"><img src="https://img.shields.io/badge/官网文档-epusdt.com-blue?style=for-the-badge" alt="Official Docs"></a>
|
<a href="https://epusdt.com"><img src="https://img.shields.io/badge/官网文档-epusdt.com-blue?style=for-the-badge" alt="Official Docs"></a>
|
||||||
<a href="https://t.me/epusdt"><img src="https://img.shields.io/badge/Telegram-频道-26A5E4?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram Channel"></a>
|
<a href="https://t.me/epusdt"><img src="https://img.shields.io/badge/Telegram-频道-26A5E4?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram Channel"></a>
|
||||||
@@ -23,15 +28,15 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🌍 What is Epusdt?
|
## What is Epusdt?
|
||||||
|
|
||||||
**Epusdt** (Easy Payment USDT) is a self-hosted **multi-chain, multi-token crypto payment gateway** built with Go. It has evolved from a TRC20-only solution into a comprehensive **multi-chain receiving platform**, enabling any website or application to accept crypto payments across multiple blockchain networks and token types. No third-party fees, no custodial risk — funds go directly into your wallet.
|
**Epusdt** (Easy Payment USDT) 是一个基于 Go 构建、支持私有化部署的 **多链多币种 Crypto 支付网关**。它从最初的 TRC20 单链方案逐步演进为完整的 **多链收款平台**,让任意网站或应用都能快速接入多条链、多种代币的加密支付能力。没有第三方托管,没有平台抽成,资金直接进入你的钱包。
|
||||||
|
|
||||||
> **⭐ GitHub Star 3000+** · **🔌 已支持站点解决方案 10+** · **🏆 Crypto 支付工具实际采用率 Top 1**
|
> **GitHub Star 3000+** · **已支持站点解决方案 10+** · **Crypto 支付工具实际采用率 Top 1**
|
||||||
|
|
||||||
Deploy it privately, integrate via HTTP API, and start receiving **crypto payments** in minutes. That's it. 🎉
|
私有部署,按 HTTP API 接入,几分钟内就可以开始接收 **Crypto Payments**。
|
||||||
|
|
||||||
### 🔗 已支持网络与代币
|
### 已支持网络与代币
|
||||||
|
|
||||||
| 网络 | 代币 |
|
| 网络 | 代币 |
|
||||||
|------|------|
|
|------|------|
|
||||||
@@ -42,11 +47,11 @@ Deploy it privately, integrate via HTTP API, and start receiving **crypto paymen
|
|||||||
| **Polygon** | USDT、USDC |
|
| **Polygon** | USDT、USDC |
|
||||||
| **更多** | 持续扩展中… |
|
| **更多** | 持续扩展中… |
|
||||||
|
|
||||||
> 💡 具体支持的链与代币以 [最新版本](https://github.com/GMWalletApp/epusdt/releases) 及 [官方文档](https://epusdt.com) 为准。
|
> 具体支持的链与代币以 [最新版本](https://github.com/GMWalletApp/epusdt/releases) 及 [官方文档](https://epusdt.com) 为准。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔌 广泛兼容,即插即用
|
## 广泛兼容,即插即用
|
||||||
|
|
||||||
无论你运营的是哪类系统,Epusdt 均可基于现有接口方案,**无需重构业务逻辑**,快速接入,立即获得 Crypto 收款能力,低成本扩展全球支付场景:
|
无论你运营的是哪类系统,Epusdt 均可基于现有接口方案,**无需重构业务逻辑**,快速接入,立即获得 Crypto 收款能力,低成本扩展全球支付场景:
|
||||||
|
|
||||||
@@ -57,28 +62,26 @@ Deploy it privately, integrate via HTTP API, and start receiving **crypto paymen
|
|||||||
| **代理面板** | [V2Board](https://github.com/v2board/v2board)、[XBoard](https://github.com/cedar2025/Xboard)、[xiaoV2board](https://github.com/wyx2685/v2board/)、[SSPanel](https://github.com/anankke/sspanel-uim) |
|
| **代理面板** | [V2Board](https://github.com/v2board/v2board)、[XBoard](https://github.com/cedar2025/Xboard)、[xiaoV2board](https://github.com/wyx2685/v2board/)、[SSPanel](https://github.com/anankke/sspanel-uim) |
|
||||||
| **建站生态** | [WordPress](https://wordpress.com/)、[WHMCS](https://www.whmcs.com/) |
|
| **建站生态** | [WordPress](https://wordpress.com/)、[WHMCS](https://www.whmcs.com/) |
|
||||||
| **Epay 兼容** | 兼容各类支持 Epay 易支付接口的平台 |
|
| **Epay 兼容** | 兼容各类支持 Epay 易支付接口的平台 |
|
||||||
| **更多** | 简易HTTP API 10分钟内接入 |
|
| **更多** | 简易 HTTP API,10 分钟内接入 |
|
||||||
|
|
||||||
👉 查看更多集成列表与插件:[plugins/](plugins/)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ✨ 核心特性
|
## 核心特性
|
||||||
|
|
||||||
- **多链多币种** — 支持 TRC20、ERC20、BEP20、Polygon 等主流网络,不再局限于单一链
|
- **多链多币种** — 支持 TRC20、ERC20、BEP20、Polygon 等主流网络
|
||||||
- **私有化部署** — 无需担心钱包被篡改、吞单,资金完全自主掌控
|
- **私有化部署** — 资金完全自主掌控
|
||||||
- **零依赖运行** — 单个二进制文件即可启动,低并发场景无需安装 MySQL + Redis,一键部署零成本维护
|
- **零依赖运行** — 单个二进制即可启动,低并发场景无需 MySQL + Redis
|
||||||
- **跨平台** — 支持 x86 / ARM 架构的 Windows / Linux / Mac 设备
|
- **跨平台** — 支持 x86 / ARM 架构的 Windows / Linux / Mac
|
||||||
- **多钱包轮询** — 自动轮换收款地址,提高订单并发处理能力
|
- **多钱包轮询** — 自动轮换收款地址,提高并发处理能力
|
||||||
- **异步队列** — 高性能消息回调,优雅处理高并发场景
|
- **异步队列** — 高性能消息回调,适配高并发场景
|
||||||
- **HTTP API** — 标准化接口,任何语言 / 框架均可10min内集成
|
- **HTTP API** — 标准化接口,任何语言 / 框架都能快速集成
|
||||||
- **Telegram Bot** — 实时支付通知,快捷管理与监控
|
- **Telegram Bot** — 实时支付通知,快捷管理与监控
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📖 文档与教程
|
## 文档与教程
|
||||||
|
|
||||||
完整文档请访问 👉 **[epusdt.com](https://epusdt.com)**
|
完整文档请访问:**[epusdt.com](https://epusdt.com)**
|
||||||
|
|
||||||
快速入门:
|
快速入门:
|
||||||
|
|
||||||
@@ -91,29 +94,26 @@ Deploy it privately, integrate via HTTP API, and start receiving **crypto paymen
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🏗️ 项目结构
|
## 项目结构
|
||||||
|
|
||||||
```
|
```text
|
||||||
Epusdt
|
Epusdt
|
||||||
├── plugins/ → 已集成的系统插件(独角数卡等)
|
├── src/ 项目核心代码
|
||||||
├── src/ → 项目核心代码
|
└── wiki/ 文档与知识库
|
||||||
├── sdk/ → 接入 SDK
|
|
||||||
├── sql/ → 数据库安装 / 升级脚本
|
|
||||||
└── wiki/ → 文档与知识库
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔧 实现原理
|
## 实现原理
|
||||||
|
|
||||||
Epusdt 通过监听多条区块链网络(TRC20、ERC20、BEP20、Polygon 等)的 API 或 RPC 节点,实时捕获钱包地址的代币入账事件,利用**金额差异**与**时效性**精确匹配交易归属:
|
Epusdt 通过监听多条区块链网络(TRC20、ERC20、BEP20、Polygon 等)的 API 或 RPC 节点,实时捕获钱包地址的代币入账事件,利用**金额差异**与**时效性**精确匹配交易归属:
|
||||||
|
|
||||||
```
|
```text
|
||||||
工作流程:
|
工作流程:
|
||||||
1. 客户发起支付,需支付 20.05 USDT
|
1. 客户发起支付,需支付 20.05 USDT
|
||||||
2. 系统在哈希表中查找可用的钱包地址 + 金额组合
|
2. 系统在哈希表中查找可用的钱包地址 + 金额组合
|
||||||
3. 若 address_1:20.05 未被占用 → 锁定该组合(有效期 10 分钟),返回给客户
|
3. 若 address_1:20.05 未被占用 -> 锁定该组合(有效期 10 分钟),返回给客户
|
||||||
4. 若已被占用 → 自动累加 0.0001 尝试下一个金额组合(最多 100 次)
|
4. 若已被占用 -> 自动累加 0.0001 尝试下一个金额组合(最多 100 次)
|
||||||
5. 后台线程持续监听所有钱包的入账事件,金额匹配则确认支付成功
|
5. 后台线程持续监听所有钱包的入账事件,金额匹配则确认支付成功
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -121,17 +121,15 @@ Epusdt 通过监听多条区块链网络(TRC20、ERC20、BEP20、Polygon 等
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 💬 社区与支持
|
## 社区与支持
|
||||||
|
|
||||||
**遇到问题?** 请优先在 GitHub 提交 [Issue](https://github.com/GMWalletApp/epusdt/issues),我们会**优先处理** Issue 中的反馈。
|
**遇到问题?** 请优先在 GitHub 提交 [Issue](https://github.com/GMWalletApp/epusdt/issues),我们会优先处理反馈。
|
||||||
|
|
||||||
加入 Telegram 社区,获取最新开发动态,参与需求调研,与超过5000名活跃用户交流使用经验,对接商业资源:
|
|
||||||
|
|
||||||
| 渠道 | 链接 |
|
| 渠道 | 链接 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| 📢 **Epusdt 频道** | [https://t.me/epusdt](https://t.me/epusdt) |
|
| Epusdt 频道 | [https://t.me/epusdt](https://t.me/epusdt) |
|
||||||
| 💬 **Epusdt 交流群** | [https://t.me/epusdt_group](https://t.me/epusdt_group) |
|
| Epusdt 交流群 | [https://t.me/epusdt_group](https://t.me/epusdt_group) |
|
||||||
| 📚 **官方文档站** | [https://epusdt.com](https://epusdt.com) |
|
| 官方文档站 | [https://epusdt.com](https://epusdt.com) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -147,15 +145,23 @@ Epusdt 通过监听多条区块链网络(TRC20、ERC20、BEP20、Polygon 等
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📜 开源协议
|
## 开源协议
|
||||||
|
|
||||||
Epusdt 遵守 [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) 开源协议。
|
Epusdt 遵守 [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) 开源协议。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚠️ 免责声明
|
## 免责声明及使用条款
|
||||||
|
|
||||||
本项目仅供学习与技术交流使用,用户在使用过程中需自行遵守所在地法律法规。由于涉及加密资产及资金安全,用户应自行审查相关代码与风险。加密资产属于高风险新兴资产(包括稳定币),其价值可能波动甚至归零,GMwallet 不对任何资产或使用结果作出保证。本内容不构成任何投资、税务、法律或金融建议,仅供教育用途,相关决策请咨询专业人士。
|
EPusdt 由 Good Morning Technology, LLC 以免费、开源、非盈利及非托管性质开发和披露,仅供学习、研究与技术交流使用。项目本身不构成投资、金融、法律、税务、合规或任何其他专业建议,也不应被视为对任何资产、交易结果、收益、资金安全、技术可用性或特定用途作出任何保证。
|
||||||
|
|
||||||
|
Good Morning Technology, LLC 为依据美国法律设立的主体,并将在适用法律法规范围内履行相应合规义务。就美国监管框架而言,虚拟货币、数字资产及相关技术服务是否构成 money transmission、money services business(MSB)或其他受监管活动,通常取决于具体业务模式,包括项目方是否接收、持有、控制或传输资金或价值,是否代表用户托管资产,以及是否从事兑换、支付、清算、结算或其他中介性金融服务。
|
||||||
|
|
||||||
|
作为免费、开源、非盈利、非托管的软件项目,EPusdt 的代码披露、文档说明、技术交流及相关开发活动,本身不应被理解为 Good Morning Technology, LLC 或其贡献者对任何用户后续使用、修改、部署、集成、分发或二次开发行为的授权、背书、控制、参与、保证或承诺。
|
||||||
|
|
||||||
|
用户对本项目的实际使用方式、使用目的及后续行为由其自行决定,Good Morning Technology, LLC 及其贡献者无法控制、审查或限制该等行为。用户应自行确保其使用、修改、部署、集成、分发或二次开发行为符合所在地适用法律法规、监管要求、制裁规则及第三方权利,并独立承担由此产生的全部风险、责任与后果。
|
||||||
|
|
||||||
|
加密资产属于高风险新兴资产类别,包括稳定币在内的数字资产均可能发生剧烈波动、脱锚、流动性不足、技术故障、监管变化或价值归零等风险。本项目所有代码、文档及相关材料均按“现状”和“可用状态”提供。除适用法律另有强制规定外,Good Morning Technology, LLC 及其贡献者不因用户使用、无法使用、错误使用、违法使用、修改、部署、集成、分发、二次开发或依赖本项目而产生的任何直接或间接损失承担责任。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
## 使用方法
|
|
||||||
### 注意此插件仅适用于独角数卡2.0.4版本以下,2.0.4版本或以上的独角数卡已经内置此插件,无需配置
|
|
||||||
|
|
||||||
1.将`app`和`routes`目录覆盖到网站根目录。
|
|
||||||
2.在独角数卡后台添加一个支付方式。
|
|
||||||
|
|
||||||
| 支付选项 | 商户id | 商户key | 商户密钥 | 备注 |
|
|
||||||
| :-----| :----- | :----- | :----- |:-----|
|
|
||||||
| Epusdt | api接口认证token | 空 | epusdt收银台地址+/api/v1/order/create-transaction| 如果独角数卡和epusdt在同一服务器则填写`127.0.0.1`不要填域名,例如`http://127.0.0.1:8000/api/v1/order/create-transaction` |
|
|
||||||
|
|
||||||
示例:
|
|
||||||

|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
* The file was created by Assimon.
|
|
||||||
*
|
|
||||||
* @author GMWalletApp<ashang@utf8.hk>
|
|
||||||
* @copyright GMWalletApp<ashang@utf8.hk>
|
|
||||||
* @link http://utf8.hk/
|
|
||||||
*/
|
|
||||||
|
|
||||||
namespace App\Http\Controllers\Pay;
|
|
||||||
|
|
||||||
|
|
||||||
use App\Exceptions\RuleValidationException;
|
|
||||||
use App\Http\Controllers\PayController;
|
|
||||||
use GuzzleHttp\Client;
|
|
||||||
use GuzzleHttp\Exception\GuzzleException;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
class EpusdtController extends PayController
|
|
||||||
{
|
|
||||||
public function gateway(string $payway, string $orderSN)
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
// 加载网关
|
|
||||||
$this->loadGateWay($orderSN, $payway);
|
|
||||||
//构造要请求的参数数组,无需改动
|
|
||||||
$parameter = [
|
|
||||||
"amount" => (float)$this->order->actual_price,//原价
|
|
||||||
"order_id" => $this->order->order_sn, //可以是用户ID,站内商户订单号,用户名
|
|
||||||
'redirect_url' => route('epusdt-return', ['order_id' => $this->order->order_sn]),
|
|
||||||
'notify_url' => url($this->payGateway->pay_handleroute . '/notify_url'),
|
|
||||||
];
|
|
||||||
$parameter['signature'] = $this->epusdtSign($parameter, $this->payGateway->merchant_id);
|
|
||||||
$client = new Client([
|
|
||||||
'headers' => [ 'Content-Type' => 'application/json' ]
|
|
||||||
]);
|
|
||||||
$response = $client->post($this->payGateway->merchant_pem, ['body' => json_encode($parameter)]);
|
|
||||||
$body = json_decode($response->getBody()->getContents(), true);
|
|
||||||
if (!isset($body['status_code']) || $body['status_code'] != 200) {
|
|
||||||
return $this->err(__('dujiaoka.prompt.abnormal_payment_channel') . $body['message']);
|
|
||||||
}
|
|
||||||
return redirect()->away($body['data']['payment_url']);
|
|
||||||
} catch (RuleValidationException $exception) {
|
|
||||||
} catch (GuzzleException $exception) {
|
|
||||||
return $this->err($exception->getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private function epusdtSign(array $parameter, string $signKey)
|
|
||||||
{
|
|
||||||
ksort($parameter);
|
|
||||||
reset($parameter); //内部指针指向数组中的第一个元素
|
|
||||||
$sign = '';
|
|
||||||
$urls = '';
|
|
||||||
foreach ($parameter as $key => $val) {
|
|
||||||
if ($val == '') continue;
|
|
||||||
if ($key != 'signature') {
|
|
||||||
if ($sign != '') {
|
|
||||||
$sign .= "&";
|
|
||||||
$urls .= "&";
|
|
||||||
}
|
|
||||||
$sign .= "$key=$val"; //拼接为url参数形式
|
|
||||||
$urls .= "$key=" . urlencode($val); //拼接为url参数形式
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$sign = md5($sign . $signKey);//密码追加进入开始MD5签名
|
|
||||||
return $sign;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function notifyUrl(Request $request)
|
|
||||||
{
|
|
||||||
$data = $request->all();
|
|
||||||
$order = $this->orderService->detailOrderSN($data['order_id']);
|
|
||||||
if (!$order) {
|
|
||||||
return 'fail';
|
|
||||||
}
|
|
||||||
$payGateway = $this->payService->detail($order->pay_id);
|
|
||||||
if (!$payGateway) {
|
|
||||||
return 'fail';
|
|
||||||
}
|
|
||||||
$signature = $this->epusdtSign($data, $payGateway->merchant_id);
|
|
||||||
if ($data['signature'] != $signature) { //不合法的数据
|
|
||||||
return 'fail'; //返回失败 继续补单
|
|
||||||
} else {
|
|
||||||
//合法的数据
|
|
||||||
//业务处理
|
|
||||||
$this->orderProcessService->completedOrder($data['order_id'], $data['amount'], $data['trade_id']);
|
|
||||||
return 'ok';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function returnUrl(Request $request)
|
|
||||||
{
|
|
||||||
$oid = $request->get('order_id');
|
|
||||||
// 异步通知还没到就跳转了,所以这里休眠2秒
|
|
||||||
sleep(2);
|
|
||||||
return redirect(url('detail-order-sn', ['orderSN' => $oid]));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
* The file was created by Assimon.
|
|
||||||
*
|
|
||||||
* @author GMWalletApp<ashang@utf8.hk>
|
|
||||||
* @copyright GMWalletApp<ashang@utf8.hk>
|
|
||||||
* @link http://utf8.hk/
|
|
||||||
*/
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
|
|
||||||
Route::get('pay-gateway/{handle}/{payway}/{orderSN}', 'PayController@redirectGateway');
|
|
||||||
|
|
||||||
// 支付相关
|
|
||||||
Route::group(['prefix' => 'pay', 'namespace' => 'Pay', 'middleware' => ['dujiaoka.pay_gate_way']], function () {
|
|
||||||
// 支付宝
|
|
||||||
Route::get('alipay/{payway}/{orderSN}', 'AlipayController@gateway');
|
|
||||||
Route::post('alipay/notify_url', 'AlipayController@notifyUrl');
|
|
||||||
// 微信
|
|
||||||
Route::get('wepay/{payway}/{orderSN}', 'WepayController@gateway');
|
|
||||||
Route::post('wepay/notify_url', 'WepayController@notifyUrl');
|
|
||||||
// 码支付
|
|
||||||
Route::get('mapay/{payway}/{orderSN}', 'MapayController@gateway');
|
|
||||||
Route::post('mapay/notify_url', 'MapayController@notifyUrl');
|
|
||||||
// Paysapi
|
|
||||||
Route::get('paysapi/{payway}/{orderSN}', 'PaysapiController@gateway');
|
|
||||||
Route::post('paysapi/notify_url', 'PaysapiController@notifyUrl');
|
|
||||||
Route::get('paysapi/return_url', 'PaysapiController@returnUrl')->name('paysapi-return');
|
|
||||||
// payjs
|
|
||||||
Route::get('payjs/{payway}/{orderSN}', 'PayjsController@gateway');
|
|
||||||
Route::post('payjs/notify_url', 'PayjsController@notifyUrl');
|
|
||||||
// 易支付
|
|
||||||
Route::get('yipay/{payway}/{orderSN}', 'YipayController@gateway');
|
|
||||||
Route::get('yipay/notify_url', 'YipayController@notifyUrl');
|
|
||||||
Route::get('yipay/return_url', 'YipayController@returnUrl')->name('yipay-return');
|
|
||||||
// paypal
|
|
||||||
Route::get('paypal/{payway}/{orderSN}', 'PaypalPayController@gateway');
|
|
||||||
Route::get('paypal/return_url', 'PaypalPayController@returnUrl')->name('paypal-return');
|
|
||||||
Route::any('paypal/notify_url', 'PaypalPayController@notifyUrl');
|
|
||||||
// V免签
|
|
||||||
Route::get('vpay/{payway}/{orderSN}', 'VpayController@gateway');
|
|
||||||
Route::get('vpay/notify_url', 'VpayController@notifyUrl');
|
|
||||||
Route::get('vpay/return_url', 'VpayController@returnUrl')->name('vpay-return');
|
|
||||||
// stripe
|
|
||||||
Route::get('stripe/{payway}/{oid}','StripeController@gateway');
|
|
||||||
Route::get('stripe/return_url','StripeController@returnUrl');
|
|
||||||
Route::get('stripe/check','StripeController@check');
|
|
||||||
Route::get('stripe/charge','StripeController@charge');
|
|
||||||
// Coinbase
|
|
||||||
Route::get('coinbase/{payway}/{orderSN}', 'CoinbaseController@gateway');
|
|
||||||
Route::post('coinbase/notify_url', 'CoinbaseController@notifyUrl');
|
|
||||||
// epusdt
|
|
||||||
Route::get('epusdt/{payway}/{orderSN}', 'EpusdtController@gateway');
|
|
||||||
Route::post('epusdt/notify_url', 'EpusdtController@notifyUrl');
|
|
||||||
Route::get('epusdt/return_url', 'EpusdtController@returnUrl')->name('epusdt-return');
|
|
||||||
|
|
||||||
});
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
-- auto-generated definition
|
|
||||||
create table orders
|
|
||||||
(
|
|
||||||
id int auto_increment
|
|
||||||
primary key,
|
|
||||||
trade_id varchar(32) not null comment 'epusdt订单号',
|
|
||||||
order_id varchar(32) not null comment '客户交易id',
|
|
||||||
block_transaction_id varchar(128) null comment '区块唯一编号',
|
|
||||||
actual_amount decimal(19, 4) not null comment '订单实际需要支付的金额,保留4位小数',
|
|
||||||
amount decimal(19, 4) not null comment '订单金额,保留4位小数',
|
|
||||||
token varchar(50) not null comment '所属钱包地址',
|
|
||||||
status int default 1 not null comment '1:等待支付,2:支付成功,3:已过期',
|
|
||||||
notify_url varchar(128) not null comment '异步回调地址',
|
|
||||||
redirect_url varchar(128) null comment '同步回调地址',
|
|
||||||
callback_num int default 0 null comment '回调次数',
|
|
||||||
callback_confirm int default 2 null comment '回调是否已确认? 1是 2否',
|
|
||||||
created_at timestamp null,
|
|
||||||
updated_at timestamp null,
|
|
||||||
deleted_at timestamp null,
|
|
||||||
constraint orders_order_id_uindex
|
|
||||||
unique (order_id),
|
|
||||||
constraint orders_trade_id_uindex
|
|
||||||
unique (trade_id)
|
|
||||||
);
|
|
||||||
|
|
||||||
create index orders_block_transaction_id_index
|
|
||||||
on orders (block_transaction_id);
|
|
||||||
|
|
||||||
-- auto-generated definition
|
|
||||||
create table wallet_address
|
|
||||||
(
|
|
||||||
id int auto_increment
|
|
||||||
primary key,
|
|
||||||
token varchar(50) not null comment '钱包token',
|
|
||||||
status int default 1 not null comment '1:启用 2:禁用',
|
|
||||||
created_at timestamp null,
|
|
||||||
updated_at timestamp null,
|
|
||||||
deleted_at timestamp null
|
|
||||||
)
|
|
||||||
comment '钱包表';
|
|
||||||
|
|
||||||
create index wallet_address_token_index
|
|
||||||
on wallet_address (token);
|
|
||||||
|
|
||||||
@@ -20,27 +20,6 @@ db_type=sqlite
|
|||||||
sqlite_database_filename=
|
sqlite_database_filename=
|
||||||
sqlite_table_prefix=
|
sqlite_table_prefix=
|
||||||
|
|
||||||
# postgres config
|
|
||||||
postgres_host=127.0.0.1
|
|
||||||
postgres_port=3306
|
|
||||||
postgres_user=mysql_user
|
|
||||||
postgres_passwd=mysql_password
|
|
||||||
postgres_database=database_name
|
|
||||||
postgres_table_prefix=
|
|
||||||
postgres_max_idle_conns=10
|
|
||||||
postgres_max_open_conns=100
|
|
||||||
postgres_max_life_time=6
|
|
||||||
|
|
||||||
# mysql config
|
|
||||||
mysql_host=127.0.0.1
|
|
||||||
mysql_port=3306
|
|
||||||
mysql_user=mysql_user
|
|
||||||
mysql_passwd=mysql_password
|
|
||||||
mysql_database=database_name
|
|
||||||
mysql_table_prefix=
|
|
||||||
mysql_max_idle_conns=10
|
|
||||||
mysql_max_open_conns=100
|
|
||||||
mysql_max_life_time=6
|
|
||||||
|
|
||||||
# sqlite runtime store config
|
# sqlite runtime store config
|
||||||
runtime_sqlite_filename=epusdt-runtime.db
|
runtime_sqlite_filename=epusdt-runtime.db
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ builds:
|
|||||||
flags:
|
flags:
|
||||||
- -trimpath
|
- -trimpath
|
||||||
ldflags:
|
ldflags:
|
||||||
- -s -w -X github.com/assimon/luuu/config.BuildVersion={{ .Version }} -X github.com/assimon/luuu/config.BuildCommit={{ .Commit }} -X github.com/assimon/luuu/config.BuildDate={{ .Date }}
|
- -s -w -X github.com/GMWalletApp/epusdt/config.BuildVersion={{ .Tag }} -X github.com/GMWalletApp/epusdt/config.BuildCommit={{ .Commit }} -X github.com/GMWalletApp/epusdt/config.BuildDate={{ .Date }}
|
||||||
goos:
|
goos:
|
||||||
- linux
|
- linux
|
||||||
- darwin
|
- darwin
|
||||||
|
|||||||
@@ -38,14 +38,16 @@ func InitApp() {
|
|||||||
}
|
}
|
||||||
// Seed admin account and JWT secret so the management console is
|
// Seed admin account and JWT secret so the management console is
|
||||||
// immediately usable on a fresh install. Both are idempotent.
|
// immediately usable on a fresh install. Both are idempotent.
|
||||||
_, isNew, err := data.EnsureDefaultAdmin()
|
initialPassword, isNew, err := data.EnsureDefaultAdmin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
color.Red.Printf("[bootstrap] ensure default admin err=%s\n", err)
|
color.Red.Printf("[bootstrap] ensure default admin err=%s\n", err)
|
||||||
}
|
}
|
||||||
if isNew {
|
if isNew {
|
||||||
color.Yellow.Println("╔════════════════════════════════════════════════════════════════════════╗")
|
color.Yellow.Println("╔════════════════════════════════════════════════════════════════════════╗")
|
||||||
color.Yellow.Println("║ Default admin account created. Fetch one-time password via API first!║")
|
color.Yellow.Println("║ Default admin account created. Save these credentials now. ║")
|
||||||
color.Yellow.Printf("║ Username: admin ║\n")
|
color.Yellow.Printf("║ Username: %-54s║\n", "admin")
|
||||||
|
color.Yellow.Printf("║ Password: %-54s║\n", initialPassword)
|
||||||
|
color.Yellow.Println("║ The one-time password API remains available until first fetch. ║")
|
||||||
color.Yellow.Println("║ GET /admin/api/v1/auth/init-password (one-time) ║")
|
color.Yellow.Println("║ GET /admin/api/v1/auth/init-password (one-time) ║")
|
||||||
color.Yellow.Println("╚════════════════════════════════════════════════════════════════════════╝")
|
color.Yellow.Println("╚════════════════════════════════════════════════════════════════════════╝")
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-22
@@ -8,7 +8,6 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -17,12 +16,6 @@ import (
|
|||||||
"github.com/tidwall/gjson"
|
"github.com/tidwall/gjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
// parseFloat is the minimal helper used by the settings bridge; kept
|
|
||||||
// here so settings_bridge.go stays import-free.
|
|
||||||
func parseFloat(s string) (float64, error) {
|
|
||||||
return strconv.ParseFloat(strings.TrimSpace(s), 64)
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
HTTPAccessLog bool
|
HTTPAccessLog bool
|
||||||
SQLDebug bool
|
SQLDebug bool
|
||||||
@@ -353,21 +346,25 @@ func GetRateForCoin(coin string, base string) float64 {
|
|||||||
if coin == base {
|
if coin == base {
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
if coin == "usdt" {
|
if forcedRate := getForcedRateForCoin(coin, base); forcedRate > 0 {
|
||||||
switch base {
|
return forcedRate
|
||||||
case "usd":
|
}
|
||||||
|
if coin == "usdt" && base == "usd" {
|
||||||
return 1
|
return 1
|
||||||
case "cny":
|
|
||||||
usdtRate := GetUsdtRate()
|
|
||||||
if usdtRate > 0 {
|
|
||||||
return 1 / usdtRate
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return getRateForCoinFromAPI(coin, base)
|
return getRateForCoinFromAPI(coin, base)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getForcedRateForCoin(coin string, base string) float64 {
|
||||||
|
raw := strings.TrimSpace(settingsForcedRateList())
|
||||||
|
if raw != "" {
|
||||||
|
if rate := gjson.Get(raw, base+"."+coin).Float(); rate > 0 {
|
||||||
|
return rate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
func getRateForCoinFromAPI(coin string, base string) float64 {
|
func getRateForCoinFromAPI(coin string, base string) float64 {
|
||||||
baseURL := GetRateApiUrl()
|
baseURL := GetRateApiUrl()
|
||||||
if baseURL == "" {
|
if baseURL == "" {
|
||||||
@@ -401,17 +398,17 @@ func getRateForCoinFromAPI(coin string, base string) float64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetUsdtRate() float64 {
|
func GetUsdtRate() float64 {
|
||||||
// Only the admin setting can force the USDT/CNY rate. When the
|
// rate.forced_rate_list stores token amount per one base currency unit.
|
||||||
// setting is unset, zero, or negative, fall back to the rate API.
|
// GetUsdtRate returns the inverse display value: CNY per USDT.
|
||||||
if forced := settingsForcedUsdtRate(); forced > 0 {
|
if forcedRate := getForcedRateForCoin("usdt", "cny"); forcedRate > 0 {
|
||||||
return forced
|
return 1 / forcedRate
|
||||||
}
|
}
|
||||||
|
|
||||||
apiRate := getRateForCoinFromAPI("usdt", "cny")
|
apiRate := getRateForCoinFromAPI("usdt", "cny")
|
||||||
if apiRate > 0 {
|
if apiRate > 0 {
|
||||||
return 1 / apiRate
|
return 1 / apiRate
|
||||||
}
|
}
|
||||||
log.Printf("usdt/cny rate unavailable: rate.forced_usdt_rate <= 0 and rate api returned no data")
|
log.Printf("usdt/cny rate unavailable: rate.forced_rate_list has no positive cny.usdt entry and rate api returned no data")
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -231,7 +231,7 @@ func TestCopyMissingStaticFilesCopiesAssetsWithoutOverwriting(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetUsdtRatePrefersPositiveAdminOverride(t *testing.T) {
|
func TestGetUsdtRatePrefersForcedRateList(t *testing.T) {
|
||||||
viper.Reset()
|
viper.Reset()
|
||||||
t.Cleanup(viper.Reset)
|
t.Cleanup(viper.Reset)
|
||||||
t.Setenv("API_RATE_URL", "")
|
t.Setenv("API_RATE_URL", "")
|
||||||
@@ -249,16 +249,19 @@ func TestGetUsdtRatePrefersPositiveAdminOverride(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
installSettingsGetter(t, map[string]string{
|
installSettingsGetter(t, map[string]string{
|
||||||
"rate.forced_usdt_rate": "7.25",
|
"rate.forced_rate_list": `{"cny":{"usdt":0.13793103448275862},"usd":{"trx":123.45}}`,
|
||||||
"rate.api_url": "https://rate.example.test",
|
"rate.api_url": "https://rate.example.test",
|
||||||
})
|
})
|
||||||
|
|
||||||
got := GetUsdtRate()
|
got := GetUsdtRate()
|
||||||
if got != 7.25 {
|
if math.Abs(got-7.25) > 1e-9 {
|
||||||
t.Fatalf("GetUsdtRate() = %v, want 7.25", got)
|
t.Fatalf("GetUsdtRate() = %v, want 7.25", got)
|
||||||
}
|
}
|
||||||
|
if rate := GetRateForCoin("trx", "usd"); rate != 123.45 {
|
||||||
|
t.Fatalf("GetRateForCoin(trx, usd) = %v, want 123.45", rate)
|
||||||
|
}
|
||||||
if apiCalled {
|
if apiCalled {
|
||||||
t.Fatalf("rate API should not be called when rate.forced_usdt_rate > 0")
|
t.Fatalf("rate API should not be called when rate.forced_rate_list has positive rate")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,7 +284,7 @@ func TestGetUsdtRateUsesAPIWhenAdminOverrideIsNotPositive(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
installSettingsGetter(t, map[string]string{
|
installSettingsGetter(t, map[string]string{
|
||||||
"rate.forced_usdt_rate": "-1",
|
"rate.forced_rate_list": `{"cny":{"usdt":0}}`,
|
||||||
"rate.api_url": "https://rate.example.test",
|
"rate.api_url": "https://rate.example.test",
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -297,6 +300,35 @@ func TestGetUsdtRateUsesAPIWhenAdminOverrideIsNotPositive(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetRateForCoinUsesAPIWhenForcedPairMissing(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Cleanup(viper.Reset)
|
||||||
|
t.Setenv("API_RATE_URL", "")
|
||||||
|
|
||||||
|
installMockHTTPClient(t, func(r *http.Request) (*http.Response, error) {
|
||||||
|
if r.URL.Path != "/cny.json" {
|
||||||
|
t.Fatalf("rate api path = %s, want /cny.json", r.URL.Path)
|
||||||
|
}
|
||||||
|
return &http.Response{
|
||||||
|
StatusCode: http.StatusOK,
|
||||||
|
Status: "200 OK",
|
||||||
|
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||||
|
Body: io.NopCloser(strings.NewReader(`{"cny":{"usdt":0.14635}}`)),
|
||||||
|
Request: r,
|
||||||
|
}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
installSettingsGetter(t, map[string]string{
|
||||||
|
"rate.forced_rate_list": `{"usd":{"trx":123.45}}`,
|
||||||
|
"rate.api_url": "https://rate.example.test",
|
||||||
|
})
|
||||||
|
|
||||||
|
rate := GetRateForCoin("usdt", "cny")
|
||||||
|
if math.Abs(rate-0.14635) > 1e-9 {
|
||||||
|
t.Fatalf("GetRateForCoin(usdt, cny) = %v, want 0.14635", rate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetUsdtRateReturnsZeroWhenAPIUnavailableWithoutAdminOverride(t *testing.T) {
|
func TestGetUsdtRateReturnsZeroWhenAPIUnavailableWithoutAdminOverride(t *testing.T) {
|
||||||
viper.Reset()
|
viper.Reset()
|
||||||
t.Cleanup(viper.Reset)
|
t.Cleanup(viper.Reset)
|
||||||
@@ -313,7 +345,7 @@ func TestGetUsdtRateReturnsZeroWhenAPIUnavailableWithoutAdminOverride(t *testing
|
|||||||
})
|
})
|
||||||
|
|
||||||
installSettingsGetter(t, map[string]string{
|
installSettingsGetter(t, map[string]string{
|
||||||
"rate.forced_usdt_rate": "0",
|
"rate.forced_rate_list": `{"cny":{"usdt":0}}`,
|
||||||
"rate.api_url": "https://rate.example.test",
|
"rate.api_url": "https://rate.example.test",
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -343,7 +375,7 @@ func TestGetRateForCoinCallsRateAPIOnceForUsdtCnyFailure(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
installSettingsGetter(t, map[string]string{
|
installSettingsGetter(t, map[string]string{
|
||||||
"rate.forced_usdt_rate": "0",
|
"rate.forced_rate_list": `{"cny":{"usdt":0}}`,
|
||||||
"rate.api_url": "https://rate.example.test",
|
"rate.api_url": "https://rate.example.test",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -18,17 +18,9 @@ func settingsRateApiUrl() string {
|
|||||||
return SettingsGetString("rate.api_url")
|
return SettingsGetString("rate.api_url")
|
||||||
}
|
}
|
||||||
|
|
||||||
func settingsForcedUsdtRate() float64 {
|
func settingsForcedRateList() string {
|
||||||
if SettingsGetString == nil {
|
if SettingsGetString == nil {
|
||||||
return 0
|
return ""
|
||||||
}
|
}
|
||||||
raw := SettingsGetString("rate.forced_usdt_rate")
|
return SettingsGetString("rate.forced_rate_list")
|
||||||
if raw == "" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
f, err := parseFloat(raw)
|
|
||||||
if err != nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return f
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"github.com/GMWalletApp/epusdt/model/request"
|
"github.com/GMWalletApp/epusdt/model/request"
|
||||||
"github.com/GMWalletApp/epusdt/model/service"
|
"github.com/GMWalletApp/epusdt/model/service"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/log"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -147,23 +148,43 @@ func (c *BaseAdminController) CloseOrder(ctx echo.Context) error {
|
|||||||
// @Router /admin/api/v1/orders/{trade_id}/mark-paid [post]
|
// @Router /admin/api/v1/orders/{trade_id}/mark-paid [post]
|
||||||
func (c *BaseAdminController) MarkOrderPaid(ctx echo.Context) error {
|
func (c *BaseAdminController) MarkOrderPaid(ctx echo.Context) error {
|
||||||
tradeID := ctx.Param("trade_id")
|
tradeID := ctx.Param("trade_id")
|
||||||
|
adminUserID := currentAdminUserID(ctx)
|
||||||
req := new(MarkPaidRequest)
|
req := new(MarkPaidRequest)
|
||||||
if err := ctx.Bind(req); err != nil {
|
if err := ctx.Bind(req); err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid bind failed admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
return c.FailJson(ctx, err)
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
|
req.BlockTransactionId = strings.TrimSpace(req.BlockTransactionId)
|
||||||
if err := c.ValidateStruct(ctx, req); err != nil {
|
if err := c.ValidateStruct(ctx, req); err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid validation failed admin_user_id=%d trade_id=%s block_transaction_id=%s err=%v", adminUserID, tradeID, req.BlockTransactionId, err)
|
||||||
return c.FailJson(ctx, err)
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid load failed admin_user_id=%d trade_id=%s block_transaction_id=%s err=%v", adminUserID, tradeID, req.BlockTransactionId, err)
|
||||||
return c.FailJson(ctx, err)
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
if order.ID == 0 {
|
if order.ID == 0 {
|
||||||
return c.FailJson(ctx, errors.New("order not found"))
|
err = errors.New("order not found")
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid rejected admin_user_id=%d trade_id=%s block_transaction_id=%s err=%v", adminUserID, tradeID, req.BlockTransactionId, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
if order.Status != mdb.StatusWaitPay {
|
if order.Status != mdb.StatusWaitPay {
|
||||||
return c.FailJson(ctx, errors.New("order is not waiting payment"))
|
err = errors.New("order is not waiting payment")
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid rejected admin_user_id=%d trade_id=%s status=%d block_transaction_id=%s err=%v", adminUserID, tradeID, order.Status, req.BlockTransactionId, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
|
if !isOnChainOrder(order.PayProvider) {
|
||||||
|
err = errors.New("order is not an on-chain payment order")
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid rejected admin_user_id=%d trade_id=%s pay_provider=%s block_transaction_id=%s err=%v", adminUserID, tradeID, order.PayProvider, req.BlockTransactionId, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
verifiedBlockTransactionID, err := service.ValidateManualOrderPayment(order, req.BlockTransactionId)
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid chain verification failed admin_user_id=%d trade_id=%s network=%s token=%s amount=%.8f block_transaction_id=%s err=%v", adminUserID, tradeID, order.Network, order.Token, order.ActualAmount, req.BlockTransactionId, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
req.BlockTransactionId = verifiedBlockTransactionID
|
||||||
err = service.OrderProcessing(&request.OrderProcessingRequest{
|
err = service.OrderProcessing(&request.OrderProcessingRequest{
|
||||||
ReceiveAddress: order.ReceiveAddress,
|
ReceiveAddress: order.ReceiveAddress,
|
||||||
Currency: order.Currency,
|
Currency: order.Currency,
|
||||||
@@ -174,8 +195,10 @@ func (c *BaseAdminController) MarkOrderPaid(ctx echo.Context) error {
|
|||||||
BlockTransactionId: req.BlockTransactionId,
|
BlockTransactionId: req.BlockTransactionId,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] mark-paid processing failed admin_user_id=%d trade_id=%s block_transaction_id=%s err=%v", adminUserID, tradeID, req.BlockTransactionId, err)
|
||||||
return c.FailJson(ctx, err)
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
|
log.Sugar.Infof("[admin-order] mark-paid success admin_user_id=%d trade_id=%s block_transaction_id=%s", adminUserID, tradeID, req.BlockTransactionId)
|
||||||
return c.SucJson(ctx, nil)
|
return c.SucJson(ctx, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,16 +216,46 @@ func (c *BaseAdminController) MarkOrderPaid(ctx echo.Context) error {
|
|||||||
// @Router /admin/api/v1/orders/{trade_id}/resend-callback [post]
|
// @Router /admin/api/v1/orders/{trade_id}/resend-callback [post]
|
||||||
func (c *BaseAdminController) ResendCallback(ctx echo.Context) error {
|
func (c *BaseAdminController) ResendCallback(ctx echo.Context) error {
|
||||||
tradeID := ctx.Param("trade_id")
|
tradeID := ctx.Param("trade_id")
|
||||||
|
adminUserID := currentAdminUserID(ctx)
|
||||||
|
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback load failed admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
if order.ID == 0 {
|
||||||
|
err = errors.New("order not found")
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback rejected admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
if order.Status != mdb.StatusPaySuccess {
|
||||||
|
err = errors.New("order is not paid (callback not applicable)")
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback rejected admin_user_id=%d trade_id=%s status=%d err=%v", adminUserID, tradeID, order.Status, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(order.NotifyUrl) == "" {
|
||||||
|
err = errors.New("order has empty notify_url")
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback rejected admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
ok, err := data.ReopenOrderCallback(tradeID)
|
ok, err := data.ReopenOrderCallback(tradeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback reopen failed admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
return c.FailJson(ctx, err)
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return c.FailJson(ctx, errors.New("order is not paid (callback not applicable)"))
|
err = errors.New("resend callback failed (concurrent state change)")
|
||||||
|
log.Sugar.Warnf("[admin-order] resend-callback rejected admin_user_id=%d trade_id=%s err=%v", adminUserID, tradeID, err)
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
}
|
}
|
||||||
|
log.Sugar.Infof("[admin-order] resend-callback queued admin_user_id=%d trade_id=%s", adminUserID, tradeID)
|
||||||
return c.SucJson(ctx, nil)
|
return c.SucJson(ctx, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isOnChainOrder(payProvider string) bool {
|
||||||
|
payProvider = strings.TrimSpace(payProvider)
|
||||||
|
return payProvider == "" || payProvider == mdb.PaymentProviderOnChain
|
||||||
|
}
|
||||||
|
|
||||||
// ExportOrders streams matching orders as CSV. No pagination — the
|
// ExportOrders streams matching orders as CSV. No pagination — the
|
||||||
// caller drives what rows to include via filter params. Capped at
|
// caller drives what rows to include via filter params. Capped at
|
||||||
// 10k rows to keep the response bounded.
|
// 10k rows to keep the response bounded.
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package admin
|
package admin
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/GMWalletApp/epusdt/model/dao"
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
@@ -14,8 +17,8 @@ import (
|
|||||||
// Supported groups and keys:
|
// Supported groups and keys:
|
||||||
//
|
//
|
||||||
// - group=rate:
|
// - group=rate:
|
||||||
// rate.forced_usdt_rate (float) — override USDT/CNY when > 0; <= 0 uses rate.api_url
|
// rate.forced_rate_list (json) — override rate map, e.g. {"cny":{"usdt":0.14635}}; base/coin keys are normalized to lowercase
|
||||||
// rate.api_url (string) — external rate API URL used when rate.forced_usdt_rate <= 0
|
// rate.api_url (string) — external rate API URL used when no positive forced rate exists
|
||||||
// rate.adjust_percent (float) — rate adjustment percentage
|
// rate.adjust_percent (float) — rate adjustment percentage
|
||||||
// rate.okx_c2c_enabled (bool) — use OKX C2C rate feed
|
// rate.okx_c2c_enabled (bool) — use OKX C2C rate feed
|
||||||
//
|
//
|
||||||
@@ -24,19 +27,35 @@ import (
|
|||||||
// epay.default_currency (string) — fiat currency for EPAY orders, e.g. "cny" (default)
|
// epay.default_currency (string) — fiat currency for EPAY orders, e.g. "cny" (default)
|
||||||
// epay.default_network (string) — blockchain network for EPAY orders, e.g. "tron" (default)
|
// epay.default_network (string) — blockchain network for EPAY orders, e.g. "tron" (default)
|
||||||
//
|
//
|
||||||
|
// - group=okpay:
|
||||||
|
// okpay.enabled (bool) — enable OkPay as a switch-network payment option
|
||||||
|
// okpay.shop_id (string) — OkPay merchant/shop identifier
|
||||||
|
// okpay.shop_token (string) — OkPay signing token
|
||||||
|
// okpay.api_url (string) — OkPay API base URL
|
||||||
|
// okpay.callback_url (string) — server callback URL used for OkPay notify
|
||||||
|
// okpay.return_url (string) — optional default browser return URL after payment
|
||||||
|
// okpay.timeout_seconds (int) — outbound OkPay API timeout in seconds
|
||||||
|
// okpay.allow_tokens (string) — comma-separated allowed tokens, e.g. "USDT,TRX"
|
||||||
|
//
|
||||||
// - group=brand:
|
// - group=brand:
|
||||||
// brand.site_name (string) — site display name
|
// brand.checkout_name (string) — cashier display name (preferred)
|
||||||
// brand.logo_url (string) — logo image URL
|
// brand.logo_url (string) — logo image URL
|
||||||
// brand.page_title (string) — payment page title
|
// brand.site_title (string) — payment page title / website title (preferred)
|
||||||
// brand.pay_success_text (string) — text shown on payment success
|
// brand.success_copy (string) — text shown on payment success (preferred)
|
||||||
// brand.support_url (string) — support / help URL
|
// brand.support_url (string) — support / help URL
|
||||||
|
// brand.background_color (string) — checkout background color
|
||||||
|
// brand.background_image_url (string) — checkout background image URL
|
||||||
|
// brand.site_name (string) — legacy cashier/site display name
|
||||||
|
// brand.page_title (string) — legacy payment page title
|
||||||
|
// brand.pay_success_text (string) — legacy success text
|
||||||
//
|
//
|
||||||
// - group=system:
|
// - group=system:
|
||||||
// system.order_expiration_time (int) — order expiry in minutes
|
// system.order_expiration_time (int) — order expiry in minutes
|
||||||
|
// system.amount_precision (int) — payment amount precision, 2-6 decimals (default 2)
|
||||||
type SettingUpsertItem struct {
|
type SettingUpsertItem struct {
|
||||||
Group string `json:"group" enums:"brand,rate,system,epay" example:"epay"`
|
Group string `json:"group" enums:"brand,rate,system,epay,okpay" example:"epay"`
|
||||||
Key string `json:"key" example:"epay.default_network"`
|
Key string `json:"key" example:"epay.default_network"`
|
||||||
Value string `json:"value" example:"tron"`
|
Value interface{} `json:"value"`
|
||||||
Type string `json:"type" enums:"string,int,bool,json" example:"string"`
|
Type string `json:"type" enums:"string,int,bool,json" example:"string"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,12 +67,12 @@ type SettingsUpsertRequest struct {
|
|||||||
// ListSettings returns all rows, optionally filtered by group.
|
// ListSettings returns all rows, optionally filtered by group.
|
||||||
// @Summary List settings
|
// @Summary List settings
|
||||||
// @Description Returns all settings, optionally filtered by group.
|
// @Description Returns all settings, optionally filtered by group.
|
||||||
// @Description Available groups: brand, rate, system, epay.
|
// @Description Available groups: brand, rate, system, epay, okpay.
|
||||||
// @Description See SettingUpsertItem for the full list of supported keys per group.
|
// @Description See SettingUpsertItem for the full list of supported keys per group.
|
||||||
// @Tags Admin Settings
|
// @Tags Admin Settings
|
||||||
// @Security AdminJWT
|
// @Security AdminJWT
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param group query string false "Group filter (brand|rate|system|epay)"
|
// @Param group query string false "Group filter (brand|rate|system|epay|okpay)"
|
||||||
// @Success 200 {object} response.ApiResponse{data=[]mdb.Setting}
|
// @Success 200 {object} response.ApiResponse{data=[]mdb.Setting}
|
||||||
// @Failure 400 {object} response.ApiResponse
|
// @Failure 400 {object} response.ApiResponse
|
||||||
// @Router /admin/api/v1/settings [get]
|
// @Router /admin/api/v1/settings [get]
|
||||||
@@ -71,11 +90,12 @@ func (c *BaseAdminController) ListSettings(ctx echo.Context) error {
|
|||||||
// ones. Errors are returned per-key so the UI can surface them.
|
// ones. Errors are returned per-key so the UI can surface them.
|
||||||
// @Summary Upsert settings
|
// @Summary Upsert settings
|
||||||
// @Description Batch insert/update settings. Returns per-key status.
|
// @Description Batch insert/update settings. Returns per-key status.
|
||||||
// @Description Supported groups: brand, rate, system, epay.
|
// @Description Supported groups: brand, rate, system, epay, okpay.
|
||||||
// @Description epay group keys: epay.default_token (e.g. "usdt"), epay.default_currency (e.g. "cny"), epay.default_network (e.g. "tron").
|
// @Description epay group keys: epay.default_token (e.g. "usdt"), epay.default_currency (e.g. "cny"), epay.default_network (e.g. "tron").
|
||||||
// @Description rate group keys: rate.forced_usdt_rate (>0 overrides USDT/CNY; <=0 uses rate.api_url), rate.api_url, rate.adjust_percent, rate.okx_c2c_enabled.
|
// @Description okpay group keys: okpay.enabled, okpay.shop_id, okpay.shop_token, okpay.api_url, okpay.callback_url, okpay.return_url, okpay.timeout_seconds, okpay.allow_tokens.
|
||||||
// @Description brand group keys: brand.site_name, brand.logo_url, brand.page_title, brand.pay_success_text, brand.support_url.
|
// @Description rate group keys: rate.forced_rate_list (JSON map, e.g. {"cny":{"usdt":0.14635}}; base/coin keys are normalized to lowercase), rate.api_url, rate.adjust_percent, rate.okx_c2c_enabled.
|
||||||
// @Description system group keys: system.order_expiration_time.
|
// @Description brand group keys: brand.checkout_name, brand.logo_url, brand.site_title, brand.success_copy, brand.support_url, brand.background_color, brand.background_image_url. Legacy aliases brand.site_name, brand.page_title and brand.pay_success_text are also supported.
|
||||||
|
// @Description system group keys: system.order_expiration_time, system.amount_precision (int, 2-6, default 2).
|
||||||
// @Tags Admin Settings
|
// @Tags Admin Settings
|
||||||
// @Security AdminJWT
|
// @Security AdminJWT
|
||||||
// @Accept json
|
// @Accept json
|
||||||
@@ -104,7 +124,25 @@ func (c *BaseAdminController) UpsertSettings(ctx echo.Context) error {
|
|||||||
out = append(out, result{Key: item.Key, OK: false, Error: "key required"})
|
out = append(out, result{Key: item.Key, OK: false, Error: "key required"})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err := data.SetSetting(item.Group, key, item.Value, item.Type); err != nil {
|
value, err := normalizeSettingValue(item.Value)
|
||||||
|
if err != nil {
|
||||||
|
out = append(out, result{Key: key, OK: false, Error: err.Error()})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
value, err = normalizeAndValidateSettingItem(item.Group, key, value)
|
||||||
|
if err != nil {
|
||||||
|
out = append(out, result{Key: key, OK: false, Error: err.Error()})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if key == mdb.SettingKeyAmountPrecision {
|
||||||
|
item.Group = mdb.SettingGroupSystem
|
||||||
|
item.Type = mdb.SettingTypeInt
|
||||||
|
}
|
||||||
|
if key == mdb.SettingKeyRateForcedRateList {
|
||||||
|
item.Group = mdb.SettingGroupRate
|
||||||
|
item.Type = mdb.SettingTypeJSON
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(item.Group, key, value, item.Type); err != nil {
|
||||||
out = append(out, result{Key: key, OK: false, Error: err.Error()})
|
out = append(out, result{Key: key, OK: false, Error: err.Error()})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -132,6 +170,93 @@ func (c *BaseAdminController) UpsertSettings(ctx echo.Context) error {
|
|||||||
return c.SucJson(ctx, out)
|
return c.SucJson(ctx, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeSettingValue(value interface{}) (string, error) {
|
||||||
|
switch v := value.(type) {
|
||||||
|
case nil:
|
||||||
|
return "", nil
|
||||||
|
case string:
|
||||||
|
return v, nil
|
||||||
|
default:
|
||||||
|
b, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("value must be JSON serializable")
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeAndValidateSettingItem(group, key, value string) (string, error) {
|
||||||
|
switch key {
|
||||||
|
case mdb.SettingKeyAmountPrecision:
|
||||||
|
if strings.ToLower(strings.TrimSpace(group)) != mdb.SettingGroupSystem {
|
||||||
|
return value, fmt.Errorf("%s must use group %s", key, mdb.SettingGroupSystem)
|
||||||
|
}
|
||||||
|
precision, err := strconv.Atoi(strings.TrimSpace(value))
|
||||||
|
if err != nil {
|
||||||
|
return value, fmt.Errorf("%s must be an integer", key)
|
||||||
|
}
|
||||||
|
if precision < data.MinAmountPrecision || precision > data.MaxAmountPrecision {
|
||||||
|
return value, fmt.Errorf("%s must be between %d and %d", key, data.MinAmountPrecision, data.MaxAmountPrecision)
|
||||||
|
}
|
||||||
|
case mdb.SettingKeyRateForcedRateList:
|
||||||
|
normalized, err := normalizeForcedRateListSetting(group, key, value)
|
||||||
|
if err != nil {
|
||||||
|
return value, err
|
||||||
|
}
|
||||||
|
return normalized, nil
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeForcedRateListSetting(group, key, value string) (string, error) {
|
||||||
|
if strings.ToLower(strings.TrimSpace(group)) != mdb.SettingGroupRate {
|
||||||
|
return value, fmt.Errorf("%s must use group %s", key, mdb.SettingGroupRate)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(value) == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var rates map[string]map[string]float64
|
||||||
|
if err := json.Unmarshal([]byte(value), &rates); err != nil {
|
||||||
|
return value, fmt.Errorf("%s must be valid JSON object", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
normalized := make(map[string]map[string]float64, len(rates))
|
||||||
|
for base, coins := range rates {
|
||||||
|
normalizedBase := strings.ToLower(strings.TrimSpace(base))
|
||||||
|
if normalizedBase == "" {
|
||||||
|
return value, fmt.Errorf("%s base currency must not be empty", key)
|
||||||
|
}
|
||||||
|
if coins == nil {
|
||||||
|
return value, fmt.Errorf("%s.%s must be an object", key, base)
|
||||||
|
}
|
||||||
|
normalizedCoins, ok := normalized[normalizedBase]
|
||||||
|
if !ok {
|
||||||
|
normalizedCoins = make(map[string]float64, len(coins))
|
||||||
|
normalized[normalizedBase] = normalizedCoins
|
||||||
|
}
|
||||||
|
for coin, rate := range coins {
|
||||||
|
normalizedCoin := strings.ToLower(strings.TrimSpace(coin))
|
||||||
|
if normalizedCoin == "" {
|
||||||
|
return value, fmt.Errorf("%s coin must not be empty", key)
|
||||||
|
}
|
||||||
|
if rate < 0 {
|
||||||
|
return value, fmt.Errorf("%s.%s.%s must be >= 0", key, base, coin)
|
||||||
|
}
|
||||||
|
if _, exists := normalizedCoins[normalizedCoin]; exists {
|
||||||
|
return value, fmt.Errorf("%s.%s.%s is duplicated after normalization", key, normalizedBase, normalizedCoin)
|
||||||
|
}
|
||||||
|
normalizedCoins[normalizedCoin] = rate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
normalizedValue, err := json.Marshal(normalized)
|
||||||
|
if err != nil {
|
||||||
|
return value, fmt.Errorf("%s must be JSON serializable", key)
|
||||||
|
}
|
||||||
|
return string(normalizedValue), nil
|
||||||
|
}
|
||||||
|
|
||||||
// DeleteSetting removes one row. The next read of that key will fall
|
// DeleteSetting removes one row. The next read of that key will fall
|
||||||
// back to the hardcoded default (see settings_data.GetSetting*).
|
// back to the hardcoded default (see settings_data.GetSetting*).
|
||||||
// @Summary Delete setting
|
// @Summary Delete setting
|
||||||
@@ -153,7 +278,3 @@ func (c *BaseAdminController) DeleteSetting(ctx echo.Context) error {
|
|||||||
}
|
}
|
||||||
return c.SucJson(ctx, nil)
|
return c.SucJson(ctx, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Public helper for the rate/usdt overrides — used by config package to
|
|
||||||
// read settings-backed values without importing the controller package.
|
|
||||||
var _ = mdb.SettingKeyRateForcedUsdt // ensure key constants remain referenced
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package comm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/model/service"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/log"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OkPayNotify receives the server-to-server OkPay payment callback.
|
||||||
|
// The handler accepts JSON or form-urlencoded payloads and returns plain-text
|
||||||
|
// acknowledgements expected by the upstream provider.
|
||||||
|
// @Summary OkPay notify callback
|
||||||
|
// @Description Receives OkPay deposit callbacks for hosted checkout child orders.
|
||||||
|
// @Description The callback is verified against the configured OkPay shop token and, on success, marks the matching child order as paid.
|
||||||
|
// @Tags Payment
|
||||||
|
// @Accept json
|
||||||
|
// @Accept x-www-form-urlencoded
|
||||||
|
// @Produce plain
|
||||||
|
// @Success 200 {string} string "success"
|
||||||
|
// @Failure 400 {string} string "fail"
|
||||||
|
// @Router /payments/okpay/v1/notify [post]
|
||||||
|
func (c *BaseCommController) OkPayNotify(ctx echo.Context) error {
|
||||||
|
req := ctx.Request()
|
||||||
|
rawBody, err := io.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[okpay] read notify body failed err=%v", err)
|
||||||
|
return ctx.String(http.StatusBadRequest, "fail")
|
||||||
|
}
|
||||||
|
req.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||||
|
|
||||||
|
form := make(map[string]string)
|
||||||
|
copyForm := func(values url.Values) {
|
||||||
|
for key, items := range values {
|
||||||
|
if len(items) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
form[key] = items[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
copyForm(req.URL.Query())
|
||||||
|
|
||||||
|
contentType := strings.ToLower(req.Header.Get(echo.HeaderContentType))
|
||||||
|
|
||||||
|
if strings.Contains(contentType, echo.MIMEApplicationJSON) && len(rawBody) > 0 {
|
||||||
|
if jsonForm, jsonErr := flattenOkPayJSONBody(rawBody); jsonErr == nil {
|
||||||
|
for key, value := range jsonForm {
|
||||||
|
form[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match the PHP example's $_POST semantics: let Echo/net/http parse both
|
||||||
|
// application/x-www-form-urlencoded and multipart/form-data.
|
||||||
|
if len(form) == 0 {
|
||||||
|
req.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||||
|
if parsedForm, formErr := ctx.FormParams(); formErr == nil {
|
||||||
|
copyForm(parsedForm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Final fallback for raw query-string style bodies.
|
||||||
|
if len(form) == 0 && len(rawBody) > 0 && looksLikeQueryPayload(string(rawBody)) {
|
||||||
|
if parsed, parseErr := url.ParseQuery(string(rawBody)); parseErr == nil && len(parsed) > 0 {
|
||||||
|
copyForm(parsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rawFormData := string(rawBody)
|
||||||
|
if rawFormData == "" {
|
||||||
|
rawFormData = req.URL.RawQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(form) == 0 {
|
||||||
|
log.Sugar.Warnf("[okpay] empty notify payload method=%s content_type=%s remote=%s raw_query=%q raw_body=%q", req.Method, req.Header.Get(echo.HeaderContentType), ctx.RealIP(), req.URL.RawQuery, rawFormData)
|
||||||
|
return ctx.String(http.StatusBadRequest, "fail")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = service.HandleOkPayNotify(form, rawFormData); err != nil {
|
||||||
|
log.Sugar.Warnf("[okpay] notify handle failed method=%s content_type=%s remote=%s form=%v raw_query=%q raw_body=%q err=%v", req.Method, req.Header.Get(echo.HeaderContentType), ctx.RealIP(), form, req.URL.RawQuery, rawFormData, err)
|
||||||
|
return ctx.String(http.StatusBadRequest, "fail")
|
||||||
|
}
|
||||||
|
return ctx.String(http.StatusOK, "success")
|
||||||
|
}
|
||||||
|
|
||||||
|
func flattenOkPayJSONBody(rawBody []byte) (map[string]string, error) {
|
||||||
|
decoder := json.NewDecoder(bytes.NewReader(rawBody))
|
||||||
|
decoder.UseNumber()
|
||||||
|
|
||||||
|
var payload map[string]interface{}
|
||||||
|
if err := decoder.Decode(&payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
flat := make(map[string]string)
|
||||||
|
for key, value := range payload {
|
||||||
|
if key == "data" {
|
||||||
|
dataMap, ok := value.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for dataKey, dataValue := range dataMap {
|
||||||
|
flat["data["+dataKey+"]"] = stringifyOkPayJSONValue(dataValue)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
flat[key] = stringifyOkPayJSONValue(value)
|
||||||
|
}
|
||||||
|
return flat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringifyOkPayJSONValue(value interface{}) string {
|
||||||
|
switch v := value.(type) {
|
||||||
|
case nil:
|
||||||
|
return ""
|
||||||
|
case string:
|
||||||
|
return strings.TrimSpace(v)
|
||||||
|
case json.Number:
|
||||||
|
return v.String()
|
||||||
|
case float64:
|
||||||
|
if v == math.Trunc(v) {
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||||
|
case bool:
|
||||||
|
if v {
|
||||||
|
return "true"
|
||||||
|
}
|
||||||
|
return "false"
|
||||||
|
default:
|
||||||
|
return strings.TrimSpace(fmt.Sprint(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func looksLikeQueryPayload(raw string) bool {
|
||||||
|
trimmed := strings.TrimSpace(raw)
|
||||||
|
if trimmed == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.Contains(trimmed, "=")
|
||||||
|
}
|
||||||
@@ -60,12 +60,14 @@ func (c *BaseCommController) CreateTransaction(ctx echo.Context) (err error) {
|
|||||||
|
|
||||||
// SwitchNetwork 切换支付网络,创建或返回子订单
|
// SwitchNetwork 切换支付网络,创建或返回子订单
|
||||||
// @Summary Switch payment network
|
// @Summary Switch payment network
|
||||||
// @Description Switch to a different payment network, creating or returning a sub-order
|
// @Description Switch to a different payment target, creating or returning a sub-order.
|
||||||
|
// @Description Normal values such as tron/solana/ethereum create on-chain child orders.
|
||||||
|
// @Description The special value okpay creates or reuses an OkPay-hosted child order and returns its payment_url.
|
||||||
// @Tags Payment
|
// @Tags Payment
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param request body request.SwitchNetworkRequest true "Switch network payload"
|
// @Param request body request.SwitchNetworkRequest true "Switch network payload"
|
||||||
// @Success 200 {object} response.ApiResponse
|
// @Success 200 {object} response.ApiResponse{data=response.CheckoutCounterResponse}
|
||||||
// @Failure 400 {object} response.ApiResponse
|
// @Failure 400 {object} response.ApiResponse
|
||||||
// @Router /pay/switch-network [post]
|
// @Router /pay/switch-network [post]
|
||||||
func (c *BaseCommController) SwitchNetwork(ctx echo.Context) (err error) {
|
func (c *BaseCommController) SwitchNetwork(ctx echo.Context) (err error) {
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package comm
|
package comm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/GMWalletApp/epusdt/model/response"
|
"github.com/GMWalletApp/epusdt/model/response"
|
||||||
"github.com/GMWalletApp/epusdt/model/service"
|
"github.com/GMWalletApp/epusdt/model/service"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
@@ -10,23 +8,18 @@ import (
|
|||||||
|
|
||||||
// CheckoutCounter 收银台
|
// CheckoutCounter 收银台
|
||||||
// @Summary Checkout counter page
|
// @Summary Checkout counter page
|
||||||
// @Description Render the payment checkout counter JSON response for a given trade
|
// @Description Return checkout initialization data when the order exists. This endpoint only confirms order existence and returns base order data; call /pay/check-status/{trade_id} for the current order status (1=waiting payment, 2=paid, 3=expired).
|
||||||
// @Tags Payment
|
// @Tags Payment
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param trade_id path string true "Trade ID"
|
// @Param trade_id path string true "Trade ID"
|
||||||
// @Success 200 {object} response.CheckoutCounterResponse
|
// @Success 200 {object} response.ApiResponse{data=response.CheckoutCounterResponse}
|
||||||
|
// @Failure 400 {object} response.ApiResponse "Order not found (status_code=10008) or other request error"
|
||||||
// @Router /pay/checkout-counter-resp/{trade_id} [get]
|
// @Router /pay/checkout-counter-resp/{trade_id} [get]
|
||||||
func (c *BaseCommController) CheckoutCounter(ctx echo.Context) (err error) {
|
func (c *BaseCommController) CheckoutCounter(ctx echo.Context) (err error) {
|
||||||
tradeId := ctx.Param("trade_id")
|
tradeId := ctx.Param("trade_id")
|
||||||
resp, err := service.GetCheckoutCounterByTradeId(tradeId)
|
resp, err := service.GetCheckoutCounterByTradeId(tradeId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == service.ErrOrder {
|
return c.FailJson(ctx, err)
|
||||||
// Unknown trade id: render the page with empty payload
|
|
||||||
// (client side shows a friendly "order not found" screen).
|
|
||||||
emptyResp := response.CheckoutCounterResponse{}
|
|
||||||
return c.SucJson(ctx, emptyResp)
|
|
||||||
}
|
|
||||||
return ctx.String(http.StatusInternalServerError, err.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.SucJson(ctx, resp)
|
return c.SucJson(ctx, resp)
|
||||||
@@ -34,12 +27,12 @@ func (c *BaseCommController) CheckoutCounter(ctx echo.Context) (err error) {
|
|||||||
|
|
||||||
// CheckStatus 支付状态检测
|
// CheckStatus 支付状态检测
|
||||||
// @Summary Check payment status
|
// @Summary Check payment status
|
||||||
// @Description Check the payment status of an order by trade ID
|
// @Description Return the current order status by trade ID. Status: 1=waiting payment, 2=paid, 3=expired.
|
||||||
// @Tags Payment
|
// @Tags Payment
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param trade_id path string true "Trade ID"
|
// @Param trade_id path string true "Trade ID"
|
||||||
// @Success 200 {object} response.ApiResponse{data=response.CheckStatusResponse}
|
// @Success 200 {object} response.ApiResponse{data=response.CheckStatusResponse}
|
||||||
// @Failure 400 {object} response.ApiResponse
|
// @Failure 400 {object} response.ApiResponse "Order not found (status_code=10008) or other request error"
|
||||||
// @Router /pay/check-status/{trade_id} [get]
|
// @Router /pay/check-status/{trade_id} [get]
|
||||||
func (c *BaseCommController) CheckStatus(ctx echo.Context) (err error) {
|
func (c *BaseCommController) CheckStatus(ctx echo.Context) (err error) {
|
||||||
tradeId := ctx.Param("trade_id")
|
tradeId := ctx.Param("trade_id")
|
||||||
|
|||||||
@@ -5,38 +5,25 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/config"
|
||||||
|
"github.com/GMWalletApp/epusdt/middleware"
|
||||||
"github.com/GMWalletApp/epusdt/model/data"
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"github.com/GMWalletApp/epusdt/model/response"
|
"github.com/GMWalletApp/epusdt/model/response"
|
||||||
"github.com/GMWalletApp/epusdt/util/constant"
|
"github.com/GMWalletApp/epusdt/util/constant"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetSupportedAssets 对外公开可用链与 token 列表。数据源是管理后台
|
func buildSupportedAssets() ([]response.NetworkTokenSupport, error) {
|
||||||
// 的 chains + chain_tokens + wallet_address 三张表的实时查询,admin
|
|
||||||
// 启用/禁用链或代币后,这个接口在下次调用时就会反映新状态(无缓存)。
|
|
||||||
// 仅返回:链 enabled=true、代币 enabled=true、且该链上至少有一个可用
|
|
||||||
// 钱包地址的组合。
|
|
||||||
// @Summary List supported (network, tokens) groupings
|
|
||||||
// @Description Public endpoint, Auth required in /admin/api/v1/supported-assets
|
|
||||||
// @Tags Supported Assets
|
|
||||||
// @Produce json
|
|
||||||
// @Success 200 {object} response.ApiResponse{data=response.SupportedAssetsResponse}
|
|
||||||
// @Failure 400 {object} response.ApiResponse
|
|
||||||
// @Router /payments/gmpay/v1/supported-assets [get]
|
|
||||||
// @Router /admin/api/v1/supported-assets [get]
|
|
||||||
func (c *BaseCommController) GetSupportedAssets(ctx echo.Context) error {
|
|
||||||
chains, err := data.ListEnabledChains()
|
chains, err := data.ListEnabledChains()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.FailJson(ctx, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
wallets, err := data.GetAvailableWalletAddress()
|
wallets, err := data.GetAvailableWalletAddress()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.FailJson(ctx, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// A chain only qualifies if it has at least one wallet available —
|
|
||||||
// without a recipient address, payments on that chain can't be
|
|
||||||
// processed even if the chain + token config says "enabled".
|
|
||||||
networkHasWallet := make(map[string]struct{})
|
networkHasWallet := make(map[string]struct{})
|
||||||
for _, w := range wallets {
|
for _, w := range wallets {
|
||||||
networkHasWallet[strings.ToLower(w.Network)] = struct{}{}
|
networkHasWallet[strings.ToLower(w.Network)] = struct{}{}
|
||||||
@@ -50,7 +37,7 @@ func (c *BaseCommController) GetSupportedAssets(ctx echo.Context) error {
|
|||||||
}
|
}
|
||||||
tokens, err := data.ListEnabledChainTokensByNetwork(network)
|
tokens, err := data.ListEnabledChainTokensByNetwork(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.FailJson(ctx, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
if len(tokens) == 0 {
|
if len(tokens) == 0 {
|
||||||
continue
|
continue
|
||||||
@@ -67,24 +54,72 @@ func (c *BaseCommController) GetSupportedAssets(ctx echo.Context) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
sort.Strings(symbols)
|
sort.Strings(symbols)
|
||||||
|
displayName := strings.TrimSpace(ch.DisplayName)
|
||||||
|
if displayName == "" {
|
||||||
|
displayName = network
|
||||||
|
}
|
||||||
supports = append(supports, response.NetworkTokenSupport{
|
supports = append(supports, response.NetworkTokenSupport{
|
||||||
Network: network,
|
Network: network,
|
||||||
|
DisplayName: displayName,
|
||||||
Tokens: symbols,
|
Tokens: symbols,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.SucJson(ctx, response.SupportedAssetsResponse{Supports: supports})
|
return supports, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListSupportedAssetRecords 查询支持项明细(无需鉴权)。
|
// GetPublicConfig returns payment/site config consumed by cashier/frontends.
|
||||||
// @Summary List supported asset records
|
// The public route returns brand/site display config plus non-sensitive
|
||||||
// @Description Public endpoint. Returns enabled chain_tokens, optionally filtered by network.
|
// epay/okpay knobs, while the authenticated admin route also includes OkPay
|
||||||
// @Tags Supported Assets
|
// credentials and internal URLs.
|
||||||
|
// @Summary Get public payment config
|
||||||
|
// @Description Returns supported_assets plus site, epay and okpay config used by cashier/frontends.
|
||||||
|
// @Description The authenticated admin variant (/admin/api/v1/config) also includes OkPay shop credentials and internal callback settings.
|
||||||
|
// @Tags Payment Config
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param network query string false "Network filter (e.g. tron, ethereum)"
|
// @Success 200 {object} response.ApiResponse{data=response.PublicConfigResponse}
|
||||||
// @Success 200 {object} response.ApiResponse{data=[]mdb.ChainToken}
|
|
||||||
// @Failure 400 {object} response.ApiResponse
|
// @Failure 400 {object} response.ApiResponse
|
||||||
// @Router /payments/gmpay/v1/supported-assets/records [get]
|
// @Router /payments/gmpay/v1/config [get]
|
||||||
|
// @Router /admin/api/v1/config [get]
|
||||||
|
func (c *BaseCommController) GetPublicConfig(ctx echo.Context) error {
|
||||||
|
supports, err := buildSupportedAssets()
|
||||||
|
if err != nil {
|
||||||
|
return c.FailJson(ctx, err)
|
||||||
|
}
|
||||||
|
okpay := response.OkPayPublicConfig{
|
||||||
|
Enabled: data.GetOkPayEnabled(),
|
||||||
|
AllowTokens: data.GetOkPayAllowTokens(),
|
||||||
|
}
|
||||||
|
if ctx.Get(middleware.AdminUserIDKey) != nil {
|
||||||
|
okpay.ShopID = data.GetOkPayShopID()
|
||||||
|
okpay.ShopToken = data.GetOkPayShopToken()
|
||||||
|
okpay.APIURL = data.GetOkPayAPIURL()
|
||||||
|
okpay.CallbackURL = data.GetOkPayCallbackURL()
|
||||||
|
okpay.ReturnURL = data.GetOkPayReturnURL()
|
||||||
|
okpay.TimeoutSeconds = data.GetOkPayTimeoutSeconds()
|
||||||
|
}
|
||||||
|
return c.SucJson(ctx, response.PublicConfigResponse{
|
||||||
|
SupportedAssets: supports,
|
||||||
|
Site: response.SitePublicConfig{
|
||||||
|
CashierName: data.GetBrandCashierName(),
|
||||||
|
LogoURL: data.GetBrandLogoURL(),
|
||||||
|
WebsiteTitle: data.GetBrandWebsiteTitle(),
|
||||||
|
SupportLink: data.GetBrandSupportURL(),
|
||||||
|
BackgroundColor: data.GetBrandBackgroundColor(),
|
||||||
|
BackgroundImageURL: data.GetBrandBackgroundImageURL(),
|
||||||
|
},
|
||||||
|
Epay: response.EpayPublicConfig{
|
||||||
|
DefaultToken: data.GetSettingString(mdb.SettingKeyEpayDefaultToken, "usdt"),
|
||||||
|
DefaultCurrency: data.GetSettingString(mdb.SettingKeyEpayDefaultCurrency, "cny"),
|
||||||
|
DefaultNetwork: data.GetSettingString(mdb.SettingKeyEpayDefaultNetwork, "tron"),
|
||||||
|
},
|
||||||
|
OkPay: okpay,
|
||||||
|
Version: config.GetAppVersion(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListSupportedAssetRecords is currently not wired to a public route.
|
||||||
|
// Kept as an internal helper candidate for future admin/debug use.
|
||||||
func (c *BaseCommController) ListSupportedAssetRecords(ctx echo.Context) error {
|
func (c *BaseCommController) ListSupportedAssetRecords(ctx echo.Context) error {
|
||||||
network := ctx.QueryParam("network")
|
network := ctx.QueryParam("network")
|
||||||
list, err := data.ListEnabledChainTokens(network)
|
list, err := data.ListEnabledChainTokens(network)
|
||||||
@@ -94,15 +129,8 @@ func (c *BaseCommController) ListSupportedAssetRecords(ctx echo.Context) error {
|
|||||||
return c.SucJson(ctx, list)
|
return c.SucJson(ctx, list)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSupportedAsset 查询单条支持项(无需鉴权)。
|
// GetSupportedAsset is currently not wired to a public route.
|
||||||
// @Summary Get a supported asset
|
// Kept as an internal helper candidate for future admin/debug use.
|
||||||
// @Description Public endpoint. Returns one chain_token row by ID. Returns 404 if the token is disabled.
|
|
||||||
// @Tags Supported Assets
|
|
||||||
// @Produce json
|
|
||||||
// @Param id path int true "ChainToken ID"
|
|
||||||
// @Success 200 {object} response.ApiResponse{data=mdb.ChainToken}
|
|
||||||
// @Failure 400 {object} response.ApiResponse
|
|
||||||
// @Router /payments/gmpay/v1/supported-assets/{id} [get]
|
|
||||||
func (c *BaseCommController) GetSupportedAsset(ctx echo.Context) error {
|
func (c *BaseCommController) GetSupportedAsset(ctx echo.Context) error {
|
||||||
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package crypto
|
package crypto
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/shengdoushi/base58"
|
"github.com/shengdoushi/base58"
|
||||||
)
|
)
|
||||||
@@ -28,3 +30,24 @@ func EncodeCheck(input []byte) string {
|
|||||||
|
|
||||||
return Encode(inputCheck)
|
return Encode(inputCheck)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecodeCheck decodes a Base58Check string and validates its 4-byte checksum.
|
||||||
|
func DecodeCheck(input string) ([]byte, error) {
|
||||||
|
raw, err := base58.Decode(input, base58.BitcoinAlphabet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(raw) < 4 {
|
||||||
|
return nil, fmt.Errorf("base58check payload too short")
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := raw[:len(raw)-4]
|
||||||
|
checksum := raw[len(raw)-4:]
|
||||||
|
|
||||||
|
h0 := sha256.Sum256(payload)
|
||||||
|
h1 := sha256.Sum256(h0[:])
|
||||||
|
if !bytes.Equal(checksum, h1[:4]) {
|
||||||
|
return nil, fmt.Errorf("base58check checksum mismatch")
|
||||||
|
}
|
||||||
|
return payload, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ func SetupTestDatabases(t testing.TB) func() {
|
|||||||
|
|
||||||
mustMigrate(t, mainDB,
|
mustMigrate(t, mainDB,
|
||||||
&mdb.Orders{},
|
&mdb.Orders{},
|
||||||
|
&mdb.ProviderOrder{},
|
||||||
&mdb.WalletAddress{},
|
&mdb.WalletAddress{},
|
||||||
&mdb.ApiKey{},
|
&mdb.ApiKey{},
|
||||||
&mdb.Setting{},
|
&mdb.Setting{},
|
||||||
@@ -84,11 +85,11 @@ func SetupTestDatabases(t testing.TB) func() {
|
|||||||
})
|
})
|
||||||
if err := dao.Mdb.Create(&mdb.Setting{
|
if err := dao.Mdb.Create(&mdb.Setting{
|
||||||
Group: "rate",
|
Group: "rate",
|
||||||
Key: "rate.forced_usdt_rate",
|
Key: "rate.forced_rate_list",
|
||||||
Value: "1.0",
|
Value: `{"cny":{"usdt":1}}`,
|
||||||
Type: "string",
|
Type: "json",
|
||||||
}).Error; err != nil {
|
}).Error; err != nil {
|
||||||
t.Fatalf("seed rate.forced_usdt_rate: %v", err)
|
t.Fatalf("seed rate.forced_rate_list: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return func() {
|
return func() {
|
||||||
|
|||||||
+23
-10
@@ -27,16 +27,9 @@ const (
|
|||||||
func CheckAdminJWT() echo.MiddlewareFunc {
|
func CheckAdminJWT() echo.MiddlewareFunc {
|
||||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
return func(ctx echo.Context) error {
|
return func(ctx echo.Context) error {
|
||||||
raw := strings.TrimSpace(ctx.Request().Header.Get("Authorization"))
|
token, err := adminTokenFromAuthorization(ctx.Request().Header.Get("Authorization"))
|
||||||
if raw == "" {
|
if err != nil {
|
||||||
return echo.NewHTTPError(http.StatusUnauthorized, "missing authorization header")
|
return err
|
||||||
}
|
|
||||||
if !strings.HasPrefix(raw, "Bearer ") {
|
|
||||||
return echo.NewHTTPError(http.StatusUnauthorized, "authorization header must use Bearer scheme")
|
|
||||||
}
|
|
||||||
token := strings.TrimSpace(raw[len("Bearer "):])
|
|
||||||
if token == "" {
|
|
||||||
return echo.NewHTTPError(http.StatusUnauthorized, "empty token")
|
|
||||||
}
|
}
|
||||||
claims, err := appjwt.Parse(token)
|
claims, err := appjwt.Parse(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -48,3 +41,23 @@ func CheckAdminJWT() echo.MiddlewareFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func adminTokenFromAuthorization(header string) (string, error) {
|
||||||
|
raw := strings.TrimSpace(header)
|
||||||
|
if raw == "" {
|
||||||
|
return "", echo.NewHTTPError(http.StatusUnauthorized, "missing authorization header")
|
||||||
|
}
|
||||||
|
|
||||||
|
const bearerPrefix = "Bearer "
|
||||||
|
token := raw
|
||||||
|
if strings.HasPrefix(raw, bearerPrefix) {
|
||||||
|
token = strings.TrimSpace(raw[len(bearerPrefix):])
|
||||||
|
} else if raw == strings.TrimSpace(bearerPrefix) {
|
||||||
|
token = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if token == "" {
|
||||||
|
return "", echo.NewHTTPError(http.StatusUnauthorized, "empty token")
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
appjwt "github.com/GMWalletApp/epusdt/util/jwt"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAdminTokenFromAuthorization(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
header string
|
||||||
|
want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "bearer token",
|
||||||
|
header: "Bearer jwt-token",
|
||||||
|
want: "jwt-token",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bare token",
|
||||||
|
header: "jwt-token",
|
||||||
|
want: "jwt-token",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "trimmed bare token",
|
||||||
|
header: " jwt-token ",
|
||||||
|
want: "jwt-token",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing header",
|
||||||
|
header: "",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty bearer token",
|
||||||
|
header: "Bearer ",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := adminTokenFromAuthorization(tt.header)
|
||||||
|
if tt.wantErr {
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("token = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckAdminJWTAcceptsBearerAndBareTokens(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyJwtSecret, "test-jwt-secret", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed jwt secret: %v", err)
|
||||||
|
}
|
||||||
|
token, err := appjwt.Sign(42, "admin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sign jwt: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
header string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "bearer token",
|
||||||
|
header: "Bearer " + token,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bare token",
|
||||||
|
header: token,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
e := echo.New()
|
||||||
|
e.Use(CheckAdminJWT())
|
||||||
|
e.GET("/", func(ctx echo.Context) error {
|
||||||
|
if got := ctx.Get(AdminUserIDKey); got != uint64(42) {
|
||||||
|
t.Fatalf("%s = %v, want 42", AdminUserIDKey, got)
|
||||||
|
}
|
||||||
|
if got := ctx.Get(AdminUsernameKey); got != "admin" {
|
||||||
|
t.Fatalf("%s = %v, want admin", AdminUsernameKey, got)
|
||||||
|
}
|
||||||
|
return ctx.NoContent(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.Header.Set(echo.HeaderAuthorization, tt.header)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
e.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusNoContent, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/config"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"github.com/gookit/color"
|
"github.com/gookit/color"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -35,6 +36,7 @@ func MdbTableInit() {
|
|||||||
{"Chain", &mdb.Chain{}},
|
{"Chain", &mdb.Chain{}},
|
||||||
{"ChainToken", &mdb.ChainToken{}},
|
{"ChainToken", &mdb.ChainToken{}},
|
||||||
{"RpcNode", &mdb.RpcNode{}},
|
{"RpcNode", &mdb.RpcNode{}},
|
||||||
|
{"ProviderOrder", &mdb.ProviderOrder{}},
|
||||||
}
|
}
|
||||||
for _, m := range migrations {
|
for _, m := range migrations {
|
||||||
if err := Mdb.AutoMigrate(m.model); err != nil {
|
if err := Mdb.AutoMigrate(m.model); err != nil {
|
||||||
@@ -132,10 +134,20 @@ func seedRpcNodes() {
|
|||||||
// seedDefaultSettings inserts built-in default settings.
|
// seedDefaultSettings inserts built-in default settings.
|
||||||
// Uses ON CONFLICT DO NOTHING so admin edits persist across restarts.
|
// Uses ON CONFLICT DO NOTHING so admin edits persist across restarts.
|
||||||
func seedDefaultSettings() {
|
func seedDefaultSettings() {
|
||||||
|
okPayCallbackURL := strings.TrimRight(strings.TrimSpace(config.GetAppUri()), "/")
|
||||||
|
if okPayCallbackURL != "" {
|
||||||
|
okPayCallbackURL += "/payments/okpay/v1/notify"
|
||||||
|
}
|
||||||
defaults := []mdb.Setting{
|
defaults := []mdb.Setting{
|
||||||
|
{Group: mdb.SettingGroupSystem, Key: mdb.SettingKeyAmountPrecision, Value: "2", Type: mdb.SettingTypeInt},
|
||||||
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultToken, Value: "usdt", Type: mdb.SettingTypeString},
|
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultToken, Value: "usdt", Type: mdb.SettingTypeString},
|
||||||
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultCurrency, Value: "cny", Type: mdb.SettingTypeString},
|
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultCurrency, Value: "cny", Type: mdb.SettingTypeString},
|
||||||
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultNetwork, Value: "tron", Type: mdb.SettingTypeString},
|
{Group: mdb.SettingGroupEpay, Key: mdb.SettingKeyEpayDefaultNetwork, Value: "tron", Type: mdb.SettingTypeString},
|
||||||
|
{Group: mdb.SettingGroupOkPay, Key: mdb.SettingKeyOkPayEnabled, Value: "false", Type: mdb.SettingTypeBool},
|
||||||
|
{Group: mdb.SettingGroupOkPay, Key: mdb.SettingKeyOkPayAPIURL, Value: "https://api.okaypay.me/shop/", Type: mdb.SettingTypeString},
|
||||||
|
{Group: mdb.SettingGroupOkPay, Key: mdb.SettingKeyOkPayCallbackURL, Value: okPayCallbackURL, Type: mdb.SettingTypeString},
|
||||||
|
{Group: mdb.SettingGroupOkPay, Key: mdb.SettingKeyOkPayTimeoutSeconds, Value: "10", Type: mdb.SettingTypeInt},
|
||||||
|
{Group: mdb.SettingGroupOkPay, Key: mdb.SettingKeyOkPayAllowTokens, Value: "USDT,TRX", Type: mdb.SettingTypeString},
|
||||||
}
|
}
|
||||||
if err := Mdb.Clauses(clause.OnConflict{DoNothing: true}).Create(&defaults).Error; err != nil {
|
if err := Mdb.Clauses(clause.OnConflict{DoNothing: true}).Create(&defaults).Error; err != nil {
|
||||||
color.Red.Printf("[store_db] seed default settings err=%s\n", err)
|
color.Red.Printf("[store_db] seed default settings err=%s\n", err)
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ func RuntimeInit() error {
|
|||||||
if err = RuntimeDB.Exec("DROP INDEX IF EXISTS transaction_lock_address_token_amount_uindex").Error; err != nil {
|
if err = RuntimeDB.Exec("DROP INDEX IF EXISTS transaction_lock_address_token_amount_uindex").Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err = RuntimeDB.Exec("DROP INDEX IF EXISTS transaction_lock_network_address_token_amount_uindex").Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err = RuntimeDB.AutoMigrate(&mdb.TransactionLock{}); err != nil {
|
if err = RuntimeDB.AutoMigrate(&mdb.TransactionLock{}); err != nil {
|
||||||
color.Red.Printf("[runtime_db] sqlite migrate DB(TransactionLock),err=%s\n", err)
|
color.Red.Printf("[runtime_db] sqlite migrate DB(TransactionLock),err=%s\n", err)
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -40,6 +40,9 @@ type InitialAdminPasswordHashInfo struct {
|
|||||||
// can print it to the console. Idempotent — subsequent calls return
|
// can print it to the console. Idempotent — subsequent calls return
|
||||||
// ("", false, nil).
|
// ("", false, nil).
|
||||||
func EnsureDefaultAdmin() (password string, created bool, err error) {
|
func EnsureDefaultAdmin() (password string, created bool, err error) {
|
||||||
|
if err := purgeDeletedInitialAdminPasswordPlain(); err != nil {
|
||||||
|
return "", false, err
|
||||||
|
}
|
||||||
var count int64
|
var count int64
|
||||||
if err := dao.Mdb.Model(&mdb.AdminUser{}).Count(&count).Error; err != nil {
|
if err := dao.Mdb.Model(&mdb.AdminUser{}).Count(&count).Error; err != nil {
|
||||||
return "", false, err
|
return "", false, err
|
||||||
@@ -68,6 +71,12 @@ func EnsureDefaultAdmin() (password string, created bool, err error) {
|
|||||||
return password, true, nil
|
return password, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func purgeDeletedInitialAdminPasswordPlain() error {
|
||||||
|
return dao.Mdb.Unscoped().
|
||||||
|
Where("`key` = ? AND deleted_at IS NOT NULL", mdb.SettingKeyInitAdminPasswordPlain).
|
||||||
|
Delete(&mdb.Setting{}).Error
|
||||||
|
}
|
||||||
|
|
||||||
func randomAdminPassword() string {
|
func randomAdminPassword() string {
|
||||||
b := make([]byte, 16)
|
b := make([]byte, 16)
|
||||||
_, _ = rand.Read(b)
|
_, _ = rand.Read(b)
|
||||||
@@ -121,9 +130,11 @@ func initAdminPasswordState(plain string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func upsertSettingRow(tx *gorm.DB, row mdb.Setting) error {
|
func upsertSettingRow(tx *gorm.DB, row mdb.Setting) error {
|
||||||
|
updates := clause.AssignmentColumns([]string{"group", "value", "type", "description", "updated_at"})
|
||||||
|
updates = append(updates, clause.Assignment{Column: clause.Column{Name: "deleted_at"}, Value: nil})
|
||||||
return tx.Clauses(clause.OnConflict{
|
return tx.Clauses(clause.OnConflict{
|
||||||
Columns: []clause.Column{{Name: "key"}},
|
Columns: []clause.Column{{Name: "key"}},
|
||||||
DoUpdates: clause.AssignmentColumns([]string{"group", "value", "type", "description", "updated_at"}),
|
DoUpdates: updates,
|
||||||
}).Create(&row).Error
|
}).Create(&row).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +165,7 @@ func ConsumeInitialAdminPassword() (string, error) {
|
|||||||
return ErrInitAdminPasswordUnavailable
|
return ErrInitAdminPasswordUnavailable
|
||||||
}
|
}
|
||||||
password = row.Value
|
password = row.Value
|
||||||
res := tx.Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).Delete(&mdb.Setting{})
|
res := tx.Unscoped().Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).Delete(&mdb.Setting{})
|
||||||
if res.Error != nil {
|
if res.Error != nil {
|
||||||
return res.Error
|
return res.Error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package data
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpsertSettingRowRestoresSoftDeletedSetting(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
row := mdb.Setting{
|
||||||
|
Group: mdb.SettingGroupSystem,
|
||||||
|
Key: mdb.SettingKeyInitAdminPasswordChanged,
|
||||||
|
Value: "false",
|
||||||
|
Type: mdb.SettingTypeBool,
|
||||||
|
}
|
||||||
|
if err := upsertSettingRow(dao.Mdb, row); err != nil {
|
||||||
|
t.Fatalf("seed setting: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Where("`key` = ?", row.Key).Delete(&mdb.Setting{}).Error; err != nil {
|
||||||
|
t.Fatalf("delete setting: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
row.Value = "true"
|
||||||
|
if err := upsertSettingRow(dao.Mdb, row); err != nil {
|
||||||
|
t.Fatalf("restore setting: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var restored mdb.Setting
|
||||||
|
if err := dao.Mdb.Where("`key` = ?", row.Key).Take(&restored).Error; err != nil {
|
||||||
|
t.Fatalf("load restored setting: %v", err)
|
||||||
|
}
|
||||||
|
if restored.Value != "true" {
|
||||||
|
t.Fatalf("restored value = %q, want true", restored.Value)
|
||||||
|
}
|
||||||
|
if restored.DeletedAt.Valid {
|
||||||
|
t.Fatalf("restored setting still has deleted_at=%v", restored.DeletedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConsumeInitialAdminPasswordHardDeletesPlaintext(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const password = "init-pass-plain"
|
||||||
|
if err := initAdminPasswordState(password); err != nil {
|
||||||
|
t.Fatalf("seed initial password state: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := ConsumeInitialAdminPassword()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("consume initial password: %v", err)
|
||||||
|
}
|
||||||
|
if got != password {
|
||||||
|
t.Fatalf("password = %q, want %q", got, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
if err := dao.Mdb.Unscoped().
|
||||||
|
Model(&mdb.Setting{}).
|
||||||
|
Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
t.Fatalf("count plaintext setting: %v", err)
|
||||||
|
}
|
||||||
|
if count != 0 {
|
||||||
|
t.Fatalf("plaintext setting rows after consume = %d, want 0", count)
|
||||||
|
}
|
||||||
|
if !GetSettingBool(mdb.SettingKeyInitAdminPasswordFetched, false) {
|
||||||
|
t.Fatal("expected fetched flag to be true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureDefaultAdminPurgesLegacySoftDeletedPlaintext(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
hash, err := HashPassword("existing-password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash password: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(&mdb.AdminUser{
|
||||||
|
Username: defaultAdminUsername,
|
||||||
|
PasswordHash: hash,
|
||||||
|
Status: mdb.AdminUserStatusEnable,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed admin: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(&mdb.Setting{
|
||||||
|
Group: mdb.SettingGroupSystem,
|
||||||
|
Key: mdb.SettingKeyInitAdminPasswordPlain,
|
||||||
|
Value: "legacy-soft-deleted-plain",
|
||||||
|
Type: mdb.SettingTypeString,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed plaintext setting: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).Delete(&mdb.Setting{}).Error; err != nil {
|
||||||
|
t.Fatalf("soft delete plaintext setting: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
password, created, err := EnsureDefaultAdmin()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ensure default admin: %v", err)
|
||||||
|
}
|
||||||
|
if created || password != "" {
|
||||||
|
t.Fatalf("created=%v password=%q, want existing admin unchanged", created, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
if err := dao.Mdb.Unscoped().
|
||||||
|
Model(&mdb.Setting{}).
|
||||||
|
Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
t.Fatalf("count plaintext setting: %v", err)
|
||||||
|
}
|
||||||
|
if count != 0 {
|
||||||
|
t.Fatalf("legacy plaintext rows after ensure = %d, want 0", count)
|
||||||
|
}
|
||||||
|
}
|
||||||
+132
-23
@@ -23,9 +23,14 @@ type PendingCallbackOrder struct {
|
|||||||
UpdatedAt carbon.Time `gorm:"column:updated_at"`
|
UpdatedAt carbon.Time `gorm:"column:updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeAmount(amount float64, precision int) (int64, string) {
|
||||||
|
precision = NormalizeAmountPrecision(precision)
|
||||||
|
value := decimal.NewFromFloat(amount).Round(int32(precision))
|
||||||
|
return value.Shift(int32(precision)).IntPart(), value.StringFixed(int32(precision))
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeLockAmount(amount float64) (int64, string) {
|
func normalizeLockAmount(amount float64) (int64, string) {
|
||||||
value := decimal.NewFromFloat(amount).Round(2)
|
return normalizeAmount(amount, GetAmountPrecision())
|
||||||
return value.Shift(2).IntPart(), value.StringFixed(2)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeLockNetwork(network string) string {
|
func normalizeLockNetwork(network string) string {
|
||||||
@@ -53,6 +58,30 @@ func applyLockAddressFilter(tx *gorm.DB, network, address string) *gorm.DB {
|
|||||||
return tx.Where("address = ?", address)
|
return tx.Where("address = ?", address)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func activeLocksForAddress(tx *gorm.DB, network, address, token string, now time.Time) *gorm.DB {
|
||||||
|
query := tx.Model(&mdb.TransactionLock{}).
|
||||||
|
Where("network = ?", normalizeLockNetwork(network)).
|
||||||
|
Where("token = ?", normalizeLockToken(token)).
|
||||||
|
Where("expires_at > ?", now)
|
||||||
|
return applyLockAddressFilter(query, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func lockMatchesAmount(lock mdb.TransactionLock, amount float64) bool {
|
||||||
|
precision := NormalizeAmountPrecision(lock.AmountPrecision)
|
||||||
|
scaledAmount, _ := normalizeAmount(amount, precision)
|
||||||
|
return lock.AmountScaled == scaledAmount
|
||||||
|
}
|
||||||
|
|
||||||
|
func lockAmountDecimal(lock mdb.TransactionLock) decimal.Decimal {
|
||||||
|
if strings.TrimSpace(lock.AmountText) != "" {
|
||||||
|
if value, err := decimal.NewFromString(lock.AmountText); err == nil {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
precision := NormalizeAmountPrecision(lock.AmountPrecision)
|
||||||
|
return decimal.NewFromInt(lock.AmountScaled).Shift(int32(-precision))
|
||||||
|
}
|
||||||
|
|
||||||
// GetOrderInfoByOrderId fetches an order by merchant order id.
|
// GetOrderInfoByOrderId fetches an order by merchant order id.
|
||||||
func GetOrderInfoByOrderId(orderId string) (*mdb.Orders, error) {
|
func GetOrderInfoByOrderId(orderId string) (*mdb.Orders, error) {
|
||||||
order := new(mdb.Orders)
|
order := new(mdb.Orders)
|
||||||
@@ -79,6 +108,56 @@ func GetOrderByBlockIdWithTransaction(tx *gorm.DB, blockID string) (*mdb.Orders,
|
|||||||
return order, err
|
return order, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrderByBlockTransactionIDs fetches the first order whose stored tx id
|
||||||
|
// matches any equivalent spelling supplied by the caller.
|
||||||
|
func GetOrderByBlockTransactionIDs(blockIDs []string) (*mdb.Orders, error) {
|
||||||
|
order := new(mdb.Orders)
|
||||||
|
seen := make(map[string]struct{}, len(blockIDs))
|
||||||
|
candidates := make([]string, 0, len(blockIDs))
|
||||||
|
for _, blockID := range blockIDs {
|
||||||
|
blockID = strings.TrimSpace(blockID)
|
||||||
|
if blockID == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[blockID]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[blockID] = struct{}{}
|
||||||
|
candidates = append(candidates, blockID)
|
||||||
|
}
|
||||||
|
if len(candidates) == 0 {
|
||||||
|
return order, nil
|
||||||
|
}
|
||||||
|
err := dao.Mdb.Model(order).Where("block_transaction_id IN ?", candidates).Limit(1).Find(order).Error
|
||||||
|
return order, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOrderByBlockTransactionIDsCaseInsensitive fetches the first order whose
|
||||||
|
// stored tx id matches any candidate after ASCII case folding. This is used
|
||||||
|
// only for hex-based chain tx ids; case-sensitive signatures must keep using
|
||||||
|
// GetOrderByBlockTransactionIDs.
|
||||||
|
func GetOrderByBlockTransactionIDsCaseInsensitive(blockIDs []string) (*mdb.Orders, error) {
|
||||||
|
order := new(mdb.Orders)
|
||||||
|
seen := make(map[string]struct{}, len(blockIDs))
|
||||||
|
candidates := make([]string, 0, len(blockIDs))
|
||||||
|
for _, blockID := range blockIDs {
|
||||||
|
blockID = strings.ToLower(strings.TrimSpace(blockID))
|
||||||
|
if blockID == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[blockID]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[blockID] = struct{}{}
|
||||||
|
candidates = append(candidates, blockID)
|
||||||
|
}
|
||||||
|
if len(candidates) == 0 {
|
||||||
|
return order, nil
|
||||||
|
}
|
||||||
|
err := dao.Mdb.Model(order).Where("LOWER(block_transaction_id) IN ?", candidates).Limit(1).Find(order).Error
|
||||||
|
return order, err
|
||||||
|
}
|
||||||
|
|
||||||
// OrderSuccessWithTransaction marks an order as paid only if it is still waiting for payment.
|
// OrderSuccessWithTransaction marks an order as paid only if it is still waiting for payment.
|
||||||
func OrderSuccessWithTransaction(tx *gorm.DB, req *request.OrderProcessingRequest) (bool, error) {
|
func OrderSuccessWithTransaction(tx *gorm.DB, req *request.OrderProcessingRequest) (bool, error) {
|
||||||
result := tx.Model(&mdb.Orders{}).
|
result := tx.Model(&mdb.Orders{}).
|
||||||
@@ -202,6 +281,18 @@ func MarkOrderSelected(tradeId string) error {
|
|||||||
Update("is_selected", true).Error
|
Update("is_selected", true).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ExpireOrderByTradeID marks a waiting order as expired. Used to retire failed
|
||||||
|
// child-order attempts that should not remain selectable/reusable.
|
||||||
|
func ExpireOrderByTradeID(tradeId string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.Orders{}).
|
||||||
|
Where("trade_id = ?", tradeId).
|
||||||
|
Where("status = ?", mdb.StatusWaitPay).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"status": mdb.StatusExpired,
|
||||||
|
"is_selected": false,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
// RefreshOrderExpiration resets created_at to now so the expiration timer restarts.
|
// RefreshOrderExpiration resets created_at to now so the expiration timer restarts.
|
||||||
// Called on the parent order when a sub-order is created or returned.
|
// Called on the parent order when a sub-order is created or returned.
|
||||||
func RefreshOrderExpiration(tradeId string) error {
|
func RefreshOrderExpiration(tradeId string) error {
|
||||||
@@ -266,29 +357,27 @@ func ExpireOrderByTradeId(tradeId string) error {
|
|||||||
func GetTradeIdByWalletAddressAndAmountAndToken(network string, address string, token string, amount float64) (string, error) {
|
func GetTradeIdByWalletAddressAndAmountAndToken(network string, address string, token string, amount float64) (string, error) {
|
||||||
network = normalizeLockNetwork(network)
|
network = normalizeLockNetwork(network)
|
||||||
address = normalizeLockAddress(network, address)
|
address = normalizeLockAddress(network, address)
|
||||||
scaledAmount, _ := normalizeLockAmount(amount)
|
var locks []mdb.TransactionLock
|
||||||
var lock mdb.TransactionLock
|
err := activeLocksForAddress(dao.RuntimeDB, network, address, token, time.Now()).
|
||||||
query := dao.RuntimeDB.Model(&mdb.TransactionLock{}).
|
Order("created_at ASC").
|
||||||
Where("network = ?", network).
|
Find(&locks).Error
|
||||||
Where("token = ?", normalizeLockToken(token)).
|
|
||||||
Where("amount_scaled = ?", scaledAmount).
|
|
||||||
Where("expires_at > ?", time.Now())
|
|
||||||
query = applyLockAddressFilter(query, network, address)
|
|
||||||
err := query.Limit(1).Find(&lock).Error
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if lock.ID <= 0 {
|
for _, lock := range locks {
|
||||||
return "", nil
|
if lockMatchesAmount(lock, amount) {
|
||||||
}
|
|
||||||
return lock.TradeId, nil
|
return lock.TradeId, nil
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
// LockTransaction reserves a network+address+token+amount pair in sqlite until expiration.
|
// LockTransaction reserves a network+address+token+amount pair in sqlite until expiration.
|
||||||
func LockTransaction(network, address, token, tradeID string, amount float64, expirationTime time.Duration) error {
|
func LockTransaction(network, address, token, tradeID string, amount float64, expirationTime time.Duration) error {
|
||||||
network = normalizeLockNetwork(network)
|
network = normalizeLockNetwork(network)
|
||||||
address = normalizeLockAddress(network, address)
|
address = normalizeLockAddress(network, address)
|
||||||
scaledAmount, amountText := normalizeLockAmount(amount)
|
precision := GetAmountPrecision()
|
||||||
|
scaledAmount, amountText := normalizeAmount(amount, precision)
|
||||||
normalizedToken := normalizeLockToken(token)
|
normalizedToken := normalizeLockToken(token)
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
lock := &mdb.TransactionLock{
|
lock := &mdb.TransactionLock{
|
||||||
@@ -297,6 +386,7 @@ func LockTransaction(network, address, token, tradeID string, amount float64, ex
|
|||||||
Token: normalizedToken,
|
Token: normalizedToken,
|
||||||
AmountScaled: scaledAmount,
|
AmountScaled: scaledAmount,
|
||||||
AmountText: amountText,
|
AmountText: amountText,
|
||||||
|
AmountPrecision: precision,
|
||||||
TradeId: tradeID,
|
TradeId: tradeID,
|
||||||
ExpiresAt: now.Add(expirationTime),
|
ExpiresAt: now.Add(expirationTime),
|
||||||
}
|
}
|
||||||
@@ -304,7 +394,6 @@ func LockTransaction(network, address, token, tradeID string, amount float64, ex
|
|||||||
return dao.RuntimeDB.Transaction(func(tx *gorm.DB) error {
|
return dao.RuntimeDB.Transaction(func(tx *gorm.DB) error {
|
||||||
expiredQuery := tx.Where("network = ?", network).
|
expiredQuery := tx.Where("network = ?", network).
|
||||||
Where("token = ?", normalizedToken).
|
Where("token = ?", normalizedToken).
|
||||||
Where("amount_scaled = ?", scaledAmount).
|
|
||||||
Where("expires_at <= ?", now)
|
Where("expires_at <= ?", now)
|
||||||
expiredQuery = applyLockAddressFilter(expiredQuery, network, address)
|
expiredQuery = applyLockAddressFilter(expiredQuery, network, address)
|
||||||
if err := expiredQuery.Delete(&mdb.TransactionLock{}).Error; err != nil {
|
if err := expiredQuery.Delete(&mdb.TransactionLock{}).Error; err != nil {
|
||||||
@@ -314,6 +403,18 @@ func LockTransaction(network, address, token, tradeID string, amount float64, ex
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var existing []mdb.TransactionLock
|
||||||
|
if err := activeLocksForAddress(tx, network, address, normalizedToken, now).
|
||||||
|
Find(&existing).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
candidateAmount := lockAmountDecimal(*lock)
|
||||||
|
for _, item := range existing {
|
||||||
|
if lockAmountDecimal(item).Equal(candidateAmount) {
|
||||||
|
return ErrTransactionLocked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(lock)
|
result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(lock)
|
||||||
if result.Error != nil {
|
if result.Error != nil {
|
||||||
return result.Error
|
return result.Error
|
||||||
@@ -329,13 +430,21 @@ func LockTransaction(network, address, token, tradeID string, amount float64, ex
|
|||||||
func UnLockTransaction(network string, address string, token string, amount float64) error {
|
func UnLockTransaction(network string, address string, token string, amount float64) error {
|
||||||
network = normalizeLockNetwork(network)
|
network = normalizeLockNetwork(network)
|
||||||
address = normalizeLockAddress(network, address)
|
address = normalizeLockAddress(network, address)
|
||||||
scaledAmount, _ := normalizeLockAmount(amount)
|
var locks []mdb.TransactionLock
|
||||||
query := dao.RuntimeDB.
|
if err := activeLocksForAddress(dao.RuntimeDB, network, address, token, time.Now()).
|
||||||
Where("network = ?", network).
|
Find(&locks).Error; err != nil {
|
||||||
Where("token = ?", normalizeLockToken(token)).
|
return err
|
||||||
Where("amount_scaled = ?", scaledAmount)
|
}
|
||||||
query = applyLockAddressFilter(query, network, address)
|
ids := make([]uint64, 0, len(locks))
|
||||||
return query.Delete(&mdb.TransactionLock{}).Error
|
for _, lock := range locks {
|
||||||
|
if lockMatchesAmount(lock, amount) {
|
||||||
|
ids = append(ids, lock.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return dao.RuntimeDB.Where("id IN ?", ids).Delete(&mdb.TransactionLock{}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func UnLockTransactionByTradeId(tradeID string) error {
|
func UnLockTransactionByTradeId(tradeID string) error {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package data
|
package data
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -41,6 +42,51 @@ func TestEvmTransactionLockAddressIsCaseInsensitive(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTransactionLockPrecisionPreventsEquivalentAmountsOnly(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if err := SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyAmountPrecision, "2", mdb.SettingTypeInt); err != nil {
|
||||||
|
t.Fatalf("set precision 2: %v", err)
|
||||||
|
}
|
||||||
|
if err := LockTransaction(mdb.NetworkTron, "TPrecisionAddress001", "USDT", "trade-old", 1.23, time.Hour); err != nil {
|
||||||
|
t.Fatalf("lock old transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyAmountPrecision, "4", mdb.SettingTypeInt); err != nil {
|
||||||
|
t.Fatalf("set precision 4: %v", err)
|
||||||
|
}
|
||||||
|
if err := LockTransaction(mdb.NetworkTron, "TPrecisionAddress001", "USDT", "trade-equivalent", 1.2300, time.Hour); !errors.Is(err, ErrTransactionLocked) {
|
||||||
|
t.Fatalf("equivalent lock error = %v, want %v", err, ErrTransactionLocked)
|
||||||
|
}
|
||||||
|
if err := LockTransaction(mdb.NetworkTron, "TPrecisionAddress001", "USDT", "trade-new", 1.2301, time.Hour); err != nil {
|
||||||
|
t.Fatalf("distinct precision lock: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransactionLockLookupUsesStoredPrecision(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if err := SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyAmountPrecision, "4", mdb.SettingTypeInt); err != nil {
|
||||||
|
t.Fatalf("set precision 4: %v", err)
|
||||||
|
}
|
||||||
|
if err := LockTransaction(mdb.NetworkTron, "TPrecisionAddress002", "USDT", "trade-precise", 1.2345, time.Hour); err != nil {
|
||||||
|
t.Fatalf("lock precise transaction: %v", err)
|
||||||
|
}
|
||||||
|
if err := SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyAmountPrecision, "2", mdb.SettingTypeInt); err != nil {
|
||||||
|
t.Fatalf("set precision 2: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotTradeID, err := GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, "TPrecisionAddress002", "USDT", 1.2345)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("lookup transaction lock: %v", err)
|
||||||
|
}
|
||||||
|
if gotTradeID != "trade-precise" {
|
||||||
|
t.Fatalf("trade id = %q, want trade-precise", gotTradeID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNonEvmTransactionLockAddressRemainsCaseSensitive(t *testing.T) {
|
func TestNonEvmTransactionLockAddressRemainsCaseSensitive(t *testing.T) {
|
||||||
cleanup := testutil.SetupTestDatabases(t)
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package data
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetProviderOrderByTradeIDAndProvider(tradeID string, provider string) (*mdb.ProviderOrder, error) {
|
||||||
|
row := new(mdb.ProviderOrder)
|
||||||
|
err := dao.Mdb.Model(row).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Limit(1).
|
||||||
|
Find(row).Error
|
||||||
|
return row, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateProviderOrderWithTransaction(tx *gorm.DB, row *mdb.ProviderOrder) error {
|
||||||
|
return tx.Model(row).Create(row).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateProviderOrderCreated(tradeID string, provider string, providerOrderID string, payURL string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.ProviderOrder{}).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"provider_order_id": providerOrderID,
|
||||||
|
"pay_url": payURL,
|
||||||
|
"status": mdb.ProviderOrderStatusPending,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func MarkProviderOrderFailed(tradeID string, provider string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.ProviderOrder{}).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Update("status", mdb.ProviderOrderStatusFailed).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func SaveProviderOrderNotify(tradeID string, provider string, notifyRaw string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.ProviderOrder{}).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Update("notify_raw", notifyRaw).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func MarkProviderOrderPaid(tradeID string, provider string, notifyRaw string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.ProviderOrder{}).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"status": mdb.ProviderOrderStatusPaid,
|
||||||
|
"notify_raw": notifyRaw,
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func MarkProviderOrderExpired(tradeID string, provider string) error {
|
||||||
|
return dao.Mdb.Model(&mdb.ProviderOrder{}).
|
||||||
|
Where("trade_id = ?", tradeID).
|
||||||
|
Where("provider = ?", provider).
|
||||||
|
Where("status IN ?", []string{mdb.ProviderOrderStatusCreating, mdb.ProviderOrderStatusPending}).
|
||||||
|
Update("status", mdb.ProviderOrderStatusExpired).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSubOrderByTokenPayProvider(parentTradeID string, token string, payProvider string) (*mdb.Orders, error) {
|
||||||
|
order := new(mdb.Orders)
|
||||||
|
err := dao.Mdb.Model(order).
|
||||||
|
Where("parent_trade_id = ?", parentTradeID).
|
||||||
|
Where("token = ?", token).
|
||||||
|
Where("pay_provider = ?", payProvider).
|
||||||
|
Where("status = ?", mdb.StatusWaitPay).
|
||||||
|
Limit(1).
|
||||||
|
Find(order).Error
|
||||||
|
return order, err
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/config"
|
||||||
"github.com/GMWalletApp/epusdt/model/dao"
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"gorm.io/gorm/clause"
|
"gorm.io/gorm/clause"
|
||||||
@@ -118,15 +119,36 @@ func GetSettingBool(key string, fallback bool) bool {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultAmountPrecision = 2
|
||||||
|
MinAmountPrecision = 2
|
||||||
|
MaxAmountPrecision = 6
|
||||||
|
)
|
||||||
|
|
||||||
|
// NormalizeAmountPrecision clamps external precision values to the supported
|
||||||
|
// range used by order creation and transaction matching.
|
||||||
|
func NormalizeAmountPrecision(precision int) int {
|
||||||
|
if precision < MinAmountPrecision || precision > MaxAmountPrecision {
|
||||||
|
return DefaultAmountPrecision
|
||||||
|
}
|
||||||
|
return precision
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAmountPrecision() int {
|
||||||
|
return NormalizeAmountPrecision(GetSettingInt(mdb.SettingKeyAmountPrecision, DefaultAmountPrecision))
|
||||||
|
}
|
||||||
|
|
||||||
// SetSetting upserts a setting row and refreshes the cache entry.
|
// SetSetting upserts a setting row and refreshes the cache entry.
|
||||||
func SetSetting(group, key, value, valueType string) error {
|
func SetSetting(group, key, value, valueType string) error {
|
||||||
if valueType == "" {
|
if valueType == "" {
|
||||||
valueType = mdb.SettingTypeString
|
valueType = mdb.SettingTypeString
|
||||||
}
|
}
|
||||||
row := mdb.Setting{Group: group, Key: key, Value: value, Type: valueType}
|
row := mdb.Setting{Group: group, Key: key, Value: value, Type: valueType}
|
||||||
|
updates := clause.AssignmentColumns([]string{"group", "value", "type", "updated_at"})
|
||||||
|
updates = append(updates, clause.Assignment{Column: clause.Column{Name: "deleted_at"}, Value: nil})
|
||||||
err := dao.Mdb.Clauses(clause.OnConflict{
|
err := dao.Mdb.Clauses(clause.OnConflict{
|
||||||
Columns: []clause.Column{{Name: "key"}},
|
Columns: []clause.Column{{Name: "key"}},
|
||||||
DoUpdates: clause.AssignmentColumns([]string{"group", "value", "type", "updated_at"}),
|
DoUpdates: updates,
|
||||||
}).Create(&row).Error
|
}).Create(&row).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -157,6 +179,97 @@ var sensitiveSettingKeys = []string{
|
|||||||
mdb.SettingKeyInitAdminPasswordChanged,
|
mdb.SettingKeyInitAdminPasswordChanged,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getFirstNonEmptySetting(fallback string, keys ...string) string {
|
||||||
|
for _, key := range keys {
|
||||||
|
value := strings.TrimSpace(GetSettingString(key, ""))
|
||||||
|
if value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandCashierName() string {
|
||||||
|
return getFirstNonEmptySetting("", mdb.SettingKeyBrandCheckoutName, mdb.SettingKeyBrandSiteName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandLogoURL() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyBrandLogoUrl, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandWebsiteTitle() string {
|
||||||
|
return getFirstNonEmptySetting("", mdb.SettingKeyBrandSiteTitle, mdb.SettingKeyBrandPageTitle)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandSupportURL() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyBrandSupportUrl, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandBackgroundColor() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyBrandBackgroundColor, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBrandBackgroundImageURL() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyBrandBackgroundImageUrl, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
// OkPay settings helpers keep the provider-specific defaults in one place so
|
||||||
|
// business logic does not need to repeat raw settings keys.
|
||||||
|
func GetOkPayEnabled() bool {
|
||||||
|
return GetSettingBool(mdb.SettingKeyOkPayEnabled, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayShopID() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyOkPayShopID, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayShopToken() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyOkPayShopToken, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayAPIURL() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyOkPayAPIURL, "https://api.okaypay.me/shop/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayCallbackURL() string {
|
||||||
|
if configured := strings.TrimSpace(GetSettingString(mdb.SettingKeyOkPayCallbackURL, "")); configured != "" {
|
||||||
|
return configured
|
||||||
|
}
|
||||||
|
appURI := strings.TrimSpace(config.GetAppUri())
|
||||||
|
if appURI == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimRight(appURI, "/") + "/payments/okpay/v1/notify"
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayReturnURL() string {
|
||||||
|
return strings.TrimSpace(GetSettingString(mdb.SettingKeyOkPayReturnURL, ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayTimeoutSeconds() int {
|
||||||
|
return GetSettingInt(mdb.SettingKeyOkPayTimeoutSeconds, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOkPayAllowTokens() []string {
|
||||||
|
raw := GetSettingString(mdb.SettingKeyOkPayAllowTokens, "USDT,TRX")
|
||||||
|
if strings.TrimSpace(raw) == "" {
|
||||||
|
return []string{"USDT", "TRX"}
|
||||||
|
}
|
||||||
|
parts := strings.Split(raw, ",")
|
||||||
|
out := make([]string, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
token := strings.ToUpper(strings.TrimSpace(part))
|
||||||
|
if token == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, token)
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return []string{"USDT", "TRX"}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// ListSettingsByGroup returns all rows for a given group (empty group = all),
|
// ListSettingsByGroup returns all rows for a given group (empty group = all),
|
||||||
// excluding any keys in sensitiveSettingKeys.
|
// excluding any keys in sensitiveSettingKeys.
|
||||||
func ListSettingsByGroup(group string) ([]mdb.Setting, error) {
|
func ListSettingsByGroup(group string) ([]mdb.Setting, error) {
|
||||||
|
|||||||
@@ -12,6 +12,19 @@ const (
|
|||||||
PaymentTypeEpay = "Epay"
|
PaymentTypeEpay = "Epay"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// PaymentProviderOnChain means this concrete order record is settled by
|
||||||
|
// sending funds to a directly assigned wallet address on a supported chain.
|
||||||
|
PaymentProviderOnChain = "on_chain"
|
||||||
|
// PaymentProviderOkPay means this concrete order record is settled through
|
||||||
|
// the third-party OkayPay/OkPay hosted checkout flow.
|
||||||
|
//
|
||||||
|
// In the current design this is typically used by a switch-network-created
|
||||||
|
// child order, while the parent order keeps its original merchant-facing
|
||||||
|
// semantics and callback behavior.
|
||||||
|
PaymentProviderOkPay = "okpay"
|
||||||
|
)
|
||||||
|
|
||||||
type Orders struct {
|
type Orders struct {
|
||||||
TradeId string `gorm:"column:trade_id;uniqueIndex:orders_trade_id_uindex" json:"trade_id" example:"T2026041612345678"`
|
TradeId string `gorm:"column:trade_id;uniqueIndex:orders_trade_id_uindex" json:"trade_id" example:"T2026041612345678"`
|
||||||
OrderId string `gorm:"column:order_id;uniqueIndex:orders_order_id_uindex" json:"order_id" example:"ORD20260416001"`
|
OrderId string `gorm:"column:order_id;uniqueIndex:orders_order_id_uindex" json:"order_id" example:"ORD20260416001"`
|
||||||
@@ -33,6 +46,16 @@ type Orders struct {
|
|||||||
CallBackConfirm int `gorm:"column:callback_confirm;default:2" json:"callback_confirm" enums:"1,2" example:"2"`
|
CallBackConfirm int `gorm:"column:callback_confirm;default:2" json:"callback_confirm" enums:"1,2" example:"2"`
|
||||||
IsSelected bool `gorm:"column:is_selected;default:false" json:"is_selected" example:"false"`
|
IsSelected bool `gorm:"column:is_selected;default:false" json:"is_selected" example:"false"`
|
||||||
PaymentType string `gorm:"column:payment_type" json:"payment_type" example:"Epay"`
|
PaymentType string `gorm:"column:payment_type" json:"payment_type" example:"Epay"`
|
||||||
|
// PayProvider identifies how this specific order row is collected.
|
||||||
|
//
|
||||||
|
// Semantics:
|
||||||
|
// - parent orders and regular chain child orders use on_chain
|
||||||
|
// - third-party hosted checkout child orders use their provider name
|
||||||
|
// (for example okpay)
|
||||||
|
//
|
||||||
|
// Existing rows default to on_chain for backward compatibility so upgrades
|
||||||
|
// can rely on AutoMigrate without rewriting old orders.
|
||||||
|
PayProvider string `gorm:"column:pay_provider;size:32;default:on_chain;index:orders_pay_provider_index" json:"pay_provider" example:"on_chain"`
|
||||||
ApiKeyID uint64 `gorm:"column:api_key_id;default:0;index:orders_api_key_id_index" json:"api_key_id" example:"1"`
|
ApiKeyID uint64 `gorm:"column:api_key_id;default:0;index:orders_api_key_id_index" json:"api_key_id" example:"1"`
|
||||||
// PayBySubId holds the primary-key ID of the sub-order that settled this parent order.
|
// PayBySubId holds the primary-key ID of the sub-order that settled this parent order.
|
||||||
// Zero when the parent order was paid directly (no sub-order involved).
|
// Zero when the parent order was paid directly (no sub-order involved).
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package mdb
|
||||||
|
|
||||||
|
const (
|
||||||
|
ProviderOrderStatusCreating = "creating"
|
||||||
|
ProviderOrderStatusPending = "pending"
|
||||||
|
ProviderOrderStatusPaid = "paid"
|
||||||
|
ProviderOrderStatusFailed = "failed"
|
||||||
|
ProviderOrderStatusExpired = "expired"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProviderOrder stores provider-specific checkout data for one internal order
|
||||||
|
// row. For OkPay this is expected to bind to the concrete child order created
|
||||||
|
// by switch-network, not to the parent merchant order.
|
||||||
|
//
|
||||||
|
// Binding rules:
|
||||||
|
// - trade_id always points to orders.trade_id
|
||||||
|
// - the bound orders row should use the same pay_provider value
|
||||||
|
// - provider identifies which downstream checkout created the provider row
|
||||||
|
// - provider_order_id is the provider's own order number (for OkPay this is
|
||||||
|
// the returned order_id from /payLink)
|
||||||
|
// - pay_url is the hosted payment URL returned by the provider
|
||||||
|
//
|
||||||
|
// The main orders table remains the source of truth for merchant-facing state,
|
||||||
|
// while this table keeps provider-specific identifiers and callback payloads.
|
||||||
|
type ProviderOrder struct {
|
||||||
|
TradeId string `gorm:"column:trade_id;size:32;not null;uniqueIndex:provider_orders_trade_id_provider_uindex,priority:1;index:provider_orders_trade_id_index" json:"trade_id" example:"T2026041612345678"`
|
||||||
|
// Provider values should match the bound Orders.PayProvider value.
|
||||||
|
Provider string `gorm:"column:provider;size:32;not null;uniqueIndex:provider_orders_trade_id_provider_uindex,priority:2;index:provider_orders_provider_status_index,priority:1" json:"provider" example:"okpay"`
|
||||||
|
// ProviderOrderID is the downstream provider's own order identifier for the
|
||||||
|
// bound concrete order row.
|
||||||
|
ProviderOrderID string `gorm:"column:provider_order_id;size:128;not null;default:'';index:provider_orders_provider_order_id_index" json:"provider_order_id" example:"ac7b86615fdb137576ae35879f7ed844"`
|
||||||
|
// PayURL is the hosted checkout URL returned by the downstream provider for
|
||||||
|
// the bound concrete order row.
|
||||||
|
PayURL string `gorm:"column:pay_url;size:512;not null;default:''" json:"pay_url" example:"https://pay.example.com/checkout/abc123"`
|
||||||
|
// Amount/Coin mirror the exact payload submitted to the provider, which may
|
||||||
|
// be useful when validating callbacks and troubleshooting mismatches.
|
||||||
|
Amount float64 `gorm:"column:amount" json:"amount" example:"14.2857"`
|
||||||
|
Coin string `gorm:"column:coin;size:16;not null;default:''" json:"coin" example:"USDT"`
|
||||||
|
Status string `gorm:"column:status;size:32;not null;default:pending;index:provider_orders_provider_status_index,priority:2" json:"status" example:"pending"`
|
||||||
|
// NotifyRaw stores the original provider callback payload for auditing and
|
||||||
|
// replay/debug use. It is provider-specific and intentionally opaque here.
|
||||||
|
NotifyRaw string `gorm:"column:notify_raw;type:text" json:"notify_raw"`
|
||||||
|
BaseModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ProviderOrder) TableName() string {
|
||||||
|
return "provider_orders"
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
package mdb
|
package mdb
|
||||||
|
|
||||||
// Setting stores non-credential runtime configuration as key/value pairs.
|
// Setting stores non-credential runtime configuration as key/value pairs.
|
||||||
// Groups: brand, rate, system, epay. Merchant credentials (pid + secret_key)
|
// Groups: brand, rate, system, epay, okpay. Merchant credentials (pid +
|
||||||
// live in the api_keys table; notification configs live in NotificationChannel.
|
// secret_key) live in the api_keys table; notification configs live in
|
||||||
// Default rows for the epay group are seeded on first startup (see
|
// NotificationChannel.
|
||||||
|
// Default rows for the epay/okpay groups are seeded on first startup (see
|
||||||
// model/dao/mdb_table_init.go seedDefaultSettings). All other groups start
|
// model/dao/mdb_table_init.go seedDefaultSettings). All other groups start
|
||||||
// empty and fall back to hardcoded defaults until an admin sets them.
|
// empty and fall back to hardcoded defaults until an admin sets them.
|
||||||
// Only exception: system.jwt_secret is auto-generated on first startup.
|
// Only exception: system.jwt_secret is auto-generated on first startup.
|
||||||
@@ -12,6 +13,7 @@ const (
|
|||||||
SettingGroupRate = "rate"
|
SettingGroupRate = "rate"
|
||||||
SettingGroupSystem = "system"
|
SettingGroupSystem = "system"
|
||||||
SettingGroupEpay = "epay"
|
SettingGroupEpay = "epay"
|
||||||
|
SettingGroupOkPay = "okpay"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -28,12 +30,18 @@ const (
|
|||||||
SettingKeyInitAdminPasswordFetched = "system.init_admin_password_fetched"
|
SettingKeyInitAdminPasswordFetched = "system.init_admin_password_fetched"
|
||||||
SettingKeyInitAdminPasswordChanged = "system.init_admin_password_changed"
|
SettingKeyInitAdminPasswordChanged = "system.init_admin_password_changed"
|
||||||
SettingKeyOrderExpiration = "system.order_expiration_time"
|
SettingKeyOrderExpiration = "system.order_expiration_time"
|
||||||
|
SettingKeyAmountPrecision = "system.amount_precision"
|
||||||
|
SettingKeyBrandCheckoutName = "brand.checkout_name"
|
||||||
SettingKeyBrandSiteName = "brand.site_name"
|
SettingKeyBrandSiteName = "brand.site_name"
|
||||||
SettingKeyBrandLogoUrl = "brand.logo_url"
|
SettingKeyBrandLogoUrl = "brand.logo_url"
|
||||||
|
SettingKeyBrandSiteTitle = "brand.site_title"
|
||||||
SettingKeyBrandPageTitle = "brand.page_title"
|
SettingKeyBrandPageTitle = "brand.page_title"
|
||||||
|
SettingKeyBrandSuccessCopy = "brand.success_copy"
|
||||||
SettingKeyBrandPaySuccess = "brand.pay_success_text"
|
SettingKeyBrandPaySuccess = "brand.pay_success_text"
|
||||||
SettingKeyBrandSupportUrl = "brand.support_url"
|
SettingKeyBrandSupportUrl = "brand.support_url"
|
||||||
SettingKeyRateForcedUsdt = "rate.forced_usdt_rate"
|
SettingKeyBrandBackgroundColor = "brand.background_color"
|
||||||
|
SettingKeyBrandBackgroundImageUrl = "brand.background_image_url"
|
||||||
|
SettingKeyRateForcedRateList = "rate.forced_rate_list"
|
||||||
SettingKeyRateAdjustPercent = "rate.adjust_percent"
|
SettingKeyRateAdjustPercent = "rate.adjust_percent"
|
||||||
SettingKeyRateOkxC2cEnabled = "rate.okx_c2c_enabled"
|
SettingKeyRateOkxC2cEnabled = "rate.okx_c2c_enabled"
|
||||||
SettingKeyRateApiUrl = "rate.api_url"
|
SettingKeyRateApiUrl = "rate.api_url"
|
||||||
@@ -42,14 +50,24 @@ const (
|
|||||||
SettingKeyEpayDefaultToken = "epay.default_token"
|
SettingKeyEpayDefaultToken = "epay.default_token"
|
||||||
SettingKeyEpayDefaultCurrency = "epay.default_currency"
|
SettingKeyEpayDefaultCurrency = "epay.default_currency"
|
||||||
SettingKeyEpayDefaultNetwork = "epay.default_network"
|
SettingKeyEpayDefaultNetwork = "epay.default_network"
|
||||||
|
|
||||||
|
// OkPay hosted-checkout settings.
|
||||||
|
SettingKeyOkPayEnabled = "okpay.enabled"
|
||||||
|
SettingKeyOkPayShopID = "okpay.shop_id"
|
||||||
|
SettingKeyOkPayShopToken = "okpay.shop_token"
|
||||||
|
SettingKeyOkPayAPIURL = "okpay.api_url"
|
||||||
|
SettingKeyOkPayCallbackURL = "okpay.callback_url"
|
||||||
|
SettingKeyOkPayReturnURL = "okpay.return_url"
|
||||||
|
SettingKeyOkPayTimeoutSeconds = "okpay.timeout_seconds"
|
||||||
|
SettingKeyOkPayAllowTokens = "okpay.allow_tokens"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Setting struct {
|
type Setting struct {
|
||||||
Group string `gorm:"column:group;size:32;index:settings_group_index" json:"group" enums:"brand,rate,system" example:"rate"`
|
Group string `gorm:"column:group;size:32;index:settings_group_index" json:"group" enums:"brand,rate,system,epay,okpay" example:"rate"`
|
||||||
Key string `gorm:"column:key;uniqueIndex:settings_key_uindex;size:128" json:"key" example:"rate.forced_usdt_rate"`
|
Key string `gorm:"column:key;uniqueIndex:settings_key_uindex;size:128" json:"key" example:"rate.forced_rate_list"`
|
||||||
Value string `gorm:"column:value;type:text" json:"value" example:"7.2"`
|
Value string `gorm:"column:value;type:text" json:"value" example:"{\"cny\":{\"usdt\":0.14635}}"`
|
||||||
Type string `gorm:"column:type;size:16;default:string" json:"type" enums:"string,int,bool,json" example:"string"`
|
Type string `gorm:"column:type;size:16;default:string" json:"type" enums:"string,int,bool,json" example:"json"`
|
||||||
Description string `gorm:"column:description;size:255" json:"description" example:"强制USDT汇率"`
|
Description string `gorm:"column:description;size:255" json:"description" example:"强制汇率列表"`
|
||||||
BaseModel
|
BaseModel
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ type TransactionLock struct {
|
|||||||
Token string `gorm:"column:token;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:3" json:"token"`
|
Token string `gorm:"column:token;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:3" json:"token"`
|
||||||
AmountScaled int64 `gorm:"column:amount_scaled;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:4" json:"amount_scaled"`
|
AmountScaled int64 `gorm:"column:amount_scaled;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:4" json:"amount_scaled"`
|
||||||
AmountText string `gorm:"column:amount_text" json:"amount_text"`
|
AmountText string `gorm:"column:amount_text" json:"amount_text"`
|
||||||
|
AmountPrecision int `gorm:"column:amount_precision;default:2;uniqueIndex:transaction_lock_network_address_token_amount_uindex,priority:5" json:"amount_precision"`
|
||||||
TradeId string `gorm:"column:trade_id;index:transaction_lock_trade_id_index" json:"trade_id"`
|
TradeId string `gorm:"column:trade_id;index:transaction_lock_trade_id_index" json:"trade_id"`
|
||||||
ExpiresAt time.Time `gorm:"column:expires_at;index:transaction_lock_expires_at_index" json:"expires_at"`
|
ExpiresAt time.Time `gorm:"column:expires_at;index:transaction_lock_expires_at_index" json:"expires_at"`
|
||||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const (
|
|||||||
NetworkTron = "tron"
|
NetworkTron = "tron"
|
||||||
NetworkSolana = "solana"
|
NetworkSolana = "solana"
|
||||||
NetworkEthereum = "ethereum"
|
NetworkEthereum = "ethereum"
|
||||||
NetworkBsc = "bsc"
|
NetworkBsc = "binance"
|
||||||
NetworkPolygon = "polygon"
|
NetworkPolygon = "polygon"
|
||||||
NetworkPlasma = "plasma"
|
NetworkPlasma = "plasma"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ type OrderProcessingRequest struct {
|
|||||||
type SwitchNetworkRequest struct {
|
type SwitchNetworkRequest struct {
|
||||||
TradeId string `json:"trade_id" validate:"required" example:"T2026041612345678"`
|
TradeId string `json:"trade_id" validate:"required" example:"T2026041612345678"`
|
||||||
Token string `json:"token" validate:"required" example:"USDT"`
|
Token string `json:"token" validate:"required" example:"USDT"`
|
||||||
Network string `json:"network" validate:"required" example:"ethereum"`
|
Network string `json:"network" validate:"required" example:"okpay,tron,solana,ethereum"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r SwitchNetworkRequest) Translates() map[string]string {
|
func (r SwitchNetworkRequest) Translates() map[string]string {
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ package response
|
|||||||
type CreateTransactionResponse struct {
|
type CreateTransactionResponse struct {
|
||||||
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
||||||
OrderId string `json:"order_id" example:"ORD20260416001"` // 客户交易id
|
OrderId string `json:"order_id" example:"ORD20260416001"` // 客户交易id
|
||||||
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,保留4位小数
|
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,按 system.amount_precision 保留小数
|
||||||
Currency string `json:"currency" example:"CNY"` // 订单货币类型 CNY USD......
|
Currency string `json:"currency" example:"CNY"` // 订单货币类型 CNY USD......
|
||||||
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,保留4位小数
|
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,按 system.amount_precision 保留小数
|
||||||
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
||||||
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
||||||
ExpirationTime int64 `json:"expiration_time" example:"1713264600"` // 过期时间 时间戳
|
ExpirationTime int64 `json:"expiration_time" example:"1713264600"` // 过期时间 时间戳
|
||||||
@@ -18,8 +18,8 @@ type OrderNotifyResponse struct {
|
|||||||
Pid string `json:"pid" example:"1000"` // 签名使用的商户 PID,商户据此查本地 secret 验签
|
Pid string `json:"pid" example:"1000"` // 签名使用的商户 PID,商户据此查本地 secret 验签
|
||||||
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
||||||
OrderId string `json:"order_id" example:"ORD20260416001"` // 客户交易id
|
OrderId string `json:"order_id" example:"ORD20260416001"` // 客户交易id
|
||||||
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,保留4位小数
|
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,按 system.amount_precision 保留小数
|
||||||
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,保留4位小数
|
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,按 system.amount_precision 保留小数
|
||||||
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
||||||
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
||||||
BlockTransactionId string `json:"block_transaction_id" example:"0xabc123..."` // 区块id
|
BlockTransactionId string `json:"block_transaction_id" example:"0xabc123..."` // 区块id
|
||||||
|
|||||||
@@ -2,14 +2,15 @@ package response
|
|||||||
|
|
||||||
type CheckoutCounterResponse struct {
|
type CheckoutCounterResponse struct {
|
||||||
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
TradeId string `json:"trade_id" example:"T2026041612345678"` // epusdt订单号
|
||||||
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,保留4位小数 法币金额
|
Amount float64 `json:"amount" example:"100.0000"` // 订单金额,按 system.amount_precision 保留小数 法币金额
|
||||||
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,保留4位小数 加密货币金额
|
ActualAmount float64 `json:"actual_amount" example:"14.2857"` // 订单实际需要支付的金额,按 system.amount_precision 保留小数 加密货币金额
|
||||||
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
Token string `json:"token" example:"USDT"` // 所属币种 TRX USDT......
|
||||||
Currency string `json:"currency" example:"CNY"` // 法币币种 CNY USD ...
|
Currency string `json:"currency" example:"CNY"` // 法币币种 CNY USD ...
|
||||||
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
ReceiveAddress string `json:"receive_address" example:"TTestTronAddress001"` // 收款钱包地址
|
||||||
Network string `json:"network" example:"tron"` // 网络 TRON ETH ...
|
Network string `json:"network" example:"tron"` // 网络 TRON ETH ...
|
||||||
ExpirationTime int64 `json:"expiration_time" example:"1713264600"` // 过期时间 时间戳
|
ExpirationTime int64 `json:"expiration_time" example:"1713264600"` // 过期时间 时间戳
|
||||||
RedirectUrl string `json:"redirect_url" example:"https://example.com/success"`
|
RedirectUrl string `json:"redirect_url" example:"https://example.com/success"`
|
||||||
|
PaymentUrl string `json:"payment_url" example:"https://pay.example.com/checkout/T2026041612345678"` // 支付链接;链上订单通常为本地收银台,OkPay 子订单为第三方 payLink
|
||||||
CreatedAt int64 `json:"created_at" example:"1713264000"` // 订单创建时间 时间戳
|
CreatedAt int64 `json:"created_at" example:"1713264000"` // 订单创建时间 时间戳
|
||||||
IsSelected bool `json:"is_selected" example:"false"`
|
IsSelected bool `json:"is_selected" example:"false"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,40 @@ package response
|
|||||||
|
|
||||||
type NetworkTokenSupport struct {
|
type NetworkTokenSupport struct {
|
||||||
Network string `json:"network" example:"tron"`
|
Network string `json:"network" example:"tron"`
|
||||||
|
DisplayName string `json:"display_name" example:"TRON"`
|
||||||
Tokens []string `json:"tokens" example:"USDT,USDC"`
|
Tokens []string `json:"tokens" example:"USDT,USDC"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SupportedAssetsResponse struct {
|
type EpayPublicConfig struct {
|
||||||
Supports []NetworkTokenSupport `json:"supports"`
|
DefaultToken string `json:"default_token" example:"usdt"`
|
||||||
|
DefaultCurrency string `json:"default_currency" example:"cny"`
|
||||||
|
DefaultNetwork string `json:"default_network" example:"tron"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SitePublicConfig struct {
|
||||||
|
CashierName string `json:"cashier_name" example:"Acme Cashier"`
|
||||||
|
LogoURL string `json:"logo_url" example:"https://cdn.example.com/logo.png"`
|
||||||
|
WebsiteTitle string `json:"website_title" example:"Acme Payments"`
|
||||||
|
SupportLink string `json:"support_link" example:"https://example.com/support"`
|
||||||
|
BackgroundColor string `json:"background_color" example:"#0f172a"`
|
||||||
|
BackgroundImageURL string `json:"background_image_url" example:"https://cdn.example.com/background.png"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type OkPayPublicConfig struct {
|
||||||
|
Enabled bool `json:"enabled" example:"true"`
|
||||||
|
AllowTokens []string `json:"allow_tokens" example:"USDT,TRX"`
|
||||||
|
ShopID string `json:"shop_id,omitempty" example:"okpay-shop-test"`
|
||||||
|
ShopToken string `json:"shop_token,omitempty" example:"secret-token"`
|
||||||
|
APIURL string `json:"api_url,omitempty" example:"https://api.okaypay.me/shop/"`
|
||||||
|
CallbackURL string `json:"callback_url,omitempty" example:"https://pay.example.com/payments/okpay/v1/notify"`
|
||||||
|
ReturnURL string `json:"return_url,omitempty" example:"https://pay.example.com/success"`
|
||||||
|
TimeoutSeconds int `json:"timeout_seconds,omitempty" example:"10"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PublicConfigResponse struct {
|
||||||
|
SupportedAssets []NetworkTokenSupport `json:"supported_assets"`
|
||||||
|
Site SitePublicConfig `json:"site"`
|
||||||
|
Epay EpayPublicConfig `json:"epay"`
|
||||||
|
OkPay OkPayPublicConfig `json:"okpay"`
|
||||||
|
Version string `json:"version" example:"v1.0.1"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,832 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tron "github.com/GMWalletApp/epusdt/crypto"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/constant"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/math"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
"github.com/ethereum/go-ethereum/ethclient"
|
||||||
|
"github.com/shopspring/decimal"
|
||||||
|
"github.com/tidwall/gjson"
|
||||||
|
)
|
||||||
|
|
||||||
|
const manualVerifyRequestTimeout = 15 * time.Second
|
||||||
|
|
||||||
|
var erc20TransferEventHash = common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")
|
||||||
|
|
||||||
|
var (
|
||||||
|
manualOrderPaymentValidatorMu sync.Mutex
|
||||||
|
manualOrderPaymentValidator manualOrderPaymentValidatorFunc = validateManualOrderPaymentDefault
|
||||||
|
)
|
||||||
|
|
||||||
|
type manualOrderPaymentValidatorFunc func(*mdb.Orders, string) (string, error)
|
||||||
|
|
||||||
|
// ValidateManualOrderPayment verifies that the supplied chain transaction
|
||||||
|
// really settles the order before an admin manually marks it paid. It returns
|
||||||
|
// the canonical transaction id that should be persisted for duplicate checks.
|
||||||
|
func ValidateManualOrderPayment(order *mdb.Orders, blockTransactionID string) (string, error) {
|
||||||
|
manualOrderPaymentValidatorMu.Lock()
|
||||||
|
validator := manualOrderPaymentValidator
|
||||||
|
manualOrderPaymentValidatorMu.Unlock()
|
||||||
|
return validator(order, blockTransactionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetManualOrderPaymentValidatorForTest swaps the chain verifier in tests so
|
||||||
|
// route/controller tests don't depend on public RPC availability.
|
||||||
|
func SetManualOrderPaymentValidatorForTest(fn func(*mdb.Orders, string) (string, error)) func() {
|
||||||
|
manualOrderPaymentValidatorMu.Lock()
|
||||||
|
old := manualOrderPaymentValidator
|
||||||
|
if fn == nil {
|
||||||
|
manualOrderPaymentValidator = validateManualOrderPaymentDefault
|
||||||
|
} else {
|
||||||
|
manualOrderPaymentValidator = fn
|
||||||
|
}
|
||||||
|
manualOrderPaymentValidatorMu.Unlock()
|
||||||
|
return func() {
|
||||||
|
manualOrderPaymentValidatorMu.Lock()
|
||||||
|
manualOrderPaymentValidator = old
|
||||||
|
manualOrderPaymentValidatorMu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualOrderPaymentDefault(order *mdb.Orders, blockTransactionID string) (string, error) {
|
||||||
|
if order == nil || order.ID == 0 {
|
||||||
|
return "", fmt.Errorf("order not found")
|
||||||
|
}
|
||||||
|
txID := strings.TrimSpace(blockTransactionID)
|
||||||
|
if txID == "" {
|
||||||
|
return "", fmt.Errorf("block_transaction_id is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
var canonicalTxID string
|
||||||
|
var err error
|
||||||
|
switch strings.ToLower(strings.TrimSpace(order.Network)) {
|
||||||
|
case mdb.NetworkTron:
|
||||||
|
canonicalTxID, err = validateManualTronPayment(order, txID)
|
||||||
|
case mdb.NetworkSolana:
|
||||||
|
canonicalTxID, err = validateManualSolanaPayment(order, txID)
|
||||||
|
case mdb.NetworkEthereum, mdb.NetworkBsc, mdb.NetworkPolygon, mdb.NetworkPlasma:
|
||||||
|
canonicalTxID, err = validateManualEvmPayment(order, txID)
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("unsupported manual payment verification network: %s", order.Network)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err = ensureManualBlockTransactionUnused(order, canonicalTxID); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return canonicalTxID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureManualBlockTransactionUnused(order *mdb.Orders, canonicalTxID string) error {
|
||||||
|
candidates := equivalentManualBlockTransactionIDs(order.Network, canonicalTxID)
|
||||||
|
var existing *mdb.Orders
|
||||||
|
var err error
|
||||||
|
if manualBlockTransactionIDIsHex(order.Network) {
|
||||||
|
existing, err = data.GetOrderByBlockTransactionIDsCaseInsensitive(candidates)
|
||||||
|
} else {
|
||||||
|
existing, err = data.GetOrderByBlockTransactionIDs(candidates)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existing.ID > 0 && existing.ID != order.ID {
|
||||||
|
return constant.OrderBlockAlreadyProcess
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func manualBlockTransactionIDIsHex(network string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(network)) {
|
||||||
|
case mdb.NetworkTron, mdb.NetworkEthereum, mdb.NetworkBsc, mdb.NetworkPolygon, mdb.NetworkPlasma:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func equivalentManualBlockTransactionIDs(network, canonicalTxID string) []string {
|
||||||
|
network = strings.ToLower(strings.TrimSpace(network))
|
||||||
|
canonicalTxID = strings.TrimSpace(canonicalTxID)
|
||||||
|
seen := make(map[string]struct{})
|
||||||
|
out := make([]string, 0, 6)
|
||||||
|
add := func(value string) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, ok := seen[value]; ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[value] = struct{}{}
|
||||||
|
out = append(out, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
add(canonicalTxID)
|
||||||
|
switch network {
|
||||||
|
case mdb.NetworkEthereum, mdb.NetworkBsc, mdb.NetworkPolygon, mdb.NetworkPlasma:
|
||||||
|
body := strings.TrimPrefix(strings.TrimPrefix(canonicalTxID, "0x"), "0X")
|
||||||
|
body = strings.ToLower(body)
|
||||||
|
add("0x" + body)
|
||||||
|
add("0x" + strings.ToUpper(body))
|
||||||
|
add("0X" + body)
|
||||||
|
add("0X" + strings.ToUpper(body))
|
||||||
|
add(body)
|
||||||
|
add(strings.ToUpper(body))
|
||||||
|
case mdb.NetworkTron:
|
||||||
|
body := strings.TrimPrefix(strings.TrimPrefix(canonicalTxID, "0x"), "0X")
|
||||||
|
body = strings.ToLower(body)
|
||||||
|
add(body)
|
||||||
|
add(strings.ToUpper(body))
|
||||||
|
add("0x" + body)
|
||||||
|
add("0x" + strings.ToUpper(body))
|
||||||
|
add("0X" + body)
|
||||||
|
add("0X" + strings.ToUpper(body))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualEvmPayment(order *mdb.Orders, txID string) (string, error) {
|
||||||
|
txHash, canonicalTxID, err := canonicalEvmHash(txID)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := data.GetEnabledChainTokenBySymbol(order.Network, order.Token)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if token == nil || token.ID == 0 || strings.TrimSpace(token.ContractAddress) == "" {
|
||||||
|
return "", fmt.Errorf("enabled token contract not configured for %s/%s", order.Network, order.Token)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), manualVerifyRequestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
clients, err := dialManualEvmClients(ctx, order.Network)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer closeManualEvmClients(clients)
|
||||||
|
|
||||||
|
if err = validateManualEvmPaymentAcrossClients(ctx, clients, order, txHash, token); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return canonicalTxID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type evmChainReader interface {
|
||||||
|
TransactionReceipt(context.Context, common.Hash) (*types.Receipt, error)
|
||||||
|
HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualEvmClient struct {
|
||||||
|
label string
|
||||||
|
reader evmChainReader
|
||||||
|
close func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeManualEvmClients(clients []manualEvmClient) {
|
||||||
|
for _, item := range clients {
|
||||||
|
if item.close != nil {
|
||||||
|
item.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualEvmPaymentAcrossClients(ctx context.Context, clients []manualEvmClient, order *mdb.Orders, txHash common.Hash, token *mdb.ChainToken) error {
|
||||||
|
var verifyErrors []string
|
||||||
|
for _, item := range clients {
|
||||||
|
if err := validateManualEvmPaymentWithClient(ctx, item.reader, order, txHash, token); err != nil {
|
||||||
|
verifyErrors = append(verifyErrors, fmt.Sprintf("%s: %v", item.label, err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(verifyErrors) > 0 {
|
||||||
|
return fmt.Errorf("manual EVM verification failed: %s", strings.Join(verifyErrors, "; "))
|
||||||
|
}
|
||||||
|
return fmt.Errorf("no enabled %s WS/HTTP RPC node configured", order.Network)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualEvmPaymentWithClient(ctx context.Context, client evmChainReader, order *mdb.Orders, txHash common.Hash, token *mdb.ChainToken) error {
|
||||||
|
receipt, err := client.TransactionReceipt(ctx, txHash)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("fetch transaction receipt: %w", err)
|
||||||
|
}
|
||||||
|
if receipt.Status != types.ReceiptStatusSuccessful {
|
||||||
|
return fmt.Errorf("transaction is not successful")
|
||||||
|
}
|
||||||
|
if receipt.BlockNumber == nil {
|
||||||
|
return fmt.Errorf("transaction receipt missing block number")
|
||||||
|
}
|
||||||
|
txHeader, err := client.HeaderByNumber(ctx, receipt.BlockNumber)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("fetch transaction block header: %w", err)
|
||||||
|
}
|
||||||
|
if err = ensureEvmTransactionNotBeforeOrder(txHeader.Time, order); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = ensureEvmConfirmations(ctx, client, order.Network, receipt.BlockNumber); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
contract, err := normalizeEvmAddress(token.ContractAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid token contract address: %w", err)
|
||||||
|
}
|
||||||
|
to, err := normalizeEvmAddress(order.ReceiveAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid order receive address: %w", err)
|
||||||
|
}
|
||||||
|
amountMismatch := false
|
||||||
|
for _, item := range receipt.Logs {
|
||||||
|
if item == nil || !strings.EqualFold(item.Address.Hex(), contract.Hex()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(item.Topics) < 3 || item.Topics[0] != erc20TransferEventHash {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(common.BytesToAddress(item.Topics[2].Bytes()).Hex(), to.Hex()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rawAmount := new(big.Int).SetBytes(item.Data)
|
||||||
|
if amountMatchesRaw(order.ActualAmount, rawAmount, token.Decimals) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
amountMismatch = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if amountMismatch {
|
||||||
|
return fmt.Errorf("transaction amount mismatch")
|
||||||
|
}
|
||||||
|
return fmt.Errorf("matching token transfer to order address not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialManualEvmClients(ctx context.Context, network string) ([]manualEvmClient, error) {
|
||||||
|
var clients []manualEvmClient
|
||||||
|
var connectErrors []string
|
||||||
|
for _, nodeType := range []string{mdb.RpcNodeTypeWs, mdb.RpcNodeTypeHttp} {
|
||||||
|
node, err := data.SelectRpcNode(network, nodeType)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if node == nil || node.ID == 0 || strings.TrimSpace(node.Url) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rpcURL := strings.TrimSpace(node.Url)
|
||||||
|
client, err := ethclient.DialContext(ctx, rpcURL)
|
||||||
|
if err == nil {
|
||||||
|
clients = append(clients, manualEvmClient{
|
||||||
|
label: fmt.Sprintf("%s %s", nodeType, rpcURL),
|
||||||
|
reader: client,
|
||||||
|
close: client.Close,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
connectErrors = append(connectErrors, fmt.Sprintf("%s %s: %v", nodeType, rpcURL, err))
|
||||||
|
}
|
||||||
|
if len(clients) > 0 {
|
||||||
|
return clients, nil
|
||||||
|
}
|
||||||
|
if len(connectErrors) > 0 {
|
||||||
|
return nil, fmt.Errorf("connect %s RPC failed: %s", network, strings.Join(connectErrors, "; "))
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("no enabled %s WS/HTTP RPC node configured", network)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureEvmTransactionNotBeforeOrder(blockTime uint64, order *mdb.Orders) error {
|
||||||
|
if order == nil {
|
||||||
|
return fmt.Errorf("order not found")
|
||||||
|
}
|
||||||
|
if int64(blockTime)*1000 < order.CreatedAt.TimestampMilli() {
|
||||||
|
return fmt.Errorf("transaction predates the order")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureEvmConfirmations(ctx context.Context, client evmChainReader, network string, txBlock *big.Int) error {
|
||||||
|
chain, err := data.GetChainByNetwork(network)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
minConfirmations := 1
|
||||||
|
if chain != nil && chain.MinConfirmations > 0 {
|
||||||
|
minConfirmations = chain.MinConfirmations
|
||||||
|
}
|
||||||
|
header, err := client.HeaderByNumber(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("fetch latest block: %w", err)
|
||||||
|
}
|
||||||
|
confirmations := new(big.Int).Sub(header.Number, txBlock)
|
||||||
|
confirmations.Add(confirmations, big.NewInt(1))
|
||||||
|
if confirmations.Sign() < 0 || confirmations.Cmp(big.NewInt(int64(minConfirmations))) < 0 {
|
||||||
|
return fmt.Errorf("transaction confirmations %s below required %d", confirmations.String(), minConfirmations)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type tronContractParam struct {
|
||||||
|
TypeURL string `json:"type_url"`
|
||||||
|
Value json.RawMessage `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualTronTransaction struct {
|
||||||
|
TxID string `json:"txID"`
|
||||||
|
RawData struct {
|
||||||
|
Contract []struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Parameter tronContractParam `json:"parameter"`
|
||||||
|
} `json:"contract"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
} `json:"raw_data"`
|
||||||
|
Ret []struct {
|
||||||
|
ContractRet string `json:"contractRet"`
|
||||||
|
} `json:"ret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualTronTxInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
BlockNumber int64 `json:"blockNumber"`
|
||||||
|
BlockTimeStamp int64 `json:"blockTimeStamp"`
|
||||||
|
ContractResult []string `json:"contractResult"`
|
||||||
|
Log []manualTronEventLog `json:"log"`
|
||||||
|
Receipt struct {
|
||||||
|
Result string `json:"result"`
|
||||||
|
} `json:"receipt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualTronEventLog struct {
|
||||||
|
Address string `json:"address"`
|
||||||
|
Topics []string `json:"topics"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualTronBlock struct {
|
||||||
|
BlockHeader struct {
|
||||||
|
RawData struct {
|
||||||
|
Number int64 `json:"number"`
|
||||||
|
} `json:"raw_data"`
|
||||||
|
} `json:"block_header"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manualTronTransferContractValue struct {
|
||||||
|
OwnerAddress string `json:"owner_address"`
|
||||||
|
ToAddress string `json:"to_address"`
|
||||||
|
Amount int64 `json:"amount"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualTronPayment(order *mdb.Orders, txID string) (string, error) {
|
||||||
|
normalizedTxID, err := normalizeTronTxID(txID)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
baseURL, apiKey, err := ResolveTronNode()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
var tx manualTronTransaction
|
||||||
|
if err = tronPostJSON(baseURL, apiKey, "/wallet/gettransactionbyid", map[string]interface{}{"value": normalizedTxID}, &tx); err != nil {
|
||||||
|
return "", fmt.Errorf("fetch tron transaction: %w", err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(tx.TxID) == "" {
|
||||||
|
return "", fmt.Errorf("transaction not found")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(tx.TxID) != "" && !strings.EqualFold(strings.TrimSpace(tx.TxID), normalizedTxID) {
|
||||||
|
return "", fmt.Errorf("transaction id mismatch")
|
||||||
|
}
|
||||||
|
if len(tx.Ret) > 0 && tx.Ret[0].ContractRet != "" && tx.Ret[0].ContractRet != "SUCCESS" {
|
||||||
|
return "", fmt.Errorf("transaction is not successful: %s", tx.Ret[0].ContractRet)
|
||||||
|
}
|
||||||
|
|
||||||
|
var info manualTronTxInfo
|
||||||
|
if err = tronPostJSON(baseURL, apiKey, "/wallet/gettransactioninfobyid", map[string]interface{}{"value": normalizedTxID}, &info); err != nil {
|
||||||
|
return "", fmt.Errorf("fetch tron transaction info: %w", err)
|
||||||
|
}
|
||||||
|
if info.BlockNumber <= 0 {
|
||||||
|
return "", fmt.Errorf("transaction is not confirmed")
|
||||||
|
}
|
||||||
|
if info.Receipt.Result != "" && info.Receipt.Result != "SUCCESS" {
|
||||||
|
return "", fmt.Errorf("transaction is not successful: %s", info.Receipt.Result)
|
||||||
|
}
|
||||||
|
if err = ensureTronConfirmations(baseURL, apiKey, order.Network, info.BlockNumber); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if info.BlockTimeStamp <= 0 {
|
||||||
|
return "", fmt.Errorf("transaction block timestamp missing")
|
||||||
|
}
|
||||||
|
if info.BlockTimeStamp < order.CreatedAt.TimestampMilli() {
|
||||||
|
return "", fmt.Errorf("transaction predates the order")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.EqualFold(strings.TrimSpace(order.Token), "TRX") {
|
||||||
|
if err = validateManualTronNativeTransfer(order, &tx); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return normalizedTxID, nil
|
||||||
|
}
|
||||||
|
if err = validateManualTronTRC20Transfer(order, &tx, &info); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return normalizedTxID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualTronNativeTransfer(order *mdb.Orders, tx *manualTronTransaction) error {
|
||||||
|
if len(tx.RawData.Contract) == 0 || tx.RawData.Contract[0].Type != "TransferContract" {
|
||||||
|
return fmt.Errorf("transaction is not a TRX transfer")
|
||||||
|
}
|
||||||
|
var val manualTronTransferContractValue
|
||||||
|
if err := json.Unmarshal(tx.RawData.Contract[0].Parameter.Value, &val); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
toAddr, err := tronHexToAddress(val.ToAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid TRX recipient address: %w", err)
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(toAddr, order.ReceiveAddress) {
|
||||||
|
return fmt.Errorf("transaction recipient mismatch")
|
||||||
|
}
|
||||||
|
if !amountMatchesRaw(order.ActualAmount, big.NewInt(val.Amount), 6) {
|
||||||
|
return fmt.Errorf("transaction amount mismatch")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualTronTRC20Transfer(order *mdb.Orders, tx *manualTronTransaction, info *manualTronTxInfo) error {
|
||||||
|
token, err := data.GetEnabledChainTokenBySymbol(mdb.NetworkTron, order.Token)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if token == nil || token.ID == 0 || strings.TrimSpace(token.ContractAddress) == "" {
|
||||||
|
return fmt.Errorf("enabled token contract not configured for tron/%s", order.Token)
|
||||||
|
}
|
||||||
|
if len(tx.RawData.Contract) == 0 || tx.RawData.Contract[0].Type != "TriggerSmartContract" {
|
||||||
|
return fmt.Errorf("transaction is not a TRC20 transfer")
|
||||||
|
}
|
||||||
|
contractHex, err := tronAddressToHex(token.ContractAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid configured TRC20 contract: %w", err)
|
||||||
|
}
|
||||||
|
return validateManualTronTRC20TransferEvent(order, info, contractHex, token.Decimals)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualTronTRC20TransferEvent(order *mdb.Orders, info *manualTronTxInfo, contractHex string, decimals int) error {
|
||||||
|
if info == nil || len(info.Log) == 0 {
|
||||||
|
return fmt.Errorf("matching TRC20 transfer event to order address not found")
|
||||||
|
}
|
||||||
|
toHex, err := tronAddressToHex(order.ReceiveAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid order receive address: %w", err)
|
||||||
|
}
|
||||||
|
transferTopic := strings.TrimPrefix(erc20TransferEventHash.Hex(), "0x")
|
||||||
|
amountMismatch := false
|
||||||
|
for _, event := range info.Log {
|
||||||
|
eventContractHex, err := normalizeTronAddressHex(event.Address)
|
||||||
|
if err != nil || eventContractHex != contractHex {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(event.Topics) < 3 || normalizeEventTopic(event.Topics[0]) != transferTopic {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
eventToHex, err := tronTopicAddressToHex(event.Topics[2])
|
||||||
|
if err != nil || eventToHex != toHex {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rawAmount, err := tronEventDataAmount(event.Data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid TRC20 transfer event amount: %w", err)
|
||||||
|
}
|
||||||
|
if amountMatchesRaw(order.ActualAmount, rawAmount, decimals) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
amountMismatch = true
|
||||||
|
}
|
||||||
|
if amountMismatch {
|
||||||
|
return fmt.Errorf("transaction amount mismatch")
|
||||||
|
}
|
||||||
|
return fmt.Errorf("matching TRC20 transfer event to order address not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureTronConfirmations(baseURL, apiKey, network string, txBlock int64) error {
|
||||||
|
var latest manualTronBlock
|
||||||
|
if err := tronPostJSON(baseURL, apiKey, "/wallet/getnowblock", map[string]interface{}{}, &latest); err != nil {
|
||||||
|
return fmt.Errorf("fetch latest tron block: %w", err)
|
||||||
|
}
|
||||||
|
chain, err := data.GetChainByNetwork(network)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
minConfirmations := 1
|
||||||
|
if chain != nil && chain.MinConfirmations > 0 {
|
||||||
|
minConfirmations = chain.MinConfirmations
|
||||||
|
}
|
||||||
|
confirmations := latest.BlockHeader.RawData.Number - txBlock + 1
|
||||||
|
if confirmations < int64(minConfirmations) {
|
||||||
|
return fmt.Errorf("transaction confirmations %d below required %d", confirmations, minConfirmations)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func tronPostJSON(baseURL, apiKey, path string, body interface{}, out interface{}) error {
|
||||||
|
payload, _ := json.Marshal(body)
|
||||||
|
req, err := http.NewRequest(http.MethodPost, strings.TrimRight(baseURL, "/")+path, bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
if apiKey = strings.TrimSpace(apiKey); apiKey != "" {
|
||||||
|
req.Header.Set("TRON-PRO-API-KEY", apiKey)
|
||||||
|
}
|
||||||
|
client := &http.Client{Timeout: manualVerifyRequestTimeout}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
raw, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(raw))
|
||||||
|
}
|
||||||
|
return json.Unmarshal(raw, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateManualSolanaPayment(order *mdb.Orders, sig string) (string, error) {
|
||||||
|
sig = strings.TrimSpace(sig)
|
||||||
|
txData, err := SolGetTransaction(sig)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("fetch solana transaction: %w", err)
|
||||||
|
}
|
||||||
|
if !gjson.GetBytes(txData, "result").Exists() || gjson.GetBytes(txData, "result").Type == gjson.Null {
|
||||||
|
return "", fmt.Errorf("transaction not found")
|
||||||
|
}
|
||||||
|
if err = ensureSolanaConfirmations(order.Network, sig); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, err := data.ListEnabledChainTokensByNetwork(mdb.NetworkSolana)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
mintTokens := make(map[string]*mdb.ChainToken, len(tokens))
|
||||||
|
var nativeSolToken *mdb.ChainToken
|
||||||
|
for i := range tokens {
|
||||||
|
sym := strings.ToUpper(strings.TrimSpace(tokens[i].Symbol))
|
||||||
|
mint := strings.TrimSpace(tokens[i].ContractAddress)
|
||||||
|
if sym == "SOL" && mint == "" {
|
||||||
|
nativeSolToken = &tokens[i]
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if mint != "" {
|
||||||
|
mintTokens[mint] = &tokens[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
instructions := gjson.GetBytes(txData, "result.transaction.message.instructions").Array()
|
||||||
|
amountMismatch := false
|
||||||
|
for _, instruction := range instructions {
|
||||||
|
transferInfo, parseErr := ParseTransferInfoFromInstruction(instruction, txData)
|
||||||
|
if parseErr != nil || transferInfo == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !isTransferToAddress(transferInfo, order.ReceiveAddress) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
token, amount := resolveSolTokenAndAmount(transferInfo, mintTokens, nativeSolToken)
|
||||||
|
if !strings.EqualFold(token, order.Token) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = ensureSolanaTransferNotBeforeOrder(transferInfo.BlockTime, order); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if amountMatchesFloat(order.ActualAmount, amount) {
|
||||||
|
return sig, nil
|
||||||
|
}
|
||||||
|
amountMismatch = true
|
||||||
|
}
|
||||||
|
if amountMismatch {
|
||||||
|
return "", fmt.Errorf("transaction amount mismatch")
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("matching solana transfer to order address not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureSolanaTransferNotBeforeOrder(blockTime int64, order *mdb.Orders) error {
|
||||||
|
if order == nil {
|
||||||
|
return fmt.Errorf("order not found")
|
||||||
|
}
|
||||||
|
if blockTime <= 0 {
|
||||||
|
return fmt.Errorf("transaction block time missing")
|
||||||
|
}
|
||||||
|
if blockTime*1000 < order.CreatedAt.TimestampMilli() {
|
||||||
|
return fmt.Errorf("transaction predates the order")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureSolanaConfirmations(network, sig string) error {
|
||||||
|
chain, err := data.GetChainByNetwork(network)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
minConfirmations := 1
|
||||||
|
if chain != nil && chain.MinConfirmations > 0 {
|
||||||
|
minConfirmations = chain.MinConfirmations
|
||||||
|
}
|
||||||
|
if minConfirmations <= 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := SolRetryClient("getSignatureStatuses", []interface{}{
|
||||||
|
[]string{sig},
|
||||||
|
map[string]interface{}{"searchTransactionHistory": true},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("fetch solana signature status: %w", err)
|
||||||
|
}
|
||||||
|
status := gjson.GetBytes(body, "result.value.0")
|
||||||
|
if !status.Exists() || status.Type == gjson.Null {
|
||||||
|
return fmt.Errorf("transaction status not found")
|
||||||
|
}
|
||||||
|
if errValue := status.Get("err"); errValue.Exists() && errValue.Type != gjson.Null {
|
||||||
|
return fmt.Errorf("transaction is not successful: %s", errValue.Raw)
|
||||||
|
}
|
||||||
|
if status.Get("confirmationStatus").String() == "finalized" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
confirmations := status.Get("confirmations").Int()
|
||||||
|
if confirmations < int64(minConfirmations) {
|
||||||
|
return fmt.Errorf("transaction confirmations %d below required %d", confirmations, minConfirmations)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func amountMatchesRaw(expected float64, rawAmount *big.Int, decimals int) bool {
|
||||||
|
if rawAmount == nil || rawAmount.Sign() <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if decimals < 0 {
|
||||||
|
decimals = 0
|
||||||
|
}
|
||||||
|
actual := decimal.NewFromBigInt(rawAmount, -int32(decimals))
|
||||||
|
return roundedAmount(expected).Equal(actual.Round(int32(data.GetAmountPrecision())))
|
||||||
|
}
|
||||||
|
|
||||||
|
func amountMatchesFloat(expected, actual float64) bool {
|
||||||
|
return roundedAmount(expected).Equal(roundedAmount(actual))
|
||||||
|
}
|
||||||
|
|
||||||
|
func roundedAmount(amount float64) decimal.Decimal {
|
||||||
|
precision := data.GetAmountPrecision()
|
||||||
|
return decimal.NewFromFloat(math.MustParsePrecFloat64(amount, precision)).Round(int32(precision))
|
||||||
|
}
|
||||||
|
|
||||||
|
func tronHexToAddress(hexAddr string) (string, error) {
|
||||||
|
hexAddr, err := normalizeTronAddressHex(hexAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
raw, err := hex.DecodeString(hexAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return tron.EncodeCheck(raw), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func tronAddressToHex(addr string) (string, error) {
|
||||||
|
raw, err := tron.DecodeCheck(strings.TrimSpace(addr))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(raw) != 21 || raw[0] != tron.PrefixMainnet {
|
||||||
|
return "", fmt.Errorf("invalid tron address")
|
||||||
|
}
|
||||||
|
return strings.ToLower(hex.EncodeToString(raw)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeTronAddressHex(hexAddr string) (string, error) {
|
||||||
|
hexAddr = normalizeTronHexAddress(hexAddr)
|
||||||
|
raw, err := hex.DecodeString(hexAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
switch len(raw) {
|
||||||
|
case 20:
|
||||||
|
raw = append([]byte{tron.PrefixMainnet}, raw...)
|
||||||
|
case 21:
|
||||||
|
if raw[0] != tron.PrefixMainnet {
|
||||||
|
return "", fmt.Errorf("invalid tron address prefix")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("invalid address length: %d", len(raw))
|
||||||
|
}
|
||||||
|
return strings.ToLower(hex.EncodeToString(raw)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeTronHexAddress(hexAddr string) string {
|
||||||
|
hexAddr = strings.TrimSpace(hexAddr)
|
||||||
|
hexAddr = strings.TrimPrefix(hexAddr, "0x")
|
||||||
|
hexAddr = strings.TrimPrefix(hexAddr, "0X")
|
||||||
|
return strings.ToLower(hexAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeEventTopic(value string) string {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
value = strings.TrimPrefix(value, "0x")
|
||||||
|
value = strings.TrimPrefix(value, "0X")
|
||||||
|
return strings.ToLower(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func tronTopicAddressToHex(topic string) (string, error) {
|
||||||
|
topic = normalizeEventTopic(topic)
|
||||||
|
if len(topic) != 64 {
|
||||||
|
return "", fmt.Errorf("invalid TRON event address topic length")
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(topic); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return normalizeTronAddressHex(topic[24:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func tronEventDataAmount(data string) (*big.Int, error) {
|
||||||
|
data = normalizeEventTopic(data)
|
||||||
|
if data == "" {
|
||||||
|
return nil, fmt.Errorf("empty event data")
|
||||||
|
}
|
||||||
|
if len(data)%2 != 0 {
|
||||||
|
return nil, fmt.Errorf("odd-length event data")
|
||||||
|
}
|
||||||
|
raw, err := hex.DecodeString(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return new(big.Int).SetBytes(raw), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isEvmHash(value string) bool {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
value = strings.TrimPrefix(value, "0x")
|
||||||
|
value = strings.TrimPrefix(value, "0X")
|
||||||
|
if len(value) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, err := hex.DecodeString(value)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalEvmHash(value string) (common.Hash, string, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
value = strings.TrimPrefix(value, "0x")
|
||||||
|
value = strings.TrimPrefix(value, "0X")
|
||||||
|
if len(value) != 64 {
|
||||||
|
return common.Hash{}, "", fmt.Errorf("invalid EVM transaction hash")
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(value); err != nil {
|
||||||
|
return common.Hash{}, "", err
|
||||||
|
}
|
||||||
|
hash := common.HexToHash("0x" + strings.ToLower(value))
|
||||||
|
return hash, hash.Hex(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeTronTxID(value string) (string, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
value = strings.TrimPrefix(value, "0x")
|
||||||
|
value = strings.TrimPrefix(value, "0X")
|
||||||
|
if len(value) != 64 {
|
||||||
|
return "", fmt.Errorf("invalid TRON transaction id length")
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(value); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return strings.ToLower(value), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeEvmAddress(value string) (common.Address, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
value = strings.TrimPrefix(value, "0x")
|
||||||
|
value = strings.TrimPrefix(value, "0X")
|
||||||
|
if len(value) != 40 {
|
||||||
|
return common.Address{}, fmt.Errorf("invalid address length")
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(value); err != nil {
|
||||||
|
return common.Address{}, err
|
||||||
|
}
|
||||||
|
return common.HexToAddress("0x" + value), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"github.com/dromara/carbon/v2"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestManualVerifyEvmHashAcceptsOptional0x(t *testing.T) {
|
||||||
|
hash := strings.Repeat("a", 64)
|
||||||
|
if !isEvmHash(hash) {
|
||||||
|
t.Fatal("expected bare EVM hash to be valid")
|
||||||
|
}
|
||||||
|
if !isEvmHash("0x" + hash) {
|
||||||
|
t.Fatal("expected 0x-prefixed EVM hash to be valid")
|
||||||
|
}
|
||||||
|
if isEvmHash("0x" + strings.Repeat("a", 63)) {
|
||||||
|
t.Fatal("expected short EVM hash to be invalid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyNormalizeEvmAddressAcceptsOptional0x(t *testing.T) {
|
||||||
|
addr := "1111111111111111111111111111111111111111"
|
||||||
|
want := common.HexToAddress("0x" + addr)
|
||||||
|
got, err := normalizeEvmAddress(addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalize bare address: %v", err)
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("bare address = %s, want %s", got.Hex(), want.Hex())
|
||||||
|
}
|
||||||
|
got, err = normalizeEvmAddress("0X" + strings.ToUpper(addr))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalize prefixed address: %v", err)
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("prefixed address = %s, want %s", got.Hex(), want.Hex())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyNormalizeTronAddressHexAcceptsOptionalPrefix(t *testing.T) {
|
||||||
|
body := "a614f803b6fd780986a42c78ec9c7f77e6ded13c"
|
||||||
|
want := "41" + body
|
||||||
|
|
||||||
|
for _, input := range []string{body, "0x" + body, want, "0X" + strings.ToUpper(want)} {
|
||||||
|
got, err := normalizeTronAddressHex(input)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalizeTronAddressHex(%q): %v", input, err)
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("normalizeTronAddressHex(%q) = %q, want %q", input, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyNormalizeTronTxIDAcceptsOptional0x(t *testing.T) {
|
||||||
|
txID := strings.Repeat("a", 64)
|
||||||
|
got, err := normalizeTronTxID(txID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalize bare txid: %v", err)
|
||||||
|
}
|
||||||
|
if got != txID {
|
||||||
|
t.Fatalf("bare txid = %q, want %q", got, txID)
|
||||||
|
}
|
||||||
|
got, err = normalizeTronTxID("0X" + strings.ToUpper(txID))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("normalize prefixed txid: %v", err)
|
||||||
|
}
|
||||||
|
if got != txID {
|
||||||
|
t.Fatalf("prefixed txid = %q, want %q", got, txID)
|
||||||
|
}
|
||||||
|
if _, err = normalizeTronTxID("0x" + strings.Repeat("a", 63)); err == nil {
|
||||||
|
t.Fatal("expected short txid to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyDialEvmClientsIncludesHTTPNode(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if err := dao.Mdb.Create(&mdb.RpcNode{
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
Type: mdb.RpcNodeTypeHttp,
|
||||||
|
Url: "http://127.0.0.1:1",
|
||||||
|
Enabled: true,
|
||||||
|
Status: mdb.RpcNodeStatusOk,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("create rpc node: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
clients, err := dialManualEvmClients(ctx, mdb.NetworkEthereum)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dialManualEvmClients(): %v", err)
|
||||||
|
}
|
||||||
|
defer closeManualEvmClients(clients)
|
||||||
|
if len(clients) != 1 {
|
||||||
|
t.Fatalf("client count = %d, want 1", len(clients))
|
||||||
|
}
|
||||||
|
if !strings.Contains(clients[0].label, mdb.RpcNodeTypeHttp) {
|
||||||
|
t.Fatalf("client label = %q, want HTTP node", clients[0].label)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyEvmRejectsTransactionBeforeOrder(t *testing.T) {
|
||||||
|
order := &mdb.Orders{BaseModel: mdb.BaseModel{CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().UnixMilli()))}}
|
||||||
|
txTime := uint64(time.Now().Add(-time.Hour).Unix())
|
||||||
|
if err := ensureEvmTransactionNotBeforeOrder(txTime, order); err == nil {
|
||||||
|
t.Fatal("expected transaction before order to be rejected")
|
||||||
|
}
|
||||||
|
txTime = uint64(time.Now().Add(time.Minute).Unix())
|
||||||
|
if err := ensureEvmTransactionNotBeforeOrder(txTime, order); err != nil {
|
||||||
|
t.Fatalf("expected transaction after order to pass: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyCanonicalEvmHash(t *testing.T) {
|
||||||
|
hash := strings.Repeat("a", 64)
|
||||||
|
_, canonical, err := canonicalEvmHash("0X" + strings.ToUpper(hash))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("canonicalEvmHash(): %v", err)
|
||||||
|
}
|
||||||
|
if canonical != "0x"+hash {
|
||||||
|
t.Fatalf("canonical hash = %q, want %q", canonical, "0x"+hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyEquivalentBlockIDsCatchLegacyVariants(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
hash := strings.Repeat("b", 64)
|
||||||
|
mixedHash := "0x" + strings.Repeat("bB", 32)
|
||||||
|
if err := dao.Mdb.Create(&mdb.Orders{
|
||||||
|
TradeId: "paid-legacy-hash",
|
||||||
|
OrderId: "paid-legacy-hash",
|
||||||
|
Status: mdb.StatusPaySuccess,
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
BlockTransactionId: mixedHash,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("create existing order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
order := &mdb.Orders{BaseModel: mdb.BaseModel{ID: 999}, Network: mdb.NetworkEthereum}
|
||||||
|
if err := ensureManualBlockTransactionUnused(order, "0x"+hash); err == nil {
|
||||||
|
t.Fatal("expected legacy hash variant to be treated as already processed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyEvmRequestFailureFallsBackToNextClient(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
contract := common.HexToAddress("0x1111111111111111111111111111111111111111")
|
||||||
|
to := common.HexToAddress("0x2222222222222222222222222222222222222222")
|
||||||
|
rawAmount := big.NewInt(1230000)
|
||||||
|
receipt := &types.Receipt{
|
||||||
|
Status: types.ReceiptStatusSuccessful,
|
||||||
|
BlockNumber: big.NewInt(10),
|
||||||
|
Logs: []*types.Log{{
|
||||||
|
Address: contract,
|
||||||
|
Topics: []common.Hash{
|
||||||
|
erc20TransferEventHash,
|
||||||
|
common.Hash{},
|
||||||
|
common.BytesToHash(to.Bytes()),
|
||||||
|
},
|
||||||
|
Data: common.LeftPadBytes(rawAmount.Bytes(), 32),
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
order := &mdb.Orders{
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
Token: "USDT",
|
||||||
|
ActualAmount: 1.23,
|
||||||
|
ReceiveAddress: to.Hex(),
|
||||||
|
BaseModel: mdb.BaseModel{CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().Add(-time.Minute).UnixMilli()))},
|
||||||
|
}
|
||||||
|
token := &mdb.ChainToken{Network: mdb.NetworkEthereum, Symbol: "USDT", ContractAddress: contract.Hex(), Decimals: 6}
|
||||||
|
|
||||||
|
err := validateManualEvmPaymentAcrossClients(context.Background(), []manualEvmClient{
|
||||||
|
{label: "ws bad", reader: &fakeEvmReader{receiptErr: errors.New("ws receipt failed")}},
|
||||||
|
{label: "http ok", reader: &fakeEvmReader{
|
||||||
|
receipt: receipt,
|
||||||
|
headers: map[string]*types.Header{
|
||||||
|
"10": {Number: big.NewInt(10), Time: uint64(time.Now().Unix())},
|
||||||
|
"latest": {Number: big.NewInt(12), Time: uint64(time.Now().Unix())},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
}, order, common.HexToHash("0x"+strings.Repeat("c", 64)), token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("validateManualEvmPaymentAcrossClients(): %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyTronTRC20UsesTransferEvent(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
contractHex := "411111111111111111111111111111111111111111"
|
||||||
|
recipientHex := "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
|
||||||
|
contractAddress, err := tronHexToAddress(contractHex)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("contract address: %v", err)
|
||||||
|
}
|
||||||
|
recipientAddress, err := tronHexToAddress(recipientHex)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("recipient address: %v", err)
|
||||||
|
}
|
||||||
|
if err = dao.Mdb.Create(&mdb.ChainToken{
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Symbol: "USDT",
|
||||||
|
ContractAddress: contractAddress,
|
||||||
|
Decimals: 6,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("create token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rawAmount := big.NewInt(1230000)
|
||||||
|
tx := manualTronTransactionFromCallData(t, contractHex, recipientHex, rawAmount)
|
||||||
|
info := &manualTronTxInfo{Log: []manualTronEventLog{{
|
||||||
|
Address: strings.TrimPrefix(contractHex, "41"),
|
||||||
|
Topics: []string{
|
||||||
|
"0x" + strings.TrimPrefix(erc20TransferEventHash.Hex(), "0x"),
|
||||||
|
strings.Repeat("0", 64),
|
||||||
|
"0x" + strings.Repeat("0", 24) + strings.TrimPrefix(recipientHex, "41"),
|
||||||
|
},
|
||||||
|
Data: "0x" + fmt.Sprintf("%064x", rawAmount),
|
||||||
|
}}}
|
||||||
|
order := &mdb.Orders{ReceiveAddress: recipientAddress, Token: "USDT", ActualAmount: 1.23}
|
||||||
|
|
||||||
|
if err = validateManualTronTRC20Transfer(order, &tx, info); err != nil {
|
||||||
|
t.Fatalf("validateManualTronTRC20Transfer(): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info.Log[0].Data = "0x" + fmt.Sprintf("%064x", big.NewInt(1240000))
|
||||||
|
if err = validateManualTronTRC20Transfer(order, &tx, info); err == nil {
|
||||||
|
t.Fatal("expected event amount mismatch to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifyTronPaymentHTTPFlow(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
txID := strings.Repeat("a", 64)
|
||||||
|
contractHex := "411111111111111111111111111111111111111111"
|
||||||
|
recipientHex := "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
|
||||||
|
contractAddress, err := tronHexToAddress(contractHex)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("contract address: %v", err)
|
||||||
|
}
|
||||||
|
recipientAddress, err := tronHexToAddress(recipientHex)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("recipient address: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rawAmount := big.NewInt(1230000)
|
||||||
|
blockTimeMs := time.Now().Add(time.Minute).UnixMilli()
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req map[string]string
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
t.Errorf("decode tron request: %v", err)
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path != "/wallet/getnowblock" && req["value"] != txID {
|
||||||
|
t.Errorf("request tx id = %q, want %q", req["value"], txID)
|
||||||
|
http.Error(w, "bad tx id", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/wallet/gettransactionbyid":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"txID": txID,
|
||||||
|
"raw_data": map[string]interface{}{
|
||||||
|
"contract": []map[string]interface{}{{
|
||||||
|
"type": "TriggerSmartContract",
|
||||||
|
"parameter": map[string]interface{}{
|
||||||
|
"value": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
"ret": []map[string]string{{"contractRet": "SUCCESS"}},
|
||||||
|
})
|
||||||
|
case "/wallet/gettransactioninfobyid":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"id": txID,
|
||||||
|
"blockNumber": 100,
|
||||||
|
"blockTimeStamp": blockTimeMs,
|
||||||
|
"receipt": map[string]string{"result": "SUCCESS"},
|
||||||
|
"log": []map[string]interface{}{{
|
||||||
|
"address": strings.TrimPrefix(contractHex, "41"),
|
||||||
|
"topics": []string{
|
||||||
|
strings.TrimPrefix(erc20TransferEventHash.Hex(), "0x"),
|
||||||
|
strings.Repeat("0", 64),
|
||||||
|
"0X" + strings.ToUpper(strings.Repeat("0", 24)+strings.TrimPrefix(recipientHex, "41")),
|
||||||
|
},
|
||||||
|
"data": fmt.Sprintf("%064x", rawAmount),
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
case "/wallet/getnowblock":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"block_header": map[string]interface{}{
|
||||||
|
"raw_data": map[string]interface{}{"number": 110},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
if err = dao.Mdb.Create(&mdb.RpcNode{
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Type: mdb.RpcNodeTypeHttp,
|
||||||
|
Url: server.URL,
|
||||||
|
Enabled: true,
|
||||||
|
Status: mdb.RpcNodeStatusOk,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("create tron rpc node: %v", err)
|
||||||
|
}
|
||||||
|
if err = dao.Mdb.Create(&mdb.ChainToken{
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Symbol: "USDT",
|
||||||
|
ContractAddress: contractAddress,
|
||||||
|
Decimals: 6,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("create token: %v", err)
|
||||||
|
}
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "manual-tron-http-flow",
|
||||||
|
OrderId: "manual-tron-http-flow",
|
||||||
|
ActualAmount: 1.23,
|
||||||
|
ReceiveAddress: recipientAddress,
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
PayProvider: mdb.PaymentProviderOnChain,
|
||||||
|
}
|
||||||
|
if err = dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := ValidateManualOrderPayment(order, "0X"+strings.ToUpper(txID))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ValidateManualOrderPayment(): %v", err)
|
||||||
|
}
|
||||||
|
if got != txID {
|
||||||
|
t.Fatalf("canonical tx id = %q, want %q", got, txID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManualVerifySolanaRejectsMissingBlockTime(t *testing.T) {
|
||||||
|
order := &mdb.Orders{BaseModel: mdb.BaseModel{CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().UnixMilli()))}}
|
||||||
|
if err := ensureSolanaTransferNotBeforeOrder(0, order); err == nil {
|
||||||
|
t.Fatal("expected missing block time to fail")
|
||||||
|
}
|
||||||
|
if err := ensureSolanaTransferNotBeforeOrder(time.Now().Add(time.Minute).Unix(), order); err != nil {
|
||||||
|
t.Fatalf("expected future block time to pass: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeEvmReader struct {
|
||||||
|
receipt *types.Receipt
|
||||||
|
receiptErr error
|
||||||
|
headers map[string]*types.Header
|
||||||
|
headerErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeEvmReader) TransactionReceipt(context.Context, common.Hash) (*types.Receipt, error) {
|
||||||
|
if f.receiptErr != nil {
|
||||||
|
return nil, f.receiptErr
|
||||||
|
}
|
||||||
|
return f.receipt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeEvmReader) HeaderByNumber(_ context.Context, number *big.Int) (*types.Header, error) {
|
||||||
|
if f.headerErr != nil {
|
||||||
|
return nil, f.headerErr
|
||||||
|
}
|
||||||
|
key := "latest"
|
||||||
|
if number != nil {
|
||||||
|
key = number.String()
|
||||||
|
}
|
||||||
|
header := f.headers[key]
|
||||||
|
if header == nil {
|
||||||
|
return nil, fmt.Errorf("missing header %s", key)
|
||||||
|
}
|
||||||
|
return header, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func manualTronTransactionFromCallData(t *testing.T, contractHex, recipientHex string, amount *big.Int) manualTronTransaction {
|
||||||
|
t.Helper()
|
||||||
|
body := strings.TrimPrefix(recipientHex, "41")
|
||||||
|
raw := fmt.Sprintf(`{
|
||||||
|
"raw_data": {
|
||||||
|
"contract": [{
|
||||||
|
"type": "TriggerSmartContract",
|
||||||
|
"parameter": {
|
||||||
|
"value": {
|
||||||
|
"contract_address": %q,
|
||||||
|
"data": %q
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}`, contractHex, "a9059cbb"+strings.Repeat("0", 24)+body+fmt.Sprintf("%064x", amount))
|
||||||
|
var tx manualTronTransaction
|
||||||
|
if err := json.Unmarshal([]byte(raw), &tx); err != nil {
|
||||||
|
t.Fatalf("unmarshal tron tx: %v", err)
|
||||||
|
}
|
||||||
|
return tx
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/request"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/constant"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/http_client"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type okPayCreateDepositResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Code int `json:"code"`
|
||||||
|
Data struct {
|
||||||
|
OrderID string `json:"order_id"`
|
||||||
|
PayURL string `json:"pay_url"`
|
||||||
|
} `json:"data"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type okPayDepositOrder struct {
|
||||||
|
ProviderOrderID string
|
||||||
|
PayURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
type okPayNotifyPayload struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
OrderID string `json:"order_id"`
|
||||||
|
UniqueID string `json:"unique_id"`
|
||||||
|
PayUserID string `json:"pay_user_id"`
|
||||||
|
Amount string `json:"amount"`
|
||||||
|
Coin string `json:"coin"`
|
||||||
|
PayStatus string `json:"pay_status"`
|
||||||
|
NotifyType string `json:"notify_type"`
|
||||||
|
Sign string `json:"sign"`
|
||||||
|
RawFormData string `json:"raw_form_data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func okPaySign(form map[string]string, shopID string, shopToken string) map[string]string {
|
||||||
|
values := url.Values{}
|
||||||
|
for key, value := range form {
|
||||||
|
if strings.TrimSpace(value) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
values.Set(key, value)
|
||||||
|
}
|
||||||
|
values.Set("id", shopID)
|
||||||
|
query, _ := url.QueryUnescape(values.Encode())
|
||||||
|
sum := md5.Sum([]byte(query + "&token=" + shopToken))
|
||||||
|
|
||||||
|
signed := make(map[string]string, len(values)+1)
|
||||||
|
for key, vals := range values {
|
||||||
|
if len(vals) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
signed[key] = vals[0]
|
||||||
|
}
|
||||||
|
signed["sign"] = strings.ToUpper(hex.EncodeToString(sum[:]))
|
||||||
|
return signed
|
||||||
|
}
|
||||||
|
|
||||||
|
func createOkPayDepositOrder(uniqueID string, amount float64, coin string, returnURL string) (*okPayDepositOrder, error) {
|
||||||
|
shopID := data.GetOkPayShopID()
|
||||||
|
shopToken := data.GetOkPayShopToken()
|
||||||
|
apiURL := strings.TrimSpace(data.GetOkPayAPIURL())
|
||||||
|
callbackURL := data.GetOkPayCallbackURL()
|
||||||
|
if shopID == "" || shopToken == "" || apiURL == "" || callbackURL == "" {
|
||||||
|
return nil, fmt.Errorf("okpay config incomplete")
|
||||||
|
}
|
||||||
|
|
||||||
|
if returnURL == "" {
|
||||||
|
returnURL = data.GetOkPayReturnURL()
|
||||||
|
}
|
||||||
|
|
||||||
|
form := map[string]string{
|
||||||
|
"unique_id": uniqueID,
|
||||||
|
"name": uniqueID,
|
||||||
|
"amount": fmt.Sprintf("%.*f", data.GetAmountPrecision(), amount),
|
||||||
|
"coin": strings.ToUpper(strings.TrimSpace(coin)),
|
||||||
|
"callback_url": callbackURL,
|
||||||
|
"return_url": returnURL,
|
||||||
|
}
|
||||||
|
form = okPaySign(form, shopID, shopToken)
|
||||||
|
|
||||||
|
base, err := url.Parse(apiURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
base.Path = path.Join(base.Path, "payLink")
|
||||||
|
|
||||||
|
client := http_client.GetHttpClient()
|
||||||
|
client.SetTimeout(time.Duration(data.GetOkPayTimeoutSeconds()) * time.Second)
|
||||||
|
|
||||||
|
var payload okPayCreateDepositResponse
|
||||||
|
resp, err := client.R().
|
||||||
|
SetFormData(form).
|
||||||
|
SetResult(&payload).
|
||||||
|
Post(base.String())
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[okpay] create order request failed unique_id=%s api_url=%s callback_url=%s return_url=%s err=%v", uniqueID, base.String(), callbackURL, returnURL, err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp.StatusCode() >= 400 {
|
||||||
|
log.Sugar.Warnf("[okpay] create order http error unique_id=%s status=%s api_url=%s callback_url=%s return_url=%s body=%s", uniqueID, resp.Status(), base.String(), callbackURL, returnURL, resp.String())
|
||||||
|
return nil, fmt.Errorf("okpay http status: %s", resp.Status())
|
||||||
|
}
|
||||||
|
if payload.Data.OrderID == "" || payload.Data.PayURL == "" {
|
||||||
|
log.Sugar.Warnf("[okpay] create order rejected unique_id=%s api_url=%s callback_url=%s return_url=%s status=%s code=%d msg=%s", uniqueID, base.String(), callbackURL, returnURL, payload.Status, payload.Code, payload.Msg)
|
||||||
|
if payload.Msg != "" {
|
||||||
|
return nil, fmt.Errorf("okpay create order failed: %s (callback_url=%s)", payload.Msg, callbackURL)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("okpay create order failed (callback_url=%s)", callbackURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &okPayDepositOrder{
|
||||||
|
ProviderOrderID: payload.Data.OrderID,
|
||||||
|
PayURL: payload.Data.PayURL,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyOkPayNotify(form map[string]string) bool {
|
||||||
|
shopID := data.GetOkPayShopID()
|
||||||
|
shopToken := data.GetOkPayShopToken()
|
||||||
|
signature := strings.TrimSpace(form["sign"])
|
||||||
|
if shopID == "" || shopToken == "" || signature == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if expected := okPayNotifySign(form, shopToken); expected != "" && strings.EqualFold(expected, signature) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned := make(map[string]string, len(form))
|
||||||
|
for key, value := range form {
|
||||||
|
if strings.EqualFold(key, "sign") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
unsigned[key] = value
|
||||||
|
}
|
||||||
|
signed := okPaySign(unsigned, shopID, shopToken)
|
||||||
|
return strings.EqualFold(strings.TrimSpace(signed["sign"]), signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
func okPayNotifySign(form map[string]string, shopToken string) string {
|
||||||
|
orderedKeys := []string{
|
||||||
|
"code",
|
||||||
|
"data[order_id]",
|
||||||
|
"data[unique_id]",
|
||||||
|
"data[pay_user_id]",
|
||||||
|
"data[amount]",
|
||||||
|
"data[coin]",
|
||||||
|
"data[status]",
|
||||||
|
"data[type]",
|
||||||
|
"id",
|
||||||
|
"status",
|
||||||
|
}
|
||||||
|
|
||||||
|
pairs := make([]string, 0, len(orderedKeys))
|
||||||
|
for _, key := range orderedKeys {
|
||||||
|
value := strings.TrimSpace(form[key])
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pairs = append(pairs, url.QueryEscape(key)+"="+url.QueryEscape(value))
|
||||||
|
}
|
||||||
|
if len(pairs) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
query, err := url.QueryUnescape(strings.Join(pairs, "&"))
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
sum := md5.Sum([]byte(query + "&token=" + shopToken))
|
||||||
|
return strings.ToUpper(hex.EncodeToString(sum[:]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOkPayNotify(form map[string]string, rawFormData string) *okPayNotifyPayload {
|
||||||
|
return &okPayNotifyPayload{
|
||||||
|
ID: strings.TrimSpace(form["id"]),
|
||||||
|
Status: strings.TrimSpace(form["status"]),
|
||||||
|
Code: strings.TrimSpace(form["code"]),
|
||||||
|
OrderID: strings.TrimSpace(form["data[order_id]"]),
|
||||||
|
UniqueID: strings.TrimSpace(form["data[unique_id]"]),
|
||||||
|
PayUserID: strings.TrimSpace(form["data[pay_user_id]"]),
|
||||||
|
Amount: strings.TrimSpace(form["data[amount]"]),
|
||||||
|
Coin: strings.TrimSpace(form["data[coin]"]),
|
||||||
|
PayStatus: strings.TrimSpace(form["data[status]"]),
|
||||||
|
NotifyType: strings.TrimSpace(form["data[type]"]),
|
||||||
|
Sign: strings.TrimSpace(form["sign"]),
|
||||||
|
RawFormData: rawFormData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleOkPayNotify(form map[string]string, rawFormData string) error {
|
||||||
|
if !verifyOkPayNotify(form) {
|
||||||
|
return fmt.Errorf("invalid okpay notify sign")
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := parseOkPayNotify(form, rawFormData)
|
||||||
|
|
||||||
|
if payload.ID == "" || payload.ID != data.GetOkPayShopID() {
|
||||||
|
return fmt.Errorf("okpay notify shop id mismatch: %s", payload.ID)
|
||||||
|
}
|
||||||
|
if payload.UniqueID == "" || payload.OrderID == "" {
|
||||||
|
return fmt.Errorf("missing okpay notify identifiers")
|
||||||
|
}
|
||||||
|
|
||||||
|
order, err := data.GetOrderInfoByTradeId(payload.UniqueID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if order.ID <= 0 {
|
||||||
|
return fmt.Errorf("okpay notify order not found: %s", payload.UniqueID)
|
||||||
|
}
|
||||||
|
if order.PayProvider != "okpay" {
|
||||||
|
return fmt.Errorf("okpay notify order provider mismatch: %s", payload.UniqueID)
|
||||||
|
}
|
||||||
|
|
||||||
|
providerRow, err := data.GetProviderOrderByTradeIDAndProvider(payload.UniqueID, order.PayProvider)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if providerRow.ID <= 0 {
|
||||||
|
return fmt.Errorf("okpay provider order not found: %s", payload.UniqueID)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = data.SaveProviderOrderNotify(payload.UniqueID, order.PayProvider, payload.RawFormData)
|
||||||
|
|
||||||
|
if !strings.EqualFold(payload.Status, "success") || !strings.EqualFold(payload.NotifyType, "deposit") || payload.PayStatus != "1" {
|
||||||
|
log.Sugar.Infof("[okpay] notify ignored trade_id=%s status=%s pay_status=%s type=%s", payload.UniqueID, payload.Status, payload.PayStatus, payload.NotifyType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if providerRow.ProviderOrderID != "" && providerRow.ProviderOrderID != payload.OrderID {
|
||||||
|
return fmt.Errorf("okpay provider order id mismatch: got=%s want=%s", payload.OrderID, providerRow.ProviderOrderID)
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(strings.TrimSpace(order.Token), strings.TrimSpace(payload.Coin)) {
|
||||||
|
return fmt.Errorf("okpay coin mismatch: got=%s want=%s", payload.Coin, order.Token)
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyAmount, err := strconv.ParseFloat(payload.Amount, 64)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid okpay amount: %w", err)
|
||||||
|
}
|
||||||
|
precision := data.GetAmountPrecision()
|
||||||
|
if fmt.Sprintf("%.*f", precision, notifyAmount) != fmt.Sprintf("%.*f", precision, order.ActualAmount) {
|
||||||
|
return fmt.Errorf("okpay amount mismatch: got=%.*f want=%.*f", precision, notifyAmount, precision, order.ActualAmount)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = OrderProcessing(&request.OrderProcessingRequest{
|
||||||
|
ReceiveAddress: order.ReceiveAddress,
|
||||||
|
Currency: order.Currency,
|
||||||
|
Token: order.Token,
|
||||||
|
Network: order.Network,
|
||||||
|
Amount: order.ActualAmount,
|
||||||
|
TradeId: order.TradeId,
|
||||||
|
BlockTransactionId: payload.OrderID,
|
||||||
|
})
|
||||||
|
processed := err == nil
|
||||||
|
if err != nil && err != constant.OrderBlockAlreadyProcess {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if processed {
|
||||||
|
sendPaymentNotification(order)
|
||||||
|
}
|
||||||
|
if err = data.MarkProviderOrderPaid(payload.UniqueID, order.PayProvider, payload.RawFormData); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"github.com/GMWalletApp/epusdt/notify"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHandleOkPayNotifySendsPaymentNotificationOnSuccess(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const (
|
||||||
|
channelType = "test-okpay-pay-success"
|
||||||
|
shopID = "okpay-shop-notify"
|
||||||
|
shopToken = "okpay-shop-token"
|
||||||
|
tradeID = "okpay-notify-success-001"
|
||||||
|
orderID = "merchant-okpay-notify-success-001"
|
||||||
|
providerOrderID = "okpay-provider-success-001"
|
||||||
|
rawFormData = "raw-okpay-form"
|
||||||
|
)
|
||||||
|
|
||||||
|
got := make(chan string, 1)
|
||||||
|
notify.RegisterSender(channelType, func(config, text string) error {
|
||||||
|
got <- text
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := dao.Mdb.Create(&mdb.NotificationChannel{
|
||||||
|
Type: channelType,
|
||||||
|
Name: "test okpay pay success",
|
||||||
|
Config: "{}",
|
||||||
|
Events: `{"pay_success":true}`,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed notification channel: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayShopID, shopID, mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay shop id: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayShopToken, shopToken, mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay shop token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: tradeID,
|
||||||
|
OrderId: orderID,
|
||||||
|
Amount: 1,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: 0.15,
|
||||||
|
ReceiveAddress: "OKPAY",
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
PaymentType: mdb.PaymentTypeEpay,
|
||||||
|
PayProvider: mdb.PaymentProviderOkPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("seed order: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(&mdb.ProviderOrder{
|
||||||
|
TradeId: tradeID,
|
||||||
|
Provider: mdb.PaymentProviderOkPay,
|
||||||
|
ProviderOrderID: providerOrderID,
|
||||||
|
Amount: 0.15,
|
||||||
|
Coin: "USDT",
|
||||||
|
Status: mdb.ProviderOrderStatusPending,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed provider order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
form := okPayNotifyTestForm(shopID, shopToken, providerOrderID, tradeID, "0.15000000", "USDT")
|
||||||
|
if err := HandleOkPayNotify(form, rawFormData); err != nil {
|
||||||
|
t.Fatalf("handle okpay notify: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case text := <-got:
|
||||||
|
if !strings.Contains(text, tradeID) {
|
||||||
|
t.Fatalf("notification text = %q, want trade id %s", text, tradeID)
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, orderID) {
|
||||||
|
t.Fatalf("notification text = %q, want order id %s", text, orderID)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timed out waiting for payment notification")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := HandleOkPayNotify(form, rawFormData); err != nil {
|
||||||
|
t.Fatalf("handle duplicate okpay notify: %v", err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case text := <-got:
|
||||||
|
t.Fatalf("duplicate notification sent: %q", text)
|
||||||
|
case <-time.After(200 * time.Millisecond):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func okPayNotifyTestForm(shopID, shopToken, providerOrderID, tradeID, amount, coin string) map[string]string {
|
||||||
|
form := map[string]string{
|
||||||
|
"code": "200",
|
||||||
|
"id": shopID,
|
||||||
|
"status": "success",
|
||||||
|
"data[order_id]": providerOrderID,
|
||||||
|
"data[unique_id]": tradeID,
|
||||||
|
"data[pay_user_id]": "123456789",
|
||||||
|
"data[amount]": amount,
|
||||||
|
"data[coin]": coin,
|
||||||
|
"data[status]": "1",
|
||||||
|
"data[type]": "deposit",
|
||||||
|
}
|
||||||
|
form["sign"] = okPayNotifySign(form, shopToken)
|
||||||
|
return form
|
||||||
|
}
|
||||||
@@ -24,7 +24,6 @@ import (
|
|||||||
const (
|
const (
|
||||||
CnyMinimumPaymentAmount = 0.01
|
CnyMinimumPaymentAmount = 0.01
|
||||||
UsdtMinimumPaymentAmount = 0.01
|
UsdtMinimumPaymentAmount = 0.01
|
||||||
UsdtAmountPerIncrement = 0.01
|
|
||||||
IncrementalMaximumNumber = 100
|
IncrementalMaximumNumber = 100
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -61,7 +60,8 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
|||||||
token := strings.ToUpper(strings.TrimSpace(req.Token))
|
token := strings.ToUpper(strings.TrimSpace(req.Token))
|
||||||
currency := strings.ToUpper(strings.TrimSpace(req.Currency))
|
currency := strings.ToUpper(strings.TrimSpace(req.Currency))
|
||||||
network := strings.ToLower(strings.TrimSpace(req.Network))
|
network := strings.ToLower(strings.TrimSpace(req.Network))
|
||||||
payAmount := math.MustParsePrecFloat64(req.Amount, 2)
|
amountPrecision := data.GetAmountPrecision()
|
||||||
|
payAmount := math.MustParsePrecFloat64(req.Amount, amountPrecision)
|
||||||
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(currency))
|
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(currency))
|
||||||
if rate <= 0 {
|
if rate <= 0 {
|
||||||
return nil, constant.RateAmountErr
|
return nil, constant.RateAmountErr
|
||||||
@@ -96,7 +96,7 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
|||||||
}
|
}
|
||||||
|
|
||||||
tradeID := GenerateCode()
|
tradeID := GenerateCode()
|
||||||
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), 2)
|
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), amountPrecision)
|
||||||
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(tradeID, network, token, amount, walletAddress)
|
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(tradeID, network, token, amount, walletAddress)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -109,7 +109,7 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
|||||||
order := &mdb.Orders{
|
order := &mdb.Orders{
|
||||||
TradeId: tradeID,
|
TradeId: tradeID,
|
||||||
OrderId: req.OrderId,
|
OrderId: req.OrderId,
|
||||||
Amount: req.Amount,
|
Amount: payAmount,
|
||||||
Currency: currency,
|
Currency: currency,
|
||||||
ActualAmount: availableAmount,
|
ActualAmount: availableAmount,
|
||||||
ReceiveAddress: availableAddress,
|
ReceiveAddress: availableAddress,
|
||||||
@@ -120,6 +120,7 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
|||||||
RedirectUrl: req.RedirectUrl,
|
RedirectUrl: req.RedirectUrl,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
PaymentType: req.PaymentType,
|
PaymentType: req.PaymentType,
|
||||||
|
PayProvider: mdb.PaymentProviderOnChain,
|
||||||
ApiKeyID: apiKeyID(apiKey),
|
ApiKeyID: apiKeyID(apiKey),
|
||||||
}
|
}
|
||||||
if err = data.CreateOrderWithTransaction(tx, order); err != nil {
|
if err = data.CreateOrderWithTransaction(tx, order); err != nil {
|
||||||
@@ -199,6 +200,11 @@ func OrderProcessing(req *request.OrderProcessingRequest) error {
|
|||||||
if err = data.ExpireOrderByTradeId(sub.TradeId); err != nil {
|
if err = data.ExpireOrderByTradeId(sub.TradeId); err != nil {
|
||||||
log.Sugar.Warnf("[order] expire sub-order failed, trade_id=%s, err=%v", sub.TradeId, err)
|
log.Sugar.Warnf("[order] expire sub-order failed, trade_id=%s, err=%v", sub.TradeId, err)
|
||||||
}
|
}
|
||||||
|
if sub.PayProvider != "" && sub.PayProvider != mdb.PaymentProviderOnChain {
|
||||||
|
if err = data.MarkProviderOrderExpired(sub.TradeId, sub.PayProvider); err != nil {
|
||||||
|
log.Sugar.Warnf("[order] expire provider order failed, trade_id=%s, provider=%s, err=%v", sub.TradeId, sub.PayProvider, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if err = data.UnLockTransaction(sub.Network, sub.ReceiveAddress, sub.Token, sub.ActualAmount); err != nil {
|
if err = data.UnLockTransaction(sub.Network, sub.ReceiveAddress, sub.Token, sub.ActualAmount); err != nil {
|
||||||
log.Sugar.Warnf("[order] unlock sub-order transaction failed, trade_id=%s, err=%v", sub.TradeId, err)
|
log.Sugar.Warnf("[order] unlock sub-order transaction failed, trade_id=%s, err=%v", sub.TradeId, err)
|
||||||
}
|
}
|
||||||
@@ -257,6 +263,11 @@ func OrderProcessing(req *request.OrderProcessingRequest) error {
|
|||||||
|
|
||||||
// Release sibling locks after their status transitions commit.
|
// Release sibling locks after their status transitions commit.
|
||||||
for _, sib := range siblings {
|
for _, sib := range siblings {
|
||||||
|
if sib.PayProvider != "" && sib.PayProvider != mdb.PaymentProviderOnChain {
|
||||||
|
if err = data.MarkProviderOrderExpired(sib.TradeId, sib.PayProvider); err != nil {
|
||||||
|
log.Sugar.Warnf("[order] expire sibling provider order failed, trade_id=%s, provider=%s, err=%v", sib.TradeId, sib.PayProvider, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if err = data.UnLockTransaction(sib.Network, sib.ReceiveAddress, sib.Token, sib.ActualAmount); err != nil {
|
if err = data.UnLockTransaction(sib.Network, sib.ReceiveAddress, sib.Token, sib.ActualAmount); err != nil {
|
||||||
log.Sugar.Warnf("[order] unlock sibling transaction failed, trade_id=%s, err=%v", sib.TradeId, err)
|
log.Sugar.Warnf("[order] unlock sibling transaction failed, trade_id=%s, err=%v", sib.TradeId, err)
|
||||||
}
|
}
|
||||||
@@ -269,6 +280,7 @@ func OrderProcessing(req *request.OrderProcessingRequest) error {
|
|||||||
func ReserveAvailableWalletAndAmount(tradeID string, network string, token string, amount float64, walletAddress []mdb.WalletAddress) (string, float64, error) {
|
func ReserveAvailableWalletAndAmount(tradeID string, network string, token string, amount float64, walletAddress []mdb.WalletAddress) (string, float64, error) {
|
||||||
availableAddress := ""
|
availableAddress := ""
|
||||||
availableAmount := amount
|
availableAmount := amount
|
||||||
|
amountPrecision := data.GetAmountPrecision()
|
||||||
|
|
||||||
tryLockWalletFunc := func(targetAmount float64) (string, error) {
|
tryLockWalletFunc := func(targetAmount float64) (string, error) {
|
||||||
for _, address := range walletAddress {
|
for _, address := range walletAddress {
|
||||||
@@ -292,8 +304,8 @@ func ReserveAvailableWalletAndAmount(tradeID string, network string, token strin
|
|||||||
}
|
}
|
||||||
if address == "" {
|
if address == "" {
|
||||||
decimalOldAmount := decimal.NewFromFloat(availableAmount)
|
decimalOldAmount := decimal.NewFromFloat(availableAmount)
|
||||||
decimalIncr := decimal.NewFromFloat(UsdtAmountPerIncrement)
|
decimalIncr := decimal.New(1, int32(-amountPrecision))
|
||||||
availableAmount = decimalOldAmount.Add(decimalIncr).InexactFloat64()
|
availableAmount = math.MustParsePrecFloat64(decimalOldAmount.Add(decimalIncr).InexactFloat64(), amountPrecision)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
availableAddress = address
|
availableAddress = address
|
||||||
@@ -346,6 +358,10 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
|||||||
return nil, constant.OrderNotWaitPay
|
return nil, constant.OrderNotWaitPay
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if network == mdb.PaymentProviderOkPay {
|
||||||
|
return switchToOkPay(parent, token)
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Same token+network as parent → mark selected and return
|
// 2. Same token+network as parent → mark selected and return
|
||||||
if strings.EqualFold(parent.Token, token) && strings.EqualFold(parent.Network, network) {
|
if strings.EqualFold(parent.Token, token) && strings.EqualFold(parent.Network, network) {
|
||||||
_ = data.MarkOrderSelected(parent.TradeId)
|
_ = data.MarkOrderSelected(parent.TradeId)
|
||||||
@@ -399,7 +415,7 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
|||||||
}
|
}
|
||||||
|
|
||||||
subTradeID := GenerateCode()
|
subTradeID := GenerateCode()
|
||||||
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), 2)
|
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), data.GetAmountPrecision())
|
||||||
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(subTradeID, network, token, amount, walletAddress)
|
availableAddress, availableAmount, err := ReserveAvailableWalletAndAmount(subTradeID, network, token, amount, walletAddress)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -427,6 +443,7 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
|||||||
Name: parent.Name,
|
Name: parent.Name,
|
||||||
CallBackConfirm: mdb.CallBackConfirmOk, // don't trigger callback on sub-order
|
CallBackConfirm: mdb.CallBackConfirmOk, // don't trigger callback on sub-order
|
||||||
PaymentType: parent.PaymentType,
|
PaymentType: parent.PaymentType,
|
||||||
|
PayProvider: mdb.PaymentProviderOnChain,
|
||||||
ApiKeyID: parent.ApiKeyID, // inherit from parent so resolveOrderApiKey never fails
|
ApiKeyID: parent.ApiKeyID, // inherit from parent so resolveOrderApiKey never fails
|
||||||
}
|
}
|
||||||
if err = data.CreateOrderWithTransaction(tx, subOrder); err != nil {
|
if err = data.CreateOrderWithTransaction(tx, subOrder); err != nil {
|
||||||
@@ -458,7 +475,140 @@ func buildCheckoutResponse(order *mdb.Orders) *response.CheckoutCounterResponse
|
|||||||
Network: order.Network,
|
Network: order.Network,
|
||||||
ExpirationTime: order.CreatedAt.AddMinutes(config.GetOrderExpirationTime()).TimestampMilli(),
|
ExpirationTime: order.CreatedAt.AddMinutes(config.GetOrderExpirationTime()).TimestampMilli(),
|
||||||
RedirectUrl: order.RedirectUrl,
|
RedirectUrl: order.RedirectUrl,
|
||||||
|
PaymentUrl: fmt.Sprintf("%s/pay/checkout-counter/%s", config.GetAppUri(), order.TradeId),
|
||||||
CreatedAt: order.CreatedAt.TimestampMilli(),
|
CreatedAt: order.CreatedAt.TimestampMilli(),
|
||||||
IsSelected: order.IsSelected,
|
IsSelected: order.IsSelected,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func switchToOkPay(parent *mdb.Orders, token string) (*response.CheckoutCounterResponse, error) {
|
||||||
|
if !data.GetOkPayEnabled() {
|
||||||
|
return nil, constant.PaymentProviderNotEnabled
|
||||||
|
}
|
||||||
|
if data.GetOkPayShopID() == "" || data.GetOkPayShopToken() == "" || data.GetOkPayAPIURL() == "" || data.GetOkPayCallbackURL() == "" {
|
||||||
|
return nil, constant.PaymentProviderConfigErr
|
||||||
|
}
|
||||||
|
if !okPayTokenAllowed(token) {
|
||||||
|
return nil, constant.PaymentProviderNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
existing, err := data.GetSubOrderByTokenPayProvider(parent.TradeId, token, mdb.PaymentProviderOkPay)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if existing.ID > 0 {
|
||||||
|
providerRow, err := data.GetProviderOrderByTradeIDAndProvider(existing.TradeId, mdb.PaymentProviderOkPay)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if providerRow.ID == 0 || strings.TrimSpace(providerRow.PayURL) == "" {
|
||||||
|
return nil, constant.SystemErr
|
||||||
|
}
|
||||||
|
_ = data.MarkOrderSelected(parent.TradeId)
|
||||||
|
_ = data.MarkOrderSelected(existing.TradeId)
|
||||||
|
_ = data.RefreshOrderExpiration(parent.TradeId)
|
||||||
|
existing.IsSelected = true
|
||||||
|
resp := buildCheckoutResponse(existing)
|
||||||
|
resp.PaymentUrl = providerRow.PayURL
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err := data.CountActiveSubOrders(parent.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if count >= MaxSubOrders {
|
||||||
|
return nil, constant.SubOrderLimitExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(parent.Currency))
|
||||||
|
if rate <= 0 {
|
||||||
|
return nil, constant.RateAmountErr
|
||||||
|
}
|
||||||
|
decimalPayAmount := decimal.NewFromFloat(parent.Amount)
|
||||||
|
decimalTokenAmount := decimalPayAmount.Mul(decimal.NewFromFloat(rate))
|
||||||
|
if decimalTokenAmount.Cmp(decimal.NewFromFloat(UsdtMinimumPaymentAmount)) == -1 {
|
||||||
|
return nil, constant.PayAmountErr
|
||||||
|
}
|
||||||
|
|
||||||
|
subTradeID := GenerateCode()
|
||||||
|
amount := math.MustParsePrecFloat64(decimalTokenAmount.InexactFloat64(), data.GetAmountPrecision())
|
||||||
|
returnURL := strings.TrimSpace(parent.RedirectUrl)
|
||||||
|
if returnURL == "" {
|
||||||
|
returnURL = data.GetOkPayReturnURL()
|
||||||
|
}
|
||||||
|
if returnURL == "" {
|
||||||
|
returnURL = fmt.Sprintf("%s/pay/checkout-counter/%s", config.GetAppUri(), parent.TradeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
tx := dao.Mdb.Begin()
|
||||||
|
subOrder := &mdb.Orders{
|
||||||
|
TradeId: subTradeID,
|
||||||
|
OrderId: subTradeID,
|
||||||
|
ParentTradeId: parent.TradeId,
|
||||||
|
Amount: parent.Amount,
|
||||||
|
Currency: parent.Currency,
|
||||||
|
ActualAmount: amount,
|
||||||
|
ReceiveAddress: "OKPAY",
|
||||||
|
Token: token,
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
IsSelected: true,
|
||||||
|
NotifyUrl: "",
|
||||||
|
RedirectUrl: parent.RedirectUrl,
|
||||||
|
Name: parent.Name,
|
||||||
|
CallBackConfirm: mdb.CallBackConfirmOk,
|
||||||
|
PaymentType: parent.PaymentType,
|
||||||
|
PayProvider: mdb.PaymentProviderOkPay,
|
||||||
|
ApiKeyID: parent.ApiKeyID,
|
||||||
|
}
|
||||||
|
if err = data.CreateOrderWithTransaction(tx, subOrder); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
providerRow := &mdb.ProviderOrder{
|
||||||
|
TradeId: subTradeID,
|
||||||
|
Provider: mdb.PaymentProviderOkPay,
|
||||||
|
ProviderOrderID: "",
|
||||||
|
PayURL: "",
|
||||||
|
Amount: amount,
|
||||||
|
Coin: token,
|
||||||
|
Status: mdb.ProviderOrderStatusCreating,
|
||||||
|
}
|
||||||
|
if err = data.CreateProviderOrderWithTransaction(tx, providerRow); err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = tx.Commit().Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
okpayOrder, err := createOkPayDepositOrder(subTradeID, amount, token, returnURL)
|
||||||
|
if err != nil {
|
||||||
|
_ = data.MarkProviderOrderFailed(subTradeID, mdb.PaymentProviderOkPay)
|
||||||
|
_ = data.ExpireOrderByTradeID(subTradeID)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = data.UpdateProviderOrderCreated(subTradeID, mdb.PaymentProviderOkPay, okpayOrder.ProviderOrderID, okpayOrder.PayURL); err != nil {
|
||||||
|
_ = data.MarkProviderOrderFailed(subTradeID, mdb.PaymentProviderOkPay)
|
||||||
|
_ = data.ExpireOrderByTradeID(subTradeID)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = data.MarkOrderSelected(parent.TradeId)
|
||||||
|
_ = data.RefreshOrderExpiration(parent.TradeId)
|
||||||
|
|
||||||
|
resp := buildCheckoutResponse(subOrder)
|
||||||
|
resp.PaymentUrl = okpayOrder.PayURL
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func okPayTokenAllowed(token string) bool {
|
||||||
|
for _, item := range data.GetOkPayAllowTokens() {
|
||||||
|
if strings.EqualFold(item, token) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
@@ -97,6 +97,59 @@ func TestCreateTransactionAssignsIncrementedAmountsAndLocks(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateTransactionUsesConfiguredAmountPrecision(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupSystem, mdb.SettingKeyAmountPrecision, "4", mdb.SettingTypeInt); err != nil {
|
||||||
|
t.Fatalf("set amount precision: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := data.AddWalletAddress("wallet_precision_1"); err != nil {
|
||||||
|
t.Fatalf("add wallet: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp1, err := CreateTransaction(newCreateTransactionRequest("order_precision_1", 1), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create first transaction: %v", err)
|
||||||
|
}
|
||||||
|
resp2, err := CreateTransaction(newCreateTransactionRequest("order_precision_2", 1), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create second transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := fmt.Sprintf("%.4f", resp1.ActualAmount); got != "1.0000" {
|
||||||
|
t.Fatalf("first actual amount = %s, want 1.0000", got)
|
||||||
|
}
|
||||||
|
if got := fmt.Sprintf("%.4f", resp2.ActualAmount); got != "1.0001" {
|
||||||
|
t.Fatalf("second actual amount = %s, want 1.0001", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateTransactionStoresNormalizedMerchantAmount(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if _, err := data.AddWalletAddress("wallet_normalized_1"); err != nil {
|
||||||
|
t.Fatalf("add wallet: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := CreateTransaction(newCreateTransactionRequest("order_normalized_1", 100.129), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create transaction: %v", err)
|
||||||
|
}
|
||||||
|
if got := fmt.Sprintf("%.2f", resp.Amount); got != "100.13" {
|
||||||
|
t.Fatalf("response amount = %s, want 100.13", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
order, err := data.GetOrderInfoByTradeId(resp.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load order: %v", err)
|
||||||
|
}
|
||||||
|
if got := fmt.Sprintf("%.2f", order.Amount); got != "100.13" {
|
||||||
|
t.Fatalf("stored amount = %s, want 100.13", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCreateTransactionUsesRateAPIWhenForcedSettingIsNotPositive(t *testing.T) {
|
func TestCreateTransactionUsesRateAPIWhenForcedSettingIsNotPositive(t *testing.T) {
|
||||||
cleanup := testutil.SetupTestDatabases(t)
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
@@ -114,8 +167,8 @@ func TestCreateTransactionUsesRateAPIWhenForcedSettingIsNotPositive(t *testing.T
|
|||||||
}, nil
|
}, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err := data.SetSetting("rate", "rate.forced_usdt_rate", "0", "string"); err != nil {
|
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0}}`, "json"); err != nil {
|
||||||
t.Fatalf("set rate.forced_usdt_rate: %v", err)
|
t.Fatalf("set rate.forced_rate_list: %v", err)
|
||||||
}
|
}
|
||||||
if err := data.SetSetting("rate", "rate.api_url", "https://rate.example.test", "string"); err != nil {
|
if err := data.SetSetting("rate", "rate.api_url", "https://rate.example.test", "string"); err != nil {
|
||||||
t.Fatalf("set rate.api_url: %v", err)
|
t.Fatalf("set rate.api_url: %v", err)
|
||||||
@@ -137,8 +190,8 @@ func TestCreateTransactionFailsWhenRateAPIUnavailableAndForcedSettingIsNotPositi
|
|||||||
cleanup := testutil.SetupTestDatabases(t)
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
|
||||||
if err := data.SetSetting("rate", "rate.forced_usdt_rate", "0", "string"); err != nil {
|
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0}}`, "json"); err != nil {
|
||||||
t.Fatalf("set rate.forced_usdt_rate: %v", err)
|
t.Fatalf("set rate.forced_rate_list: %v", err)
|
||||||
}
|
}
|
||||||
if err := data.SetSetting("rate", "rate.api_url", "", "string"); err != nil {
|
if err := data.SetSetting("rate", "rate.api_url", "", "string"); err != nil {
|
||||||
t.Fatalf("clear rate.api_url: %v", err)
|
t.Fatalf("clear rate.api_url: %v", err)
|
||||||
@@ -612,6 +665,81 @@ func TestOrderProcessingSubOrderPaidParentKeepsOwnFields(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestOrderProcessingParentDirectPayExpiresOkPayProviderOrder(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if _, err := data.AddWalletAddress("TTestTronAddress001"); err != nil {
|
||||||
|
t.Fatalf("add tron wallet: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
parentReq := newCreateTransactionRequest("order_parent_direct_okpay_expire", 1)
|
||||||
|
parentReq.Network = mdb.NetworkTron
|
||||||
|
parentResp, err := CreateTransaction(parentReq, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create parent order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
subOrder := &mdb.Orders{
|
||||||
|
TradeId: "okpay_sub_parent_direct_expire",
|
||||||
|
OrderId: "okpay_sub_parent_direct_expire",
|
||||||
|
ParentTradeId: parentResp.TradeId,
|
||||||
|
Amount: parentResp.Amount,
|
||||||
|
Currency: parentResp.Currency,
|
||||||
|
ActualAmount: 0.15,
|
||||||
|
ReceiveAddress: "OKPAY",
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
NotifyUrl: "",
|
||||||
|
CallBackConfirm: mdb.CallBackConfirmOk,
|
||||||
|
PayProvider: mdb.PaymentProviderOkPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(subOrder).Error; err != nil {
|
||||||
|
t.Fatalf("create okpay sub-order: %v", err)
|
||||||
|
}
|
||||||
|
providerRow := &mdb.ProviderOrder{
|
||||||
|
TradeId: subOrder.TradeId,
|
||||||
|
Provider: mdb.PaymentProviderOkPay,
|
||||||
|
ProviderOrderID: "okp-parent-direct-expire",
|
||||||
|
PayURL: "https://t.me/ExampleWalletBot?start=shop_deposit--okpay-order-parent-direct-expire",
|
||||||
|
Amount: subOrder.ActualAmount,
|
||||||
|
Coin: subOrder.Token,
|
||||||
|
Status: mdb.ProviderOrderStatusPending,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(providerRow).Error; err != nil {
|
||||||
|
t.Fatalf("create provider row: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = OrderProcessing(&request.OrderProcessingRequest{
|
||||||
|
ReceiveAddress: parentResp.ReceiveAddress,
|
||||||
|
Token: strings.ToUpper(parentResp.Token),
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
TradeId: parentResp.TradeId,
|
||||||
|
Amount: parentResp.ActualAmount,
|
||||||
|
BlockTransactionId: "block_parent_direct_okpay_expire",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("order processing parent direct pay: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expiredSub, err := data.GetOrderInfoByTradeId(subOrder.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload sub-order: %v", err)
|
||||||
|
}
|
||||||
|
if expiredSub.Status != mdb.StatusExpired {
|
||||||
|
t.Fatalf("sub-order status = %d, want %d", expiredSub.Status, mdb.StatusExpired)
|
||||||
|
}
|
||||||
|
|
||||||
|
expiredProviderRow, err := data.GetProviderOrderByTradeIDAndProvider(subOrder.TradeId, mdb.PaymentProviderOkPay)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload provider row: %v", err)
|
||||||
|
}
|
||||||
|
if expiredProviderRow.Status != mdb.ProviderOrderStatusExpired {
|
||||||
|
t.Fatalf("provider row status = %q, want %q", expiredProviderRow.Status, mdb.ProviderOrderStatusExpired)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestOrderProcessingSubOrderExpiresSiblingsAndReleasesLocks verifies that when one
|
// TestOrderProcessingSubOrderExpiresSiblingsAndReleasesLocks verifies that when one
|
||||||
// sub-order is paid all sibling sub-orders are expired and their runtime locks (as
|
// sub-order is paid all sibling sub-orders are expired and their runtime locks (as
|
||||||
// well as the parent's lock) are released.
|
// well as the parent's lock) are released.
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/GMWalletApp/epusdt/config"
|
"github.com/GMWalletApp/epusdt/config"
|
||||||
"github.com/GMWalletApp/epusdt/model/data"
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
|
||||||
"github.com/GMWalletApp/epusdt/model/response"
|
"github.com/GMWalletApp/epusdt/model/response"
|
||||||
|
"github.com/GMWalletApp/epusdt/util/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrOrder = errors.New("不存在待支付订单或已过期")
|
// ErrOrder is returned when checkout initialization cannot find the trade id.
|
||||||
|
var ErrOrder = constant.OrderNotExists
|
||||||
|
|
||||||
// GetCheckoutCounterByTradeId returns checkout info for a pending order.
|
// GetCheckoutCounterByTradeId returns checkout initialization data for an existing order.
|
||||||
|
// It does not decide the payment state; callers should use CheckStatus for that.
|
||||||
func GetCheckoutCounterByTradeId(tradeId string) (*response.CheckoutCounterResponse, error) {
|
func GetCheckoutCounterByTradeId(tradeId string) (*response.CheckoutCounterResponse, error) {
|
||||||
orderInfo, err := data.GetOrderInfoByTradeId(tradeId)
|
orderInfo, err := data.GetOrderInfoByTradeId(tradeId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if orderInfo.ID <= 0 || orderInfo.Status != mdb.StatusWaitPay {
|
if orderInfo.ID <= 0 {
|
||||||
return nil, ErrOrder
|
return nil, ErrOrder
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ import (
|
|||||||
// gProcessedSignatures 已处理签名缓存,避免重复调用 getTransaction
|
// gProcessedSignatures 已处理签名缓存,避免重复调用 getTransaction
|
||||||
var gProcessedSignatures sync.Map // sig -> unix timestamp
|
var gProcessedSignatures sync.Map // sig -> unix timestamp
|
||||||
|
|
||||||
|
var processSolanaOrder = OrderProcessing
|
||||||
|
|
||||||
type TransferInfo struct {
|
type TransferInfo struct {
|
||||||
Source string // Source address (for SOL) or source ATA (for SPL tokens)
|
Source string // Source address (for SOL) or source ATA (for SPL tokens)
|
||||||
Destination string // Destination address (for SOL) or destination ATA (for SPL tokens)
|
Destination string // Destination address (for SOL) or destination ATA (for SPL tokens)
|
||||||
@@ -150,6 +152,7 @@ func SolCallBack(address string, wg *sync.WaitGroup) {
|
|||||||
// Process each transaction signature
|
// Process each transaction signature
|
||||||
for sigIdx, txSig := range result {
|
for sigIdx, txSig := range result {
|
||||||
sig := txSig.Signature
|
sig := txSig.Signature
|
||||||
|
retrySignature := false
|
||||||
|
|
||||||
// Skip failed transactions
|
// Skip failed transactions
|
||||||
if txSig.Err != nil {
|
if txSig.Err != nil {
|
||||||
@@ -213,6 +216,7 @@ func SolCallBack(address string, wg *sync.WaitGroup) {
|
|||||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkSolana, address, token, amount)
|
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkSolana, address, token, amount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Sugar.Errorf("[SOL][%s] sig=%s query transaction_lock failed: %v", address, sig, err)
|
log.Sugar.Errorf("[SOL][%s] sig=%s query transaction_lock failed: %v", address, sig, err)
|
||||||
|
retrySignature = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if tradeID == "" {
|
if tradeID == "" {
|
||||||
@@ -226,6 +230,7 @@ func SolCallBack(address string, wg *sync.WaitGroup) {
|
|||||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Sugar.Errorf("[SOL][%s] sig=%s load order failed for trade_id=%s: %v", address, sig, tradeID, err)
|
log.Sugar.Errorf("[SOL][%s] sig=%s load order failed for trade_id=%s: %v", address, sig, tradeID, err)
|
||||||
|
retrySignature = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
log.Sugar.Infof("[SOL][%s] order loaded: trade_id=%s order_id=%s status=%d created_at_ms=%d",
|
log.Sugar.Infof("[SOL][%s] order loaded: trade_id=%s order_id=%s status=%d created_at_ms=%d",
|
||||||
@@ -252,13 +257,14 @@ func SolCallBack(address string, wg *sync.WaitGroup) {
|
|||||||
}
|
}
|
||||||
log.Sugar.Infof("[SOL][%s] calling OrderProcessing: trade_id=%s sig=%s token=%s amount=%.2f",
|
log.Sugar.Infof("[SOL][%s] calling OrderProcessing: trade_id=%s sig=%s token=%s amount=%.2f",
|
||||||
address, tradeID, sig, token, amount)
|
address, tradeID, sig, token, amount)
|
||||||
err = OrderProcessing(req)
|
err = processSolanaOrder(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
||||||
log.Sugar.Infof("[SOL][%s] sig=%s already resolved: trade_id=%s reason=%v", address, sig, tradeID, err)
|
log.Sugar.Infof("[SOL][%s] sig=%s already resolved: trade_id=%s reason=%v", address, sig, tradeID, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
log.Sugar.Errorf("[SOL][%s] sig=%s OrderProcessing failed for trade_id=%s: %v", address, sig, tradeID, err)
|
log.Sugar.Errorf("[SOL][%s] sig=%s OrderProcessing failed for trade_id=%s: %v", address, sig, tradeID, err)
|
||||||
|
retrySignature = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,6 +274,11 @@ func SolCallBack(address string, wg *sync.WaitGroup) {
|
|||||||
log.Sugar.Infof("[SOL][%s] payment fully processed: trade_id=%s sig=%s", address, tradeID, sig)
|
log.Sugar.Infof("[SOL][%s] payment fully processed: trade_id=%s sig=%s", address, tradeID, sig)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if retrySignature {
|
||||||
|
log.Sugar.Debugf("[SOL][%s] sig=%s not marked processed because retryable processing failed", address, sig)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
// 标记已处理
|
// 标记已处理
|
||||||
gProcessedSignatures.Store(sig, time.Now().Unix())
|
gProcessedSignatures.Store(sig, time.Now().Unix())
|
||||||
}
|
}
|
||||||
@@ -471,7 +482,7 @@ const (
|
|||||||
Token2022ProgramID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
|
Token2022ProgramID = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ADJustAmount 将链上原始金额转为可读金额(除以 10^decimals,保留 2 位小数)
|
// ADJustAmount 将链上原始金额转为可读金额(除以 10^decimals,保留到系统支持的最大匹配精度)
|
||||||
func ADJustAmount(amount uint64, decimals int) float64 {
|
func ADJustAmount(amount uint64, decimals int) float64 {
|
||||||
if amount == 0 {
|
if amount == 0 {
|
||||||
return 0
|
return 0
|
||||||
@@ -480,8 +491,7 @@ func ADJustAmount(amount uint64, decimals int) float64 {
|
|||||||
// 10^decimals
|
// 10^decimals
|
||||||
decimalDivisor := decimal.New(1, int32(decimals))
|
decimalDivisor := decimal.New(1, int32(decimals))
|
||||||
adjustedAmount := decimalAmount.Div(decimalDivisor)
|
adjustedAmount := decimalAmount.Div(decimalDivisor)
|
||||||
// Round to 2 decimal places
|
return math.MustParsePrecFloat64(adjustedAmount.InexactFloat64(), data.MaxAmountPrecision)
|
||||||
return math.MustParsePrecFloat64(adjustedAmount.InexactFloat64(), 2)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func MatchUsdtAtaAddress(address string, ataTo string) bool {
|
func MatchUsdtAtaAddress(address string, ataTo string) bool {
|
||||||
|
|||||||
@@ -2,12 +2,19 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/GMWalletApp/epusdt/internal/testutil"
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
"github.com/GMWalletApp/epusdt/model/dao"
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/request"
|
||||||
"github.com/tidwall/gjson"
|
"github.com/tidwall/gjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -52,6 +59,139 @@ func TestResolveSolanaRpcURLWithRow(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSolCallBackDoesNotCacheSignatureAfterRetryableOrderProcessingError(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
clearProcessedSignatures()
|
||||||
|
t.Cleanup(clearProcessedSignatures)
|
||||||
|
|
||||||
|
const (
|
||||||
|
address = "2uFTf9TZ8gd7Kg6hkb79TxfaeNpaAgpJ8uVHguv2Yweu"
|
||||||
|
sig = "retryable-sol-signature"
|
||||||
|
tradeID = "sol-retryable-order-001"
|
||||||
|
amount = 1.23
|
||||||
|
)
|
||||||
|
blockTime := time.Now().Add(time.Minute).Unix()
|
||||||
|
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var rpcReq struct {
|
||||||
|
Method string `json:"method"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&rpcReq); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
switch rpcReq.Method {
|
||||||
|
case "getSignaturesForAddress":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"result": []map[string]interface{}{
|
||||||
|
{
|
||||||
|
"signature": sig,
|
||||||
|
"slot": 1,
|
||||||
|
"err": nil,
|
||||||
|
"blockTime": blockTime,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
case "getTransaction":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"result": map[string]interface{}{
|
||||||
|
"blockTime": blockTime,
|
||||||
|
"meta": map[string]interface{}{"err": nil},
|
||||||
|
"transaction": map[string]interface{}{
|
||||||
|
"message": map[string]interface{}{
|
||||||
|
"instructions": []map[string]interface{}{
|
||||||
|
{
|
||||||
|
"programId": SystemProgramID,
|
||||||
|
"parsed": map[string]interface{}{
|
||||||
|
"type": "transfer",
|
||||||
|
"info": map[string]interface{}{
|
||||||
|
"source": "source-wallet",
|
||||||
|
"destination": address,
|
||||||
|
"lamports": 1_230_000_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
http.Error(w, "unexpected method "+rpcReq.Method, http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
if err := dao.Mdb.Create(&mdb.RpcNode{
|
||||||
|
Network: mdb.NetworkSolana,
|
||||||
|
Url: server.URL,
|
||||||
|
Type: mdb.RpcNodeTypeHttp,
|
||||||
|
Weight: 1,
|
||||||
|
Enabled: true,
|
||||||
|
Status: mdb.RpcNodeStatusOk,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed solana rpc_node: %v", err)
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(&mdb.ChainToken{
|
||||||
|
Network: mdb.NetworkSolana,
|
||||||
|
Symbol: "SOL",
|
||||||
|
ContractAddress: "",
|
||||||
|
Decimals: SOL_Decimals,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed SOL chain token: %v", err)
|
||||||
|
}
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: tradeID,
|
||||||
|
OrderId: "merchant-sol-retryable-001",
|
||||||
|
Amount: 100,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: amount,
|
||||||
|
ReceiveAddress: address,
|
||||||
|
Token: "SOL",
|
||||||
|
Network: mdb.NetworkSolana,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("seed order: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.LockTransaction(mdb.NetworkSolana, address, "SOL", tradeID, amount, time.Hour); err != nil {
|
||||||
|
t.Fatalf("lock transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
oldProcessSolanaOrder := processSolanaOrder
|
||||||
|
calls := 0
|
||||||
|
processSolanaOrder = func(req *request.OrderProcessingRequest) error {
|
||||||
|
calls++
|
||||||
|
if req.TradeId != tradeID {
|
||||||
|
t.Fatalf("order processing trade_id = %q, want %q", req.TradeId, tradeID)
|
||||||
|
}
|
||||||
|
return errors.New("temporary database error")
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
processSolanaOrder = oldProcessSolanaOrder
|
||||||
|
})
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(1)
|
||||||
|
SolCallBack(address, &wg)
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("order processing calls = %d, want 1", calls)
|
||||||
|
}
|
||||||
|
if _, ok := gProcessedSignatures.Load(sig); ok {
|
||||||
|
t.Fatalf("signature %s was cached after retryable order processing error", sig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSolClientHealthy(t *testing.T) {
|
func TestSolClientHealthy(t *testing.T) {
|
||||||
requireSolanaIntegration(t)
|
requireSolanaIntegration(t)
|
||||||
|
|
||||||
@@ -78,6 +218,13 @@ func TestSolClientHealthy(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func clearProcessedSignatures() {
|
||||||
|
gProcessedSignatures.Range(func(key, value interface{}) bool {
|
||||||
|
gProcessedSignatures.Delete(key)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func TestSolClientGetSignaturesForAddress(t *testing.T) {
|
func TestSolClientGetSignaturesForAddress(t *testing.T) {
|
||||||
requireSolanaIntegration(t)
|
requireSolanaIntegration(t)
|
||||||
|
|
||||||
@@ -236,7 +383,7 @@ func TestAdjustAmount(t *testing.T) {
|
|||||||
name: "USDT amount (6 decimals)",
|
name: "USDT amount (6 decimals)",
|
||||||
amount: 123456789,
|
amount: 123456789,
|
||||||
decimals: 6,
|
decimals: 6,
|
||||||
want: 123.46,
|
want: 123.456789,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "USDC amount (6 decimals)",
|
name: "USDC amount (6 decimals)",
|
||||||
@@ -260,7 +407,7 @@ func TestAdjustAmount(t *testing.T) {
|
|||||||
name: "Small amount",
|
name: "Small amount",
|
||||||
amount: 1,
|
amount: 1,
|
||||||
decimals: 6,
|
decimals: 6,
|
||||||
want: 0.0,
|
want: 0.000001,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,47 +36,64 @@ func ResolveTronNode() (string, string, error) {
|
|||||||
return resolveTronNode()
|
return resolveTronNode()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TryProcessTronTRC20Transfer(toAddr string, rawValue *big.Int, txHash string, blockTsMs int64) {
|
func TryProcessTronTRC20Transfer(token mdb.ChainToken, toAddr string, rawValue *big.Int, txHash string, blockTsMs int64) {
|
||||||
|
tokenSym := strings.ToUpper(strings.TrimSpace(token.Symbol))
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
log.Sugar.Errorf("[TRC20][%s] TryProcessTronTRC20Transfer panic: %v", toAddr, err)
|
log.Sugar.Errorf("[TRC20-%s][%s] TryProcessTronTRC20Transfer panic: %v", tokenSym, toAddr, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
addr := strings.TrimSpace(toAddr)
|
addr := strings.TrimSpace(toAddr)
|
||||||
if addr == "" || rawValue == nil || rawValue.Sign() <= 0 {
|
if tokenSym == "" || addr == "" || rawValue == nil || rawValue.Sign() <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
decimals := token.Decimals
|
||||||
|
if decimals < 0 {
|
||||||
|
decimals = 0
|
||||||
|
}
|
||||||
|
|
||||||
decimalQuant := decimal.NewFromBigInt(rawValue, 0)
|
decimalQuant := decimal.NewFromBigInt(rawValue, 0)
|
||||||
amount := math.MustParsePrecFloat64(decimalQuant.Div(decimal.NewFromInt(1_000_000)).InexactFloat64(), 2)
|
amount := math.MustParsePrecFloat64(decimalQuant.Div(decimal.New(1, int32(decimals))).InexactFloat64(), data.MaxAmountPrecision)
|
||||||
if amount <= 0 {
|
if amount <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if token.MinAmount > 0 && amount < token.MinAmount {
|
||||||
|
log.Sugar.Debugf("[TRC20-%s][%s] skip below min amount hash=%s amount=%.2f min=%.2f", tokenSym, addr, txHash, amount, token.MinAmount)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, addr, "USDT", amount)
|
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, addr, tokenSym, amount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Sugar.Warnf("[TRC20][%s] lock lookup: %v", addr, err)
|
log.Sugar.Warnf("[TRC20-%s][%s] lock lookup: %v", tokenSym, addr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if tradeID == "" {
|
if tradeID == "" {
|
||||||
log.Sugar.Debugf("[TRC20][%s] skip unmatched tx hash=%s amount=%.2f", addr, txHash, amount)
|
log.Sugar.Debugf("[TRC20-%s][%s] skip unmatched tx hash=%s amount=%.2f", tokenSym, addr, txHash, amount)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Sugar.Warnf("[TRC20][%s] load order: %v", addr, err)
|
log.Sugar.Warnf("[TRC20-%s][%s] load order: %v", tokenSym, addr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.ToLower(strings.TrimSpace(order.Network)) != mdb.NetworkTron {
|
||||||
|
log.Sugar.Warnf("[TRC20-%s][%s] skip trade_id=%s network=%q", tokenSym, addr, tradeID, order.Network)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.ToUpper(strings.TrimSpace(order.Token)) != tokenSym {
|
||||||
|
log.Sugar.Warnf("[TRC20-%s][%s] skip trade_id=%s token mismatch order=%s", tokenSym, addr, tradeID, order.Token)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if blockTsMs > 0 && blockTsMs < order.CreatedAt.TimestampMilli() {
|
if blockTsMs > 0 && blockTsMs < order.CreatedAt.TimestampMilli() {
|
||||||
log.Sugar.Warnf("[TRC20][%s] skip tx %s because block time %d is before order create time %d", addr, txHash, blockTsMs, order.CreatedAt.TimestampMilli())
|
log.Sugar.Warnf("[TRC20-%s][%s] skip tx %s because block time %d is before order create time %d", tokenSym, addr, txHash, blockTsMs, order.CreatedAt.TimestampMilli())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
req := &request.OrderProcessingRequest{
|
req := &request.OrderProcessingRequest{
|
||||||
ReceiveAddress: addr,
|
ReceiveAddress: addr,
|
||||||
Token: "USDT",
|
Token: tokenSym,
|
||||||
Network: mdb.NetworkTron,
|
Network: mdb.NetworkTron,
|
||||||
TradeId: tradeID,
|
TradeId: tradeID,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
@@ -85,15 +102,15 @@ func TryProcessTronTRC20Transfer(toAddr string, rawValue *big.Int, txHash string
|
|||||||
err = OrderProcessing(req)
|
err = OrderProcessing(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
||||||
log.Sugar.Infof("[TRC20][%s] skip resolved transfer trade_id=%s hash=%s err=%v", addr, tradeID, txHash, err)
|
log.Sugar.Infof("[TRC20-%s][%s] skip resolved transfer trade_id=%s hash=%s err=%v", tokenSym, addr, tradeID, txHash, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Sugar.Errorf("[TRC20][%s] OrderProcessing trade_id=%s hash=%s: %v", addr, tradeID, txHash, err)
|
log.Sugar.Errorf("[TRC20-%s][%s] OrderProcessing trade_id=%s hash=%s: %v", tokenSym, addr, tradeID, txHash, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sendPaymentNotification(order)
|
sendPaymentNotification(order)
|
||||||
log.Sugar.Infof("[TRC20][%s] payment processed trade_id=%s hash=%s", addr, tradeID, txHash)
|
log.Sugar.Infof("[TRC20-%s][%s] payment processed trade_id=%s hash=%s", tokenSym, addr, tradeID, txHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TryProcessTronTRXTransfer(toAddr string, rawSun int64, txHash string, blockTsMs int64) {
|
func TryProcessTronTRXTransfer(toAddr string, rawSun int64, txHash string, blockTsMs int64) {
|
||||||
@@ -109,7 +126,7 @@ func TryProcessTronTRXTransfer(toAddr string, rawSun int64, txHash string, block
|
|||||||
}
|
}
|
||||||
|
|
||||||
decimalQuant := decimal.NewFromInt(rawSun)
|
decimalQuant := decimal.NewFromInt(rawSun)
|
||||||
amount := math.MustParsePrecFloat64(decimalQuant.Div(decimal.NewFromInt(1_000_000)).InexactFloat64(), 2)
|
amount := math.MustParsePrecFloat64(decimalQuant.Div(decimal.NewFromInt(1_000_000)).InexactFloat64(), data.MaxAmountPrecision)
|
||||||
if amount <= 0 {
|
if amount <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -178,71 +195,42 @@ func TryProcessEvmERC20Transfer(chainNetwork string, contract common.Address, to
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
var usdt, usdc common.Address
|
net := evmChainLogLabel(chainNetwork)
|
||||||
var polygonUsdcE common.Address
|
tokenConfig, err := data.GetEnabledChainTokenByContract(chainNetwork, contract.Hex())
|
||||||
switch chainNetwork {
|
if err != nil {
|
||||||
case mdb.NetworkEthereum:
|
log.Sugar.Warnf("[%s-WS] load chain token contract=%s: %v", net, contract.Hex(), err)
|
||||||
usdt = common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7")
|
|
||||||
usdc = common.HexToAddress("0xA0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
|
|
||||||
case mdb.NetworkBsc:
|
|
||||||
usdt = common.HexToAddress("0x55d398326f99059fF775485246999027B3197955")
|
|
||||||
usdc = common.HexToAddress("0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d")
|
|
||||||
case mdb.NetworkPolygon:
|
|
||||||
usdt = common.HexToAddress("0xc2132D05D31c914a87C6611C10748AEb04B58e8F")
|
|
||||||
usdc = common.HexToAddress("0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359")
|
|
||||||
polygonUsdcE = common.HexToAddress("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174")
|
|
||||||
case mdb.NetworkPlasma:
|
|
||||||
// USDT0(官方),6 decimals;链上暂无与 ETH 同级的 Circle USDC 部署,仅匹配 USDT 订单
|
|
||||||
usdt = common.HexToAddress("0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb")
|
|
||||||
default:
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if tokenConfig == nil || tokenConfig.ID == 0 {
|
||||||
var tokenSym string
|
log.Sugar.Warnf("[%s-WS] skip unconfigured contract %s", net, contract.Hex())
|
||||||
switch {
|
return
|
||||||
case contract == usdt:
|
}
|
||||||
tokenSym = "USDT"
|
tokenSym := strings.ToUpper(strings.TrimSpace(tokenConfig.Symbol))
|
||||||
case contract == usdc || (polygonUsdcE != (common.Address{}) && contract == polygonUsdcE):
|
if tokenSym == "" {
|
||||||
tokenSym = "USDC"
|
log.Sugar.Warnf("[%s-WS] skip contract %s with empty token symbol", net, contract.Hex())
|
||||||
default:
|
|
||||||
net := evmChainLogLabel(chainNetwork)
|
|
||||||
log.Sugar.Warnf("[%s-WS] skip unsupported contract %s", net, contract.Hex())
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
net := evmChainLogLabel(chainNetwork)
|
|
||||||
walletAddr := strings.ToLower(toAddr.Hex())
|
walletAddr := strings.ToLower(toAddr.Hex())
|
||||||
if rawValue == nil || rawValue.Sign() <= 0 {
|
if rawValue == nil || rawValue.Sign() <= 0 {
|
||||||
log.Sugar.Infof("[%s-%s][%s] skip non-positive or nil amount", net, tokenSym, walletAddr)
|
log.Sugar.Infof("[%s-%s][%s] skip non-positive or nil amount", net, tokenSym, walletAddr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
decimals := tokenConfig.Decimals
|
||||||
chainTokens, err := data.ListChainTokens(chainNetwork)
|
if decimals < 0 {
|
||||||
if err != nil {
|
decimals = 0
|
||||||
log.Sugar.Warnf("[%s-%s] load chain tokens: %v", net, tokenSym, err)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
var tokenConfig *mdb.ChainToken
|
pow := decimal.New(1, int32(decimals))
|
||||||
for _, t := range chainTokens {
|
|
||||||
if strings.EqualFold(t.Symbol, tokenSym) {
|
|
||||||
tokenConfig = &t
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if tokenConfig == nil || !tokenConfig.Enabled {
|
|
||||||
log.Sugar.Warnf("[%s-%s] token not enabled or configured in chain_tokens", net, tokenSym)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
pow := decimal.New(1, int32(tokenConfig.Decimals))
|
|
||||||
log.Sugar.Warnf("tokenConfig.Decimals %d pow %s", tokenConfig.Decimals, pow.String())
|
|
||||||
|
|
||||||
decimalQuant := decimal.NewFromBigInt(rawValue, 0)
|
decimalQuant := decimal.NewFromBigInt(rawValue, 0)
|
||||||
amount := math.MustParsePrecFloat64(decimalQuant.Div(pow).InexactFloat64(), 2)
|
amount := math.MustParsePrecFloat64(decimalQuant.Div(pow).InexactFloat64(), data.MaxAmountPrecision)
|
||||||
if amount <= 0 {
|
if amount <= 0 {
|
||||||
log.Sugar.Warnf("[%s-%s][%s] skip non-positive amount %.2f", net, tokenSym, walletAddr, amount)
|
log.Sugar.Warnf("[%s-%s][%s] skip non-positive amount %.2f", net, tokenSym, walletAddr, amount)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if tokenConfig.MinAmount > 0 && amount < tokenConfig.MinAmount {
|
||||||
|
log.Sugar.Debugf("[%s-%s][%s] skip below min amount hash=%s amount=%.2f min=%.2f", net, tokenSym, walletAddr, txHash, amount, tokenConfig.MinAmount)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
log.Sugar.Debugf("[%s-%s][%s] processing transfer hash=%s amount=%.2f", net, tokenSym, walletAddr, txHash, amount)
|
log.Sugar.Debugf("[%s-%s][%s] processing transfer hash=%s amount=%.2f", net, tokenSym, walletAddr, txHash, amount)
|
||||||
|
|
||||||
@@ -269,6 +257,10 @@ func TryProcessEvmERC20Transfer(chainNetwork string, contract common.Address, to
|
|||||||
log.Sugar.Warnf("[%s-%s][%s] skip trade_id=%s token mismatch order=%s", net, tokenSym, walletAddr, tradeID, order.Token)
|
log.Sugar.Warnf("[%s-%s][%s] skip trade_id=%s token mismatch order=%s", net, tokenSym, walletAddr, tradeID, order.Token)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if blockTsMs > 0 && blockTsMs < order.CreatedAt.TimestampMilli() {
|
||||||
|
log.Sugar.Warnf("[%s-%s][%s] skip tx %s because block time %d is before order create time %d", net, tokenSym, walletAddr, txHash, blockTsMs, order.CreatedAt.TimestampMilli())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
req := &request.OrderProcessingRequest{
|
req := &request.OrderProcessingRequest{
|
||||||
ReceiveAddress: walletAddr,
|
ReceiveAddress: walletAddr,
|
||||||
@@ -305,11 +297,13 @@ func sendPaymentNotification(order *mdb.Orders) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
precision := data.GetAmountPrecision()
|
||||||
|
amountFormat := fmt.Sprintf("%%.%df", precision)
|
||||||
msg := fmt.Sprintf(
|
msg := fmt.Sprintf(
|
||||||
"🎉 <b>收款成功通知</b>\n\n"+
|
"🎉 <b>收款成功通知</b>\n\n"+
|
||||||
"💰 <b>金额信息</b>\n"+
|
"💰 <b>金额信息</b>\n"+
|
||||||
"├ 订单金额:<code>%.2f %s</code>\n"+
|
"├ 订单金额:<code>"+amountFormat+" %s</code>\n"+
|
||||||
"└ 实际到账:<code>%.2f %s</code>\n\n"+
|
"└ 实际到账:<code>"+amountFormat+" %s</code>\n\n"+
|
||||||
"📋 <b>订单信息</b>\n"+
|
"📋 <b>订单信息</b>\n"+
|
||||||
"├ 交易号:<code>%s</code>\n"+
|
"├ 交易号:<code>%s</code>\n"+
|
||||||
"├ 订单号:<code>%s</code>\n"+
|
"├ 订单号:<code>%s</code>\n"+
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math/big"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/GMWalletApp/epusdt/internal/testutil"
|
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||||
"github.com/GMWalletApp/epusdt/model/dao"
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"github.com/GMWalletApp/epusdt/notify"
|
"github.com/GMWalletApp/epusdt/notify"
|
||||||
|
"github.com/ethereum/go-ethereum/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSendPaymentNotificationUsesLatestOrderUpdatedAt(t *testing.T) {
|
func TestSendPaymentNotificationUsesLatestOrderUpdatedAt(t *testing.T) {
|
||||||
@@ -77,3 +80,132 @@ func TestSendPaymentNotificationUsesLatestOrderUpdatedAt(t *testing.T) {
|
|||||||
t.Fatal("timed out waiting for notification")
|
t.Fatal("timed out waiting for notification")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTryProcessEvmERC20TransferUsesChainTokenContract(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const (
|
||||||
|
tradeID = "T202605110001"
|
||||||
|
orderID = "ORD202605110001"
|
||||||
|
tokenSym = "FOO"
|
||||||
|
amount = 12.34
|
||||||
|
)
|
||||||
|
contract := common.HexToAddress("0x1111111111111111111111111111111111111111")
|
||||||
|
receiveAddress := common.HexToAddress("0x2222222222222222222222222222222222222222")
|
||||||
|
|
||||||
|
if err := dao.Mdb.Create(&mdb.ChainToken{
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
Symbol: tokenSym,
|
||||||
|
ContractAddress: contract.Hex(),
|
||||||
|
Decimals: 8,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed chain token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: tradeID,
|
||||||
|
OrderId: orderID,
|
||||||
|
Amount: 100,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: amount,
|
||||||
|
Token: tokenSym,
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
ReceiveAddress: strings.ToLower(receiveAddress.Hex()),
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("seed order: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.LockTransaction(mdb.NetworkEthereum, order.ReceiveAddress, order.Token, order.TradeId, order.ActualAmount, time.Hour); err != nil {
|
||||||
|
t.Fatalf("lock transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rawValue := big.NewInt(1_234_000_000) // 12.34 with 8 decimals
|
||||||
|
TryProcessEvmERC20Transfer(mdb.NetworkEthereum, contract, receiveAddress, rawValue, "0xfoo-hash", time.Now().UnixMilli())
|
||||||
|
|
||||||
|
paid, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load paid order: %v", err)
|
||||||
|
}
|
||||||
|
if paid.Status != mdb.StatusPaySuccess {
|
||||||
|
t.Fatalf("order status = %d, want %d", paid.Status, mdb.StatusPaySuccess)
|
||||||
|
}
|
||||||
|
if paid.BlockTransactionId != "0xfoo-hash" {
|
||||||
|
t.Fatalf("block transaction id = %q, want %q", paid.BlockTransactionId, "0xfoo-hash")
|
||||||
|
}
|
||||||
|
|
||||||
|
lockTradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkEthereum, receiveAddress.Hex(), tokenSym, amount)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("lookup released lock: %v", err)
|
||||||
|
}
|
||||||
|
if lockTradeID != "" {
|
||||||
|
t.Fatalf("runtime lock still exists for trade_id=%q", lockTradeID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTryProcessEvmERC20TransferSkipsTransfersBeforeOrderCreation(t *testing.T) {
|
||||||
|
cleanup := testutil.SetupTestDatabases(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
const (
|
||||||
|
tradeID = "T202605110002"
|
||||||
|
orderID = "ORD202605110002"
|
||||||
|
tokenSym = "USDT"
|
||||||
|
amount = 25.5
|
||||||
|
)
|
||||||
|
contract := common.HexToAddress("0x3333333333333333333333333333333333333333")
|
||||||
|
receiveAddress := common.HexToAddress("0x4444444444444444444444444444444444444444")
|
||||||
|
|
||||||
|
if err := dao.Mdb.Create(&mdb.ChainToken{
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
Symbol: tokenSym,
|
||||||
|
ContractAddress: contract.Hex(),
|
||||||
|
Decimals: 6,
|
||||||
|
Enabled: true,
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatalf("seed chain token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: tradeID,
|
||||||
|
OrderId: orderID,
|
||||||
|
Amount: 100,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: amount,
|
||||||
|
Token: tokenSym,
|
||||||
|
Network: mdb.NetworkEthereum,
|
||||||
|
ReceiveAddress: strings.ToLower(receiveAddress.Hex()),
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("seed order: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.LockTransaction(mdb.NetworkEthereum, order.ReceiveAddress, order.Token, order.TradeId, order.ActualAmount, time.Hour); err != nil {
|
||||||
|
t.Fatalf("lock transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rawValue := big.NewInt(25_500_000) // 25.5 with 6 decimals
|
||||||
|
oldBlockTsMs := order.CreatedAt.TimestampMilli() - 1
|
||||||
|
TryProcessEvmERC20Transfer(mdb.NetworkEthereum, contract, receiveAddress, rawValue, "0xold-hash", oldBlockTsMs)
|
||||||
|
|
||||||
|
got, err := data.GetOrderInfoByTradeId(tradeID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("load order: %v", err)
|
||||||
|
}
|
||||||
|
if got.Status != mdb.StatusWaitPay {
|
||||||
|
t.Fatalf("order status = %d, want %d", got.Status, mdb.StatusWaitPay)
|
||||||
|
}
|
||||||
|
if got.BlockTransactionId != "" {
|
||||||
|
t.Fatalf("block transaction id = %q, want empty", got.BlockTransactionId)
|
||||||
|
}
|
||||||
|
|
||||||
|
lockTradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkEthereum, receiveAddress.Hex(), tokenSym, amount)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("lookup retained lock: %v", err)
|
||||||
|
}
|
||||||
|
if lockTradeID != tradeID {
|
||||||
|
t.Fatalf("runtime lock trade_id = %q, want %q", lockTradeID, tradeID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,15 +2,18 @@ package route
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/GMWalletApp/epusdt/config"
|
||||||
"github.com/GMWalletApp/epusdt/model/dao"
|
"github.com/GMWalletApp/epusdt/model/dao"
|
||||||
"github.com/GMWalletApp/epusdt/model/data"
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/service"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -320,6 +323,16 @@ func TestAdminInitPasswordFlow(t *testing.T) {
|
|||||||
if fetchData["password"] != initPassword {
|
if fetchData["password"] != initPassword {
|
||||||
t.Fatalf("expected initial password %s, got %v", initPassword, fetchData["password"])
|
t.Fatalf("expected initial password %s, got %v", initPassword, fetchData["password"])
|
||||||
}
|
}
|
||||||
|
var plaintextRows int64
|
||||||
|
if err := dao.Mdb.Unscoped().
|
||||||
|
Model(&mdb.Setting{}).
|
||||||
|
Where("`key` = ?", mdb.SettingKeyInitAdminPasswordPlain).
|
||||||
|
Count(&plaintextRows).Error; err != nil {
|
||||||
|
t.Fatalf("count init password plaintext rows: %v", err)
|
||||||
|
}
|
||||||
|
if plaintextRows != 0 {
|
||||||
|
t.Fatalf("expected init password plaintext to be hard-deleted, got %d rows", plaintextRows)
|
||||||
|
}
|
||||||
|
|
||||||
recFetch2 := doGet(e, "/admin/api/v1/auth/init-password")
|
recFetch2 := doGet(e, "/admin/api/v1/auth/init-password")
|
||||||
if recFetch2.Code != http.StatusBadRequest {
|
if recFetch2.Code != http.StatusBadRequest {
|
||||||
@@ -647,6 +660,138 @@ func TestAdminOrders_MarkPaidNotFound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdminOrders_MarkPaidSuccessAfterVerification(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "trade-admin-mark-paid-ok",
|
||||||
|
OrderId: "order-admin-mark-paid-ok",
|
||||||
|
Amount: 10,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: 1.23,
|
||||||
|
ReceiveAddress: "TTestTronAddress001",
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
NotifyUrl: "https://merchant.example/notify",
|
||||||
|
PayProvider: mdb.PaymentProviderOnChain,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
verified := false
|
||||||
|
restore := service.SetManualOrderPaymentValidatorForTest(func(got *mdb.Orders, blockID string) (string, error) {
|
||||||
|
verified = true
|
||||||
|
if got.TradeId != order.TradeId {
|
||||||
|
t.Fatalf("validator trade_id = %s, want %s", got.TradeId, order.TradeId)
|
||||||
|
}
|
||||||
|
if blockID != "block-admin-ok" {
|
||||||
|
t.Fatalf("validator block id = %s, want block-admin-ok", blockID)
|
||||||
|
}
|
||||||
|
return "canonical-block-admin-ok", nil
|
||||||
|
})
|
||||||
|
defer restore()
|
||||||
|
|
||||||
|
rec := doPostAdmin(e, "/admin/api/v1/orders/"+order.TradeId+"/mark-paid", map[string]interface{}{
|
||||||
|
"block_transaction_id": "block-admin-ok",
|
||||||
|
}, token)
|
||||||
|
t.Logf("MarkOrderPaid success: status=%d body=%s", rec.Code, rec.Body.String())
|
||||||
|
assertOK(t, rec)
|
||||||
|
if !verified {
|
||||||
|
t.Fatal("expected chain verifier to be called")
|
||||||
|
}
|
||||||
|
|
||||||
|
paid, err := data.GetOrderInfoByTradeId(order.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload order: %v", err)
|
||||||
|
}
|
||||||
|
if paid.Status != mdb.StatusPaySuccess {
|
||||||
|
t.Fatalf("status = %d, want %d", paid.Status, mdb.StatusPaySuccess)
|
||||||
|
}
|
||||||
|
if paid.BlockTransactionId != "canonical-block-admin-ok" {
|
||||||
|
t.Fatalf("block_transaction_id = %q", paid.BlockTransactionId)
|
||||||
|
}
|
||||||
|
if paid.CallBackConfirm != mdb.CallBackConfirmNo {
|
||||||
|
t.Fatalf("callback_confirm = %d, want %d", paid.CallBackConfirm, mdb.CallBackConfirmNo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminOrders_MarkPaidRejectsVerificationFailure(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "trade-admin-mark-paid-bad-proof",
|
||||||
|
OrderId: "order-admin-mark-paid-bad-proof",
|
||||||
|
Amount: 10,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: 1.23,
|
||||||
|
ReceiveAddress: "TTestTronAddress001",
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
NotifyUrl: "https://merchant.example/notify",
|
||||||
|
PayProvider: mdb.PaymentProviderOnChain,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
restore := service.SetManualOrderPaymentValidatorForTest(func(*mdb.Orders, string) (string, error) {
|
||||||
|
return "", errors.New("transaction amount mismatch")
|
||||||
|
})
|
||||||
|
defer restore()
|
||||||
|
|
||||||
|
rec := doPostAdmin(e, "/admin/api/v1/orders/"+order.TradeId+"/mark-paid", map[string]interface{}{
|
||||||
|
"block_transaction_id": "block-admin-bad",
|
||||||
|
}, token)
|
||||||
|
t.Logf("MarkOrderPaid verifier failure: status=%d body=%s", rec.Code, rec.Body.String())
|
||||||
|
if rec.Code == http.StatusOK {
|
||||||
|
t.Fatalf("expected failure, got 200: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
reloaded, err := data.GetOrderInfoByTradeId(order.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload order: %v", err)
|
||||||
|
}
|
||||||
|
if reloaded.Status != mdb.StatusWaitPay || reloaded.BlockTransactionId != "" {
|
||||||
|
t.Fatalf("order changed after failed verification: status=%d block=%q", reloaded.Status, reloaded.BlockTransactionId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminOrders_MarkPaidRejectsNonOnChainOrder(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "trade-admin-mark-paid-provider",
|
||||||
|
OrderId: "order-admin-mark-paid-provider",
|
||||||
|
Amount: 10,
|
||||||
|
Currency: "CNY",
|
||||||
|
ActualAmount: 1.23,
|
||||||
|
ReceiveAddress: "TTestTronAddress001",
|
||||||
|
Token: "USDT",
|
||||||
|
Network: mdb.NetworkTron,
|
||||||
|
Status: mdb.StatusWaitPay,
|
||||||
|
NotifyUrl: "https://merchant.example/notify",
|
||||||
|
PayProvider: mdb.PaymentProviderOkPay,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
called := false
|
||||||
|
restore := service.SetManualOrderPaymentValidatorForTest(func(*mdb.Orders, string) (string, error) {
|
||||||
|
called = true
|
||||||
|
return "block-admin-provider", nil
|
||||||
|
})
|
||||||
|
defer restore()
|
||||||
|
|
||||||
|
rec := doPostAdmin(e, "/admin/api/v1/orders/"+order.TradeId+"/mark-paid", map[string]interface{}{
|
||||||
|
"block_transaction_id": "block-admin-provider",
|
||||||
|
}, token)
|
||||||
|
t.Logf("MarkOrderPaid provider order: status=%d body=%s", rec.Code, rec.Body.String())
|
||||||
|
if rec.Code == http.StatusOK {
|
||||||
|
t.Fatalf("expected failure, got 200: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
t.Fatal("verifier should not run for non-on-chain order")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestAdminOrders_ResendCallbackNotFound verifies resend-callback graceful error.
|
// TestAdminOrders_ResendCallbackNotFound verifies resend-callback graceful error.
|
||||||
func TestAdminOrders_ResendCallbackNotFound(t *testing.T) {
|
func TestAdminOrders_ResendCallbackNotFound(t *testing.T) {
|
||||||
e, token := setupAdminTestEnv(t)
|
e, token := setupAdminTestEnv(t)
|
||||||
@@ -657,6 +802,59 @@ func TestAdminOrders_ResendCallbackNotFound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdminOrders_ResendCallbackRejectsEmptyNotifyURL(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "trade-admin-resend-empty-url",
|
||||||
|
OrderId: "order-admin-resend-empty-url",
|
||||||
|
Status: mdb.StatusPaySuccess,
|
||||||
|
CallBackConfirm: mdb.CallBackConfirmOk,
|
||||||
|
CallbackNum: 3,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := doPostAdmin(e, "/admin/api/v1/orders/"+order.TradeId+"/resend-callback", nil, token)
|
||||||
|
t.Logf("ResendCallback empty notify_url: status=%d body=%s", rec.Code, rec.Body.String())
|
||||||
|
if rec.Code == http.StatusOK {
|
||||||
|
t.Fatalf("expected failure, got 200: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
reloaded, err := data.GetOrderInfoByTradeId(order.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload order: %v", err)
|
||||||
|
}
|
||||||
|
if reloaded.CallBackConfirm != mdb.CallBackConfirmOk || reloaded.CallbackNum != 3 {
|
||||||
|
t.Fatalf("callback state changed: confirm=%d num=%d", reloaded.CallBackConfirm, reloaded.CallbackNum)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminOrders_ResendCallbackRequeuesPaidOrder(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
order := &mdb.Orders{
|
||||||
|
TradeId: "trade-admin-resend-ok",
|
||||||
|
OrderId: "order-admin-resend-ok",
|
||||||
|
Status: mdb.StatusPaySuccess,
|
||||||
|
NotifyUrl: "https://merchant.example/notify",
|
||||||
|
CallBackConfirm: mdb.CallBackConfirmOk,
|
||||||
|
CallbackNum: 3,
|
||||||
|
}
|
||||||
|
if err := dao.Mdb.Create(order).Error; err != nil {
|
||||||
|
t.Fatalf("create order: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := doPostAdmin(e, "/admin/api/v1/orders/"+order.TradeId+"/resend-callback", nil, token)
|
||||||
|
t.Logf("ResendCallback success: status=%d body=%s", rec.Code, rec.Body.String())
|
||||||
|
assertOK(t, rec)
|
||||||
|
reloaded, err := data.GetOrderInfoByTradeId(order.TradeId)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reload order: %v", err)
|
||||||
|
}
|
||||||
|
if reloaded.CallBackConfirm != mdb.CallBackConfirmNo || reloaded.CallbackNum != 0 {
|
||||||
|
t.Fatalf("callback state = confirm %d num %d, want no/0", reloaded.CallBackConfirm, reloaded.CallbackNum)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Dashboard ───────────────────────────────────────────────────────────────
|
// ─── Dashboard ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
// TestAdminDashboard_AllRoutes verifies all dashboard endpoints return 200.
|
// TestAdminDashboard_AllRoutes verifies all dashboard endpoints return 200.
|
||||||
@@ -682,21 +880,150 @@ func TestAdminDashboard_AllRoutes(t *testing.T) {
|
|||||||
func TestAdminSettings_ListAndUpsert(t *testing.T) {
|
func TestAdminSettings_ListAndUpsert(t *testing.T) {
|
||||||
e, token := setupAdminTestEnv(t)
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayShopToken, "token-visible-in-settings", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay.shop_token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
// List settings.
|
// List settings.
|
||||||
rec := doGetAdmin(e, "/admin/api/v1/settings", token)
|
rec := doGetAdmin(e, "/admin/api/v1/settings", token)
|
||||||
t.Logf("ListSettings: %s", rec.Body.String())
|
t.Logf("ListSettings: %s", rec.Body.String())
|
||||||
assertOK(t, rec)
|
resp := assertOK(t, rec)
|
||||||
|
rows, ok := resp["data"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected settings array, got %T", resp["data"])
|
||||||
|
}
|
||||||
|
foundToken := false
|
||||||
|
for _, row := range rows {
|
||||||
|
item, _ := row.(map[string]interface{})
|
||||||
|
if item["key"] == mdb.SettingKeyOkPayShopToken {
|
||||||
|
foundToken = true
|
||||||
|
if item["value"] != "token-visible-in-settings" {
|
||||||
|
t.Fatalf("okpay.shop_token value = %v, want token-visible-in-settings", item["value"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !foundToken {
|
||||||
|
t.Fatalf("expected admin settings list to expose %s", mdb.SettingKeyOkPayShopToken)
|
||||||
|
}
|
||||||
|
|
||||||
// Upsert a setting.
|
// Upsert a setting.
|
||||||
rec = doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
rec = doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
"items": []map[string]interface{}{
|
"items": []map[string]interface{}{
|
||||||
{"group": "rate", "key": "rate.forced_usdt_rate", "value": "7.5", "type": "string"},
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": map[string]interface{}{
|
||||||
|
"cny": map[string]interface{}{"usdt": 0.14635},
|
||||||
|
"usd": map[string]interface{}{"usdt": 1},
|
||||||
|
}, "type": "json"},
|
||||||
},
|
},
|
||||||
}, token)
|
}, token)
|
||||||
t.Logf("UpsertSettings: %s", rec.Body.String())
|
t.Logf("UpsertSettings: %s", rec.Body.String())
|
||||||
assertOK(t, rec)
|
assertOK(t, rec)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdminSettings_ForcedRateListValidation(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
rec := doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": map[string]interface{}{
|
||||||
|
" CNY ": map[string]interface{}{" USDT ": 0.14635},
|
||||||
|
}, "type": "string"},
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": `{"cny":`, "type": "json"},
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": map[string]interface{}{
|
||||||
|
"CNY": map[string]interface{}{"USDT": 0.14635},
|
||||||
|
"cny": map[string]interface{}{"usdt": 0.14636},
|
||||||
|
}, "type": "json"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
resp := assertOK(t, rec)
|
||||||
|
results, ok := resp["data"].([]interface{})
|
||||||
|
if !ok || len(results) != 3 {
|
||||||
|
t.Fatalf("expected three results, got %T %v", resp["data"], resp["data"])
|
||||||
|
}
|
||||||
|
first, _ := results[0].(map[string]interface{})
|
||||||
|
if first["ok"] != true {
|
||||||
|
t.Fatalf("valid forced rate list result = %v", first)
|
||||||
|
}
|
||||||
|
second, _ := results[1].(map[string]interface{})
|
||||||
|
if second["ok"] != false {
|
||||||
|
t.Fatalf("invalid forced rate list result = %v, want ok=false", second)
|
||||||
|
}
|
||||||
|
third, _ := results[2].(map[string]interface{})
|
||||||
|
if third["ok"] != false {
|
||||||
|
t.Fatalf("duplicate forced rate list result = %v, want ok=false", third)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := data.GetSettingString(mdb.SettingKeyRateForcedRateList, ""); got != `{"cny":{"usdt":0.14635}}` {
|
||||||
|
t.Fatalf("forced rate list value = %q", got)
|
||||||
|
}
|
||||||
|
if rate := config.GetRateForCoin("USDT", "CNY"); rate != 0.14635 {
|
||||||
|
t.Fatalf("GetRateForCoin(USDT, CNY) = %v, want 0.14635", rate)
|
||||||
|
}
|
||||||
|
var row mdb.Setting
|
||||||
|
if err := dao.Mdb.Where("`key` = ?", mdb.SettingKeyRateForcedRateList).Take(&row).Error; err != nil {
|
||||||
|
t.Fatalf("load forced rate list: %v", err)
|
||||||
|
}
|
||||||
|
if row.Type != mdb.SettingTypeJSON {
|
||||||
|
t.Fatalf("forced rate list type = %q, want %q", row.Type, mdb.SettingTypeJSON)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminSettings_AmountPrecisionValidationAndListing(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
rec := doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "system", "key": mdb.SettingKeyAmountPrecision, "value": "4", "type": "int"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
resp := assertOK(t, rec)
|
||||||
|
results, ok := resp["data"].([]interface{})
|
||||||
|
if !ok || len(results) != 1 {
|
||||||
|
t.Fatalf("expected one result, got %T %v", resp["data"], resp["data"])
|
||||||
|
}
|
||||||
|
result, _ := results[0].(map[string]interface{})
|
||||||
|
if result["ok"] != true {
|
||||||
|
t.Fatalf("amount precision upsert result = %v", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doGetAdmin(e, "/admin/api/v1/settings?group=system", token)
|
||||||
|
resp = assertOK(t, rec)
|
||||||
|
rows, ok := resp["data"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected settings array, got %T", resp["data"])
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, row := range rows {
|
||||||
|
item, _ := row.(map[string]interface{})
|
||||||
|
if item["key"] == mdb.SettingKeyAmountPrecision {
|
||||||
|
found = true
|
||||||
|
if item["value"] != "4" {
|
||||||
|
t.Fatalf("amount precision value = %v, want 4", item["value"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("expected settings list to include %s", mdb.SettingKeyAmountPrecision)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "system", "key": mdb.SettingKeyAmountPrecision, "value": "7", "type": "int"},
|
||||||
|
{"group": "system", "key": mdb.SettingKeyAmountPrecision, "value": "abc", "type": "int"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
resp = assertOK(t, rec)
|
||||||
|
results, ok = resp["data"].([]interface{})
|
||||||
|
if !ok || len(results) != 2 {
|
||||||
|
t.Fatalf("expected two results, got %T %v", resp["data"], resp["data"])
|
||||||
|
}
|
||||||
|
for _, item := range results {
|
||||||
|
result, _ := item.(map[string]interface{})
|
||||||
|
if result["ok"] != false {
|
||||||
|
t.Fatalf("invalid amount precision result = %v, want ok=false", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestAdminSettings_DeleteNonExistent verifies deleting a non-existent setting.
|
// TestAdminSettings_DeleteNonExistent verifies deleting a non-existent setting.
|
||||||
func TestAdminSettings_DeleteNonExistent(t *testing.T) {
|
func TestAdminSettings_DeleteNonExistent(t *testing.T) {
|
||||||
e, token := setupAdminTestEnv(t)
|
e, token := setupAdminTestEnv(t)
|
||||||
@@ -708,6 +1035,204 @@ func TestAdminSettings_DeleteNonExistent(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdminSettings_DeleteThenReupsertRestoresSetting(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
rec := doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateApiUrl, "value": "https://rate.old.example", "type": "string"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
|
||||||
|
rec = doDeleteAdmin(e, "/admin/api/v1/settings/"+mdb.SettingKeyRateApiUrl, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
if got := data.GetSettingString(mdb.SettingKeyRateApiUrl, "fallback"); got != "fallback" {
|
||||||
|
t.Fatalf("deleted setting still in cache/read path: got %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateApiUrl, "value": "https://rate.new.example", "type": "string"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
|
||||||
|
rec = doGetAdmin(e, "/admin/api/v1/settings?group=rate", token)
|
||||||
|
resp := assertOK(t, rec)
|
||||||
|
rows, ok := resp["data"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected settings array, got %T", resp["data"])
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, row := range rows {
|
||||||
|
item, _ := row.(map[string]interface{})
|
||||||
|
if item["key"] == mdb.SettingKeyRateApiUrl {
|
||||||
|
found = true
|
||||||
|
if item["value"] != "https://rate.new.example" {
|
||||||
|
t.Fatalf("rate.api_url value = %v, want new value", item["value"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("expected settings list to include restored %s", mdb.SettingKeyRateApiUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
var restored mdb.Setting
|
||||||
|
if err := dao.Mdb.Unscoped().Where("`key` = ?", mdb.SettingKeyRateApiUrl).Take(&restored).Error; err != nil {
|
||||||
|
t.Fatalf("load restored setting unscoped: %v", err)
|
||||||
|
}
|
||||||
|
if restored.DeletedAt.Valid {
|
||||||
|
t.Fatalf("restored setting still has deleted_at=%v", restored.DeletedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminSettings_DeleteThenReupsertRestoresForcedRateList(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
rec := doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": map[string]interface{}{
|
||||||
|
"CNY": map[string]interface{}{"USDT": 0.14635},
|
||||||
|
}, "type": "json"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
|
||||||
|
rec = doDeleteAdmin(e, "/admin/api/v1/settings/"+mdb.SettingKeyRateForcedRateList, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
if got := data.GetSettingString(mdb.SettingKeyRateForcedRateList, "fallback"); got != "fallback" {
|
||||||
|
t.Fatalf("deleted forced rate list still in cache/read path: got %q", got)
|
||||||
|
}
|
||||||
|
if got := config.GetRateForCoin("USDT", "CNY"); got != 0 {
|
||||||
|
t.Fatalf("deleted forced rate list still used by rate lookup: got %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": "rate", "key": mdb.SettingKeyRateForcedRateList, "value": map[string]interface{}{
|
||||||
|
"CNY": map[string]interface{}{"USDT": 0.15},
|
||||||
|
}, "type": "json"},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
|
||||||
|
if got := data.GetSettingString(mdb.SettingKeyRateForcedRateList, ""); got != `{"cny":{"usdt":0.15}}` {
|
||||||
|
t.Fatalf("restored forced rate list = %q", got)
|
||||||
|
}
|
||||||
|
if got := config.GetRateForCoin("USDT", "CNY"); got != 0.15 {
|
||||||
|
t.Fatalf("restored forced rate list lookup = %v, want 0.15", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
var restored mdb.Setting
|
||||||
|
if err := dao.Mdb.Unscoped().Where("`key` = ?", mdb.SettingKeyRateForcedRateList).Take(&restored).Error; err != nil {
|
||||||
|
t.Fatalf("load restored forced rate list unscoped: %v", err)
|
||||||
|
}
|
||||||
|
if restored.DeletedAt.Valid {
|
||||||
|
t.Fatalf("restored forced rate list still has deleted_at=%v", restored.DeletedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminConfig_ExposesOkPayCredentials(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupBrand, mdb.SettingKeyBrandCheckoutName, "admin cashier", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed brand.checkout_name: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayEnabled, "true", mdb.SettingTypeBool); err != nil {
|
||||||
|
t.Fatalf("seed okpay.enabled: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayShopID, "shop-admin-1", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay.shop_id: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayShopToken, "token-admin-1", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay.shop_token: %v", err)
|
||||||
|
}
|
||||||
|
if err := data.SetSetting(mdb.SettingGroupOkPay, mdb.SettingKeyOkPayCallbackURL, "https://example.com/notify", mdb.SettingTypeString); err != nil {
|
||||||
|
t.Fatalf("seed okpay.callback_url: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := doGetAdmin(e, "/admin/api/v1/config", token)
|
||||||
|
resp := assertOK(t, rec)
|
||||||
|
dataObj, _ := resp["data"].(map[string]interface{})
|
||||||
|
site, ok := dataObj["site"].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected site object, got %T", dataObj["site"])
|
||||||
|
}
|
||||||
|
if site["cashier_name"] != "admin cashier" {
|
||||||
|
t.Fatalf("cashier_name = %v, want admin cashier", site["cashier_name"])
|
||||||
|
}
|
||||||
|
okpay, ok := dataObj["okpay"].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected okpay object, got %T", dataObj["okpay"])
|
||||||
|
}
|
||||||
|
if okpay["shop_id"] != "shop-admin-1" {
|
||||||
|
t.Fatalf("shop_id = %v, want shop-admin-1", okpay["shop_id"])
|
||||||
|
}
|
||||||
|
if okpay["shop_token"] != "token-admin-1" {
|
||||||
|
t.Fatalf("shop_token = %v, want token-admin-1", okpay["shop_token"])
|
||||||
|
}
|
||||||
|
if okpay["callback_url"] != "https://example.com/notify" {
|
||||||
|
t.Fatalf("callback_url = %v", okpay["callback_url"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdminSettings_UpsertBrandReflectsInConfig(t *testing.T) {
|
||||||
|
e, token := setupAdminTestEnv(t)
|
||||||
|
|
||||||
|
updateBrand := func(cashier, logo, title, support, bgColor, bgImage string) {
|
||||||
|
rec := doPutAdmin(e, "/admin/api/v1/settings", map[string]interface{}{
|
||||||
|
"items": []map[string]interface{}{
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandCheckoutName, "value": cashier, "type": mdb.SettingTypeString},
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandLogoUrl, "value": logo, "type": mdb.SettingTypeString},
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandSiteTitle, "value": title, "type": mdb.SettingTypeString},
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandSupportUrl, "value": support, "type": mdb.SettingTypeString},
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandBackgroundColor, "value": bgColor, "type": mdb.SettingTypeString},
|
||||||
|
{"group": mdb.SettingGroupBrand, "key": mdb.SettingKeyBrandBackgroundImageUrl, "value": bgImage, "type": mdb.SettingTypeString},
|
||||||
|
},
|
||||||
|
}, token)
|
||||||
|
assertOK(t, rec)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertSite := func(path, wantCashier, wantLogo, wantTitle, wantSupport, wantBgColor, wantBgImage string) {
|
||||||
|
rec := doGet(e, path)
|
||||||
|
if strings.HasPrefix(path, "/admin/") {
|
||||||
|
rec = doGetAdmin(e, path, token)
|
||||||
|
}
|
||||||
|
resp := assertOK(t, rec)
|
||||||
|
dataObj, _ := resp["data"].(map[string]interface{})
|
||||||
|
site, ok := dataObj["site"].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s expected site object, got %T", path, dataObj["site"])
|
||||||
|
}
|
||||||
|
if site["cashier_name"] != wantCashier {
|
||||||
|
t.Fatalf("%s cashier_name=%v, want %s", path, site["cashier_name"], wantCashier)
|
||||||
|
}
|
||||||
|
if site["logo_url"] != wantLogo {
|
||||||
|
t.Fatalf("%s logo_url=%v, want %s", path, site["logo_url"], wantLogo)
|
||||||
|
}
|
||||||
|
if site["website_title"] != wantTitle {
|
||||||
|
t.Fatalf("%s website_title=%v, want %s", path, site["website_title"], wantTitle)
|
||||||
|
}
|
||||||
|
if site["support_link"] != wantSupport {
|
||||||
|
t.Fatalf("%s support_link=%v, want %s", path, site["support_link"], wantSupport)
|
||||||
|
}
|
||||||
|
if site["background_color"] != wantBgColor {
|
||||||
|
t.Fatalf("%s background_color=%v, want %s", path, site["background_color"], wantBgColor)
|
||||||
|
}
|
||||||
|
if site["background_image_url"] != wantBgImage {
|
||||||
|
t.Fatalf("%s background_image_url=%v, want %s", path, site["background_image_url"], wantBgImage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateBrand("cashier-v1", "https://cdn.example.com/v1.png", "title-v1", "https://example.com/help-v1", "#111111", "https://cdn.example.com/bg-v1.png")
|
||||||
|
assertSite("/payments/gmpay/v1/config", "cashier-v1", "https://cdn.example.com/v1.png", "title-v1", "https://example.com/help-v1", "#111111", "https://cdn.example.com/bg-v1.png")
|
||||||
|
assertSite("/admin/api/v1/config", "cashier-v1", "https://cdn.example.com/v1.png", "title-v1", "https://example.com/help-v1", "#111111", "https://cdn.example.com/bg-v1.png")
|
||||||
|
|
||||||
|
updateBrand("cashier-v2", "https://cdn.example.com/v2.png", "title-v2", "https://example.com/help-v2", "#222222", "https://cdn.example.com/bg-v2.png")
|
||||||
|
assertSite("/payments/gmpay/v1/config", "cashier-v2", "https://cdn.example.com/v2.png", "title-v2", "https://example.com/help-v2", "#222222", "https://cdn.example.com/bg-v2.png")
|
||||||
|
assertSite("/admin/api/v1/config", "cashier-v2", "https://cdn.example.com/v2.png", "title-v2", "https://example.com/help-v2", "#222222", "https://cdn.example.com/bg-v2.png")
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Notification Channels ───────────────────────────────────────────────────
|
// ─── Notification Channels ───────────────────────────────────────────────────
|
||||||
|
|
||||||
// TestAdminNotificationChannels_CRUD verifies notification channel routes.
|
// TestAdminNotificationChannels_CRUD verifies notification channel routes.
|
||||||
|
|||||||
+6
-5
@@ -45,9 +45,11 @@ func RegisterRoute(e *echo.Echo) {
|
|||||||
// gmpay v1 routes
|
// gmpay v1 routes
|
||||||
gmpayV1 := paymentRoute.Group("/gmpay/v1")
|
gmpayV1 := paymentRoute.Group("/gmpay/v1")
|
||||||
gmpayV1.POST("/order/create-transaction", comm.Ctrl.CreateTransaction, middleware.CheckApiSign())
|
gmpayV1.POST("/order/create-transaction", comm.Ctrl.CreateTransaction, middleware.CheckApiSign())
|
||||||
gmpayV1.GET("/supported-assets", comm.Ctrl.GetSupportedAssets)
|
gmpayV1.GET("/config", comm.Ctrl.GetPublicConfig)
|
||||||
// gmpayV1.GET("/supported-assets/records", comm.Ctrl.ListSupportedAssetRecords)
|
|
||||||
// gmpayV1.GET("/supported-assets/:id", comm.Ctrl.GetSupportedAsset)
|
// okpay v1 routes
|
||||||
|
okpayV1 := paymentRoute.Group("/okpay/v1")
|
||||||
|
okpayV1.POST("/notify", comm.Ctrl.OkPayNotify)
|
||||||
|
|
||||||
// epay v1 routes
|
// epay v1 routes
|
||||||
//
|
//
|
||||||
@@ -222,8 +224,7 @@ func registerAdminRoutes(e *echo.Echo) {
|
|||||||
authed.POST("/notification-channels/:id/status", admin.Ctrl.ChangeNotificationChannelStatus)
|
authed.POST("/notification-channels/:id/status", admin.Ctrl.ChangeNotificationChannelStatus)
|
||||||
authed.DELETE("/notification-channels/:id", admin.Ctrl.DeleteNotificationChannel)
|
authed.DELETE("/notification-channels/:id", admin.Ctrl.DeleteNotificationChannel)
|
||||||
|
|
||||||
// gmpayV1.GET("/supported-assets", comm.Ctrl.GetSupportedAssets)
|
authed.GET("/config", comm.Ctrl.GetPublicConfig) // wrap for admin console, same payload as public endpoint
|
||||||
authed.GET("/supported-assets", comm.Ctrl.GetSupportedAssets) // wrap for admin console, same handler as public endpoint
|
|
||||||
|
|
||||||
// Chains
|
// Chains
|
||||||
authed.GET("/chains", admin.Ctrl.ListChains)
|
authed.GET("/chains", admin.Ctrl.ListChains)
|
||||||
|
|||||||
+806
-46
File diff suppressed because it is too large
Load Diff
@@ -12,13 +12,13 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
tron "github.com/GMWalletApp/epusdt/crypto"
|
tron "github.com/GMWalletApp/epusdt/crypto"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/data"
|
||||||
|
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||||
"github.com/GMWalletApp/epusdt/model/service"
|
"github.com/GMWalletApp/epusdt/model/service"
|
||||||
"github.com/GMWalletApp/epusdt/util/log"
|
"github.com/GMWalletApp/epusdt/util/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// USDT 合约地址 (TRC20 主网)
|
|
||||||
USDTContractHex = "41a614f803b6fd780986a42c78ec9c7f77e6ded13c" // Base58: TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
|
|
||||||
// transfer(address,uint256) 方法签名前4字节
|
// transfer(address,uint256) 方法签名前4字节
|
||||||
TransferMethodID = "a9059cbb"
|
TransferMethodID = "a9059cbb"
|
||||||
|
|
||||||
@@ -46,6 +46,31 @@ func HexToTronAddress(hexAddr string) (string, error) {
|
|||||||
return tron.EncodeCheck(raw), nil
|
return tron.EncodeCheck(raw), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TronAddressToHex(addr string) (string, error) {
|
||||||
|
addr = strings.TrimSpace(addr)
|
||||||
|
if addr == "" {
|
||||||
|
return "", fmt.Errorf("地址为空")
|
||||||
|
}
|
||||||
|
raw, err := tron.DecodeCheck(addr)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(raw) != 21 {
|
||||||
|
return "", fmt.Errorf("地址长度非法: %d bytes", len(raw))
|
||||||
|
}
|
||||||
|
if raw[0] != 0x41 {
|
||||||
|
return "", fmt.Errorf("非法 TRON 主网地址前缀: 0x%x", raw[0])
|
||||||
|
}
|
||||||
|
return strings.ToLower(hex.EncodeToString(raw)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeTronHexAddress(hexAddr string) string {
|
||||||
|
hexAddr = strings.TrimSpace(hexAddr)
|
||||||
|
hexAddr = strings.TrimPrefix(hexAddr, "0x")
|
||||||
|
hexAddr = strings.TrimPrefix(hexAddr, "0X")
|
||||||
|
return strings.ToLower(hexAddr)
|
||||||
|
}
|
||||||
|
|
||||||
type BlockHeader struct {
|
type BlockHeader struct {
|
||||||
RawData struct {
|
RawData struct {
|
||||||
Number int64 `json:"number"`
|
Number int64 `json:"number"`
|
||||||
@@ -89,12 +114,13 @@ type Block struct {
|
|||||||
Transactions []Transaction `json:"transactions"`
|
Transactions []Transaction `json:"transactions"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type USDTTransfer struct {
|
type TRC20Transfer struct {
|
||||||
TxID string
|
TxID string
|
||||||
From string
|
From string
|
||||||
To string
|
To string
|
||||||
Raw *big.Int // 原始数值(6 decimals)
|
Raw *big.Int
|
||||||
Status string
|
Status string
|
||||||
|
Token mdb.ChainToken
|
||||||
}
|
}
|
||||||
|
|
||||||
type TRXTransfer struct {
|
type TRXTransfer struct {
|
||||||
@@ -156,7 +182,33 @@ func GetBlockByNum(baseURL string, apiKey string, num int64) (*Block, error) {
|
|||||||
return &block, json.Unmarshal(b, &block)
|
return &block, json.Unmarshal(b, &block)
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseUSDTTransfer(tx Transaction) *USDTTransfer {
|
func loadTronTRC20TokenMap() map[string]mdb.ChainToken {
|
||||||
|
tokens, err := data.ListEnabledChainTokensByNetwork(mdb.NetworkTron)
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[TRON-BLOCK] load chain_tokens: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tokenMap := make(map[string]mdb.ChainToken)
|
||||||
|
for _, token := range tokens {
|
||||||
|
symbol := strings.ToUpper(strings.TrimSpace(token.Symbol))
|
||||||
|
contractAddress := strings.TrimSpace(token.ContractAddress)
|
||||||
|
if symbol == "TRX" || contractAddress == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
contractHex, err := TronAddressToHex(contractAddress)
|
||||||
|
if err != nil {
|
||||||
|
log.Sugar.Warnf("[TRON-BLOCK] skip invalid TRC20 contract symbol=%s address=%s err=%v", symbol, contractAddress, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tokenMap[contractHex] = token
|
||||||
|
}
|
||||||
|
return tokenMap
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTRC20Transfer(tx Transaction, tokenMap map[string]mdb.ChainToken) *TRC20Transfer {
|
||||||
|
if len(tokenMap) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
if len(tx.RawData.Contract) == 0 {
|
if len(tx.RawData.Contract) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -170,9 +222,9 @@ func parseUSDTTransfer(tx Transaction) *USDTTransfer {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否是 USDT 合约
|
contractHex := normalizeTronHexAddress(val.ContractAddress)
|
||||||
contractHex := strings.ToLower(strings.TrimPrefix(val.ContractAddress, "0x"))
|
token, ok := tokenMap[contractHex]
|
||||||
if contractHex != USDTContractHex {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,12 +265,13 @@ func parseUSDTTransfer(tx Transaction) *USDTTransfer {
|
|||||||
status = tx.Ret[0].ContractRet
|
status = tx.Ret[0].ContractRet
|
||||||
}
|
}
|
||||||
|
|
||||||
return &USDTTransfer{
|
return &TRC20Transfer{
|
||||||
TxID: tx.TxID,
|
TxID: tx.TxID,
|
||||||
From: fromAddr,
|
From: fromAddr,
|
||||||
To: toAddr,
|
To: toAddr,
|
||||||
Raw: amountBig,
|
Raw: amountBig,
|
||||||
Status: status,
|
Status: status,
|
||||||
|
Token: token,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,14 +315,14 @@ func parseTRXTransfer(tx Transaction) *TRXTransfer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func processBlock(block *Block) {
|
func processBlock(block *Block, tokenMap map[string]mdb.ChainToken) {
|
||||||
blockTsMs := block.BlockHeader.RawData.Timestamp
|
blockTsMs := block.BlockHeader.RawData.Timestamp
|
||||||
for _, tx := range block.Transactions {
|
for _, tx := range block.Transactions {
|
||||||
if t := parseUSDTTransfer(tx); t != nil {
|
if t := parseTRC20Transfer(tx, tokenMap); t != nil {
|
||||||
if t.Status != "SUCCESS" {
|
if t.Status != "SUCCESS" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
service.TryProcessTronTRC20Transfer(t.To, t.Raw, t.TxID, blockTsMs)
|
service.TryProcessTronTRC20Transfer(t.Token, t.To, t.Raw, t.TxID, blockTsMs)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if t := parseTRXTransfer(tx); t != nil {
|
if t := parseTRXTransfer(tx); t != nil {
|
||||||
@@ -287,7 +340,7 @@ type Scanner struct {
|
|||||||
lastBlock int64
|
lastBlock int64
|
||||||
// 统计
|
// 统计
|
||||||
totalBlocks int64
|
totalBlocks int64
|
||||||
totalUSDTTxs int64
|
totalTRC20Txs int64
|
||||||
totalTRXTxs int64
|
totalTRXTxs int64
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -314,7 +367,7 @@ func (s *Scanner) Init() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Scanner) Run() {
|
func (s *Scanner) Run() {
|
||||||
log.Sugar.Info("[TRON-BLOCK] start scanning (USDT TRC20 + TRX)")
|
log.Sugar.Info("[TRON-BLOCK] start scanning (TRC20 + TRX)")
|
||||||
ticker := time.NewTicker(PollInterval)
|
ticker := time.NewTicker(PollInterval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
@@ -324,7 +377,7 @@ func (s *Scanner) Run() {
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-statTicker.C:
|
case <-statTicker.C:
|
||||||
log.Sugar.Infof("[TRON-BLOCK] stats blocks=%d usdt=%d trx=%d", s.totalBlocks, s.totalUSDTTxs, s.totalTRXTxs)
|
log.Sugar.Infof("[TRON-BLOCK] stats blocks=%d trc20=%d trx=%d", s.totalBlocks, s.totalTRC20Txs, s.totalTRXTxs)
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
s.poll()
|
s.poll()
|
||||||
}
|
}
|
||||||
@@ -342,6 +395,7 @@ func (s *Scanner) poll() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tokenMap := loadTronTRC20TokenMap()
|
||||||
for num := s.lastBlock + 1; num <= latestNum; num++ {
|
for num := s.lastBlock + 1; num <= latestNum; num++ {
|
||||||
var block *Block
|
var block *Block
|
||||||
if num == latestNum {
|
if num == latestNum {
|
||||||
@@ -354,13 +408,13 @@ func (s *Scanner) poll() {
|
|||||||
}
|
}
|
||||||
time.Sleep(200 * time.Millisecond)
|
time.Sleep(200 * time.Millisecond)
|
||||||
}
|
}
|
||||||
processBlock(block)
|
processBlock(block, tokenMap)
|
||||||
s.lastBlock = num
|
s.lastBlock = num
|
||||||
s.totalBlocks++
|
s.totalBlocks++
|
||||||
|
|
||||||
for _, tx := range block.Transactions {
|
for _, tx := range block.Transactions {
|
||||||
if parseUSDTTransfer(tx) != nil {
|
if parseTRC20Transfer(tx, tokenMap) != nil {
|
||||||
s.totalUSDTTxs++
|
s.totalTRC20Txs++
|
||||||
} else if parseTRXTransfer(tx) != nil {
|
} else if parseTRXTransfer(tx) != nil {
|
||||||
s.totalTRXTxs++
|
s.totalTRXTxs++
|
||||||
}
|
}
|
||||||
@@ -369,10 +423,15 @@ func (s *Scanner) poll() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func StartTronBlockScannerListener() {
|
func StartTronBlockScannerListener() {
|
||||||
|
for {
|
||||||
scanner := NewScanner()
|
scanner := NewScanner()
|
||||||
if err := scanner.Init(); err != nil {
|
if err := scanner.Init(); err != nil {
|
||||||
log.Sugar.Errorf("[TRON-BLOCK] init: %v", err)
|
log.Sugar.Errorf("[TRON-BLOCK] init: %v, retrying...", err)
|
||||||
return
|
time.Sleep(10 * time.Second)
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
scanner.Run()
|
scanner.Run()
|
||||||
|
log.Sugar.Warn("[TRON-BLOCK] scanner stopped, restarting...")
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package task
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestTronAddressToHexConvertsBase58Contract(t *testing.T) {
|
||||||
|
got, err := TronAddressToHex("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TronAddressToHex(): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const want = "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("TronAddressToHex() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeTronHexAddress(t *testing.T) {
|
||||||
|
got := normalizeTronHexAddress("0X41A614F803B6FD780986A42C78EC9C7F77E6DED13C")
|
||||||
|
const want = "41a614f803b6fd780986a42c78ec9c7f77e6ded13c"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("normalizeTronHexAddress() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,9 @@ var Errno = map[int]string{
|
|||||||
10013: "order is not awaiting payment",
|
10013: "order is not awaiting payment",
|
||||||
10014: "chain is not enabled",
|
10014: "chain is not enabled",
|
||||||
10016: "supported asset not found",
|
10016: "supported asset not found",
|
||||||
|
10017: "payment provider is not enabled",
|
||||||
|
10018: "payment provider configuration is incomplete",
|
||||||
|
10019: "payment provider does not support this token or network",
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -38,6 +41,9 @@ var (
|
|||||||
OrderNotWaitPay = Err(10013)
|
OrderNotWaitPay = Err(10013)
|
||||||
ChainNotEnabled = Err(10014)
|
ChainNotEnabled = Err(10014)
|
||||||
SupportedAssetNotFound = Err(10016)
|
SupportedAssetNotFound = Err(10016)
|
||||||
|
PaymentProviderNotEnabled = Err(10017)
|
||||||
|
PaymentProviderConfigErr = Err(10018)
|
||||||
|
PaymentProviderNotSupport = Err(10019)
|
||||||
)
|
)
|
||||||
|
|
||||||
type RspError struct {
|
type RspError struct {
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
import{t as e}from"./unauthorized-error-DKwsOXnK.js";var t=e;export{t as component};
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{t as e}from"./unauthorized-error-DkFdLxfv.js";var t=e;export{t as component};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{t as e}from"./forbidden-CxIEu3wC.js";var t=e;export{t as component};
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{t as e}from"./forbidden-s6H4egxL.js";var t=e;export{t as component};
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{t as e}from"./not-found-error-D9glqlci.js";var t=e;export{t as component};
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{t as e}from"./not-found-error-CZZt4CsO.js";var t=e;export{t as component};
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{t as e}from"./general-error-Cwxn1dbd.js";var t=e;export{t as component};
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{t as e}from"./general-error-BPYa4EqL.js";var t=e;export{t as component};
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{t as e}from"./maintenance-error-_xUDTkL_.js";var t=e;export{t as component};
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{t as e}from"./maintenance-error-Bk0apz-t.js";var t=e;export{t as component};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
|||||||
import{Cd as e,Dd as t,wd as n}from"./messages-Bhh1Viqz.js";import{o as r,s as i,t as a}from"./useRouter-IcH5TSf9.js";import{t as o}from"./useStore-DdaKVvoY.js";import{f as s}from"./ClientOnly-FdPNE-Ha.js";import"./redirect-dE0wk0WH.js";import{a as c,i as l,r as u,s as d,t as f}from"./Match-BoLpbSXg.js";import{n as p}from"./matchContext-ByMpvvGc.js";import{t as m}from"./atom-DI1Bn-1s.js";function h(e){if(typeof document<`u`&&document.querySelector){let t=e.stores.location.get(),n=t.state.__hashScrollIntoViewOptions??!0;if(n&&t.hash!==``){let e=document.getElementById(t.hash);e&&e.scrollIntoView(n)}}}var g=t(n(),1);function _(){let e=a(),t=g.useRef({router:e,mounted:!1}),[n,c]=g.useState(!1),l=o(e.stores.isLoading,e=>e),u=o(e.stores.hasPending,e=>e),f=i(l),p=l||n||u,_=i(p),v=l||u,y=i(v);return e.startTransition=e=>{c(!0),g.startTransition(()=>{e(),c(!1)})},g.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return s(e.latestLocation.publicHref)!==s(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),r(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),r(()=>{f&&!l&&e.emit({type:`onLoad`,...d(e.stores.location.get(),e.stores.resolvedLocation.get())})},[f,e,l]),r(()=>{y&&!v&&e.emit({type:`onBeforeRouteMount`,...d(e.stores.location.get(),e.stores.resolvedLocation.get())})},[v,y,e]),r(()=>{if(_&&!p){let t=d(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),m(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())}),t.hrefChanged&&h(e)}},[p,_,e]),null}var v=e();function y(){let e=a(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,v.jsx)(t,{}):null,r=(0,v.jsxs)(typeof document<`u`&&e.ssr?u:g.Suspense,{fallback:n,children:[(0,v.jsx)(_,{}),(0,v.jsx)(b,{})]});return e.options.InnerWrap?(0,v.jsx)(e.options.InnerWrap,{children:r}):r}function b(){let e=a(),t=o(e.stores.firstId,e=>e),n=o(e.stores.loadedAt,e=>e),r=t?(0,v.jsx)(f,{matchId:t}):null;return(0,v.jsx)(p.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,v.jsx)(l,{getResetKey:()=>n,errorComponent:c,onCatch:void 0,children:r})})}function x(){let e=a();return o(e.stores.matchRouteDeps,e=>e),g.useCallback(t=>{let{pending:n,caseSensitive:r,fuzzy:i,includeSearch:a,...o}=t;return e.matchRoute(o,{pending:n,caseSensitive:r,fuzzy:i,includeSearch:a})},[e])}export{x as n,y as t};
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{r as e}from"./chunk-DECur_0Z.js";import{t}from"./react-CO2uhaBc.js";import{Cf as n}from"./messages-CA0k74Lg.js";import{o as r,s as i,t as a}from"./useRouter-DtTm7XkK.js";import{t as o}from"./useStore-CupyIEEP.js";import{f as s}from"./ClientOnly-DJrTKhNk.js";import"./redirect-DMNGvjzO.js";import{a as c,i as l,r as u,s as d,t as f}from"./Match-CBdZnJ7h.js";import{n as p}from"./matchContext-BFCdcHzo.js";import{t as m}from"./atom-DQpaPCwp.js";function h(e){if(typeof document<`u`&&document.querySelector){let t=e.stores.location.get(),n=t.state.__hashScrollIntoViewOptions??!0;if(n&&t.hash!==``){let e=document.getElementById(t.hash);e&&e.scrollIntoView(n)}}}var g=e(t(),1);function _(){let e=a(),t=g.useRef({router:e,mounted:!1}),[n,c]=g.useState(!1),l=o(e.stores.isLoading,e=>e),u=o(e.stores.hasPending,e=>e),f=i(l),p=l||n||u,_=i(p),v=l||u,y=i(v);return e.startTransition=e=>{c(!0),g.startTransition(()=>{e(),c(!1)})},g.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return s(e.latestLocation.publicHref)!==s(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),r(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),r(()=>{f&&!l&&e.emit({type:`onLoad`,...d(e.stores.location.get(),e.stores.resolvedLocation.get())})},[f,e,l]),r(()=>{y&&!v&&e.emit({type:`onBeforeRouteMount`,...d(e.stores.location.get(),e.stores.resolvedLocation.get())})},[v,y,e]),r(()=>{if(_&&!p){let t=d(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),m(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())}),t.hrefChanged&&h(e)}},[p,_,e]),null}var v=n();function y(){let e=a(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,v.jsx)(t,{}):null,r=(0,v.jsxs)(typeof document<`u`&&e.ssr?u:g.Suspense,{fallback:n,children:[(0,v.jsx)(_,{}),(0,v.jsx)(b,{})]});return e.options.InnerWrap?(0,v.jsx)(e.options.InnerWrap,{children:r}):r}function b(){let e=a(),t=o(e.stores.firstId,e=>e),n=o(e.stores.loadedAt,e=>e),r=t?(0,v.jsx)(f,{matchId:t}):null;return(0,v.jsx)(p.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,v.jsx)(l,{getResetKey:()=>n,errorComponent:c,onCatch:void 0,children:r})})}function x(){let e=a();return o(e.stores.matchRouteDeps,e=>e),g.useCallback(t=>{let{pending:n,caseSensitive:r,fuzzy:i,includeSearch:a,...o}=t;return e.matchRoute(o,{pending:n,caseSensitive:r,fuzzy:i,includeSearch:a})},[e])}export{x as n,y as t};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{h as e}from"./editor.api2-EJ2HlU1X.js";import"./toggleHighContrast-D5DdjvyL.js";var t={},n={},r=class e{static getOrCreate(t){return n[t]||(n[t]=new e(t)),n[t]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((e,t)=>{this._lazyLoadPromiseResolve=e,this._lazyLoadPromiseReject=t})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,t[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}};function i(n){let i=n.id;t[i]=n,e.register(n);let a=r.getOrCreate(i);e.registerTokensProviderFactory(i,{create:async()=>(await a.load()).language}),e.onLanguageEncountered(i,async()=>{let t=await a.load();e.setLanguageConfiguration(i,t.conf)})}export{i as t};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{Cf as e}from"./messages-CA0k74Lg.js";import{m as t}from"./search-provider-DWK6TDJZ.js";import{n,t as r}from"./theme-switch-KnQlFw6B.js";import{t as i}from"./general-error-BPYa4EqL.js";import{t as a}from"./not-found-error-CZZt4CsO.js";import{t as o}from"./_error-D4LX2IBE.js";import{t as s}from"./unauthorized-error-DkFdLxfv.js";import{t as c}from"./forbidden-CxIEu3wC.js";import{t as l}from"./maintenance-error-Bk0apz-t.js";import{n as u,r as d,t as f}from"./header-CPV8ardC.js";var p=e();function m(){let{error:e}=o.useParams(),m={unauthorized:s,forbidden:c,"not-found":a,"internal-server-error":i,"maintenance-error":l}[e]||a;return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(f,{className:`border-b`,fixed:!0,children:[(0,p.jsx)(u,{}),(0,p.jsxs)(`div`,{className:`ms-auto flex items-center space-x-4`,children:[(0,p.jsx)(n,{}),(0,p.jsx)(r,{}),(0,p.jsx)(t,{}),(0,p.jsx)(d,{})]})]}),(0,p.jsx)(`div`,{className:`flex-1 [&>div]:h-full`,children:(0,p.jsx)(m,{})})]})}export{m as component};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/_error-B9-a0cdE.js","assets/search-provider-DWK6TDJZ.js","assets/chunk-DECur_0Z.js","assets/dist-CRowTfGU.js","assets/dist-D_tdgZ66.js","assets/messages-CA0k74Lg.js","assets/react-CO2uhaBc.js","assets/confirm-dialog-BNVecbxK.js","assets/button-CfqkRSM8.js","assets/clsx-D9aGYY3V.js","assets/dist-BfYQgKqf.js","assets/dist-mJssHgzR.js","assets/dist-SPNRXZQu.js","assets/dist-HEKr0dx0.js","assets/es2015-DuM6Ss-a.js","assets/dist-CPm5TblV.js","assets/dist-XIAMhfzx.js","assets/dist-DPvlEg8c.js","assets/dist-DgKWRoFp.js","assets/dist-BOraPTE4.js","assets/dist-BixeH3nX.js","assets/dist-cJGSCQbF.js","assets/separator-DZMLZkQo.js","assets/tooltip-DcWYpxEL.js","assets/dist-CSGBXlDH.js","assets/dist-puuGF5Ru.js","assets/auth-store-CeX2QaQI.js","assets/dist-BJ92XTI_.js","assets/with-selector-DBfssCrY.js","assets/cookies-BzZOQYPw.js","assets/useRouter-DtTm7XkK.js","assets/useNavigate-7u4DX0Ho.js","assets/useStore-CupyIEEP.js","assets/command-BS0F4xWI.js","assets/createLucideIcon-Br0Bd5k2.js","assets/dialog-B3xx2MKo.js","assets/x-BG8b_1Kq.js","assets/skeleton-Dd8Z_2kW.js","assets/wallet-B9YaRua4.js","assets/sun-BwqrnykR.js","assets/shield-check-LJiSka38.js","assets/logo-3EWDGjCa.js","assets/input-Dyq5zXZe.js","assets/font-provider-DWuumz_Z.js","assets/theme-provider-RRpWB-Nr.js","assets/theme-switch-KnQlFw6B.js","assets/dropdown-menu-DzCpLWTE.js","assets/check-DldThLle.js","assets/header-CPV8ardC.js","assets/link-FSeyVZmM.js","assets/ClientOnly-DJrTKhNk.js","assets/forbidden-CxIEu3wC.js","assets/general-error-BPYa4EqL.js","assets/maintenance-error-Bk0apz-t.js","assets/not-found-error-CZZt4CsO.js","assets/unauthorized-error-DkFdLxfv.js"])))=>i.map(i=>d[i]);
|
||||||
|
import{n as e,t}from"./lazyRouteComponent-FYLLYRy0.js";import{t as n}from"./preload-helper-vQKTmgnp.js";var r=e(`/_authenticated/errors/$error`)({component:t(()=>n(()=>import(`./_error-B9-a0cdE.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55])),`component`)});export{r as t};
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/_error-aP8WfZ0L.js","assets/messages-Bhh1Viqz.js","assets/search-provider-Decv_5jQ.js","assets/dist-BTQ1T4Z1.js","assets/dist-DfdMgsbg.js","assets/confirm-dialog-DEI3bDRD.js","assets/button-CMgGM5Zo.js","assets/dist-DCwMhmtb.js","assets/dist-BOgRCYiY.js","assets/dist-BcPwnnrp.js","assets/dist-q78A-MEc.js","assets/es2015-DPp95FAP.js","assets/dist-8IaROFd6.js","assets/dist-DYutcIDs.js","assets/dist-CFWQDH7X.js","assets/dist-LQc8uwm4.js","assets/dist-CBPejFXg.js","assets/dist-CYYy0EBp.js","assets/dist-DB9dWkN8.js","assets/separator-Dp_coI-W.js","assets/tooltip-BmTb484u.js","assets/dist-aKZxtpke.js","assets/dist-Bofa-lcL.js","assets/auth-store-B0MXCdkM.js","assets/dist-bcH04SHd.js","assets/with-selector-Cn8s6enx.js","assets/cookies-DtK8C3EL.js","assets/useRouter-IcH5TSf9.js","assets/useNavigate-BAxMzgsd.js","assets/useStore-DdaKVvoY.js","assets/command-DZRbaUDS.js","assets/createLucideIcon-B033Mmf5.js","assets/x-ZpCeFU3T.js","assets/skeleton-BJZJu227.js","assets/circle-check-BFJeWPCP.js","assets/sun-TG0uyxhT.js","assets/shield-check-CJEjPJqE.js","assets/wallet-BHv0jBxM.js","assets/logo-B5lF0pzp.js","assets/input-BRm9segX.js","assets/font-provider-DlVfsvee.js","assets/theme-provider-BIsY189-.js","assets/theme-switch-D8VX-5g_.js","assets/dropdown-menu-DkKDP9Gn.js","assets/check-BrSI5FnG.js","assets/header-DZp29x0-.js","assets/link-cKoSDPwi.js","assets/ClientOnly-FdPNE-Ha.js","assets/forbidden-s6H4egxL.js","assets/general-error-Cwxn1dbd.js","assets/maintenance-error-_xUDTkL_.js","assets/not-found-error-D9glqlci.js","assets/unauthorized-error-DKwsOXnK.js"])))=>i.map(i=>d[i]);
|
|
||||||
import{n as e,r as t,t as n}from"./preload-helper-B2PzqQRQ.js";var r=t(`/_authenticated/errors/$error`)({component:e(()=>n(()=>import(`./_error-aP8WfZ0L.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52])),`component`)});export{r as t};
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{Cd as e}from"./messages-Bhh1Viqz.js";import{m as t}from"./search-provider-Decv_5jQ.js";import{n,t as r}from"./theme-switch-D8VX-5g_.js";import{t as i}from"./general-error-Cwxn1dbd.js";import{t as a}from"./not-found-error-D9glqlci.js";import{t as o}from"./_error-DcF4FKJZ.js";import{t as s}from"./unauthorized-error-DKwsOXnK.js";import{t as c}from"./forbidden-s6H4egxL.js";import{t as l}from"./maintenance-error-_xUDTkL_.js";import{n as u,r as d,t as f}from"./header-DZp29x0-.js";var p=e();function m(){let{error:e}=o.useParams(),m={unauthorized:s,forbidden:c,"not-found":a,"internal-server-error":i,"maintenance-error":l}[e]||a;return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsxs)(f,{className:`border-b`,fixed:!0,children:[(0,p.jsx)(u,{}),(0,p.jsxs)(`div`,{className:`ms-auto flex items-center space-x-4`,children:[(0,p.jsx)(n,{}),(0,p.jsx)(r,{}),(0,p.jsx)(t,{}),(0,p.jsx)(d,{})]})]}),(0,p.jsx)(`div`,{className:`flex-1 [&>div]:h-full`,children:(0,p.jsx)(m,{})})]})}export{m as component};
|
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
|||||||
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/_trade_id-Q3vN9SK7.js","assets/chunk-DECur_0Z.js","assets/button-CfqkRSM8.js","assets/clsx-D9aGYY3V.js","assets/messages-CA0k74Lg.js","assets/react-CO2uhaBc.js","assets/select-0mb7fNAV.js","assets/dist-CSGBXlDH.js","assets/dist-D_tdgZ66.js","assets/dist-SPNRXZQu.js","assets/dist-HEKr0dx0.js","assets/dist-cJGSCQbF.js","assets/dist-CRowTfGU.js","assets/dist-BOraPTE4.js","assets/dist-XIAMhfzx.js","assets/dist-mJssHgzR.js","assets/es2015-DuM6Ss-a.js","assets/dist-BixeH3nX.js","assets/dist-puuGF5Ru.js","assets/createLucideIcon-Br0Bd5k2.js","assets/check-DldThLle.js","assets/chevron-down-BPPKEraq.js","assets/auth-store-CeX2QaQI.js","assets/dist-BJ92XTI_.js","assets/with-selector-DBfssCrY.js","assets/cookies-BzZOQYPw.js","assets/useNavigate-7u4DX0Ho.js","assets/useRouter-DtTm7XkK.js","assets/copy-to-clipboard--eZunBzP.js","assets/arrow-left-Ck1MERx0.js","assets/radio-group-DkPZzBqR.js","assets/dist-DPvlEg8c.js","assets/dist-CPm5TblV.js","assets/dist-DgKWRoFp.js","assets/loader-circle-DRj7MiMc.js","assets/triangle-alert-D6KmQYVs.js","assets/x-BG8b_1Kq.js","assets/labels-CdV8bTde.js","assets/checkout-model-BfGeSuFW.js"])))=>i.map(i=>d[i]);
|
||||||
|
import{n as e,t}from"./lazyRouteComponent-FYLLYRy0.js";import{t as n}from"./preload-helper-vQKTmgnp.js";var r=e(`/cashier/$trade_id/`)({component:t(()=>n(()=>import(`./_trade_id-Q3vN9SK7.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38])),`component`)});export{r as t};
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/_trade_id-CN7o2QQi.js","assets/messages-Bhh1Viqz.js","assets/button-CMgGM5Zo.js","assets/select-CiLcNbAG.js","assets/dist-aKZxtpke.js","assets/dist-DfdMgsbg.js","assets/dist-BcPwnnrp.js","assets/dist-q78A-MEc.js","assets/dist-DB9dWkN8.js","assets/dist-BTQ1T4Z1.js","assets/dist-CBPejFXg.js","assets/dist-DYutcIDs.js","assets/dist-BOgRCYiY.js","assets/es2015-DPp95FAP.js","assets/dist-CYYy0EBp.js","assets/dist-Bofa-lcL.js","assets/createLucideIcon-B033Mmf5.js","assets/check-BrSI5FnG.js","assets/chevron-down-Bp5qPJdK.js","assets/auth-store-B0MXCdkM.js","assets/dist-bcH04SHd.js","assets/with-selector-Cn8s6enx.js","assets/cookies-DtK8C3EL.js","assets/useNavigate-BAxMzgsd.js","assets/useRouter-IcH5TSf9.js","assets/copy-to-clipboard-BF7uZfYk.js","assets/loader-circle-USrlthPz.js","assets/x-ZpCeFU3T.js"])))=>i.map(i=>d[i]);
|
|
||||||
import{n as e,r as t,t as n}from"./preload-helper-B2PzqQRQ.js";import{t as r}from"./createLucideIcon-B033Mmf5.js";var i=r(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),a=t(`/cashier/$trade_id/`)({component:e(()=>n(()=>import(`./_trade_id-CN7o2QQi.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27])),`component`)});export{i as n,a as t};
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
|||||||
import{Cd as e,Ft as t,It as n,Lt as r,Mt as i,Nt as a,Pt as o,Rt as s,dd as c,fd as l}from"./messages-Bhh1Viqz.js";import{i as u,n as d,t as f}from"./button-CMgGM5Zo.js";import{n as p,r as m}from"./font-provider-DlVfsvee.js";import{n as h}from"./theme-provider-BIsY189-.js";import{t as g}from"./chevron-down-Bp5qPJdK.js";import{n as _,t as v}from"./radio-group-BEhmAVSM.js";import{r as y,s as b}from"./zod-CqUOr1xx.js";import{a as x,c as S,i as C,l as w,n as T,o as E,r as D,s as O,t as k}from"./form-By70kcBQ.js";import{t as A}from"./page-header-CBQ6sv9V.js";import{t as j}from"./show-submitted-data-C7180yzk.js";var M=e(),N=b({theme:y([`light`,`dark`]),font:y(m)});function P(){let{font:e,setFont:r}=p(),{theme:s,setTheme:y}=h(),b={theme:s,font:e},A=w({resolver:S(N),defaultValues:b});function P(t){t.font!==e&&r(t.font),t.theme!==s&&y(t.theme),j(t)}return(0,M.jsx)(k,{...A,children:(0,M.jsxs)(`form`,{className:`space-y-8`,onSubmit:A.handleSubmit(P),children:[(0,M.jsx)(C,{control:A.control,name:`font`,render:({field:e})=>(0,M.jsxs)(x,{children:[(0,M.jsx)(E,{children:n()}),(0,M.jsxs)(`div`,{className:`relative w-max`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(`select`,{className:u(d({variant:`outline`}),`w-50 appearance-none font-normal capitalize`,`dark:bg-background dark:hover:bg-background`),...e,children:m.map(e=>(0,M.jsx)(`option`,{value:e,children:e},e))})}),(0,M.jsx)(g,{className:`absolute inset-e-3 top-2.5 h-4 w-4 opacity-50`})]}),(0,M.jsx)(D,{className:`font-manrope`,children:t()}),(0,M.jsx)(O,{})]})}),(0,M.jsx)(C,{control:A.control,name:`theme`,render:({field:e})=>(0,M.jsxs)(x,{children:[(0,M.jsx)(E,{children:o()}),(0,M.jsx)(D,{children:a()}),(0,M.jsx)(O,{}),(0,M.jsxs)(v,{className:`grid max-w-md grid-cols-2 gap-8 pt-2`,defaultValue:e.value,onValueChange:e.onChange,children:[(0,M.jsx)(x,{children:(0,M.jsxs)(E,{className:`[&:has([data-state=checked])>div]:border-primary`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(_,{className:`sr-only`,value:`light`})}),(0,M.jsx)(`div`,{className:`items-center rounded-md border-2 border-muted p-1 hover:border-accent`,children:(0,M.jsxs)(`div`,{className:`space-y-2 rounded-sm bg-[#ecedef] p-2`,children:[(0,M.jsxs)(`div`,{className:`space-y-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-2 w-20 rounded-lg bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]})]})}),(0,M.jsx)(`span`,{className:`block w-full p-2 text-center font-normal`,children:l()})]})}),(0,M.jsx)(x,{children:(0,M.jsxs)(E,{className:`[&:has([data-state=checked])>div]:border-primary`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(_,{className:`sr-only`,value:`dark`})}),(0,M.jsx)(`div`,{className:`items-center rounded-md border-2 border-muted bg-popover p-1 hover:bg-accent hover:text-accent-foreground`,children:(0,M.jsxs)(`div`,{className:`space-y-2 rounded-sm bg-slate-950 p-2`,children:[(0,M.jsxs)(`div`,{className:`space-y-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-2 w-20 rounded-lg bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]})]})}),(0,M.jsx)(`span`,{className:`block w-full p-2 text-center font-normal`,children:c()})]})})]})]})}),(0,M.jsx)(f,{type:`submit`,children:i()})]})})}function F(){return(0,M.jsx)(A,{description:r(),title:s(),variant:`section`,children:(0,M.jsx)(P,{})})}var I=F;export{I as component};
|
import{Cf as e,cn as t,df as n,dn as r,ff as i,fn as a,ln as o,on as s,sn as c,un as l}from"./messages-CA0k74Lg.js";import{i as u,n as d,t as f}from"./button-CfqkRSM8.js";import{n as p,r as m}from"./font-provider-DWuumz_Z.js";import{n as h}from"./theme-provider-RRpWB-Nr.js";import{t as g}from"./chevron-down-BPPKEraq.js";import{n as _,t as v}from"./radio-group-DkPZzBqR.js";import{r as y,s as b}from"./zod-CtXLSkFW.js";import{a as x,c as S,i as C,l as w,n as T,o as E,r as D,s as O,t as k}from"./form-C3PRruHl.js";import{t as A}from"./page-header-DLBUeYaU.js";import{t as j}from"./show-submitted-data-Idyx5pnC.js";var M=e(),N=b({theme:y([`light`,`dark`]),font:y(m)});function P(){let{font:e,setFont:r}=p(),{theme:a,setTheme:y}=h(),b={theme:a,font:e},A=w({resolver:S(N),defaultValues:b});function P(t){t.font!==e&&r(t.font),t.theme!==a&&y(t.theme),j(t)}return(0,M.jsx)(k,{...A,children:(0,M.jsxs)(`form`,{className:`space-y-8`,onSubmit:A.handleSubmit(P),children:[(0,M.jsx)(C,{control:A.control,name:`font`,render:({field:e})=>(0,M.jsxs)(x,{children:[(0,M.jsx)(E,{children:l()}),(0,M.jsxs)(`div`,{className:`relative w-max`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(`select`,{className:u(d({variant:`outline`}),`w-50 appearance-none font-normal capitalize`,`dark:bg-background dark:hover:bg-background`),...e,children:m.map(e=>(0,M.jsx)(`option`,{value:e,children:e},e))})}),(0,M.jsx)(g,{className:`absolute inset-e-3 top-2.5 h-4 w-4 opacity-50`})]}),(0,M.jsx)(D,{className:`font-manrope`,children:o()}),(0,M.jsx)(O,{})]})}),(0,M.jsx)(C,{control:A.control,name:`theme`,render:({field:e})=>(0,M.jsxs)(x,{children:[(0,M.jsx)(E,{children:t()}),(0,M.jsx)(D,{children:c()}),(0,M.jsx)(O,{}),(0,M.jsxs)(v,{className:`grid max-w-md grid-cols-2 gap-8 pt-2`,defaultValue:e.value,onValueChange:e.onChange,children:[(0,M.jsx)(x,{children:(0,M.jsxs)(E,{className:`[&:has([data-state=checked])>div]:border-primary`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(_,{className:`sr-only`,value:`light`})}),(0,M.jsx)(`div`,{className:`items-center rounded-md border-2 border-muted p-1 hover:border-accent`,children:(0,M.jsxs)(`div`,{className:`space-y-2 rounded-sm bg-[#ecedef] p-2`,children:[(0,M.jsxs)(`div`,{className:`space-y-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-2 w-20 rounded-lg bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-white p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-[#ecedef]`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-[#ecedef]`})]})]})}),(0,M.jsx)(`span`,{className:`block w-full p-2 text-center font-normal`,children:i()})]})}),(0,M.jsx)(x,{children:(0,M.jsxs)(E,{className:`[&:has([data-state=checked])>div]:border-primary`,children:[(0,M.jsx)(T,{children:(0,M.jsx)(_,{className:`sr-only`,value:`dark`})}),(0,M.jsx)(`div`,{className:`items-center rounded-md border-2 border-muted bg-popover p-1 hover:bg-accent hover:text-accent-foreground`,children:(0,M.jsxs)(`div`,{className:`space-y-2 rounded-sm bg-slate-950 p-2`,children:[(0,M.jsxs)(`div`,{className:`space-y-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-2 w-20 rounded-lg bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]}),(0,M.jsxs)(`div`,{className:`flex items-center space-x-2 rounded-md bg-slate-800 p-2 shadow-xs`,children:[(0,M.jsx)(`div`,{className:`h-4 w-4 rounded-full bg-slate-400`}),(0,M.jsx)(`div`,{className:`h-2 w-25 rounded-lg bg-slate-400`})]})]})}),(0,M.jsx)(`span`,{className:`block w-full p-2 text-center font-normal`,children:n()})]})})]})]})}),(0,M.jsx)(f,{type:`submit`,children:s()})]})})}function F(){return(0,M.jsx)(A,{description:r(),title:a(),variant:`section`,children:(0,M.jsx)(P,{})})}var I=F;export{I as component};
|
||||||
@@ -1 +1 @@
|
|||||||
import{t as e}from"./createLucideIcon-B033Mmf5.js";var t=e(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]);export{t};
|
import{t as e}from"./createLucideIcon-Br0Bd5k2.js";var t=e(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]);export{t};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import{r as e}from"./chunk-DECur_0Z.js";import{t}from"./react-CO2uhaBc.js";import{Cf as n}from"./messages-CA0k74Lg.js";var r=e(t(),1),i=n(),a=(0,r.createContext)({isTyping:!1,passwordLength:0,setIsTyping:()=>void 0,setPasswordLength:()=>void 0,setShowPassword:()=>void 0,showPassword:!1});function o({children:e}){let[t,n]=(0,r.useState)(!1),[o,s]=(0,r.useState)(!1),[c,l]=(0,r.useState)(0);return(0,i.jsx)(a.Provider,{value:{isTyping:t,passwordLength:c,setIsTyping:n,setPasswordLength:l,setShowPassword:s,showPassword:o},children:e})}function s(){return(0,r.useContext)(a)}export{s as n,o as t};
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{Cd as e,Dd as t,wd as n}from"./messages-Bhh1Viqz.js";var r=t(n(),1),i=e(),a=(0,r.createContext)({isTyping:!1,passwordLength:0,setIsTyping:()=>void 0,setPasswordLength:()=>void 0,setShowPassword:()=>void 0,showPassword:!1});function o({children:e}){let[t,n]=(0,r.useState)(!1),[o,s]=(0,r.useState)(!1),[c,l]=(0,r.useState)(0);return(0,i.jsx)(a.Provider,{value:{isTyping:t,passwordLength:c,setIsTyping:n,setPasswordLength:l,setShowPassword:s,showPassword:o},children:e})}function s(){return(0,r.useContext)(a)}export{s as n,o as t};
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
import{Cf as e}from"./messages-CA0k74Lg.js";import{i as t,o as n,r}from"./button-CfqkRSM8.js";var i=e(),a=r(`inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap rounded-full border border-transparent px-2 py-0.5 font-medium text-xs transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3`,{variants:{variant:{default:`bg-primary text-primary-foreground [a&]:hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90`,destructive:`bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90`,outline:`border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,ghost:`[a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,link:`text-primary underline-offset-4 [a&]:hover:underline`}},defaultVariants:{variant:`default`}});function o({className:e,variant:r=`default`,asChild:o=!1,...s}){return(0,i.jsx)(o?n:`span`,{className:t(a({variant:r}),e),"data-slot":`badge`,"data-variant":r,...s})}export{o as t};
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{Cd as e}from"./messages-Bhh1Viqz.js";import{i as t,r as n,s as r}from"./button-CMgGM5Zo.js";var i=e(),a=n(`inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap rounded-full border border-transparent px-2 py-0.5 font-medium text-xs transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3`,{variants:{variant:{default:`bg-primary text-primary-foreground [a&]:hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90`,destructive:`bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90`,outline:`border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,ghost:`[a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,link:`text-primary underline-offset-4 [a&]:hover:underline`}},defaultVariants:{variant:`default`}});function o({className:e,variant:n=`default`,asChild:o=!1,...s}){return(0,i.jsx)(o?r:`span`,{className:t(a({variant:n}),e),"data-slot":`badge`,"data-variant":n,...s})}export{o as t};
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
|||||||
import{Cd as e}from"./messages-Bhh1Viqz.js";import{i as t}from"./button-CMgGM5Zo.js";var n=e();function r({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm`,e),"data-slot":`card`,...r})}function i({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6`,e),"data-slot":`card-header`,...r})}function a({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`font-semibold leading-none`,e),"data-slot":`card-title`,...r})}function o({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`text-muted-foreground text-sm`,e),"data-slot":`card-description`,...r})}function s({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`px-6`,e),"data-slot":`card-content`,...r})}export{a,i,s as n,o as r,r as t};
|
import{Cf as e}from"./messages-CA0k74Lg.js";import{i as t}from"./button-CfqkRSM8.js";var n=e();function r({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm`,e),"data-slot":`card`,...r})}function i({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6`,e),"data-slot":`card-header`,...r})}function a({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`font-semibold leading-none`,e),"data-slot":`card-title`,...r})}function o({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`text-muted-foreground text-sm`,e),"data-slot":`card-description`,...r})}function s({className:e,...r}){return(0,n.jsx)(`div`,{className:t(`px-6`,e),"data-slot":`card-content`,...r})}export{a,i,s as n,o as r,r as t};
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user