Cosmos-- 三.教程 -- 10.Nameservice模块的CLI

cosmos主网即将上线,对文档做了大量更新。特地翻译了一下,方便小伙伴们阅览, 之后会持续更新

第三章教程:

  1. 开始
  2. 程序目标
  3. 开始编写你的程序
  4. Keeper
  5. Msg和Handler
  6. SetName
  7. BuyName
  8. Querier
  9. Codec文件
  10. Nameservice模块的CLI
  11. nameservice模块的REST接口
  12. 引入你的模块并完成程序
  13. Entrypoint
  14. 编译你的程序
  15. 编译并运行程序
  16. 运行REST路由

Nameservice模块的CLI

Cosmos SDK使用cobra库进行CLI交互。该库使每个模块都可以轻松地公开自己的操作命令。要开始定义用户与模块的CLI交互,请创建以下文件:

  • ./x/nameservice/client/cli/query.go
  • ./x/nameservice/client/cli/tx.go
  • ./x/nameservice/client/module_client.go

Querier

query.go文件中为你模块的每个Queryresolvewhois)定义cobra.Command:

package cli

import (
    "fmt"

    "github.com/cosmos/cosmos-sdk/client/context"
    "github.com/cosmos/cosmos-sdk/codec"
    "github.com/spf13/cobra"
)

// GetCmdResolveName queries information about a name
func GetCmdResolveName(queryRoute string, cdc *codec.Codec) *cobra.Command {
    return &cobra.Command{
        Use:   "resolve [name]",
        Short: "resolve name",
        Args:  cobra.ExactArgs(1),
        RunE: func(cmd *cobra.Command, args []string) error {
            cliCtx := context.NewCLIContext().WithCodec(cdc)
            name := args[0]

            res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/resolve/%s", queryRoute, name), nil)
            if err != nil {
                fmt.Printf("could not resolve name - %s \n", string(name))
                return nil
            }

            fmt.Println(string(res))

            return nil
        },
    }
}

// GetCmdWhois queries information about a domain
func GetCmdWhois(queryRoute string, cdc *codec.Codec) *cobra.Command {
    return &cobra.Command{
        Use:   "whois [name]",
        Short: "Query whois info of name",
        Args:  cobra.ExactArgs(1),
        RunE: func(cmd *cobra.Command, args []string) error {
            cliCtx := context.NewCLIContext().WithCodec(cdc)
            name := args[0]

            res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/whois/%s", queryRoute, name), nil)
            if err != nil {
                fmt.Printf("could not resolve whois - %s \n", string(name))
                return nil
            }

            fmt.Println(string(res))

            return nil
        },
    }
}

注意上述代码中:

  • CLI引入了一个新的context:CLIContext。它包含有关CLI交互所需的用户输入和应用程序配置的数据。
  • cliCtx.QueryWithData()函数所需的path直接从你的查询路径中映射。
    • 路径的第一部分用于区分SDK应用程序可能的querier类型:custom用于Querier
    • 第二部分(nameservice)是将查询路由到的模块的名称。
    • 最后是要调用模块中的特定的querier。
    • 在这个例子中,第四部分是查询。这是因为查询参数是一个简单的字符串。要启用更复杂的查询输入,你需要使用.QueryWithData()函数的第二个参数来传入data。有关此示例,请参阅Staking模块中的querier

Transaction

现在已经定义了查询交互,是时候继续在tx.go中的交易生成了:

你的应用程序需要导入你刚编写的代码。这里导入路径设置为此存储库(github.com/cosmos/sdk-application-tutorial/x/nameservice)。如果您是在自己的仓库中进行的前面的操作,则需要更改导入路径(github.com/{.Username}/{.Project.Repo}/x/nameservice)。

package cli

import (
    "github.com/spf13/cobra"

    "github.com/cosmos/cosmos-sdk/client/context"
    "github.com/cosmos/cosmos-sdk/client/utils"
    "github.com/cosmos/cosmos-sdk/codec"
    "github.com/cosmos/sdk-application-tutorial/x/nameservice"

    sdk "github.com/cosmos/cosmos-sdk/types"
    authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
)

