cosmos-sdk/x/bank/client/rest/sendtx.go

84 lines
2.4 KiB
Go
Raw Normal View History

2018-03-10 09:33:05 -08:00
package rest
import (
"net/http"
"github.com/gorilla/mux"
2019-02-04 07:48:26 -08:00
"github.com/cosmos/cosmos-sdk/client/context"
clientrest "github.com/cosmos/cosmos-sdk/client/rest"
"github.com/cosmos/cosmos-sdk/codec"
2018-08-06 11:11:30 -07:00
"github.com/cosmos/cosmos-sdk/crypto/keys"
2018-03-10 09:33:05 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
2018-08-06 11:11:30 -07:00
"github.com/cosmos/cosmos-sdk/x/bank"
2018-03-10 09:33:05 -08:00
)
2018-04-18 21:49:24 -07:00
// RegisterRoutes - Central function to define routes that get registered by the main application
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) {
r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, kb, cliCtx)).Methods("POST")
2018-04-18 21:49:24 -07:00
}
// SendReq defines the properties of a send request's body.
type SendReq struct {
2019-02-04 07:48:26 -08:00
BaseReq rest.BaseReq `json:"base_req"`
Amount sdk.Coins `json:"amount"`
2018-03-10 09:33:05 -08:00
}
var msgCdc = codec.New()
func init() {
bank.RegisterCodec(msgCdc)
}
// SendRequestHandlerFn - http request handler to send coins to a address.
func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc {
2018-03-10 09:33:05 -08:00
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
bech32Addr := vars["address"]
toAddr, err := sdk.AccAddressFromBech32(bech32Addr)
if err != nil {
2019-02-04 07:48:26 -08:00
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
2018-03-10 09:33:05 -08:00
var req SendReq
if !rest.ReadRESTReq(w, r, cdc, &req) {
return
}
req.BaseReq = req.BaseReq.Sanitize()
if !req.BaseReq.ValidateBasic(w) {
return
}
if req.BaseReq.GenerateOnly {
// When generate only is supplied, the from field must be a valid Bech32
// address.
fromAddr, err := sdk.AccAddressFromBech32(req.BaseReq.From)
if err != nil {
2019-02-04 07:48:26 -08:00
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
msg := bank.NewMsgSend(fromAddr, toAddr, req.Amount)
clientrest.WriteGenerateStdTxResponse(w, cdc, cliCtx, req.BaseReq, []sdk.Msg{msg})
return
}
// derive the from account address and name from the Keybase
fromAddress, fromName, err := context.GetFromFields(req.BaseReq.From)
2018-03-10 09:33:05 -08:00
if err != nil {
2019-02-04 07:48:26 -08:00
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
2018-03-10 09:33:05 -08:00
return
}
cliCtx = cliCtx.WithFromName(fromName).WithFromAddress(fromAddress)
msg := bank.NewMsgSend(cliCtx.GetFromAddress(), toAddr, req.Amount)
clientrest.CompleteAndBroadcastTxREST(w, cliCtx, req.BaseReq, []sdk.Msg{msg}, cdc)
2018-03-10 09:33:05 -08:00
}
}