Cosmos-- 三.教程 -- 12.引入你的模块并完成程序

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路由

引入你的模块并完成程序

现在你的模块已就绪,它可以和其它两个模块authbank被合并到./app.go文件中:

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

package app

import (
    "encoding/json"

    "github.com/tendermint/tendermint/libs/log"

    "github.com/cosmos/cosmos-sdk/codec"
    "github.com/cosmos/cosmos-sdk/x/auth"
    "github.com/cosmos/cosmos-sdk/x/bank"
    "github.com/cosmos/cosmos-sdk/x/params"
    "github.com/cosmos/cosmos-sdk/x/staking"
    "github.com/cosmos/sdk-application-tutorial/x/nameservice"

    bam "github.com/cosmos/cosmos-sdk/baseapp"
    sdk "github.com/cosmos/cosmos-sdk/types"
    abci "github.com/tendermint/tendermint/abci/types"
    cmn "github.com/tendermint/tendermint/libs/common"
    dbm "github.com/tendermint/tendermint/libs/db"
    tmtypes "github.com/tendermint/tendermint/types"
)

接下来,你需要在nameServiceApp结构体中添加存储的key和Keepers,并更新构造函数:

const (
    appName = "nameservice"
)

type nameServiceApp struct {
    *bam.BaseApp
    cdc *codec.Codec

    keyMain          *sdk.KVStoreKey
    keyAccount       *sdk.KVStoreKey
    keyNSnames       *sdk.KVStoreKey
    keyNSowners      *sdk.KVStoreKey
    keyNSprices      *sdk.KVStoreKey
    keyFeeCollection *sdk.KVStoreKey
    keyParams        *sdk.KVStoreKey
    tkeyParams       *sdk.TransientStoreKey

    accountKeeper       auth.AccountKeeper
    bankKeeper          bank.Keeper
    feeCollectionKeeper auth.FeeCollectionKeeper
    paramsKeeper        params.Keeper
    nsKeeper            nameservice.Keeper
}

func NewNameServiceApp(logger log.Logger, db dbm.DB) *nameServiceApp {

  // First define the top level codec that will be shared by the different modules
  cdc := MakeCodec()

  // BaseApp handles interactions with Tendermint through the ABCI protocol
  bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc))

  // Here you initialize your application with the store keys it requires
    var app = &nameServiceApp{
        BaseApp: bApp,
        cdc:     cdc,

        keyMain:          sdk.NewKVStoreKey("main"),
        keyAccount:       sdk.NewKVStoreKey("acc"),
        keyNSnames:       sdk.NewKVStoreKey("ns_names"),
        keyNSowners:      sdk.NewKVStoreKey("ns_owners"),
        keyNSprices:      sdk.NewKVStoreKey("ns_prices"),
        keyFeeCollection: sdk.NewKVStoreKey("fee_collection"),
        keyParams:        sdk.NewKVStoreKey("params"),
        tkeyParams:       sdk.NewTransientStoreKey("transient_params"),
    }

  return app
}

此时,构造函数仍然缺乏重要的逻辑。它需要:

  • 从每个所需模块中实例化所需的Keeper
  • 生成每个Keeper所需的storeKey
  • 注册每个模块的handlerbaseapp路由器的AddRoute()方法用来做这个。
  • 注册每个模块的querierbaseappqueryRouter中的AddRoute()方法用来做这个。
  • KVStores挂载到baseApp的multistore提供的key值。
  • 设置initChainer来定义初始应用程序状态。

你最终的构造函数应该如下所示:

