wallet/pkg/rest/tron_v1_custodial.go

85 lines
2 KiB
Go
Raw Permalink Normal View History

2024-08-31 14:46:20 +00:00
package rest
import (
"net/http"
store "custodial/pkg/store"
trc "custodial/pkg/tron"
gin "github.com/gin-gonic/gin"
)
type TRXAprroveCustodyRequest struct {
Address string `json:"address"`
}
type TRXApproveCustodyResponse struct {
Status string `json:"status"`
TXID string `json:"txid"`
}
// @BasePath /api/v1
//
// TronApproveUsdtV1 godoc
//
// @Summary Approve USDT Spender
// @Schemes
// @Description Approve USDT spender for account
// @Tags Tron
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param message body TRXAprroveCustodyRequest true "Account Info"
// @Success 200 {object} TRXApproveCustodyResponse
// @Failure 400 {object} ErrorResponse
// @Router /tron/approve-usdt-custody [post]
func TronApproveUsdtCustodyV1(c *gin.Context) {
var req TRXAprroveCustodyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
storedAccount, err := store.GetAccountByAddress(req.Address, store.Tron)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// if storedAccount.GetSpender() != "" {
// c.JSON(http.StatusBadRequest, gin.H{"error": "Spender already approved"})
// return
// }
trcSpender, _ := trc.GetSpender()
approveAmount := "1000000000000"
hdIndex := storedAccount.GetHDIndex()
account, err := trc.DeriveAccount(hdIndex)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
balance, err := trc.TronBalance(account.Address())
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
if balance.TRXRaw < 1000000 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Not enough TRX to pay for transaction"})
return
}
txid, err := account.ApproveUSDTSpender(trcSpender.Address(), approveAmount)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
storedAccount.(*store.TronAccount).Spender = trcSpender.Address()
store.UpdateAccount(storedAccount)
c.JSON(http.StatusOK, gin.H{"txid": txid, "status": "ok"})
}