wallet/pkg/rest/eth_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"
eth "custodial/pkg/eth"
store "custodial/pkg/store"
gin "github.com/gin-gonic/gin"
)
type CreateEthAccountRequest struct {
AccountID string `json:"account_id"`
}
type CreateEthAccountResponse struct {
Address string `json:"address"`
}
// @BasePath /api/v1
//
// EthCreateAccount godoc
//
// @Summary Create a new account
// @Schemes
// @Description Create a new etherum account identified by account_id
// @Tags Ethereum
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param message body CreateEthAccountRequest true "Account Info"
// @Success 200 {object} CreateEthAccountResponse
// @Failure 400 {object} ErrorResponse
// @Router /eth/create-account [post]
func EthCreateAccountV1(c *gin.Context) {
var req CreateEthAccountRequest
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.Ethereum)
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 := eth.DeriveAccount(lastHdIndex)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ethAccount := store.EthereumAccount{
AccountID: req.AccountID,
Address: account.Address().String(),
HDIndex: lastHdIndex,
}
err = store.CreateAccount(&ethAccount)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"address": account.Address()})
}