cosmos-sdk/x/bank/client/cli/sendtx.go
Alexander Bezobchuk ea46da7126
Merge PR #3970: Fix Tx Sign Offline Mode
- Add shorthand flags `-a` and `-s` for the account and sequence numbers respectively
- Mark the account and sequence numbers required during "offline" mode
- Always do an RPC query for account and sequence number during "online" mode
  - If clients wish to provide such values, they must use `--offline`. This makes the whole flow/UX easier to reason about.

closes: #3893
2019-03-26 10:36:10 -04:00

71 lines
1.7 KiB
Go

package cli
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/spf13/cobra"
)
const (
flagTo = "to"
flagAmount = "amount"
)
// SendTxCmd will create a send tx and sign it with the given key.
func SendTxCmd(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "send [to_address] [amount]",
Short: "Create and sign a send tx",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
cliCtx := context.NewCLIContext().
WithCodec(cdc).
WithAccountDecoder(cdc)
if err := cliCtx.EnsureAccountExists(); err != nil {
return err
}
to, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
return err
}
// parse coins trying to be sent
coins, err := sdk.ParseCoins(args[1])
if err != nil {
return err
}
from := cliCtx.GetFromAddress()
account, err := cliCtx.GetAccount(from)
if err != nil {
return err
}
// ensure account has enough coins
if !account.GetCoins().IsAllGTE(coins) {
return fmt.Errorf("address %s doesn't have enough coins to pay for this transaction", from)
}
// build and sign the transaction, then broadcast to Tendermint
msg := bank.NewMsgSend(from, to, coins)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}, false)
},
}
cmd = client.PostCommands(cmd)[0]
cmd.MarkFlagRequired(client.FlagFrom)
return cmd
}