wallet/pkg/rest/eth_v1_custodial.go
Anton Nesterov b19bf34e5f
[init]
2024-08-31 16:54:43 +02:00

85 lines
2.1 KiB
Go

package rest
import (
"net/http"
eth "custodial/pkg/eth"
store "custodial/pkg/store"
gin "github.com/gin-gonic/gin"
)
type ETHApproveCustodyRequest struct {
Address string `json:"address"`
}
type ETHApproveCustodyResponse struct {
Status string `json:"status"`
TXID string `json:"txid"`
}
// @BasePath /api/v1
//
// EthApproveUsdtCustodyV1 godoc
//
// @Summary Approve USDT Castody for Spender Account
// @Schemes
// @Description Approve USDT spender address for account
// @Tags Ethereum
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param message body ETHApproveCustodyRequest true "Account Info"
// @Success 200 {object} ETHApproveCustodyResponse
// @Failure 400 {object} ErrorResponse
// @Router /eth/approve-usdt-custody [post]
func EthApproveUsdtCustodyV1(c *gin.Context) {
var req ETHApproveCustodyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
storedAccount, err := store.GetAccountByAddress(req.Address, store.Ethereum)
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
// }
ethSpender, _ := eth.GetSpender()
approveAmount := "1000000000000"
hdIndex := storedAccount.GetHDIndex()
account, err := eth.DeriveAccount(hdIndex)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
balance, err := eth.EthBalance(account.Address().String())
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
if balance.ETHRaw < 1000000 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Not enough ETH to pay for transaction"})
return
}
txid, err := account.ApproveUSDTSpender(ethSpender.Address().String(), approveAmount)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
storedAccount.(*store.EthereumAccount).Spender = ethSpender.Address().String()
store.UpdateAccount(storedAccount)
c.JSON(http.StatusOK, gin.H{"txid": txid, "status": "ok"})
}