forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendtx.go
66 lines (55 loc) · 1.68 KB
/
sendtx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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)
},
}
return client.PostCommands(cmd)[0]
}