Module CLI

Command-Line Interface For CosmosSDK Module

Loc:cosmos-sdk/x/stake/client/cli/tx.go

stake的cli源码解析

1
func GetCmdDelegate(cdc *wire.Codec) *cobra.Command {
2
cmd := &cobra.Command{
3
Use: "delegate",
4
Short: "delegate coins to an existing validator/candidate",
5
RunE: func(cmd *cobra.Command, args []string) error {
6
...
Copied!
上面是Go语言 cobra 包 构建命令的基本结构,它主要是解析delegate命令。
    Use 代表子命令的名字
    RunE 命令的主要逻辑
1
amount, err := sdk.ParseCoin(viper.GetString(FlagAmount))
2
if err != nil {
3
return err
4
}
5
6
delegatorAddr, err := sdk.GetAddress(viper.GetString(FlagAddressDelegator))
7
candidateAddr, err := sdk.GetAddress(viper.GetString(FlagAddressCandidate))
8
if err != nil {
9
return err
10
}
11
12
msg := stake.NewMsgDelegate(delegatorAddr, candidateAddr, amount)
13
14
// build and sign the transaction, then broadcast to Tendermint
15
ctx := context.NewCoreContextFromViper().WithDecoder(authcmd.GetAccountDecoder(cdc))
16
17
res, err := ctx.EnsureSignBuildBroadcast(ctx.FromAddressName, msg, cdc)
18
if err != nil {
19
return err
20
}
21
22
fmt.Printf("Committed at block %d. Hash: %s\n", res.Height, res.Hash.String())
23
return nil
24
},
25
}
26
27
cmd.Flags().AddFlagSet(fsAmount)
28
cmd.Flags().AddFlagSet(fsDelegator)
29
cmd.Flags().AddFlagSet(fsCandidate)
30
return cmd
Copied!
    viper.GetString从相应的Flag字段获取字段后面的参数,以字符串读入。
    sdk.Parsecoin parses a cli input for one coin type
    sdk.GetAddress create an Address from a string
    stake.NewMsgDelegate 根据上面信息创建出msg
    最后构建和签名交易,在tendermint层进行广播
    AddFlagSet(fsAmount) 添加命令所需参数
1
const FlagAmount = "amount"
2
fsAmount = flag.NewFlagSet("", flag.ContinueOnError)
3
fsAmount.String(FlagAmount, "1steak", "Amount of coins to bond")
Copied!
fsAmount具体的构建流程

gaiacli 上面添加stake的cmd

1
// add query/post commands (custom to binary)
2
rootCmd.AddCommand(
3
client.GetCommands(
4
...
5
stakecmd.GetCmdQueryCandidate("stake", cdc),
6
stakecmd.GetCmdQueryCandidates("stake", cdc),
7
stakecmd.GetCmdQueryDelegatorBond("stake", cdc),
8
)...)
9
rootCmd.AddCommand(
10
client.PostCommands(
11
...
12
stakecmd.GetCmdDeclareCandidacy(cdc),
13
stakecmd.GetCmdEditCandidacy(cdc),
14
stakecmd.GetCmdDelegate(cdc),
15
stakecmd.GetCmdUnbond(cdc),
16
)...)
Copied!
    GetCommands() 添加查询的命令
    PostCommands() 添加带参数的命令
Last modified 3yr ago