// NewNameServiceApp is a constructor function for nameServiceApp
func NewNameServiceApp(logger log.Logger, db dbm.DB) *nameServiceApp {

    // First define the top level codec that will be shared by the different modules
    cdc := MakeCodec()

    // BaseApp handles interactions with Tendermint through the ABCI protocol
    bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc))

    // Here you initialize your application with the store keys it requires
    var app = &nameServiceApp{
        BaseApp: bApp,
        cdc:     cdc,

        keyMain:          sdk.NewKVStoreKey("main"),
        keyAccount:       sdk.NewKVStoreKey("acc"),
        keyNSnames:       sdk.NewKVStoreKey("ns_names"),
        keyNSowners:      sdk.NewKVStoreKey("ns_owners"),
        keyNSprices:      sdk.NewKVStoreKey("ns_prices"),
        keyFeeCollection: sdk.NewKVStoreKey("fee_collection"),
        keyParams:        sdk.NewKVStoreKey("params"),
        tkeyParams:       sdk.NewTransientStoreKey("transient_params"),
    }

    // The ParamsKeeper handles parameter storage for the application
    app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams, app.tkeyParams)

    // The AccountKeeper handles address -> account lookups
    app.accountKeeper = auth.NewAccountKeeper(
        app.cdc,
        app.keyAccount,
        app.paramsKeeper.Subspace(auth.DefaultParamspace),
        auth.ProtoBaseAccount,
    )

    // The BankKeeper allows you perform sdk.Coins interactions
    app.bankKeeper = bank.NewBaseKeeper(
        app.accountKeeper,
        app.paramsKeeper.Subspace(bank.DefaultParamspace),
        bank.DefaultCodespace,
    )

    // The FeeCollectionKeeper collects transaction fees and renders them to the fee distribution module
    app.feeCollectionKeeper = auth.NewFeeCollectionKeeper(cdc, app.keyFeeCollection)

    // The NameserviceKeeper is the Keeper from the module for this tutorial
    // It handles interactions with the namestore
    app.nsKeeper = nameservice.NewKeeper(
        app.bankKeeper,
        app.keyNSnames,
        app.keyNSowners,
        app.keyNSprices,
        app.cdc,
    )

    // The AnteHandler handles signature verification and transaction pre-processing
    app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper))

    // The app.Router is the main transaction router where each module registers its routes
    // Register the bank and nameservice routes here
    app.Router().
        AddRoute("bank", bank.NewHandler(app.bankKeeper)).
        AddRoute("nameservice", nameservice.NewHandler(app.nsKeeper))

    // The app.QueryRouter is the main query router where each module registers its routes
    app.QueryRouter().
        AddRoute("nameservice", nameservice.NewQuerier(app.nsKeeper))

    // The initChainer handles translating the genesis.json file into initial state for the network
    app.SetInitChainer(app.initChainer)

    app.MountStores(
        app.keyMain,
        app.keyAccount,
        app.keyNSnames,
        app.keyNSowners,
        app.keyNSprices,
        app.keyFeeCollection,
        app.keyParams,
        app.tkeyParams,
    )

    err := app.LoadLatestVersion(app.keyMain)
    if err != nil {
        cmn.Exit(err.Error())
    }

    return app
}

注意:上面提到的TransientStore是KVStore的内存实现,用于未持久化的状态。

initChainer定义了genesis.json中的帐户如何在初始化区块链时被映射到应用程序状态。ExportAppStateAndValidators函数可帮助引导初始化应用程序的状态。你现在不需要太关心它们。

构造函数注册了initChainer函数,但尚未定义。继续创建它:

// GenesisState represents chain state at the start of the chain. Any initial state (account balances) are stored here.
type GenesisState struct {
    AuthData auth.GenesisState   `json:"auth"`
    BankData bank.GenesisState   `json:"bank"`
    Accounts []*auth.BaseAccount `json:"accounts"`
}

func (app *nameServiceApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
    stateJSON := req.AppStateBytes

    genesisState := new(GenesisState)
    err := app.cdc.UnmarshalJSON(stateJSON, genesisState)
    if err != nil {
        panic(err)
    }

    for _, acc := range genesisState.Accounts {
        acc.AccountNumber = app.accountKeeper.GetNextAccountNumber(ctx)
        app.accountKeeper.SetAccount(ctx, acc)
    }

    auth.InitGenesis(ctx, app.accountKeeper, app.feeCollectionKeeper, genesisState.AuthData)
    bank.InitGenesis(ctx, app.bankKeeper, genesisState.BankData)

    return abci.ResponseInitChain{}
}

// ExportAppStateAndValidators does the things
func (app *nameServiceApp) ExportAppStateAndValidators() (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) {
    ctx := app.NewContext(true, abci.Header{})
    accounts := []*auth.BaseAccount{}

    appendAccountsFn := func(acc auth.Account) bool {
        account := &auth.BaseAccount{
            Address: acc.GetAddress(),
            Coins:   acc.GetCoins(),
        }

        accounts = append(accounts, account)
        return false
    }

    app.accountKeeper.IterateAccounts(ctx, appendAccountsFn)

    genState := GenesisState{
        Accounts: accounts,
        AuthData: auth.DefaultGenesisState(),
        BankData: bank.DefaultGenesisState(),
    }

    appState, err = codec.MarshalJSONIndent(app.cdc, genState)
    if err != nil {
        return nil, nil, err
    }

    return appState, validators, err
}

最后添加一个辅助函数来生成一个animo--*codec.Codec,它可以正确地注册你应用程序中使用的所有模块:

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

推荐阅读更多精彩内容