cosmos-sdk/client/tx/broadcast.go

61 lines
1.6 KiB
Go
Raw Normal View History

2018-03-09 01:15:56 -08:00
package tx
import (
"net/http"
"github.com/cosmos/cosmos-sdk/client/context"
2018-09-27 07:06:40 -07:00
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
"io/ioutil"
2018-03-09 01:15:56 -08:00
)
2018-09-27 07:06:40 -07:00
const (
// Returns with the response from CheckTx.
flagSync = "sync"
2018-09-27 07:06:40 -07:00
// Returns right away, with no response
flagAsync = "async"
// Only returns error if mempool.BroadcastTx errs (ie. problem with the app) or if we timeout waiting for tx to commit.
flagBlock = "block"
)
// BroadcastBody Tx Broadcast Body
type BroadcastBody struct {
2018-09-29 20:42:12 -07:00
TxBytes []byte `json:"tx"`
Return string `json:"return"`
2018-03-09 01:15:56 -08:00
}
2018-09-27 07:06:40 -07:00
// BroadcastTxRequest REST Handler
// nolint: gocyclo
func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2018-09-27 07:06:40 -07:00
var m BroadcastBody
body, err := ioutil.ReadAll(r.Body)
if err != nil {
2018-09-27 07:06:40 -07:00
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
2018-09-27 07:06:40 -07:00
err = cdc.UnmarshalJSON(body, &m)
if err != nil {
2018-09-27 07:06:40 -07:00
utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
var res interface{}
2018-09-27 07:06:40 -07:00
switch m.Return {
case flagBlock:
res, err = cliCtx.BroadcastTx(m.TxBytes)
2018-09-27 07:06:40 -07:00
case flagSync:
res, err = cliCtx.BroadcastTxSync(m.TxBytes)
2018-09-27 07:06:40 -07:00
case flagAsync:
res, err = cliCtx.BroadcastTxAsync(m.TxBytes)
2018-09-27 07:06:40 -07:00
default:
utils.WriteErrorResponse(w, http.StatusInternalServerError, "unsupported return type. supported types: block, sync, async")
return
}
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
utils.PostProcessResponse(w, cdc, res, cliCtx.Indent)
}
2018-03-09 01:15:56 -08:00
}