wallet/pkg/rest/tron_v1_account.go

77 lines
1.7 KiB
Go
Raw 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 CreateTronAccountRequest struct {
AccountID string `json:"account_id"`
}
type CreateTronAccountResponse struct {
Address string `json:"address"`
}
// @BasePath /api/v1
//
// TronCreateAccount godoc
//
// @Summary Create a new account
// @Schemes
// @Description Create a new tron account identified by account_id
// @Tags Tron
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param message body CreateTronAccountRequest true "Account Info"
// @Success 200 {object} CreateTronAccountResponse
// @Failure 400 {object} ErrorResponse
// @Router /tron/create-account [post]
func TronCreateAccountV1(c *gin.Context) {
var req CreateTronAccountRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.AccountID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "account_id is required"})
return
}
last, err := store.LastAccount(store.Tron)
if err != nil && err.Error() != "record not found" {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
lastHdIndex := 0
if last != nil {
lastHdIndex = last.GetHDIndex() + 1
}
account, err := trc.DeriveAccount(lastHdIndex)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
trxAccount := store.TronAccount{
AccountID: req.AccountID,
Address: account.Address(),
HDIndex: lastHdIndex,
}
err = store.CreateAccount(&trxAccount)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"address": account.Address()})
}