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

67 lines
1.8 KiB
Go
Raw Normal View History

2018-03-10 09:33:05 -08:00
package rest
import (
"net/http"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
"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/x/bank"
2018-04-25 07:18:06 -07:00
"github.com/cosmos/cosmos-sdk/x/bank/client"
2018-08-06 11:11:30 -07:00
"github.com/gorilla/mux"
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) {
2018-08-06 11:11:30 -07:00
r.HandleFunc("/accounts/{address}/send", SendRequestHandlerFn(cdc, kb, cliCtx)).Methods("POST")
r.HandleFunc("/tx/broadcast", BroadcastTxRequestHandlerFn(cdc, cliCtx)).Methods("POST")
2018-04-18 21:49:24 -07:00
}
type sendReq struct {
BaseReq utils.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"]
to, err := sdk.AccAddressFromBech32(bech32Addr)
if err != nil {
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
2018-03-10 09:33:05 -08:00
var req sendReq
err = utils.ReadRESTReq(w, r, cdc, &req)
2018-03-14 05:01:55 -07:00
if err != nil {
return
}
baseReq := req.BaseReq.Sanitize()
if !baseReq.ValidateBasic(w) {
return
}
info, err := kb.Get(baseReq.Name)
2018-03-10 09:33:05 -08:00
if err != nil {
utils.WriteErrorResponse(w, http.StatusUnauthorized, err.Error())
2018-03-10 09:33:05 -08:00
return
}
msg := client.CreateMsg(sdk.AccAddress(info.GetPubKey().Address()), to, req.Amount)
utils.CompleteAndBroadcastTxREST(w, r, cliCtx, baseReq, []sdk.Msg{msg}, cdc)
2018-03-10 09:33:05 -08:00
}
}