rpc, evm: refactor (#588)

* stargate: refactor

* remove evm CLI

* rpc: refactor

* more fixes

* fixes fixes fixes

* changelog

* refactor according to namespaces

* fix

* lint

* remove export logic

* fix rpc test

* godoc
This commit is contained in:
Federico Kunze
2020-10-22 17:39:51 -03:00
committed by GitHub
parent be09a6ee1b
commit 4501bbccdc
36 changed files with 2396 additions and 2587 deletions
+6 -6
View File
@@ -37,7 +37,7 @@ func GetCmdGetStorageAt(queryRoute string, cdc *codec.Codec) *cobra.Command {
Short: "Gets storage for an account at a given key",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
clientCtx := context.NewCLIContext().WithCodec(cdc)
account, err := accountToHex(args[0])
if err != nil {
@@ -46,7 +46,7 @@ func GetCmdGetStorageAt(queryRoute string, cdc *codec.Codec) *cobra.Command {
key := formatKeyToHash(args[1])
res, _, err := cliCtx.Query(
res, _, err := clientCtx.Query(
fmt.Sprintf("custom/%s/storage/%s/%s", queryRoute, account, key))
if err != nil {
@@ -54,7 +54,7 @@ func GetCmdGetStorageAt(queryRoute string, cdc *codec.Codec) *cobra.Command {
}
var out types.QueryResStorage
cdc.MustUnmarshalJSON(res, &out)
return cliCtx.PrintOutput(out)
return clientCtx.PrintOutput(out)
},
}
}
@@ -66,14 +66,14 @@ func GetCmdGetCode(queryRoute string, cdc *codec.Codec) *cobra.Command {
Short: "Gets code from an account",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
clientCtx := context.NewCLIContext().WithCodec(cdc)
account, err := accountToHex(args[0])
if err != nil {
return errors.Wrap(err, "could not parse account address")
}
res, _, err := cliCtx.Query(
res, _, err := clientCtx.Query(
fmt.Sprintf("custom/%s/code/%s", queryRoute, account))
if err != nil {
@@ -82,7 +82,7 @@ func GetCmdGetCode(queryRoute string, cdc *codec.Codec) *cobra.Command {
var out types.QueryResCode
cdc.MustUnmarshalJSON(res, &out)
return cliCtx.PrintOutput(out)
return clientCtx.PrintOutput(out)
},
}
}
-164
View File
@@ -1,164 +0,0 @@
package cli
import (
"bufio"
"fmt"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client/utils"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
emint "github.com/cosmos/ethermint/types"
"github.com/cosmos/ethermint/x/evm/types"
)
// GetTxCmd defines the CLI commands regarding evm module transactions
func GetTxCmd(cdc *codec.Codec) *cobra.Command {
evmTxCmd := &cobra.Command{
Use: types.ModuleName,
Short: "EVM transaction subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
evmTxCmd.AddCommand(flags.PostCommands(
GetCmdSendTx(cdc),
GetCmdGenCreateTx(cdc),
)...)
return evmTxCmd
}
// GetCmdSendTx generates an Ethermint transaction (excludes create operations)
func GetCmdSendTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "send [to_address] [amount (in aphotons)] [<data>]",
Short: "send transaction to address (call operations included)",
Args: cobra.RangeArgs(2, 3),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc))
toAddr, err := cosmosAddressFromArg(args[0])
if err != nil {
return errors.Wrap(err, "must provide a valid Bech32 address for to_address")
}
// Ambiguously decode amount from any base
amount, err := strconv.ParseInt(args[1], 0, 64)
if err != nil {
return err
}
var data []byte
if len(args) > 2 {
payload := args[2]
if !strings.HasPrefix(payload, "0x") {
payload = "0x" + payload
}
data, err = hexutil.Decode(payload)
if err != nil {
return err
}
}
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
if err != nil {
return errors.Wrap(err, "Could not retrieve account sequence")
}
// TODO: Potentially allow overriding of gas price and gas limit
msg := types.NewMsgEthermint(seq, &toAddr, sdk.NewInt(amount), txBldr.Gas(),
sdk.NewInt(emint.DefaultGasPrice), data, from)
err = msg.ValidateBasic()
if err != nil {
return err
}
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
}
// GetCmdGenCreateTx generates an Ethermint transaction (excludes create operations)
func GetCmdGenCreateTx(cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
Use: "create [contract bytecode] [<amount (in aphotons)>]",
Short: "create contract through the evm using compiled bytecode",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
inBuf := bufio.NewReader(cmd.InOrStdin())
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc))
payload := args[0]
if !strings.HasPrefix(payload, "0x") {
payload = "0x" + payload
}
data, err := hexutil.Decode(payload)
if err != nil {
return err
}
var amount int64
if len(args) > 1 {
// Ambiguously decode amount from any base
amount, err = strconv.ParseInt(args[1], 0, 64)
if err != nil {
return errors.Wrap(err, "invalid amount")
}
}
from := cliCtx.GetFromAddress()
_, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
if err != nil {
return errors.Wrap(err, "Could not retrieve account sequence")
}
// TODO: Potentially allow overriding of gas price and gas limit
msg := types.NewMsgEthermint(seq, nil, sdk.NewInt(amount), txBldr.Gas(),
sdk.NewInt(emint.DefaultGasPrice), data, from)
err = msg.ValidateBasic()
if err != nil {
return err
}
if err = authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}); err != nil {
return err
}
contractAddr := ethcrypto.CreateAddress(common.BytesToAddress(from.Bytes()), seq)
fmt.Printf(
"Contract will be deployed to: \nHex: %s\nCosmos Address: %s\n",
contractAddr.Hex(),
sdk.AccAddress(contractAddr.Bytes()),
)
return nil
},
}
}
-16
View File
@@ -45,19 +45,3 @@ func formatKeyToHash(key string) string {
return ethkey.Hex()
}
func cosmosAddressFromArg(addr string) (sdk.AccAddress, error) {
if strings.HasPrefix(addr, sdk.GetConfig().GetBech32AccountAddrPrefix()) {
// Check to see if address is Cosmos bech32 formatted
toAddr, err := sdk.AccAddressFromBech32(addr)
if err != nil {
return nil, errors.Wrap(err, "invalid bech32 formatted address")
}
return toAddr, nil
}
// Strip 0x prefix if exists
addr = strings.TrimPrefix(addr, "0x")
return sdk.AccAddressFromHex(addr)
}
-21
View File
@@ -61,24 +61,3 @@ func TestCosmosToEthereumTypes(t *testing.T) {
require.NoError(t, err)
require.Equal(t, hexString, ethDecoded)
}
func TestAddressToCosmosAddress(t *testing.T) {
baseAddr, err := sdk.AccAddressFromHex("6A98D72760f7bbA69d62Ed6F48278451251948E7")
require.NoError(t, err)
// Test cosmos string back to address
cosmosFormatted, err := cosmosAddressFromArg(baseAddr.String())
require.NoError(t, err)
require.Equal(t, baseAddr, cosmosFormatted)
// Test account address from Ethereum address
ethAddr := common.BytesToAddress(baseAddr.Bytes())
ethFormatted, err := cosmosAddressFromArg(ethAddr.Hex())
require.NoError(t, err)
require.Equal(t, baseAddr, ethFormatted)
// Test encoding without the 0x prefix
ethFormatted, err = cosmosAddressFromArg(ethAddr.Hex()[2:])
require.NoError(t, err)
require.Equal(t, baseAddr, ethFormatted)
}
+1 -2
View File
@@ -52,7 +52,6 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
// RegisterRESTRoutes Registers rest routes
func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) {
//rpc.RegisterRoutes(ctx, rtr, StoreKey)
}
// GetQueryCmd Gets the root query command of this module
@@ -62,7 +61,7 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command {
// GetTxCmd Gets the root tx command of this module
func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command {
return cli.GetTxCmd(cdc)
return nil
}
//____________________________________________________________________________
+4 -4
View File
@@ -37,17 +37,17 @@ func GetCmdFunded(cdc *codec.Codec) *cobra.Command {
Short: "Gets storage for an account at a given key",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
clientCtx := context.NewCLIContext().WithCodec(cdc)
res, height, err := cliCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryFunded))
res, height, err := clientCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryFunded))
if err != nil {
return err
}
var out sdk.Coins
cdc.MustUnmarshalJSON(res, &out)
cliCtx = cliCtx.WithHeight(height)
return cliCtx.PrintOutput(out)
clientCtx = clientCtx.WithHeight(height)
return clientCtx.PrintOutput(out)
},
}
}
+4 -4
View File
@@ -41,7 +41,7 @@ func GetCmdRequest(cdc *codec.Codec) *cobra.Command {
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
cliCtx := context.NewCLIContext().WithCodec(cdc)
clientCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(authclient.GetTxEncoder(cdc))
amount, err := sdk.ParseCoins(args[0])
@@ -51,7 +51,7 @@ func GetCmdRequest(cdc *codec.Codec) *cobra.Command {
var recipient sdk.AccAddress
if len(args) == 1 {
recipient = cliCtx.GetFromAddress()
recipient = clientCtx.GetFromAddress()
} else {
recipient, err = sdk.AccAddressFromBech32(args[1])
}
@@ -60,12 +60,12 @@ func GetCmdRequest(cdc *codec.Codec) *cobra.Command {
return err
}
msg := types.NewMsgFund(amount, cliCtx.GetFromAddress(), recipient)
msg := types.NewMsgFund(amount, clientCtx.GetFromAddress(), recipient)
if err := msg.ValidateBasic(); err != nil {
return err
}
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
return authclient.GenerateOrBroadcastMsgs(clientCtx, txBldr, []sdk.Msg{msg})
},
}
}
+10 -10
View File
@@ -15,9 +15,9 @@ import (
)
// RegisterRoutes register REST endpoints for the faucet module
func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc(fmt.Sprintf("/%s/request", types.ModuleName), requestHandler(cliCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/funded", types.ModuleName), fundedHandlerFn(cliCtx)).Methods("GET")
func RegisterRoutes(clientCtx context.CLIContext, r *mux.Router) {
r.HandleFunc(fmt.Sprintf("/%s/request", types.ModuleName), requestHandler(clientCtx)).Methods("POST")
r.HandleFunc(fmt.Sprintf("/%s/funded", types.ModuleName), fundedHandlerFn(clientCtx)).Methods("GET")
}
// PostRequestBody defines fund request's body.
@@ -27,10 +27,10 @@ type PostRequestBody struct {
Recipient string `json:"receipient" yaml:"receipient"`
}
func requestHandler(cliCtx context.CLIContext) http.HandlerFunc {
func requestHandler(clientCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req PostRequestBody
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
if !rest.ReadRESTReq(w, r, clientCtx.Codec, &req) {
rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request")
return
}
@@ -65,19 +65,19 @@ func requestHandler(cliCtx context.CLIContext) http.HandlerFunc {
return
}
authclient.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg})
authclient.WriteGenerateStdTxResponse(w, clientCtx, baseReq, []sdk.Msg{msg})
}
}
func fundedHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
func fundedHandlerFn(clientCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
res, height, err := cliCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryFunded))
res, height, err := clientCtx.Query(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryFunded))
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
cliCtx = cliCtx.WithHeight(height)
rest.PostProcessResponse(w, cliCtx, res)
clientCtx = clientCtx.WithHeight(height)
rest.PostProcessResponse(w, clientCtx, res)
}
}