bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 72쪽
, nil
}
```
Because `AddCount` is a named keeper method, it can also be called from `BeginBlock`, governance hooks, or other modules, not just from the `MsgServer`.
### Module accounts
A module account is an on-chain account owned by a module instead of a user. Modules use module accounts to hold funds, receive fees, or get special permissions like minting or burning.
Because `x/counter` receives fees from users, it needs a module account entry in [`app.go`](https://github.com/cosmos/example/blob/main/app.go):
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
maccPerms = map[string][]string{
// ...
countertypes.ModuleName: nil,
}
```
This lives in the `maccPerms` map in [`app.go`](https://github.com/cosmos/example/blob/main/app.go). Here, `nil` means the module account can receive funds but does not get extra permissions like minting or burning.
## Sentinel errors
Rather than returning generic errors, `x/counter` defines named sentinel errors with registered codes. That makes failures easier to understand and easier for clients to match on programmatically.
### Where the code lives
* [`x/counter/keeper/errors.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/errors.go) defines the registered module errors
* [`x/counter/keeper/keeper.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper.go) returns those errors from business logic checks
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// keeper/errors.go
var (
// Codes start at 2: code 0 is reserved for success and code 1 for internal errors.
ErrNumTooLarge = errors.Register("counter", 2, "requested integer to add is too large")
ErrExceedsMaxAdd = errors.Register("counter", 3, "add value exceeds max allowed")
ErrInsufficientFunds = errors.Register("counter", 4, "insufficient funds to pay add cost")
)
```
Registered errors produce structured error responses on-chain that clients can match against by code, not just by string. Each error code must be unique within the module and start at `2`: code `0` is the ABCI success code, and code `1` is reserved for internal errors. Registering an error as code `0` is accepted silently, but a transaction failing with it reports `code: 0`, which every client reads as success. To check whether an error is of a specific sentinel type, use `errors.Is(err, ErrInsufficientFunds)`. This works correctly even when the error has been wrapped with additional context via `errorsmod.Wrap` or `errorsmod.Wrapf`.
All validation — both stateless field checks and stateful business logic checks — should live in the `msgServer` method or the keeper function it calls. The older `ValidateBasic` method on message types is deprecated: prefer performing all validation inside the message server. If your message type does implement `ValidateBasic`, the SDK still calls it for backward compatibility, but new modules should not rely on it.
## Telemetry
[Telemetry](/sdk/latest/guides/testing/telemetry) records how often the counter is updated so you can observe module activity in an OpenTelemetry-compatible system.
### Where the code lives
* [`x/counter/keeper/telemetry.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/telemetry.go) defines the meter and counter metric
* [`x/counter/keeper/keeper.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper.go) records the metric from `AddCount`
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// x/counter/keeper/telemetry.go
var (
meter = otel.Meter("github.com/cosmos/example/x/counter")
countMetric metric.Int64Counter
)
func init() {
var err error
countMetric, err = meter.Int64Counter("count")
if err != nil {
panic(err)
}
}
```
`countMetric.Add(ctx, int64(amount))` in `AddCount` increments an OpenTelemetry counter every time the module state is updated. This makes module activity visible in any OTel-compatible observability system.
## AutoCLI
[AutoCLI](/sdk/latest/guides/tooling/autocli) exposes the module's queries and transactions as CLI commands. The full module example keeps the same basic AutoCLI setup as the minimal module and adds the recommended setting for custom command integration.
### Where the code lives
* [`x/counter/autocli.go`](https://github.com/cosmos/example/blob/main/x/counter/autocli.go) defines the generated query and tx commands
### Try it
These commands come from the AutoCLI configuration. `count` and `add` are customized explicitly in `autocli.go`, and `params` is still available from the generated query service.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled query counter count
exampled query counter params
exampled tx counter add 5 --from alice --chain-id demo --yes
```
Both modules use AutoCLI. The only difference is that `x/counter` sets `EnhanceCustomCommand: true`, which merges any hand-written CLI commands with the auto-generated ones. Since neither module has hand-written commands, it is a no-op here, but it is a good default for fuller modules.
The [`autocli.go`](https://github.com/cosmos/example/blob/main/x/counter/autocli.go) file in `x/counter`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// autocli.go
func (a AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
return &autocliv1.ModuleOptions{
Query: &autocliv1.ServiceCommandDescriptor{
Service: "example.counter.Query",
EnhanceCustomCommand: true,
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "Count",
Use: "count",
Short: "Query the current counter value",
},
},
},
Tx: &autocliv1.ServiceCommandDescriptor{
Service: "example.counter.Msg",
EnhanceCustomCommand: true,
RpcCommandOptions: []*autocliv1.RpcCommandOptions{
{
RpcMethod: "Add",
Use: "add [amount]",
Short: "Add to the counter",
PositionalArgs: []*autocliv1.PositionalArgDescriptor{{ProtoField: "add"}},
},
},
},
}
}
```
## Simulation
[Simulation](/sdk/latest/guides/testing/simulator) lets the SDK generate randomized transactions against the module during fuzz-style testing.
### Where the code lives
* [`x/counter/simulation/msg_factory.go`](https://github.com/cosmos/example/blob/main/x/counter/simulation/msg_factory.go) defines how to generate random `Add` messages
* [`x/counter/module.go`](https://github.com/cosmos/example/blob/main/x/counter/module.go) registers those weighted operations
### Test it
You can exercise simulation through the repo's simulation test targets described in the running and testing tutorial.
`x/counter` implements `simsx`-based simulation, which lets the SDK's simulation framework generate random `Add` transactions during fuzz testing:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
// x/counter/simulation/msg_factory.go
func MsgAddFactory() simsx.SimMsgFactoryFn[*types.MsgAddRequest] {
return func(ctx context.Context, testData *simsx.ChainDataSource, reporter simsx.SimulationReporter) ([]simsx.SimAccount, *types.MsgAddRequest) {
sender := testData.AnyAccount(reporter)
if reporter.IsSkipped() {
return nil, nil
}
r := testData.Rand()
addAmount := uint64(r.Intn(100) + 1)
msg := &types.MsgAddRequest{
Sender: sender.AddressBech32,
Add: addAmount,
}
return []simsx.SimAccount{sender}, msg
}
}
```
`module.go` registers this factory:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (a AppModule) WeightedOperationsX(weights simsx.WeightSource, reg simsx.Registry) {
reg.Add(weights.Get("msg_add", 100), simulation.MsgAddFactory())
}
```
## BeginBlock and EndBlock
These [hooks](/sdk/latest/learn/concepts/modules#block-hooks) let a module run code automatically at the start or end of every block. In `x/counter`, they are purposefully empty to demonstrate where and how these features can be added.
### Where the code lives
* [`x/counter/module.go`](https://github.com/cosmos/example/blob/main/x/counter/module.go) implements `BeginBlock` and `EndBlock`
* [`app.go`](https://github.com/cosmos/example/blob/main/app.go) adds the module to `SetOrderBeginBlockers` and `SetOrderEndBlockers`
### app.go changes
Because the module advertises block hooks, [`app.go`](https://github.com/cosmos/example/blob/main/app.go) must include `countertypes.ModuleName` in both blocker order lists.
### Add this to your module
To add begin and end blockers to your own module, make two changes:
1. Implement the hooks in `x/<module>/module.go`
2. Add your module name to `SetOrderBeginBlockers` and `SetOrderEndBlockers` in `app.go`
`module.go` implements `HasBeginBlocker` and `HasEndBlocker`:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
func (a AppModule) BeginBlock(ctx context.Context) error {
// optional: logic to execute at the start of every block
return nil
}
func (a AppModule) EndBlock(ctx context.Context) error {
// optional: logic to execute at the end of every block
return nil
}
```
In [`app.go`](https://github.com/cosmos/example/blob/main/app.go), the module is added to the blocker order lists like this:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
app.ModuleManager.SetOrderBeginBlockers(
// ...
countertypes.ModuleName,
)
app.ModuleManager.SetOrderEndBlockers(
// ...
countertypes.ModuleName,
)
```
`x/counter` has no per-block logic, so both methods return nil. They exist to demonstrate the pattern: modules that need per-block execution (staking, distribution) implement real logic here. For example, a counter that auto-increments every block would call `k.AddCount(ctx, 1)` from `BeginBlock` instead of exposing a message type.
## Unit tests
The full module example includes a real [test suite](/sdk/latest/learn/concepts/testing) for keeper logic, query behavior, message handling, and bank keeper interactions.
### Where the code lives
* [`x/counter/keeper/keeper_test.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper_test.go)
* [`x/counter/keeper/msg_server_test.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/msg_server_test.go)
* [`x/counter/keeper/query_server_test.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/query_server_test.go)
### Run them
You can run the counter module tests directly with:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
go test ./x/counter/...
```
### Add this to your module
Start with keeper, message server, and query server tests. If your module depends on another keeper, use a small mock interface like `MockBankKeeper` so you can control success and failure cases in isolation.
`x/counter` ships a full test suite in [`x/counter/keeper/`](https://github.com/cosmos/example/tree/main/x/counter/keeper):
| File | What it tests |
| - | - |
| `keeper_test.go` | `KeeperTestSuite` setup, `InitGenesis`, `ExportGenesis`, `GetCount`, `AddCount`, `SetParams` |
| `msg_server_test.go` | `MsgAdd`, event emission, `MsgUpdateParams` |
| `query_server_test.go` | `QueryCount`, `QueryParams` |
All three files share the `KeeperTestSuite` struct defined in [`keeper_test.go`](https://github.com/cosmos/example/blob/main/x/counter/keeper/keeper_test.go), which sets up an isolated in-memory store, a mock bank keeper, and a real keeper instance:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type KeeperTestSuite struct {
suite.Suite
ctx sdk.Context
keeper *keeper.Keeper
queryClient types.QueryClient
msgServer types.MsgServer
bankKeeper *MockBankKeeper
authority string
}
```
`MockBankKeeper` lets tests control exactly what the bank keeper returns without needing a real bank module:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
type MockBankKeeper struct {
SendCoinsFromAccountToModuleFn func(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
}
```
Tests set `SendCoinsFromAccountToModuleFn` to simulate success or failure:
```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
s.bankKeeper.SendCoinsFromAccountToModuleFn = func(...) error {
return errors.New("insufficient funds")
}
```
## Gas
`minimum-gas-prices` in `app.toml` sets the minimum fee a node requires before it will accept and relay a transaction. The local dev chain started by `make start` sets this to `0stake`, so transactions are accepted with no fee beyond the `AddCost` module parameter.
To require a minimum network fee, set it in `app.toml`:
```toml theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
minimum-gas-prices = "0.025stake"
```
Transactions that don't meet the minimum will be rejected by the node before they reach your module. This is a per-node setting, not a chain-wide consensus rule, so validators on a live network each configure their own threshold.
Next: [Running and Testing →](/sdk/latest/tutorials/example/05-run-and-test)
# Run, Test, and Configure
Source: https://docs.cosmos.network/sdk/latest/tutorials/example/05-run-and-test
Learn how to run and test a chain
Now that you've [built a module from scratch](/sdk/latest/tutorials/example/03-build-a-module) and walked through the [full counter module](/sdk/latest/tutorials/example/04-counter-walkthrough), the next step is learning the workflow for running and validating a production-ready chain. This page shows how to start the chain locally, interact with it through the CLI, and use the main layers of testing before shipping changes.
## Single-node local chain
Use a single-node chain for the fastest local development loop. It gives you one validator with predictable state so you can quickly test queries and transactions.
### Start
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
make start
```
This builds the binary, initializes chain data, and starts a single validator node. It handles cleanup automatically — existing chain state is reset on each run.
The chain uses:
* Chain ID: `demo`
* Pre-funded accounts: `alice`, `bob`
* Default denomination: `stake`
### Stop
Press `Ctrl+C` in the terminal running `make start`.
### Reset chain state
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
make start
```
Re-running `make start` resets state automatically. There is no separate reset command.
## Localnet (multi-node)
Localnet runs four nodes in Docker to give you a setup closer to a real network than the single-node chain. `scripts/localnet/init.sh` creates a genesis transaction for `node0` only, so the network is **one validator plus three full nodes**, not four validators. The chain ID is `example-localnet`, and each node has a single key named `validator` rather than the `alice` and `bob` accounts used by `make start`.
Before you begin, note that this section needs Docker running, and that the following host ports must be free: `26656`, `26657`, `1317`, `9090` for `node0`, then `26666`, `26667`, `1318`, `9091` for `node1`, `26676`, `26677`, `1319`, `9092` for `node2`, and `26686`, `26687`, `1320`, `9093` for `node3`.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
# Build the node image and initialize four node directories under build/localnet.
# Takes several minutes the first time, since it compiles the chain in Docker.
make localnet-init
# Start all four nodes
make localnet-start
# Follow the logs. This does not exit on its own; press Ctrl+C to stop following
make localnet-logs
# Stop
make localnet-stop
# Delete build/localnet immediately, without confirming
make localnet-clean
```
### Confirm the network is healthy
Each node exposes its own RPC port. Check that every node has found the other three and that they are advancing together:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
for port in 26657 26667 26677 26687; do
curl -s http://localhost:$port/status | grep -o '"latest_block_height":"[0-9]*"'
curl -s http://localhost:$port/net_info | grep -o '"n_peers":"[0-9]*"'
done
```
Each node should report `"n_peers":"3"` and a block height that climbs on repeated calls.
### Send a transaction
The localnet uses a different chain ID and key name than `make start`, so the commands in the CLI reference below need adjusting. Run them inside a container:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
docker exec node0 exampled tx counter add 7 \
--from validator --chain-id example-localnet \
--keyring-backend test --home /data/node0 --yes
```
Then confirm the state replicated by querying a different node:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
docker exec node2 exampled query counter count --home /data/node2
```
## CLI reference
Once the chain is running, these are the core [CLI](/sdk/latest/learn/concepts/cli-grpc-rest#cli) commands you'll use to inspect state and submit transactions. For the gRPC and REST equivalents of every query and transaction the standard modules define, see the [API reference](/sdk/latest/api-reference/index).
### Query commands
Use query commands to read module state without changing anything on-chain.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
# Query the current counter value
exampled query counter count
# Query the module parameters
exampled query counter params
# Query with a specific node (if not using default localhost:26657)
exampled query counter count --node tcp://localhost:26657
```
### Transaction commands
Use transaction commands to submit state-changing messages to the chain.
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
# Add to the counter
exampled tx counter add 10 --from alice --chain-id demo --yes
# Add with a gas limit
exampled tx counter add 10 --from alice --chain-id demo --gas 200000 --yes
```
### Updating module parameters
Counter params are governance-gated. `MsgUpdateParams` accepts only the gov module address as its
authority, so there is no direct CLI command for it: signing `update-params` with a user key such as
`alice` always fails with `ErrInvalidSigner`. Params change through a governance proposal instead.
Look up the gov module address for your chain, which is the only valid authority:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled query auth module-account gov
```
Write a `proposal.json` containing the message, using that address as `authority`. On the local `demo`
chain the value is `cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn`:
```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
{
"messages": [
{
"@type": "/example.counter.MsgUpdateParams",
"authority": "cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn",
"params": {
"max_add_value": "50",
"add_cost": [{"denom": "stake", "amount": "200"}]
}
}
],
"metadata": "ipfs://CID",
"deposit": "10000000stake",
"title": "Update counter params",
"summary": "Set max_add_value to 50 and add_cost to 200stake"
}
```
The `deposit` must meet the chain's `min_deposit`, which is `10000000stake` locally. Check it with
`exampled query gov params`. Then submit and vote:
```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}}
exampled tx gov submit-proposal proposal.json --from alice --chain-id demo --yes
exampled tx gov vote 1 yes --from alice --chain-id demo 프로젝트로 돌아가기