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

77 lines
1.7 KiB
Go

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()})
}