// GetCmdBuyName is the CLI command for sending a BuyName transaction
func GetCmdBuyName(cdc *codec.Codec) *cobra.Command {
    return &cobra.Command{
        Use:   "buy-name [name] [amount]",
        Short: "bid for existing name or claim new name",
        Args:  cobra.ExactArgs(2),
        RunE: func(cmd *cobra.Command, args []string) error {
            cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc)

            txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))

            if err := cliCtx.EnsureAccountExists(); err != nil {
                return err
            }

            coins, err := sdk.ParseCoins(args[1])
            if err != nil {
                return err
            }

            msg := nameservice.NewMsgBuyName(args[0], coins, cliCtx.GetFromAddress())
            err = msg.ValidateBasic()
            if err != nil {
                return err
            }

            cliCtx.PrintResponse = true

            return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, []sdk.Msg{msg})
        },
    }
}

// GetCmdSetName is the CLI command for sending a SetName transaction
func GetCmdSetName(cdc *codec.Codec) *cobra.Command {
    return &cobra.Command{
        Use:   "set-name [name] [value]",
        Short: "set the value associated with a name that you own",
        Args:  cobra.ExactArgs(2),
        RunE: func(cmd *cobra.Command, args []string) error {
            cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc)

            txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))

            if err := cliCtx.EnsureAccountExists(); err != nil {
                return err
            }

            msg := nameservice.NewMsgSetName(args[0], args[1], cliCtx.GetFromAddress())
            err := msg.ValidateBasic()
            if err != nil {
                return err
            }

            cliCtx.PrintResponse = true

            // return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
            return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, []sdk.Msg{msg})
        },
    }
}

注意在上述代码中:

Module Client

导出此功能的最后一部分称为ModuleClient,在./x/nameservice/client/module_client.go文件中实现。Module Client为模块提供了导出客户端功能的标准方法。

注意:你的应用程序需要导入你刚编写的代码。这里导入路径设置为此仓库(github.com/cosmos/sdk-application-tutorial/x/nameservice)。如果你是在自己项目中编写的,则需要更改导入路径成(github.com/{.Username}/ {.Project.Repo}/x/nameservice)。

package client

import (
    "github.com/cosmos/cosmos-sdk/client"
    nameservicecmd "github.com/cosmos/sdk-application-tutorial/x/nameservice/client/cli"
    "github.com/spf13/cobra"
    amino "github.com/tendermint/go-amino"
)

// ModuleClient exports all client functionality from this module
type ModuleClient struct {
    storeKey string
    cdc      *amino.Codec
}

func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient {
    return ModuleClient{storeKey, cdc}
}

// GetQueryCmd returns the cli query commands for this module
func (mc ModuleClient) GetQueryCmd() *cobra.Command {
    // Group gov queries under a subcommand
    govQueryCmd := &cobra.Command{
        Use:   "nameservice",
        Short: "Querying commands for the nameservice module",
    }

    govQueryCmd.AddCommand(client.GetCommands(
        nameservicecmd.GetCmdResolveName(mc.storeKey, mc.cdc),
        nameservicecmd.GetCmdWhois(mc.storeKey, mc.cdc),
    )...)

    return govQueryCmd
}

// GetTxCmd returns the transaction commands for this module
func (mc ModuleClient) GetTxCmd() *cobra.Command {
    govTxCmd := &cobra.Command{
        Use:   "nameservice",
        Short: "Nameservice transactions subcommands",
    }

    govTxCmd.AddCommand(client.PostCommands(
        nameservicecmd.GetCmdBuyName(mc.cdc),
        nameservicecmd.GetCmdSetName(mc.cdc),
    )...)

    return govTxCmd
}

上述代码要注意:

  • 此抽象允许客户端以标准方式从模块导入客户端功能。当我们构建入口时,你将看到这一点。
  • 有一个未解决的问题是将其余功能(在本教程的下一部分中描述)添加到此接口。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容