bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 71쪽
dd", Use: "add [amount]", Short: "Add to the counter",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{{ProtoField: "add"}}},
},
},
}
}
```
`PositionalArgs` maps the first CLI argument to the `add` field in `MsgAddRequest`, so `add 4` works instead of `add --add 4`.
## Step 10: Wire into app.go
In this step, you wire your new module into the application so the chain creates its store, constructs its keeper, and includes it in module startup and genesis handling. For a full explanation of what `app.go` does and why the wiring order matters, see [app.go Overview](/sdk/latest/learn/concepts/app-go).
Open `app.go` and find each marker comment. Paste the code directly below it.
### 1. Imports
Add the counter module, keeper, and shared types imports to `app.go`.
Find the comment in `app.go` and add the code directly below it.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 1: add counter imports below
counter "github.com/cosmos/example/x/counter"
counterkeeper "github.com/cosmos/example/x/counter/keeper"
countertypes "github.com/cosmos/example/x/counter/types"
```
### 2. Keeper Field
Store the counter keeper on `ExampleApp` so the rest of the app can reference it.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 2: add the counter keeper field below
CounterKeeper *counterkeeper.Keeper
```
### 3. Store Key
Give the counter module its own KV store namespace.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 3: add the counter store key below
countertypes.StoreKey,
```
### 4. Keeper Instantiation
Construct the counter keeper using the module store and app codec.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 4: create the counter keeper below
app.CounterKeeper = counterkeeper.NewKeeper(
runtime.NewKVStoreService(keys[countertypes.StoreKey]),
appCodec,
)
```
### 5. Module Manager
Register the counter module with the app's module manager.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 5: register the counter module below
counter.NewAppModule(appCodec, app.CounterKeeper),
```
### 6. Genesis Order
Include the counter module when the app initializes state from genesis.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 6: add the counter module to genesis order below
countertypes.ModuleName,
```
### 7. Export Order
Include the counter module when the app exports state back out to genesis.
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// counter tutorial app wiring 7: add the counter module to export order below
countertypes.ModuleName,
```
## Step 11: Build
Run the following to compile the app and make sure the new module wiring is valid before you try to run the chain.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
go build ./...
```
Fix any compilation errors before continuing.
## Step 12: Test your module
Now you'll run the app locally and use one transaction plus one query to confirm the module works end-to-end.
### Start the chain
First, install the binary and start the demo chain.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
make install
make start
```
This builds and installs `exampled` and then runs `scripts/local_node.sh`, which:
* resets the local chain data
* initializes genesis
* creates and funds the `alice` and `bob` test accounts
* creates a validator transaction
* starts the chain
You'll see the chain running and it should start producing blocks.
### Submit a transaction
Open a second terminal and submit a transaction that adds `4` to the counter:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled tx counter add 4 --from alice --chain-id demo --yes
```
If the transaction succeeds, the response should include `code: 0`, which means the chain accepted the
transaction and it passed validation without an application error:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
code: 0
codespace: ""
data: ""
events: []
gas_used: "0"
gas_wanted: "0"
height: "0"
info: ""
logs: []
raw_log: ""
timestamp: ""
tx: null
txhash: 548D95784704575A347140E05A3ED84A05067DF4AD43F8E6FA20C94FAE8430E0
```
This is the broadcast acknowledgement, returned before the transaction is in a block, so `height: "0"`
and the empty fields are expected rather than a sign of failure. To see the executed result, query the
transaction by its hash:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled query tx <txhash>
```
### Query the chain
Query the counter to confirm the stored value changed using the query command that `AutoCLI` generated earlier:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled query counter count
```
You should see the following output:
```text theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
count: "4"
```
Congratulations, you've just created a Cosmos module from scratch and wired it into a real chain!
If you are planning to build a production module, see [Module Design Considerations](/sdk/latest/guides/module-design/module-design-considerations) for guidance on state structure, message surface, dependencies, and upgrade planning before you ship.
## Next steps
The simple counter module you built here follows the same structure as the full `x/counter` example in the `main` branch. Next, you'll see how the full module extends that foundation with features like params, fee collection, tests, and more.
Next: [Full Counter Module Walkthrough →](/sdk/latest/tutorials/example/04-counter-walkthrough)
# Full Counter Module Walkthrough
Source: https://docs.cosmos.network/sdk/latest/tutorials/example/04-counter-walkthrough
If you came here from the module building tutorial, switch back to the `main` branch of the [`cosmos/example` repo](https://github.com/cosmos/example) first:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
git checkout main
```
The minimal counter you built in the previous tutorial captures the core SDK module pattern. The full `x/counter` module example in `main` follows the same pattern and adds several features on top.
This walkthrough is meant to show you exactly what each feature is, what it does, and how you can add a similar feature to any module.
## Minimal vs full counter
The full counter in the `main` branch adds quite a bit of functionality to the minimal tutorial counter.
| Feature | minimal x/counter | full x/counter |
| - | - | - |
| [State](#params-and-authority) | `count` | `count` + `params` |
| [Messages](#params-and-authority) | `Add` | `Add` + `UpdateParams` |
| [Queries](#params-and-authority) | `Count` | `Count` + `Params` |
| [Validation](#expected-keepers-and-fee-collection) | None | `MaxAddValue` limit, overflow check |
| [Fees](#expected-keepers-and-fee-collection) | None | `AddCost` charged via bank module |
| [Authority](#params-and-authority) | None | Governance-gated param updates |
| [Errors](#sentinel-errors) | Generic | Named sentinel errors |
| [Telemetry](#telemetry) | None | OpenTelemetry counter metric |
| [CLI](#autocli) | AutoCLI | AutoCLI + `EnhanceCustomCommand` |
| [Simulation](#simulation) | None | `simsx` weighted operations |
| [Block hooks](#beginblock-and-endblock) | None | `BeginBlock` + `EndBlock` |
| [Unit tests](#unit-tests) | None | Full keeper/msg/query test suite |
The wiring code in [`msg_server.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/msg_server.go), [`query_server.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/query_server.go), [`module.go`](https://github.com/cosmos/example/blob/main/x/counter/module.go), and [`types/`](https://github.com/cosmos/example/tree/main/x/counter/types) is structurally similar between the two. Much of the new keeper logic lives in a single method: `AddCount` in [`keeper.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper.go).
## Params and authority
A [module param](/sdk/latest/learn/concepts/modules#params) is on-chain configuration that controls how the module behaves without changing the code.
The full counter adds a `Params` type that lets the chain governance configure the module's behavior at runtime. In the full module, params control how large an `Add` can be and how much it costs.
### Where the code lives
* [`proto/example/counter/v1/state.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/state.proto) defines the `Params` type
* [`proto/example/counter/v1/tx.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/tx.proto) adds the `UpdateParams` message
* [`proto/example/counter/v1/query.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/query.proto) adds the `Params` query
* [`x/counter/keeper/keeper.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper.go) stores the params and authority
* [`x/counter/keeper/msg_server.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/msg_server.go) checks the authority on updates
* [`x/counter/keeper/query_server.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/query_server.go) returns the current params
### Try it
You can inspect the current params with:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled query counter params
```
### Add this to your module
To add runtime-configurable params to your own module, make these changes:
1. Define a `Params` type in proto
2. Add a privileged `UpdateParams` message
3. Add a query to read the current params
4. Store the params and authority in your keeper
5. Check the authority in `MsgServer` before writing new params
### state.proto
The relevant addition in [`state.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/state.proto) is:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
message Params {
uint64 max_add_value = 1;
repeated cosmos.base.v1beta1.Coin add_cost = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins",
(amino.dont_omitempty) = true
];
}
```
`MaxAddValue` caps how much a single `Add` call can increment the counter. `AddCost` sets an optional fee charged for each add operation.
### tx.proto - UpdateParams
The relevant addition in [`tx.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/tx.proto) is:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse);
message MsgUpdateParams {
option (cosmos.msg.v1.signer) = "authority";
string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
Params params = 2 [(gogoproto.nullable) = false];
}
message MsgUpdateParamsResponse {}
```
`UpdateParams` is a privileged message. Only the `authority` address can call it. By default that address is the governance module account, so params can only be changed through a governance proposal.
### query.proto - Params
[`query.proto`](https://github.com/cosmos/example/blob/main/proto/example/counter/v1/query.proto) adds a second query to expose the current params:
```proto theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
rpc Params(QueryParamsRequest) returns (QueryParamsResponse);
```
### The authority pattern
The keeper stores the authority address and checks it on every `UpdateParams` call:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type Keeper struct {
// ...
// authority is the address capable of executing a MsgUpdateParams message.
// Typically, this should be the x/gov module account.
authority string
}
```
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// msg_server.go
func (m msgServer) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
if m.authority != msg.Authority {
return nil, sdkerrors.Wrapf(govtypes.ErrInvalidSigner,
"invalid authority; expected %s, got %s", m.authority, msg.Authority)
}
if err := m.SetParams(ctx, msg.Params); err != nil {
return nil, err
}
return &types.MsgUpdateParamsResponse{}, nil
}
```
The authority defaults to the governance module account at keeper construction:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(),
```
This pattern, storing authority in the keeper and checking it in `MsgServer`, is the standard Cosmos SDK approach to governance-gated configuration.
To point a module at a different authority, `NewKeeper` accepts functional options. `WithAuthority` replaces the default after the keeper is built:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// x/counter/keeper/keeper.go
type Options func(k *Keeper)
// WithAuthority sets a custom authority on the module. This allows developers to set accounts other than the
// governance module to control this module's params.
func WithAuthority(authority string) Options {
return func(k *Keeper) {
k.authority = authority
}
}
```
Most chains keep the governance default, so `app.go` passes no options.
## Expected keepers and fee collection
This section shows the standard Cosmos SDK pattern for [module-to-module interaction](/sdk/latest/learn/concepts/modules#inter-module-access). `x/counter` uses an expected keeper to call into the bank module and charge a fee for each add operation.
### Where the code lives
* [`x/counter/types/expected_keepers.go`](https://github.com/cosmos/example/blob/main/x/counter/types/expected_keepers.go) defines the narrow bank keeper interface
* [`x/counter/keeper/keeper.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper.go) stores the bank keeper dependency and charges the fee in `AddCount`
* [`app.go`](https://github.com/cosmos/example/blob/main/app.go) passes `app.BankKeeper` into `counterkeeper.NewKeeper`
* [`app.go`](https://github.com/cosmos/example/blob/main/app.go) adds a module account entry so the counter module can receive fees
### app.go changes
This feature requires two `app.go` changes:
* add `countertypes.ModuleName: nil` to `maccPerms`
* pass `app.BankKeeper` into `counterkeeper.NewKeeper(...)`
In [`app.go`](https://github.com/cosmos/example/blob/main/app.go), those changes look like this:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
maccPerms = map[string][]string{
// ...
countertypes.ModuleName: nil,
}
```
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.CounterKeeper = counterkeeper.NewKeeper(
runtime.NewKVStoreService(keys[countertypes.StoreKey]),
appCodec,
app.BankKeeper,
)
```
The full signature is `NewKeeper(storeService, cdc, bankKeeper, opts ...Options)`. The trailing options are how you override the default governance authority, covered in [the authority pattern](#the-authority-pattern) above.
### Try it
Submit an add transaction and the configured `AddCost` fee will be charged from the sender:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled tx counter add 5 --from alice --chain-id demo --yes
```
### Add this to your module
To add fee collection through the bank module, make these changes:
1. Define a narrow bank keeper interface in `types/expected_keepers.go`
2. Add a `bankKeeper` field to your keeper
3. Charge the fee inside your keeper business logic
4. Add a module account entry in `maccPerms`
5. Pass `app.BankKeeper` into your keeper constructor in `app.go`
### expected\_keepers.go
Rather than importing the bank module directly, the counter module defines the minimal interface it needs:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// x/counter/types/expected_keepers.go
type BankKeeper interface {
SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
}
```
This keeps the dependency explicit and narrow. The counter module cannot accidentally call any other bank method.
### Keeper struct
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type Keeper struct {
Schema collections.Schema
counter collections.Item[uint64]
params collections.Item[types.Params]
bankKeeper types.BankKeeper
authority string
}
```
### Fee charging in AddCount
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (k *Keeper) AddCount(ctx context.Context, sender string, amount uint64) (uint64, error) {
params, err := k.GetParams(ctx)
if err != nil {
return 0, err
}
if params.MaxAddValue > 0 && amount > params.MaxAddValue {
return 0, ErrExceedsMaxAdd
}
count, err := k.GetCount(ctx)
if err != nil {
return 0, err
}
// Reject adds that would wrap the counter past the top of the uint64 range.
// Written as a subtraction so the check itself cannot overflow. MaxAddValue
// usually keeps amount small, but setting it to 0 disables that cap, so the
// result has to be checked here rather than inferred from the input.
if amount > math.MaxUint64-count {
return 0, ErrNumTooLarge
}
// Charge the user if add cost is set. All validation happens above, so a
// rejected add never reaches this point.
if !params.AddCost.IsZero() {
senderAddr, err := sdk.AccAddressFromBech32(sender)
if err != nil {
return 0, err
}
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, senderAddr, types.ModuleName, params.AddCost); err != nil {
return 0, sdkerrors.Wrap(ErrInsufficientFunds, err.Error())
}
}
newCount := count + amount
if err := k.counter.Set(ctx, newCount); err != nil {
return 0, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
"count_increased",
sdk.NewAttribute("count", fmt.Sprintf("%v", newCount)),
),
)
countMetric.Add(ctx, int64(amount))
return newCount, nil
}
```
Note the shape of the overflow guard. Go wraps silently on unsigned overflow, so `count + amount` exceeding the `uint64` range would leave the counter holding a smaller number with no error raised. Testing the input alone cannot catch that, because the value that overflows is the sum. Comparing `amount` against `math.MaxUint64 - count` tests the result while keeping the comparison itself inside the range. Any module doing unchecked arithmetic on user-supplied values needs the same treatment.
All the business logic, validation, fee charging, state mutation, events, and telemetry, lives in `AddCount`. The `MsgServer` stays thin:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (m msgServer) Add(ctx context.Context, request *types.MsgAddRequest) (*types.MsgAddResponse, error) {
newCount, err := m.AddCount(ctx, request.GetSender(), request.GetAdd())
if err != nil {
return nil, err
}
return &types.MsgAddResponse{UpdatedCount: newCount}프로젝트로 돌아가기