mirror of
https://github.com/GMWalletApp/epusdt.git
synced 2026-07-07 18:26:16 +00:00
feat: support TON and USDT Jetton payments
- add TON chain, token, RPC, address normalization, and order matching support - add liteclient scanner with masterchain/shard catch-up and Jetton validation - add TON manual payment verification and focused tests
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
tron "github.com/GMWalletApp/epusdt/crypto"
|
||||
"github.com/GMWalletApp/epusdt/model/data"
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
addressutil "github.com/GMWalletApp/epusdt/util/address"
|
||||
"github.com/GMWalletApp/epusdt/util/constant"
|
||||
"github.com/GMWalletApp/epusdt/util/math"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
@@ -23,6 +24,10 @@ import (
|
||||
"github.com/ethereum/go-ethereum/ethclient"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
"github.com/xssnick/tonutils-go/ton"
|
||||
"github.com/xssnick/tonutils-go/ton/jetton"
|
||||
)
|
||||
|
||||
const manualVerifyRequestTimeout = 15 * time.Second
|
||||
@@ -82,6 +87,8 @@ func validateManualOrderPaymentDefault(order *mdb.Orders, blockTransactionID str
|
||||
canonicalTxID, err = validateManualTronPayment(order, txID)
|
||||
case mdb.NetworkSolana:
|
||||
canonicalTxID, err = validateManualSolanaPayment(order, txID)
|
||||
case mdb.NetworkTon:
|
||||
canonicalTxID, err = validateManualTonPayment(order, txID)
|
||||
case mdb.NetworkEthereum, mdb.NetworkBsc, mdb.NetworkPolygon, mdb.NetworkPlasma:
|
||||
canonicalTxID, err = validateManualEvmPayment(order, txID)
|
||||
default:
|
||||
@@ -636,6 +643,245 @@ func tronPostJSON(baseURL, apiKey, path string, body interface{}, out interface{
|
||||
return json.Unmarshal(raw, out)
|
||||
}
|
||||
|
||||
type manualTonTxRef struct {
|
||||
ReceiveRaw string
|
||||
LT uint64
|
||||
HashHex string
|
||||
HasLT bool
|
||||
}
|
||||
|
||||
func validateManualTonPayment(order *mdb.Orders, txID string) (string, error) {
|
||||
ref, err := parseManualTonTxRef(txID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
orderAddr, err := addressutil.ParseTonMainnetAddress(order.ReceiveAddress)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid order receive address: %w", err)
|
||||
}
|
||||
if ref.ReceiveRaw != "" && ref.ReceiveRaw != orderAddr.Raw {
|
||||
return "", fmt.Errorf("transaction recipient mismatch")
|
||||
}
|
||||
|
||||
nodes, err := data.ListManualPaymentRpcCandidates(mdb.NetworkTon, mdb.RpcNodeTypeLite)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return "", fmt.Errorf("no enabled %s %s RPC node configured in rpc_nodes", mdb.NetworkTon, mdb.RpcNodeTypeLite)
|
||||
}
|
||||
|
||||
var verifyErrors []string
|
||||
for _, node := range nodes {
|
||||
api, closeFn, err := dialManualTonClient(node)
|
||||
if err != nil {
|
||||
verifyErrors = append(verifyErrors, fmt.Sprintf("%s: connect: %v", manualRpcNodeLabel(node), err))
|
||||
continue
|
||||
}
|
||||
canonicalID, err := validateManualTonPaymentWithAPI(context.Background(), api, order, orderAddr.Address, ref)
|
||||
closeFn()
|
||||
if err != nil {
|
||||
verifyErrors = append(verifyErrors, fmt.Sprintf("%s: %v", manualRpcNodeLabel(node), err))
|
||||
continue
|
||||
}
|
||||
return canonicalID, nil
|
||||
}
|
||||
if len(verifyErrors) > 0 {
|
||||
return "", fmt.Errorf("manual TON verification failed: %s", strings.Join(verifyErrors, "; "))
|
||||
}
|
||||
return "", fmt.Errorf("no enabled %s %s RPC node configured in rpc_nodes", mdb.NetworkTon, mdb.RpcNodeTypeLite)
|
||||
}
|
||||
|
||||
func parseManualTonTxRef(input string) (manualTonTxRef, error) {
|
||||
raw := strings.TrimSpace(input)
|
||||
if raw == "" {
|
||||
return manualTonTxRef{}, fmt.Errorf("block_transaction_id is required")
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(raw), "ton:") {
|
||||
body := raw[4:]
|
||||
last := strings.LastIndex(body, ":")
|
||||
if last <= 0 || last == len(body)-1 {
|
||||
return manualTonTxRef{}, fmt.Errorf("invalid ton canonical transaction id")
|
||||
}
|
||||
hashHex, err := normalizeTonTxHashHex(body[last+1:])
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, err
|
||||
}
|
||||
left := body[:last]
|
||||
mid := strings.LastIndex(left, ":")
|
||||
if mid <= 0 || mid == len(left)-1 {
|
||||
return manualTonTxRef{}, fmt.Errorf("invalid ton canonical transaction id")
|
||||
}
|
||||
lt, err := parseUint64Strict(left[mid+1:])
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, fmt.Errorf("invalid ton transaction lt")
|
||||
}
|
||||
receiveRaw, err := addressutil.TonRawAddressKey(left[:mid])
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, fmt.Errorf("invalid ton canonical recipient: %w", err)
|
||||
}
|
||||
return manualTonTxRef{ReceiveRaw: receiveRaw, LT: lt, HashHex: hashHex, HasLT: true}, nil
|
||||
}
|
||||
if idx := strings.Index(raw, ":"); idx > 0 {
|
||||
lt, err := parseUint64Strict(raw[:idx])
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, fmt.Errorf("invalid ton transaction lt")
|
||||
}
|
||||
hashHex, err := normalizeTonTxHashHex(raw[idx+1:])
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, err
|
||||
}
|
||||
return manualTonTxRef{LT: lt, HashHex: hashHex, HasLT: true}, nil
|
||||
}
|
||||
hashHex, err := normalizeTonTxHashHex(raw)
|
||||
if err != nil {
|
||||
return manualTonTxRef{}, err
|
||||
}
|
||||
return manualTonTxRef{HashHex: hashHex}, nil
|
||||
}
|
||||
|
||||
func normalizeTonTxHashHex(raw string) (string, error) {
|
||||
hashHex := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(raw, "0x"), "0X")))
|
||||
if len(hashHex) != 64 {
|
||||
return "", fmt.Errorf("invalid ton transaction hash length")
|
||||
}
|
||||
if _, err := hex.DecodeString(hashHex); err != nil {
|
||||
return "", fmt.Errorf("invalid ton transaction hash")
|
||||
}
|
||||
return hashHex, nil
|
||||
}
|
||||
|
||||
func parseUint64Strict(raw string) (uint64, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0, fmt.Errorf("empty integer")
|
||||
}
|
||||
var out uint64
|
||||
for _, ch := range raw {
|
||||
if ch < '0' || ch > '9' {
|
||||
return 0, fmt.Errorf("invalid integer")
|
||||
}
|
||||
out = out*10 + uint64(ch-'0')
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func dialManualTonClient(node mdb.RpcNode) (ton.APIClientWrapped, func(), error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), manualVerifyRequestTimeout)
|
||||
defer cancel()
|
||||
return ConnectTonLiteAPI(ctx, node.Url, manualVerifyRequestTimeout, 3)
|
||||
}
|
||||
|
||||
func validateManualTonPaymentWithAPI(ctx context.Context, api ton.APIClientWrapped, order *mdb.Orders, receive *address.Address, ref manualTonTxRef) (string, error) {
|
||||
master, err := api.CurrentMasterchainInfo(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("fetch current masterchain: %w", err)
|
||||
}
|
||||
txs, err := listManualTonCandidateTransactions(ctx, api, master, receive, ref)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("list ton account transactions: %w", err)
|
||||
}
|
||||
if len(txs) == 0 {
|
||||
return "", fmt.Errorf("transaction not found")
|
||||
}
|
||||
|
||||
state, err := manualTonTokenState(ctx, api, master, receive)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return validateManualTonPaymentCandidates(order, receive, ref, txs, state)
|
||||
}
|
||||
|
||||
func validateManualTonPaymentCandidates(order *mdb.Orders, receive *address.Address, ref manualTonTxRef, txs []*tlb.Transaction, state *manualTonState) (string, error) {
|
||||
if state == nil {
|
||||
state = &manualTonState{jettonWallets: make(map[string]mdb.ChainToken)}
|
||||
}
|
||||
var matched []*TonObservedTransfer
|
||||
for _, tx := range txs {
|
||||
if tx == nil {
|
||||
continue
|
||||
}
|
||||
hashHex := hex.EncodeToString(tx.Hash)
|
||||
if !strings.EqualFold(hashHex, ref.HashHex) {
|
||||
continue
|
||||
}
|
||||
if ref.HasLT && tx.LT != ref.LT {
|
||||
continue
|
||||
}
|
||||
transfer, err := ParseTonInboundTransfer(tx, receive, state.nativeToken, state.jettonWallets)
|
||||
if err != nil || transfer == nil {
|
||||
continue
|
||||
}
|
||||
if err = EnsureTonTransferMatchesOrder(order, transfer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
matched = append(matched, transfer)
|
||||
}
|
||||
if len(matched) == 0 {
|
||||
return "", fmt.Errorf("matching ton transfer to order address not found")
|
||||
}
|
||||
if len(matched) > 1 && !ref.HasLT {
|
||||
return "", fmt.Errorf("ton transaction hash matched multiple recent transactions; submit canonical id or lt:hash")
|
||||
}
|
||||
receiveRaw := addressutil.TonRawAddressObjectKey(receive)
|
||||
return TonCanonicalBlockTransactionID(receiveRaw, matched[0].LT, matched[0].TxHashHex), nil
|
||||
}
|
||||
|
||||
func listManualTonCandidateTransactions(ctx context.Context, api ton.APIClientWrapped, master *ton.BlockIDExt, receive *address.Address, ref manualTonTxRef) ([]*tlb.Transaction, error) {
|
||||
waiter := api.WaitForBlock(master.SeqNo)
|
||||
if ref.HasLT {
|
||||
hashBytes, err := hex.DecodeString(ref.HashHex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return waiter.ListTransactions(ctx, receive, 1, ref.LT, hashBytes)
|
||||
}
|
||||
|
||||
account, err := waiter.GetAccount(ctx, master, receive)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch ton account state: %w", err)
|
||||
}
|
||||
if account == nil || account.LastTxLT == 0 || len(account.LastTxHash) == 0 {
|
||||
return nil, fmt.Errorf("transaction not found")
|
||||
}
|
||||
return waiter.ListTransactions(ctx, receive, 100, account.LastTxLT, account.LastTxHash)
|
||||
}
|
||||
|
||||
type manualTonState struct {
|
||||
nativeToken *mdb.ChainToken
|
||||
jettonWallets map[string]mdb.ChainToken
|
||||
}
|
||||
|
||||
func manualTonTokenState(ctx context.Context, api ton.APIClientWrapped, master *ton.BlockIDExt, receive *address.Address) (*manualTonState, error) {
|
||||
tokens, err := data.ListEnabledChainTokensByNetwork(mdb.NetworkTon)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state := &manualTonState{jettonWallets: make(map[string]mdb.ChainToken)}
|
||||
for i := range tokens {
|
||||
sym := strings.ToUpper(strings.TrimSpace(tokens[i].Symbol))
|
||||
contract := strings.TrimSpace(tokens[i].ContractAddress)
|
||||
if sym == TonNativeSymbol && contract == "" {
|
||||
token := tokens[i]
|
||||
state.nativeToken = &token
|
||||
continue
|
||||
}
|
||||
if contract == "" {
|
||||
continue
|
||||
}
|
||||
masterAddr, err := addressutil.ParseTonMainnetAddress(contract)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
wallet, err := jetton.NewJettonMasterClient(api, masterAddr.Address).GetJettonWalletAtBlock(ctx, receive, master)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
state.jettonWallets[addressutil.TonRawAddressObjectKey(wallet.Address())] = tokens[i]
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func validateManualSolanaPayment(order *mdb.Orders, sig string) (string, error) {
|
||||
sig = strings.TrimSpace(sig)
|
||||
nodes, err := data.ListManualPaymentRpcCandidates(mdb.NetworkSolana, mdb.RpcNodeTypeHttp)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -16,11 +18,33 @@ import (
|
||||
"github.com/GMWalletApp/epusdt/internal/testutil"
|
||||
"github.com/GMWalletApp/epusdt/model/dao"
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
addressutil "github.com/GMWalletApp/epusdt/util/address"
|
||||
"github.com/dromara/carbon/v2"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
"github.com/xssnick/tonutils-go/ton"
|
||||
"github.com/xssnick/tonutils-go/ton/jetton"
|
||||
"github.com/xssnick/tonutils-go/tvm/cell"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func upsertTestChainToken(t *testing.T, token mdb.ChainToken) {
|
||||
t.Helper()
|
||||
if err := dao.Mdb.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "network"}, {Name: "symbol"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"contract_address",
|
||||
"decimals",
|
||||
"enabled",
|
||||
"min_amount",
|
||||
}),
|
||||
}).Create(&token).Error; err != nil {
|
||||
t.Fatalf("upsert token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualVerifyEvmHashAcceptsOptional0x(t *testing.T) {
|
||||
hash := strings.Repeat("a", 64)
|
||||
if !isEvmHash(hash) {
|
||||
@@ -89,6 +113,215 @@ func TestManualVerifyNormalizeTronTxIDAcceptsOptional0x(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseManualTonTxRefAcceptsCanonicalLTAndHashOnly(t *testing.T) {
|
||||
receiveRaw := "0:ba295e33b3c4c9b5265aa4ead1166a92931ce9abea120a8c5e91044a1257f89c"
|
||||
hash := strings.Repeat("a", 64)
|
||||
|
||||
ref, err := parseManualTonTxRef("ton:" + receiveRaw + ":123:" + strings.ToUpper(hash))
|
||||
if err != nil {
|
||||
t.Fatalf("parse canonical TON tx ref: %v", err)
|
||||
}
|
||||
if ref.ReceiveRaw != receiveRaw || ref.LT != 123 || ref.HashHex != hash || !ref.HasLT {
|
||||
t.Fatalf("canonical ref = %#v", ref)
|
||||
}
|
||||
|
||||
ref, err = parseManualTonTxRef("456:0X" + strings.ToUpper(hash))
|
||||
if err != nil {
|
||||
t.Fatalf("parse lt:hash TON tx ref: %v", err)
|
||||
}
|
||||
if ref.ReceiveRaw != "" || ref.LT != 456 || ref.HashHex != hash || !ref.HasLT {
|
||||
t.Fatalf("lt:hash ref = %#v", ref)
|
||||
}
|
||||
|
||||
ref, err = parseManualTonTxRef("0X" + strings.ToUpper(hash))
|
||||
if err != nil {
|
||||
t.Fatalf("parse hash-only TON tx ref: %v", err)
|
||||
}
|
||||
if ref.ReceiveRaw != "" || ref.LT != 0 || ref.HashHex != hash || ref.HasLT {
|
||||
t.Fatalf("hash-only ref = %#v", ref)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeManualTonAPI struct {
|
||||
ton.APIClientWrapped
|
||||
master *ton.BlockIDExt
|
||||
account *tlb.Account
|
||||
txs []*tlb.Transaction
|
||||
getAccountCalls int
|
||||
listCalls []manualTonListCall
|
||||
}
|
||||
|
||||
type manualTonListCall struct {
|
||||
limit uint32
|
||||
lt uint64
|
||||
hashHex string
|
||||
}
|
||||
|
||||
func (f *fakeManualTonAPI) CurrentMasterchainInfo(context.Context) (*ton.BlockIDExt, error) {
|
||||
return f.master, nil
|
||||
}
|
||||
|
||||
func (f *fakeManualTonAPI) WaitForBlock(uint32) ton.APIClientWrapped {
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeManualTonAPI) GetAccount(context.Context, *ton.BlockIDExt, *address.Address) (*tlb.Account, error) {
|
||||
f.getAccountCalls++
|
||||
if f.account == nil {
|
||||
return &tlb.Account{}, nil
|
||||
}
|
||||
return f.account, nil
|
||||
}
|
||||
|
||||
func (f *fakeManualTonAPI) ListTransactions(_ context.Context, _ *address.Address, limit uint32, lt uint64, txHash []byte) ([]*tlb.Transaction, error) {
|
||||
f.listCalls = append(f.listCalls, manualTonListCall{
|
||||
limit: limit,
|
||||
lt: lt,
|
||||
hashHex: hex.EncodeToString(txHash),
|
||||
})
|
||||
return f.txs, nil
|
||||
}
|
||||
|
||||
func TestValidateManualTonPaymentWithAPINativeTON(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := dao.Mdb.Model(&mdb.ChainToken{}).
|
||||
Where("network = ? AND symbol = ?", mdb.NetworkTon, "USDT").
|
||||
Update("enabled", false).Error; err != nil {
|
||||
t.Fatalf("disable TON USDT token: %v", err)
|
||||
}
|
||||
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x66}, 32)).Bounce(false).Testnet(false)
|
||||
tx := tonTestInboundTx(t, sender, receive, tlb.MustFromTON("1.23"), nil)
|
||||
order := &mdb.Orders{
|
||||
BaseModel: mdb.BaseModel{ID: 1, CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().Add(-time.Minute).UnixMilli()))},
|
||||
Network: mdb.NetworkTon,
|
||||
Token: "TON",
|
||||
ActualAmount: 1.23,
|
||||
ReceiveAddress: receive.Bounce(false).String(),
|
||||
}
|
||||
api := &fakeManualTonAPI{
|
||||
master: &ton.BlockIDExt{Workchain: address.MasterchainID, Shard: -0x8000000000000000, SeqNo: 9},
|
||||
txs: []*tlb.Transaction{tx},
|
||||
}
|
||||
ref := manualTonTxRef{LT: tx.LT, HashHex: hex.EncodeToString(tx.Hash), HasLT: true}
|
||||
|
||||
got, err := validateManualTonPaymentWithAPI(context.Background(), api, order, receive, ref)
|
||||
if err != nil {
|
||||
t.Fatalf("validateManualTonPaymentWithAPI(): %v", err)
|
||||
}
|
||||
if api.getAccountCalls != 0 {
|
||||
t.Fatalf("exact TON ref fetched account state %d times, want 0", api.getAccountCalls)
|
||||
}
|
||||
if len(api.listCalls) != 1 {
|
||||
t.Fatalf("ListTransactions calls = %#v, want one exact lookup", api.listCalls)
|
||||
}
|
||||
if call := api.listCalls[0]; call.limit != 1 || call.lt != tx.LT || call.hashHex != hex.EncodeToString(tx.Hash) {
|
||||
t.Fatalf("ListTransactions exact call = %#v, want limit=1 lt/hash from ref", call)
|
||||
}
|
||||
want := TonCanonicalBlockTransactionID(receive.StringRaw(), tx.LT, hex.EncodeToString(tx.Hash))
|
||||
if got != want {
|
||||
t.Fatalf("canonical id = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateManualTonPaymentCandidatesUSDTJetton(t *testing.T) {
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x68}, 32)).Bounce(false).Testnet(false)
|
||||
jettonWallet := address.NewAddress(0, 0, bytes.Repeat([]byte{0x69}, 32)).Bounce(false).Testnet(false)
|
||||
body, err := tlb.ToCell(jetton.TransferNotification{
|
||||
QueryID: 7,
|
||||
Amount: tlb.MustFromNano(big.NewInt(1_000_000), 6),
|
||||
Sender: sender,
|
||||
ForwardPayload: cell.BeginCell().EndCell(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build jetton notification body: %v", err)
|
||||
}
|
||||
tx := tonTestInboundTx(t, jettonWallet, receive, tlb.FromNanoTONU(1), body)
|
||||
order := &mdb.Orders{
|
||||
BaseModel: mdb.BaseModel{ID: 1, CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().Add(-time.Minute).UnixMilli()))},
|
||||
Network: mdb.NetworkTon,
|
||||
Token: "USDT",
|
||||
ActualAmount: 1,
|
||||
ReceiveAddress: receive.Bounce(false).String(),
|
||||
}
|
||||
state := &manualTonState{
|
||||
jettonWallets: map[string]mdb.ChainToken{
|
||||
addressutil.TonRawAddressObjectKey(jettonWallet): {
|
||||
BaseModel: mdb.BaseModel{ID: 2},
|
||||
Network: mdb.NetworkTon,
|
||||
Symbol: "USDT",
|
||||
Decimals: 6,
|
||||
Enabled: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := validateManualTonPaymentCandidates(order, receive, manualTonTxRef{
|
||||
LT: tx.LT,
|
||||
HashHex: hex.EncodeToString(tx.Hash),
|
||||
HasLT: true,
|
||||
}, []*tlb.Transaction{tx}, state)
|
||||
if err != nil {
|
||||
t.Fatalf("validateManualTonPaymentCandidates(): %v", err)
|
||||
}
|
||||
want := TonCanonicalBlockTransactionID(receive.StringRaw(), tx.LT, hex.EncodeToString(tx.Hash))
|
||||
if got != want {
|
||||
t.Fatalf("canonical id = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateManualTonPaymentWithAPIRejectsAmbiguousHashOnly(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := dao.Mdb.Model(&mdb.ChainToken{}).
|
||||
Where("network = ? AND symbol = ?", mdb.NetworkTon, "USDT").
|
||||
Update("enabled", false).Error; err != nil {
|
||||
t.Fatalf("disable TON USDT token: %v", err)
|
||||
}
|
||||
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x67}, 32)).Bounce(false).Testnet(false)
|
||||
tx1 := tonTestInboundTx(t, sender, receive, tlb.MustFromTON("1.23"), nil)
|
||||
tx2 := tonTestInboundTx(t, sender, receive, tlb.MustFromTON("1.23"), nil)
|
||||
tx2.LT = tx1.LT + 1
|
||||
order := &mdb.Orders{
|
||||
BaseModel: mdb.BaseModel{ID: 1, CreatedAt: *carbon.NewTime(carbon.CreateFromTimestampMilli(time.Now().Add(-time.Minute).UnixMilli()))},
|
||||
Network: mdb.NetworkTon,
|
||||
Token: "TON",
|
||||
ActualAmount: 1.23,
|
||||
ReceiveAddress: receive.Bounce(false).String(),
|
||||
}
|
||||
api := &fakeManualTonAPI{
|
||||
master: &ton.BlockIDExt{Workchain: address.MasterchainID, Shard: -0x8000000000000000, SeqNo: 9},
|
||||
account: &tlb.Account{
|
||||
LastTxLT: tx2.LT,
|
||||
LastTxHash: tx2.Hash,
|
||||
},
|
||||
txs: []*tlb.Transaction{tx1, tx2},
|
||||
}
|
||||
|
||||
_, err := validateManualTonPaymentWithAPI(context.Background(), api, order, receive, manualTonTxRef{
|
||||
HashHex: hex.EncodeToString(tx1.Hash),
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "matched multiple") {
|
||||
t.Fatalf("validate ambiguous hash-only error = %v, want multiple-match error", err)
|
||||
}
|
||||
if api.getAccountCalls != 1 {
|
||||
t.Fatalf("hash-only TON ref fetched account state %d times, want 1", api.getAccountCalls)
|
||||
}
|
||||
if len(api.listCalls) != 1 {
|
||||
t.Fatalf("ListTransactions calls = %#v, want one recent lookup", api.listCalls)
|
||||
}
|
||||
if call := api.listCalls[0]; call.limit != 100 || call.lt != tx2.LT || call.hashHex != hex.EncodeToString(tx2.Hash) {
|
||||
t.Fatalf("ListTransactions recent call = %#v, want account last tx cursor", call)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualVerifyDialEvmClientsIncludesHTTPNode(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
@@ -369,15 +602,13 @@ func TestManualVerifyTronTRC20UsesTransferEvent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("recipient address: %v", err)
|
||||
}
|
||||
if err = dao.Mdb.Create(&mdb.ChainToken{
|
||||
upsertTestChainToken(t, 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)
|
||||
@@ -491,15 +722,13 @@ func TestManualVerifyTronPaymentHTTPFlow(t *testing.T) {
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create tron rpc node: %v", err)
|
||||
}
|
||||
if err = dao.Mdb.Create(&mdb.ChainToken{
|
||||
upsertTestChainToken(t, 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",
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
"github.com/GMWalletApp/epusdt/model/request"
|
||||
"github.com/GMWalletApp/epusdt/model/response"
|
||||
addressutil "github.com/GMWalletApp/epusdt/util/address"
|
||||
"github.com/GMWalletApp/epusdt/util/constant"
|
||||
"github.com/GMWalletApp/epusdt/util/log"
|
||||
"github.com/GMWalletApp/epusdt/util/math"
|
||||
@@ -48,11 +49,27 @@ func normalizeOrderAddressByNetwork(network, address string) string {
|
||||
switch network {
|
||||
case mdb.NetworkEthereum, mdb.NetworkBsc, mdb.NetworkPolygon, mdb.NetworkPlasma:
|
||||
return strings.ToLower(address)
|
||||
case mdb.NetworkTon:
|
||||
if normalized, err := addressutil.NormalizeTonAddress(address); err == nil {
|
||||
return normalized
|
||||
}
|
||||
return address
|
||||
default:
|
||||
return address
|
||||
}
|
||||
}
|
||||
|
||||
func ensureEnabledOrderAsset(network, token string) (*mdb.ChainToken, error) {
|
||||
tokenRow, err := data.GetEnabledChainTokenBySymbol(network, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tokenRow == nil || tokenRow.ID == 0 {
|
||||
return nil, constant.SupportedAssetNotFound
|
||||
}
|
||||
return tokenRow, nil
|
||||
}
|
||||
|
||||
// CreateTransaction creates a new payment order.
|
||||
func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey) (*response.CreateTransactionResponse, error) {
|
||||
token := strings.ToUpper(strings.TrimSpace(req.Token))
|
||||
@@ -68,6 +85,21 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
||||
|
||||
amountPrecision := data.GetAmountPrecision()
|
||||
payAmount := math.MustParsePrecFloat64(req.Amount, amountPrecision)
|
||||
exist, err := data.GetOrderInfoByOrderId(req.OrderId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if exist.ID > 0 {
|
||||
return nil, constant.OrderAlreadyExists
|
||||
}
|
||||
|
||||
if !data.IsChainEnabled(network) {
|
||||
return nil, constant.ChainNotEnabled
|
||||
}
|
||||
if _, err = ensureEnabledOrderAsset(network, token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(currency))
|
||||
if rate <= 0 {
|
||||
return nil, constant.RateAmountErr
|
||||
@@ -82,17 +114,6 @@ func CreateTransaction(req *request.CreateTransactionRequest, apiKey *mdb.ApiKey
|
||||
return nil, constant.PayAmountErr
|
||||
}
|
||||
|
||||
exist, err := data.GetOrderInfoByOrderId(req.OrderId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if exist.ID > 0 {
|
||||
return nil, constant.OrderAlreadyExists
|
||||
}
|
||||
|
||||
if !data.IsChainEnabled(network) {
|
||||
return nil, constant.ChainNotEnabled
|
||||
}
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(network)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -485,7 +506,16 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
||||
return nil, constant.SubOrderLimitExceeded
|
||||
}
|
||||
|
||||
// 5. Calculate amount for the new network
|
||||
// 5. Validate the target chain and asset before any rate lookup so
|
||||
// disabled/unknown tokens return the stable unsupported-asset error.
|
||||
if !data.IsChainEnabled(network) {
|
||||
return nil, constant.ChainNotEnabled
|
||||
}
|
||||
if _, err = ensureEnabledOrderAsset(network, token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 6. Calculate amount for the new network
|
||||
rate := config.GetRateForCoin(strings.ToLower(token), strings.ToLower(parent.Currency))
|
||||
if rate <= 0 {
|
||||
return nil, constant.RateAmountErr
|
||||
@@ -496,10 +526,7 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
||||
return nil, constant.PayAmountErr
|
||||
}
|
||||
|
||||
// 6. Find and lock wallet
|
||||
if !data.IsChainEnabled(network) {
|
||||
return nil, constant.ChainNotEnabled
|
||||
}
|
||||
// 7. Find and lock wallet
|
||||
walletAddress, err := data.GetAvailableWalletAddressByNetwork(network)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -518,7 +545,7 @@ func SwitchNetwork(req *request.SwitchNetworkRequest) (*response.CheckoutCounter
|
||||
return nil, constant.NotAvailableAmountErr
|
||||
}
|
||||
|
||||
// 7. Create sub-order
|
||||
// 8. Create sub-order
|
||||
tx := dao.Mdb.Begin()
|
||||
subOrder := &mdb.Orders{
|
||||
TradeId: subTradeID,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"github.com/GMWalletApp/epusdt/util/constant"
|
||||
"github.com/GMWalletApp/epusdt/util/http_client"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
)
|
||||
|
||||
func newCreateTransactionRequest(orderID string, amount float64) *request.CreateTransactionRequest {
|
||||
@@ -281,6 +283,424 @@ func TestCreateTransactionNormalizesEvmReceiveAddressToLowercase(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTransactionCreatesTonOrderAndRawLock(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"ton":0.5}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
wallet, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw())
|
||||
if err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
|
||||
req := newCreateTransactionRequest("order_ton_native_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
|
||||
resp, err := CreateTransaction(req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create TON transaction: %v", err)
|
||||
}
|
||||
if resp.ReceiveAddress != wallet.Address {
|
||||
t.Fatalf("receive address = %q, want %q", resp.ReceiveAddress, wallet.Address)
|
||||
}
|
||||
if resp.Token != "TON" {
|
||||
t.Fatalf("token = %q, want TON", resp.Token)
|
||||
}
|
||||
if got := fmt.Sprintf("%.2f", resp.ActualAmount); got != "5.00" {
|
||||
t.Fatalf("actual amount = %s, want 5.00", got)
|
||||
}
|
||||
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.StringRaw(), "TON", resp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup ton runtime lock: %v", err)
|
||||
}
|
||||
if tradeID != resp.TradeId {
|
||||
t.Fatalf("runtime lock trade_id = %q, want %q", tradeID, resp.TradeId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTransactionCreatesTonOrderWithConfiguredPrecision(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.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"ton":0.12345}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
if _, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw()); err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
|
||||
req := newCreateTransactionRequest("order_ton_precision_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
resp, err := CreateTransaction(req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create TON transaction: %v", err)
|
||||
}
|
||||
if got := fmt.Sprintf("%.4f", resp.ActualAmount); got != "1.2345" {
|
||||
t.Fatalf("actual amount = %s, want 1.2345", got)
|
||||
}
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.Bounce(true).String(), "TON", 1.2345)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup ton runtime lock: %v", err)
|
||||
}
|
||||
if tradeID != resp.TradeId {
|
||||
t.Fatalf("runtime lock trade_id = %q, want %q", tradeID, resp.TradeId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTransactionRejectsUnsupportedTonToken(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
req := newCreateTransactionRequest("order_ton_gram_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "GRAM"
|
||||
|
||||
_, err := CreateTransaction(req, nil)
|
||||
if err != constant.SupportedAssetNotFound {
|
||||
t.Fatalf("create unsupported TON token error = %v, want %v", err, constant.SupportedAssetNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTransactionRejectsDisabledTonTokenBeforeRate(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := dao.Mdb.Model(&mdb.ChainToken{}).
|
||||
Where("network = ? AND symbol = ?", mdb.NetworkTon, "TON").
|
||||
Update("enabled", false).Error; err != nil {
|
||||
t.Fatalf("disable TON token: %v", err)
|
||||
}
|
||||
req := newCreateTransactionRequest("order_ton_disabled_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
|
||||
_, err := CreateTransaction(req, nil)
|
||||
if err != constant.SupportedAssetNotFound {
|
||||
t.Fatalf("create disabled TON token error = %v, want %v", err, constant.SupportedAssetNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTransactionSupportedTonTokenWithoutRateReturnsRateError(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"ton":0}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
if err := data.SetSetting("rate", "rate.api_url", "", "string"); err != nil {
|
||||
t.Fatalf("clear rate api url: %v", err)
|
||||
}
|
||||
req := newCreateTransactionRequest("order_ton_missing_rate_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
|
||||
_, err := CreateTransaction(req, nil)
|
||||
if err != constant.RateAmountErr {
|
||||
t.Fatalf("create TON without rate error = %v, want %v", err, constant.RateAmountErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSwitchNetworkCreatesTonSubOrderAndRawLock(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0.1,"ton":0.5}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
if _, err := data.AddWalletAddress("TTestTronAddress001"); err != nil {
|
||||
t.Fatalf("add tron wallet: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
wallet, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw())
|
||||
if err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
|
||||
parentReq := newCreateTransactionRequest("order_switch_ton_1", 10)
|
||||
parentReq.Network = mdb.NetworkTron
|
||||
parentResp, err := CreateTransaction(parentReq, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create parent transaction: %v", err)
|
||||
}
|
||||
|
||||
subResp, err := SwitchNetwork(&request.SwitchNetworkRequest{
|
||||
TradeId: parentResp.TradeId,
|
||||
Token: "TON",
|
||||
Network: mdb.NetworkTon,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("switch to TON: %v", err)
|
||||
}
|
||||
if subResp.Network != mdb.NetworkTon || subResp.Token != "TON" {
|
||||
t.Fatalf("sub order network/token = %s/%s, want ton/TON", subResp.Network, subResp.Token)
|
||||
}
|
||||
if subResp.ReceiveAddress != wallet.Address {
|
||||
t.Fatalf("sub order receive address = %q, want %q", subResp.ReceiveAddress, wallet.Address)
|
||||
}
|
||||
if got := fmt.Sprintf("%.2f", subResp.ActualAmount); got != "5.00" {
|
||||
t.Fatalf("sub order actual amount = %s, want 5.00", got)
|
||||
}
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.StringRaw(), "TON", subResp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup TON sub-order lock: %v", err)
|
||||
}
|
||||
if tradeID != subResp.TradeId {
|
||||
t.Fatalf("TON sub-order lock trade_id = %q, want %q", tradeID, subResp.TradeId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSwitchNetworkRejectsUnsupportedTonToken(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0.1}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
if _, err := data.AddWalletAddress("TTestTronAddress002"); err != nil {
|
||||
t.Fatalf("add tron wallet: %v", err)
|
||||
}
|
||||
parentResp, err := CreateTransaction(newCreateTransactionRequest("order_switch_gram_1", 10), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create parent transaction: %v", err)
|
||||
}
|
||||
|
||||
_, err = SwitchNetwork(&request.SwitchNetworkRequest{
|
||||
TradeId: parentResp.TradeId,
|
||||
Token: "GRAM",
|
||||
Network: mdb.NetworkTon,
|
||||
})
|
||||
if err != constant.SupportedAssetNotFound {
|
||||
t.Fatalf("switch unsupported TON token error = %v, want %v", err, constant.SupportedAssetNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryProcessTonTransferMarksOrderPaidAndReleasesRawLock(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"ton":0.5}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
if _, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw()); err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
req := newCreateTransactionRequest("order_ton_process_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
resp, err := CreateTransaction(req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create TON transaction: %v", err)
|
||||
}
|
||||
|
||||
transfer := &TonObservedTransfer{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true},
|
||||
RawAmount: big.NewInt(5_000_000_000),
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTimeMs: time.Now().Add(time.Second).UnixMilli(),
|
||||
LT: 100,
|
||||
TxHashHex: strings.Repeat("1", 64),
|
||||
BlockID: TonCanonicalBlockTransactionID(addr.StringRaw(), 100, strings.Repeat("1", 64)),
|
||||
}
|
||||
TryProcessTonTransfer(transfer)
|
||||
|
||||
order, err := data.GetOrderInfoByTradeId(resp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("reload order: %v", err)
|
||||
}
|
||||
if order.Status != mdb.StatusPaySuccess {
|
||||
t.Fatalf("order status = %d, want %d", order.Status, mdb.StatusPaySuccess)
|
||||
}
|
||||
if order.BlockTransactionId != transfer.BlockID {
|
||||
t.Fatalf("block transaction id = %q, want %q", order.BlockTransactionId, transfer.BlockID)
|
||||
}
|
||||
lock, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.StringRaw(), "TON", resp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup ton lock: %v", err)
|
||||
}
|
||||
if lock != "" {
|
||||
t.Fatalf("TON lock still exists after payment: %s", lock)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryProcessTonJettonTransferMarksUSDTOrderPaid(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0.1}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
if _, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw()); err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
req := newCreateTransactionRequest("order_ton_usdt_process_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "USDT"
|
||||
resp, err := CreateTransaction(req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create TON USDT transaction: %v", err)
|
||||
}
|
||||
|
||||
transfer := &TonObservedTransfer{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 2}, Network: mdb.NetworkTon, Symbol: "USDT", Decimals: 6, Enabled: true},
|
||||
RawAmount: big.NewInt(1_000_000),
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTimeMs: time.Now().Add(time.Second).UnixMilli(),
|
||||
LT: 110,
|
||||
TxHashHex: strings.Repeat("4", 64),
|
||||
BlockID: TonCanonicalBlockTransactionID(addr.StringRaw(), 110, strings.Repeat("4", 64)),
|
||||
}
|
||||
TryProcessTonTransfer(transfer)
|
||||
|
||||
order, err := data.GetOrderInfoByTradeId(resp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("reload order: %v", err)
|
||||
}
|
||||
if order.Status != mdb.StatusPaySuccess {
|
||||
t.Fatalf("order status = %d, want %d", order.Status, mdb.StatusPaySuccess)
|
||||
}
|
||||
if order.BlockTransactionId != transfer.BlockID {
|
||||
t.Fatalf("block transaction id = %q, want %q", order.BlockTransactionId, transfer.BlockID)
|
||||
}
|
||||
lock, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.StringRaw(), "USDT", resp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup TON USDT lock: %v", err)
|
||||
}
|
||||
if lock != "" {
|
||||
t.Fatalf("TON USDT lock still exists after payment: %s", lock)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryProcessTonTransferSkipsTransfersBeforeOrderCreation(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"ton":0.5}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
if _, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw()); err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
req := newCreateTransactionRequest("order_ton_old_transfer_1", 10)
|
||||
req.Network = mdb.NetworkTon
|
||||
req.Token = "TON"
|
||||
resp, err := CreateTransaction(req, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create TON transaction: %v", err)
|
||||
}
|
||||
order, err := data.GetOrderInfoByTradeId(resp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("load order: %v", err)
|
||||
}
|
||||
|
||||
TryProcessTonTransfer(&TonObservedTransfer{
|
||||
ReceiveAddress: resp.ReceiveAddress,
|
||||
Token: mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true},
|
||||
RawAmount: big.NewInt(5_000_000_000),
|
||||
Amount: resp.ActualAmount,
|
||||
BlockTimeMs: order.CreatedAt.TimestampMilli() - 1,
|
||||
LT: 101,
|
||||
TxHashHex: strings.Repeat("2", 64),
|
||||
BlockID: TonCanonicalBlockTransactionID(addr.StringRaw(), 101, strings.Repeat("2", 64)),
|
||||
})
|
||||
|
||||
order, err = data.GetOrderInfoByTradeId(resp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("reload order: %v", err)
|
||||
}
|
||||
if order.Status != mdb.StatusWaitPay {
|
||||
t.Fatalf("order status = %d, want wait-pay", order.Status)
|
||||
}
|
||||
if order.BlockTransactionId != "" {
|
||||
t.Fatalf("old transfer set block transaction id = %q", order.BlockTransactionId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryProcessTonSubOrderPaysParentAndReleasesLocks(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := data.SetSetting("rate", "rate.forced_rate_list", `{"cny":{"usdt":0.1,"ton":0.5}}`, "json"); err != nil {
|
||||
t.Fatalf("set forced rate: %v", err)
|
||||
}
|
||||
if _, err := data.AddWalletAddress("TTestTronAddressForTonSub"); err != nil {
|
||||
t.Fatalf("add tron wallet: %v", err)
|
||||
}
|
||||
addr := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
if _, err := data.AddWalletAddressWithNetwork(mdb.NetworkTon, addr.StringRaw()); err != nil {
|
||||
t.Fatalf("add ton wallet: %v", err)
|
||||
}
|
||||
|
||||
parentReq := newCreateTransactionRequest("order_ton_sub_parent_1", 10)
|
||||
parentReq.Network = mdb.NetworkTron
|
||||
parentResp, err := CreateTransaction(parentReq, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create parent order: %v", err)
|
||||
}
|
||||
subResp, err := SwitchNetwork(&request.SwitchNetworkRequest{
|
||||
TradeId: parentResp.TradeId,
|
||||
Token: "TON",
|
||||
Network: mdb.NetworkTon,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("switch to TON: %v", err)
|
||||
}
|
||||
|
||||
TryProcessTonTransfer(&TonObservedTransfer{
|
||||
ReceiveAddress: subResp.ReceiveAddress,
|
||||
Token: mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true},
|
||||
RawAmount: big.NewInt(5_000_000_000),
|
||||
Amount: subResp.ActualAmount,
|
||||
BlockTimeMs: time.Now().Add(time.Second).UnixMilli(),
|
||||
LT: 102,
|
||||
TxHashHex: strings.Repeat("3", 64),
|
||||
BlockID: TonCanonicalBlockTransactionID(addr.StringRaw(), 102, strings.Repeat("3", 64)),
|
||||
})
|
||||
|
||||
parent, err := data.GetOrderInfoByTradeId(parentResp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("reload parent order: %v", err)
|
||||
}
|
||||
if parent.Status != mdb.StatusPaySuccess {
|
||||
t.Fatalf("parent status = %d, want paid", parent.Status)
|
||||
}
|
||||
sub, err := data.GetOrderInfoByTradeId(subResp.TradeId)
|
||||
if err != nil {
|
||||
t.Fatalf("reload sub order: %v", err)
|
||||
}
|
||||
if sub.Status != mdb.StatusPaySuccess {
|
||||
t.Fatalf("sub status = %d, want paid", sub.Status)
|
||||
}
|
||||
parentLock, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTron, parentResp.ReceiveAddress, parentResp.Token, parentResp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup parent lock: %v", err)
|
||||
}
|
||||
if parentLock != "" {
|
||||
t.Fatalf("parent lock still exists: %s", parentLock)
|
||||
}
|
||||
subLock, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, addr.StringRaw(), "TON", subResp.ActualAmount)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup sub lock: %v", err)
|
||||
}
|
||||
if subLock != "" {
|
||||
t.Fatalf("TON sub-order lock still exists: %s", subLock)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderProcessingMarksPaidAndReleasesLock(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -12,8 +12,24 @@ import (
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
"github.com/GMWalletApp/epusdt/notify"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func upsertTaskServiceTestChainToken(t *testing.T, token mdb.ChainToken) {
|
||||
t.Helper()
|
||||
if err := dao.Mdb.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "network"}, {Name: "symbol"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"contract_address",
|
||||
"decimals",
|
||||
"enabled",
|
||||
"min_amount",
|
||||
}),
|
||||
}).Create(&token).Error; err != nil {
|
||||
t.Fatalf("seed chain token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendPaymentNotificationUsesLatestOrderUpdatedAt(t *testing.T) {
|
||||
cleanup := testutil.SetupTestDatabases(t)
|
||||
defer cleanup()
|
||||
@@ -158,15 +174,13 @@ func TestTryProcessEvmERC20TransferSkipsTransfersBeforeOrderCreation(t *testing.
|
||||
contract := common.HexToAddress("0x3333333333333333333333333333333333333333")
|
||||
receiveAddress := common.HexToAddress("0x4444444444444444444444444444444444444444")
|
||||
|
||||
if err := dao.Mdb.Create(&mdb.ChainToken{
|
||||
upsertTaskServiceTestChainToken(t, 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,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/xssnick/tonutils-go/liteclient"
|
||||
"github.com/xssnick/tonutils-go/ton"
|
||||
)
|
||||
|
||||
// ConnectTonLiteAPI builds a tonutils-go API client from a liteserver global
|
||||
// config URL. Scanner and manual verification use this same connection setup.
|
||||
func ConnectTonLiteAPI(ctx context.Context, configURL string, requestTimeout time.Duration, reconnectLimit int) (ton.APIClientWrapped, func(), error) {
|
||||
configURL = strings.TrimSpace(configURL)
|
||||
if configURL == "" {
|
||||
return nil, func() {}, fmt.Errorf("ton lite config url is empty")
|
||||
}
|
||||
if reconnectLimit <= 0 {
|
||||
reconnectLimit = 3
|
||||
}
|
||||
cfg, err := liteclient.GetConfigFromUrl(ctx, configURL)
|
||||
if err != nil {
|
||||
return nil, func() {}, err
|
||||
}
|
||||
pool := liteclient.NewConnectionPool()
|
||||
pool.SetOnDisconnect(pool.DefaultReconnect(3*time.Second, reconnectLimit))
|
||||
if err = pool.AddConnectionsFromConfig(ctx, cfg); err != nil {
|
||||
pool.Stop()
|
||||
return nil, func() {}, err
|
||||
}
|
||||
base := ton.NewAPIClient(pool, ton.ProofCheckPolicyFast)
|
||||
base.SetTrustedBlockFromConfig(cfg)
|
||||
api := base.WithRetry(2).WithTimeout(requestTimeout).WithLSInfoInErrors()
|
||||
return api, pool.Stop, nil
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"github.com/GMWalletApp/epusdt/model/data"
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
"github.com/GMWalletApp/epusdt/model/request"
|
||||
addressutil "github.com/GMWalletApp/epusdt/util/address"
|
||||
"github.com/GMWalletApp/epusdt/util/constant"
|
||||
"github.com/GMWalletApp/epusdt/util/log"
|
||||
"github.com/GMWalletApp/epusdt/util/math"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
"github.com/xssnick/tonutils-go/ton/jetton"
|
||||
"github.com/xssnick/tonutils-go/tvm/cell"
|
||||
)
|
||||
|
||||
const (
|
||||
TonNativeSymbol = "TON"
|
||||
TonTransferNotificationOpcode = 0x7362d09c
|
||||
)
|
||||
|
||||
type TonObservedTransfer struct {
|
||||
ReceiveAddress string
|
||||
Token mdb.ChainToken
|
||||
RawAmount *big.Int
|
||||
Amount float64
|
||||
BlockTimeMs int64
|
||||
LT uint64
|
||||
TxHashHex string
|
||||
BlockID string
|
||||
SenderAddress string
|
||||
JettonWallet string
|
||||
}
|
||||
|
||||
func TonCanonicalBlockTransactionID(receiveRaw string, lt uint64, txHashHex string) string {
|
||||
return fmt.Sprintf("ton:%s:%d:%s", strings.ToLower(strings.TrimSpace(receiveRaw)), lt, strings.ToLower(strings.TrimSpace(txHashHex)))
|
||||
}
|
||||
|
||||
func ParseTonInboundTransfer(tx *tlb.Transaction, receive *address.Address, nativeToken *mdb.ChainToken, jettonWalletTokens map[string]mdb.ChainToken) (*TonObservedTransfer, error) {
|
||||
if tx == nil || receive == nil || tx.IO.In == nil || tx.IO.In.MsgType != tlb.MsgTypeInternal {
|
||||
return nil, nil
|
||||
}
|
||||
if isTonTransactionBounced(tx) {
|
||||
return nil, nil
|
||||
}
|
||||
in := tx.IO.In.AsInternal()
|
||||
if in == nil || in.DstAddr == nil || !in.DstAddr.Equals(receive) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
receiveRaw := addressutil.TonRawAddressObjectKey(receive)
|
||||
txHashHex := hex.EncodeToString(tx.Hash)
|
||||
blockID := TonCanonicalBlockTransactionID(receiveRaw, tx.LT, txHashHex)
|
||||
blockTimeMs := int64(tx.Now) * 1000
|
||||
if in.SrcAddr != nil {
|
||||
srcRaw := addressutil.TonRawAddressObjectKey(in.SrcAddr)
|
||||
if token, ok := jettonWalletTokens[srcRaw]; ok {
|
||||
transfer, err := parseTonJettonTransferNotification(in)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
amount := tonRawAmountToFloat(transfer.Amount.Nano(), token.Decimals)
|
||||
if amount <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if token.MinAmount > 0 && amount < token.MinAmount {
|
||||
return nil, nil
|
||||
}
|
||||
return &TonObservedTransfer{
|
||||
ReceiveAddress: addressutil.NormalizeTonAddressObject(receive),
|
||||
Token: token,
|
||||
RawAmount: transfer.Amount.Nano(),
|
||||
Amount: amount,
|
||||
BlockTimeMs: blockTimeMs,
|
||||
LT: tx.LT,
|
||||
TxHashHex: txHashHex,
|
||||
BlockID: blockID,
|
||||
SenderAddress: addressutil.NormalizeTonAddressObject(transfer.Sender),
|
||||
JettonWallet: addressutil.NormalizeTonAddressObject(in.SrcAddr),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
if tonPayloadIsTransferNotification(in.Body) {
|
||||
return nil, nil
|
||||
}
|
||||
if nativeToken == nil || nativeToken.ID == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rawNano := in.Amount.Nano()
|
||||
if rawNano == nil || rawNano.Sign() <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
amount := tonRawAmountToFloat(rawNano, nativeToken.Decimals)
|
||||
if amount <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if nativeToken.MinAmount > 0 && amount < nativeToken.MinAmount {
|
||||
return nil, nil
|
||||
}
|
||||
return &TonObservedTransfer{
|
||||
ReceiveAddress: addressutil.NormalizeTonAddressObject(receive),
|
||||
Token: *nativeToken,
|
||||
RawAmount: rawNano,
|
||||
Amount: amount,
|
||||
BlockTimeMs: blockTimeMs,
|
||||
LT: tx.LT,
|
||||
TxHashHex: txHashHex,
|
||||
BlockID: blockID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TryProcessTonTransfer(transfer *TonObservedTransfer) {
|
||||
if transfer == nil {
|
||||
return
|
||||
}
|
||||
tokenSym := strings.ToUpper(strings.TrimSpace(transfer.Token.Symbol))
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Sugar.Errorf("[TON-%s][%s] TryProcessTonTransfer panic: %v", tokenSym, transfer.ReceiveAddress, err)
|
||||
}
|
||||
}()
|
||||
|
||||
receive := strings.TrimSpace(transfer.ReceiveAddress)
|
||||
if tokenSym == "" || receive == "" || transfer.Amount <= 0 || transfer.BlockID == "" {
|
||||
return
|
||||
}
|
||||
log.Sugar.Infof("[TON-%s][%s] observed transfer tx=%s lt=%d amount=%.6f", tokenSym, receive, transfer.BlockID, transfer.LT, transfer.Amount)
|
||||
|
||||
tradeID, err := data.GetTradeIdByWalletAddressAndAmountAndToken(mdb.NetworkTon, receive, tokenSym, transfer.Amount)
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[TON-%s][%s] lock lookup: %v", tokenSym, receive, err)
|
||||
return
|
||||
}
|
||||
if tradeID == "" {
|
||||
log.Sugar.Infof("[TON-%s][%s] skip unmatched transfer tx=%s amount=%.6f", tokenSym, receive, transfer.BlockID, transfer.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
order, err := data.GetOrderInfoByTradeId(tradeID)
|
||||
if err != nil {
|
||||
log.Sugar.Warnf("[TON-%s][%s] load order: %v", tokenSym, receive, err)
|
||||
return
|
||||
}
|
||||
if strings.ToLower(strings.TrimSpace(order.Network)) != mdb.NetworkTon {
|
||||
log.Sugar.Warnf("[TON-%s][%s] skip trade_id=%s network=%q", tokenSym, receive, tradeID, order.Network)
|
||||
return
|
||||
}
|
||||
if strings.ToUpper(strings.TrimSpace(order.Token)) != tokenSym {
|
||||
log.Sugar.Warnf("[TON-%s][%s] skip trade_id=%s token mismatch order=%s", tokenSym, receive, tradeID, order.Token)
|
||||
return
|
||||
}
|
||||
if !tonOrderAddressMatches(order.ReceiveAddress, receive) {
|
||||
log.Sugar.Warnf("[TON-%s][%s] skip trade_id=%s receive address mismatch order=%s", tokenSym, receive, tradeID, order.ReceiveAddress)
|
||||
return
|
||||
}
|
||||
if transfer.BlockTimeMs > 0 && transfer.BlockTimeMs < order.CreatedAt.TimestampMilli() {
|
||||
log.Sugar.Warnf("[TON-%s][%s] skip tx %s because block time %d is before order create time %d", tokenSym, receive, transfer.BlockID, transfer.BlockTimeMs, order.CreatedAt.TimestampMilli())
|
||||
return
|
||||
}
|
||||
|
||||
req := &request.OrderProcessingRequest{
|
||||
ReceiveAddress: order.ReceiveAddress,
|
||||
Token: tokenSym,
|
||||
Network: mdb.NetworkTon,
|
||||
TradeId: tradeID,
|
||||
Amount: transfer.Amount,
|
||||
BlockTransactionId: transfer.BlockID,
|
||||
}
|
||||
err = OrderProcessing(req)
|
||||
if err != nil {
|
||||
if errors.Is(err, constant.OrderBlockAlreadyProcess) || errors.Is(err, constant.OrderStatusConflict) {
|
||||
log.Sugar.Infof("[TON-%s][%s] skip resolved transfer trade_id=%s tx=%s err=%v", tokenSym, receive, tradeID, transfer.BlockID, err)
|
||||
return
|
||||
}
|
||||
log.Sugar.Errorf("[TON-%s][%s] OrderProcessing trade_id=%s tx=%s: %v", tokenSym, receive, tradeID, transfer.BlockID, err)
|
||||
return
|
||||
}
|
||||
|
||||
sendPaymentNotification(order)
|
||||
log.Sugar.Infof("[TON-%s][%s] payment processed trade_id=%s tx=%s", tokenSym, receive, tradeID, transfer.BlockID)
|
||||
}
|
||||
|
||||
func tonOrderAddressMatches(a, b string) bool {
|
||||
ar, errA := addressutil.TonRawAddressKey(a)
|
||||
br, errB := addressutil.TonRawAddressKey(b)
|
||||
return errA == nil && errB == nil && ar == br
|
||||
}
|
||||
|
||||
func tonRawAmountToFloat(rawAmount *big.Int, decimals int) float64 {
|
||||
if rawAmount == nil || rawAmount.Sign() <= 0 {
|
||||
return 0
|
||||
}
|
||||
if decimals < 0 {
|
||||
decimals = 0
|
||||
}
|
||||
amount := decimal.NewFromBigInt(rawAmount, -int32(decimals))
|
||||
return math.MustParsePrecFloat64(amount.InexactFloat64(), data.MaxAmountPrecision)
|
||||
}
|
||||
|
||||
func parseTonJettonTransferNotification(in *tlb.InternalMessage) (*jetton.TransferNotification, error) {
|
||||
if in == nil || in.Body == nil {
|
||||
return nil, fmt.Errorf("missing jetton transfer notification body")
|
||||
}
|
||||
var transfer jetton.TransferNotification
|
||||
if err := tlb.LoadFromCell(&transfer, in.Body.BeginParse()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transfer, nil
|
||||
}
|
||||
|
||||
func tonPayloadIsTransferNotification(body *cell.Cell) bool {
|
||||
if body == nil {
|
||||
return false
|
||||
}
|
||||
op, err := body.BeginParse().LoadUInt(32)
|
||||
return err == nil && op == TonTransferNotificationOpcode
|
||||
}
|
||||
|
||||
func isTonTransactionBounced(tx *tlb.Transaction) bool {
|
||||
if tx == nil {
|
||||
return false
|
||||
}
|
||||
if dsc, ok := tx.Description.(tlb.TransactionDescriptionOrdinary); ok && dsc.BouncePhase != nil {
|
||||
if _, ok = dsc.BouncePhase.Phase.(tlb.BouncePhaseOk); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EnsureTonTransferMatchesOrder(order *mdb.Orders, transfer *TonObservedTransfer) error {
|
||||
if order == nil || order.ID == 0 {
|
||||
return fmt.Errorf("order not found")
|
||||
}
|
||||
if transfer == nil {
|
||||
return fmt.Errorf("matching ton transfer to order address not found")
|
||||
}
|
||||
if strings.ToLower(strings.TrimSpace(order.Network)) != mdb.NetworkTon {
|
||||
return fmt.Errorf("order network mismatch")
|
||||
}
|
||||
if !strings.EqualFold(order.Token, transfer.Token.Symbol) {
|
||||
return fmt.Errorf("transaction token mismatch")
|
||||
}
|
||||
if !tonOrderAddressMatches(order.ReceiveAddress, transfer.ReceiveAddress) {
|
||||
return fmt.Errorf("transaction recipient mismatch")
|
||||
}
|
||||
if transfer.BlockTimeMs <= 0 || transfer.BlockTimeMs < order.CreatedAt.TimestampMilli() {
|
||||
return fmt.Errorf("transaction predates the order")
|
||||
}
|
||||
if !amountMatchesRaw(order.ActualAmount, transfer.RawAmount, transfer.Token.Decimals) {
|
||||
return fmt.Errorf("transaction amount mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/big"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/GMWalletApp/epusdt/model/mdb"
|
||||
addressutil "github.com/GMWalletApp/epusdt/util/address"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
"github.com/xssnick/tonutils-go/tlb"
|
||||
"github.com/xssnick/tonutils-go/ton/jetton"
|
||||
"github.com/xssnick/tonutils-go/tvm/cell"
|
||||
)
|
||||
|
||||
func tonTestInboundTx(t *testing.T, src, dst *address.Address, amount tlb.Coins, body *cell.Cell) *tlb.Transaction {
|
||||
t.Helper()
|
||||
return &tlb.Transaction{
|
||||
LT: 123,
|
||||
Now: uint32(time.Now().Unix()),
|
||||
Hash: bytes.Repeat([]byte{0x11}, 32),
|
||||
IO: struct {
|
||||
In *tlb.Message `tlb:"maybe ^"`
|
||||
Out *tlb.MessagesList `tlb:"maybe ^"`
|
||||
}{
|
||||
In: &tlb.Message{
|
||||
MsgType: tlb.MsgTypeInternal,
|
||||
Msg: &tlb.InternalMessage{
|
||||
SrcAddr: src,
|
||||
DstAddr: dst,
|
||||
Amount: amount,
|
||||
Body: body,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTonInboundTransferNativeTON(t *testing.T) {
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x22}, 32)).Bounce(false).Testnet(false)
|
||||
native := &mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true}
|
||||
|
||||
tx := tonTestInboundTx(t, sender, receive, tlb.MustFromTON("1.23"), cell.BeginCell().EndCell())
|
||||
transfer, err := ParseTonInboundTransfer(tx, receive, native, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTonInboundTransfer(): %v", err)
|
||||
}
|
||||
if transfer == nil {
|
||||
t.Fatal("expected native TON transfer")
|
||||
}
|
||||
if transfer.Token.Symbol != "TON" {
|
||||
t.Fatalf("token = %q, want TON", transfer.Token.Symbol)
|
||||
}
|
||||
if transfer.Amount != 1.23 {
|
||||
t.Fatalf("amount = %v, want 1.23", transfer.Amount)
|
||||
}
|
||||
if transfer.ReceiveAddress != addressutil.NormalizeTonAddressObject(receive) {
|
||||
t.Fatalf("receive address = %q", transfer.ReceiveAddress)
|
||||
}
|
||||
if !strings.HasPrefix(transfer.BlockID, "ton:"+addressutil.TonRawAddressObjectKey(receive)+":123:") {
|
||||
t.Fatalf("block id = %q, want canonical TON prefix", transfer.BlockID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTonInboundTransferJettonNotification(t *testing.T) {
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x33}, 32)).Bounce(false).Testnet(false)
|
||||
jettonWallet := address.NewAddress(0, 0, bytes.Repeat([]byte{0x44}, 32)).Bounce(false).Testnet(false)
|
||||
native := &mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true}
|
||||
usdt := mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 2}, Network: mdb.NetworkTon, Symbol: "USDT", Decimals: 6, Enabled: true}
|
||||
|
||||
body, err := tlb.ToCell(jetton.TransferNotification{
|
||||
QueryID: 7,
|
||||
Amount: tlb.MustFromNano(big.NewInt(1230000), 6),
|
||||
Sender: sender,
|
||||
ForwardPayload: cell.BeginCell().EndCell(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build jetton notification body: %v", err)
|
||||
}
|
||||
|
||||
tx := tonTestInboundTx(t, jettonWallet, receive, tlb.FromNanoTONU(1), body)
|
||||
transfer, err := ParseTonInboundTransfer(tx, receive, native, map[string]mdb.ChainToken{
|
||||
addressutil.TonRawAddressObjectKey(jettonWallet): usdt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTonInboundTransfer(): %v", err)
|
||||
}
|
||||
if transfer == nil {
|
||||
t.Fatal("expected USDT jetton transfer")
|
||||
}
|
||||
if transfer.Token.Symbol != "USDT" {
|
||||
t.Fatalf("token = %q, want USDT", transfer.Token.Symbol)
|
||||
}
|
||||
if transfer.Amount != 1.23 {
|
||||
t.Fatalf("amount = %v, want 1.23", transfer.Amount)
|
||||
}
|
||||
if transfer.SenderAddress != addressutil.NormalizeTonAddressObject(sender) {
|
||||
t.Fatalf("sender address = %q", transfer.SenderAddress)
|
||||
}
|
||||
if transfer.JettonWallet != addressutil.NormalizeTonAddressObject(jettonWallet) {
|
||||
t.Fatalf("jetton wallet = %q", transfer.JettonWallet)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTonInboundTransferJettonNotificationWithNoGasComputeSkip(t *testing.T) {
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x33}, 32)).Bounce(false).Testnet(false)
|
||||
jettonWallet := address.NewAddress(0, 0, bytes.Repeat([]byte{0x44}, 32)).Bounce(false).Testnet(false)
|
||||
usdt := mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 2}, Network: mdb.NetworkTon, Symbol: "USDT", Decimals: 6, Enabled: true}
|
||||
|
||||
body, err := tlb.ToCell(jetton.TransferNotification{
|
||||
QueryID: 7,
|
||||
Amount: tlb.MustFromNano(big.NewInt(150000), 6),
|
||||
Sender: sender,
|
||||
ForwardPayload: cell.BeginCell().EndCell(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build jetton notification body: %v", err)
|
||||
}
|
||||
|
||||
tx := tonTestInboundTx(t, jettonWallet, receive, tlb.FromNanoTONU(1), body)
|
||||
tx.Description = tlb.TransactionDescriptionOrdinary{
|
||||
ComputePhase: tlb.ComputePhase{Phase: tlb.ComputePhaseSkipped{
|
||||
Reason: tlb.ComputeSkipReason{Type: tlb.ComputeSkipReasonNoGas},
|
||||
}},
|
||||
Aborted: true,
|
||||
}
|
||||
transfer, err := ParseTonInboundTransfer(tx, receive, nil, map[string]mdb.ChainToken{
|
||||
addressutil.TonRawAddressObjectKey(jettonWallet): usdt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTonInboundTransfer(): %v", err)
|
||||
}
|
||||
if transfer == nil {
|
||||
t.Fatal("expected no-gas jetton notification to be accepted")
|
||||
}
|
||||
if transfer.Token.Symbol != "USDT" {
|
||||
t.Fatalf("token = %q, want USDT", transfer.Token.Symbol)
|
||||
}
|
||||
if transfer.Amount != 0.15 {
|
||||
t.Fatalf("amount = %v, want 0.15", transfer.Amount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTonInboundTransferDoesNotCountUntrustedJettonNotificationAsTON(t *testing.T) {
|
||||
receive := address.MustParseAddr("EQC6KV4zs8TJtSZapOrRFmqSkxzpq-oSCoxekQRKElf4nC1I")
|
||||
sender := address.NewAddress(0, 0, bytes.Repeat([]byte{0x33}, 32)).Bounce(false).Testnet(false)
|
||||
untrustedJettonWallet := address.NewAddress(0, 0, bytes.Repeat([]byte{0x55}, 32)).Bounce(false).Testnet(false)
|
||||
native := &mdb.ChainToken{BaseModel: mdb.BaseModel{ID: 1}, Network: mdb.NetworkTon, Symbol: "TON", Decimals: 9, Enabled: true}
|
||||
|
||||
body, err := tlb.ToCell(jetton.TransferNotification{
|
||||
QueryID: 7,
|
||||
Amount: tlb.MustFromNano(big.NewInt(1230000), 6),
|
||||
Sender: sender,
|
||||
ForwardPayload: cell.BeginCell().EndCell(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build jetton notification body: %v", err)
|
||||
}
|
||||
|
||||
tx := tonTestInboundTx(t, untrustedJettonWallet, receive, tlb.FromNanoTONU(1), body)
|
||||
transfer, err := ParseTonInboundTransfer(tx, receive, native, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTonInboundTransfer(): %v", err)
|
||||
}
|
||||
if transfer != nil {
|
||||
t.Fatalf("untrusted jetton notification produced transfer: %#v", transfer)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user