* Change --gas=0 semantic in order to enable gas auto estimate. * REST clients have been modified to simulate the execution of the tx first to then populate the context with the estimated gas amount returned by the simulation. * The simulation returns both an unadjusted gas estimate and an adjusted one. The adjustment is required to ensure that the ensuing execution doesn't fail due to state changes that might have occurred. Gas adjustment can be controlled via the CLI's --gas-adjustment flag. * Tiny refactorig of REST endpoints error handling. Closes: #1246
69 lines
1.9 KiB
Go
69 lines
1.9 KiB
Go
package rest
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/cosmos/cosmos-sdk/client/context"
|
|
"github.com/cosmos/cosmos-sdk/client/utils"
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
|
"github.com/cosmos/cosmos-sdk/wire"
|
|
"github.com/cosmos/cosmos-sdk/x/auth"
|
|
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
|
|
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
// register REST routes
|
|
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *wire.Codec, storeName string) {
|
|
r.HandleFunc(
|
|
"/accounts/{address}",
|
|
QueryAccountRequestHandlerFn(storeName, cdc, authcmd.GetAccountDecoder(cdc), cliCtx),
|
|
).Methods("GET")
|
|
}
|
|
|
|
// query accountREST Handler
|
|
func QueryAccountRequestHandlerFn(
|
|
storeName string, cdc *wire.Codec,
|
|
decoder auth.AccountDecoder, cliCtx context.CLIContext,
|
|
) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
bech32addr := vars["address"]
|
|
|
|
addr, err := sdk.AccAddressFromBech32(bech32addr)
|
|
if err != nil {
|
|
utils.WriteErrorResponse(&w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName)
|
|
if err != nil {
|
|
utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("couldn't query account. Error: %s", err.Error()))
|
|
return
|
|
}
|
|
|
|
// the query will return empty if there is no data for this account
|
|
if len(res) == 0 {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
// decode the value
|
|
account, err := decoder(res)
|
|
if err != nil {
|
|
utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("couldn't parse query result. Result: %s. Error: %s", res, err.Error()))
|
|
return
|
|
}
|
|
|
|
// print out whole account
|
|
output, err := cdc.MarshalJSON(account)
|
|
if err != nil {
|
|
utils.WriteErrorResponse(&w, http.StatusInternalServerError, fmt.Sprintf("couldn't marshall query result. Error: %s", err.Error()))
|
|
return
|
|
}
|
|
|
|
w.Write(output)
|
|
}
|
|
}
|