From 30f24972527444b1ec8277fd32de1c2225575121 Mon Sep 17 00:00:00 2001 From: Cordt Date: Sat, 13 Sep 2025 15:08:13 -0600 Subject: [PATCH 1/5] restructuring sdk-053-1 --- docs.json | 615 ++-- docs/ibc/next/changelog/release-notes.mdx | 501 +-- docs/sdk/proposed-nav-next.json | 37 + docs/sdk/proposed-nav-v0.47.json | 8 + docs/sdk/proposed-nav-v0.50.json | 8 + docs/sdk/proposed-nav-v0.53.json | 224 ++ docs/sdk/sdk-categorization.json | 210 ++ docs/sdk/v0.47/changelog/release-notes.mdx | 407 +++ docs/sdk/v0.50/changelog/release-notes.mdx | 508 +++ docs/sdk/v0.50/release-notes.mdx | 38 + .../advanced => apis-clients}/autocli.mdx | 0 .../{learn/advanced => apis-clients}/cli.mdx | 0 .../advanced => apis-clients}/grpc_rest.mdx | 0 .../v0.53/app-wiring-runtime/app-go-di.mdx | 169 + docs/sdk/v0.53/app-wiring-runtime/app-go.mdx | 17 + .../v0.53/app-wiring-runtime/app-mempool.mdx | 99 + .../v0.53/app-wiring-runtime/app-testnet.mdx | 237 ++ .../v0.53/app-wiring-runtime/app-upgrade.mdx | 222 ++ .../baseapp.mdx | 0 docs/sdk/v0.53/app-wiring-runtime/runtime.mdx | 155 + .../runtx_middleware.mdx | 0 .../app-wiring-runtime/vote-extensions.mdx | 125 + docs/sdk/v0.53/changelog/release-notes.mdx | 508 +++ .../beginner => core-concepts}/accounts.mdx | 0 .../app-anatomy.mdx | 0 .../advanced => core-concepts}/config.mdx | 0 .../advanced => core-concepts}/context.mdx | 0 .../advanced => core-concepts}/events.mdx | 0 .../advanced => core-concepts}/node.mdx | 0 .../advanced => core-concepts}/ocap.mdx | 0 .../intro => core-concepts}/overview.mdx | 0 .../sdk-app-architecture.mdx | 0 .../intro => core-concepts}/sdk-design.mdx | 0 .../advanced => core-concepts}/telemetry.mdx | 0 .../what-is-an-oracle.mdx | 0 .../why-app-specific.mdx | 0 .../encoding.mdx | 0 .../proto-docs.mdx | 0 .../protobuf-annotations.mdx | 136 + .../messages-and-queries.mdx | 140 + .../v0.53/messaging-queries/msg-services.mdx | 124 + .../query-lifecycle.mdx | 0 .../messaging-queries/query-services.mdx | 62 + .../v0.53/module-anatomy-keepers/errors.mdx | 60 + .../v0.53/module-anatomy-keepers/genesis.mdx | 83 + .../module-anatomy-keepers/invariants.mdx | 95 + .../v0.53/module-anatomy-keepers/keeper.mdx | 97 + .../module-interfaces.mdx | 169 + .../module-anatomy-keepers/module-manager.mdx | 333 ++ .../v0.53/module-anatomy-keepers/preblock.mdx | 36 + .../module-anatomy-keepers/structure.mdx | 99 + docs/sdk/v0.53/module-reference/auth.mdx | 712 ++++ docs/sdk/v0.53/module-reference/authz.mdx | 375 ++ docs/sdk/v0.53/module-reference/bank.mdx | 1041 ++++++ docs/sdk/v0.53/module-reference/consensus.mdx | 10 + docs/sdk/v0.53/module-reference/crisis.mdx | 115 + .../v0.53/module-reference/distribution.mdx | 1130 ++++++ docs/sdk/v0.53/module-reference/epochs.mdx | 182 + docs/sdk/v0.53/module-reference/evidence.mdx | 438 +++ docs/sdk/v0.53/module-reference/feegrant.mdx | 398 +++ docs/sdk/v0.53/module-reference/gov.mdx | 2587 ++++++++++++++ docs/sdk/v0.53/module-reference/group.mdx | 2168 ++++++++++++ docs/sdk/v0.53/module-reference/mint.mdx | 460 +++ docs/sdk/v0.53/module-reference/nft.mdx | 92 + docs/sdk/v0.53/module-reference/params.mdx | 82 + .../v0.53/module-reference/protocolpool.mdx | 165 + docs/sdk/v0.53/module-reference/slashing.mdx | 816 +++++ docs/sdk/v0.53/module-reference/staking.mdx | 3057 +++++++++++++++++ docs/sdk/v0.53/module-reference/upgrade.mdx | 612 ++++ .../interact-node.mdx | 0 .../run-node => node-operations}/keyring.mdx | 0 .../run-node => node-operations}/run-node.mdx | 0 .../run-production.mdx | 0 .../run-testnet.mdx | 0 .../run-node => node-operations}/txs.mdx | 0 docs/sdk/v0.53/{ => node-operations}/user.mdx | 0 docs/sdk/v0.53/overview.mdx | 98 + docs/sdk/v0.53/release-notes.mdx | 39 + docs/sdk/v0.53/runtime-abci/checktx.mdx | 53 + docs/sdk/v0.53/runtime-abci/introduction.mdx | 52 + .../v0.53/runtime-abci/prepare-proposal.mdx | 48 + .../v0.53/runtime-abci/process-proposal.mdx | 35 + .../{learn/advanced => state-store}/store.mdx | 0 .../simulation.mdx | 0 .../v0.53/testing-simulation/simulator.mdx | 178 + docs/sdk/v0.53/testing-simulation/testing.mdx | 128 + .../gas-fees.mdx | 0 .../transactions.mdx | 0 .../tx-lifecycle.mdx | 0 .../upgrades-migrations/module-upgrade.mdx | 68 + .../upgrade.mdx | 0 scripts/versioning/README.md | 40 +- scripts/versioning/release-notes.js | 195 +- 93 files changed, 19944 insertions(+), 952 deletions(-) create mode 100644 docs/sdk/proposed-nav-next.json create mode 100644 docs/sdk/proposed-nav-v0.47.json create mode 100644 docs/sdk/proposed-nav-v0.50.json create mode 100644 docs/sdk/proposed-nav-v0.53.json create mode 100644 docs/sdk/sdk-categorization.json create mode 100644 docs/sdk/v0.47/changelog/release-notes.mdx create mode 100644 docs/sdk/v0.50/changelog/release-notes.mdx create mode 100644 docs/sdk/v0.50/release-notes.mdx rename docs/sdk/v0.53/{learn/advanced => apis-clients}/autocli.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => apis-clients}/cli.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => apis-clients}/grpc_rest.mdx (100%) create mode 100644 docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx create mode 100644 docs/sdk/v0.53/app-wiring-runtime/app-go.mdx create mode 100644 docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx create mode 100644 docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx create mode 100644 docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx rename docs/sdk/v0.53/{learn/advanced => app-wiring-runtime}/baseapp.mdx (100%) create mode 100644 docs/sdk/v0.53/app-wiring-runtime/runtime.mdx rename docs/sdk/v0.53/{learn/advanced => app-wiring-runtime}/runtx_middleware.mdx (100%) create mode 100644 docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx create mode 100644 docs/sdk/v0.53/changelog/release-notes.mdx rename docs/sdk/v0.53/{learn/beginner => core-concepts}/accounts.mdx (100%) rename docs/sdk/v0.53/{learn/beginner => core-concepts}/app-anatomy.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/config.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/context.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/events.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/node.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/ocap.mdx (100%) rename docs/sdk/v0.53/{learn/intro => core-concepts}/overview.mdx (100%) rename docs/sdk/v0.53/{learn/intro => core-concepts}/sdk-app-architecture.mdx (100%) rename docs/sdk/v0.53/{learn/intro => core-concepts}/sdk-design.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => core-concepts}/telemetry.mdx (100%) rename docs/sdk/v0.53/{tutorials/vote-extensions/oracle => core-concepts}/what-is-an-oracle.mdx (100%) rename docs/sdk/v0.53/{learn/intro => core-concepts}/why-app-specific.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => encoding-protobuf}/encoding.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => encoding-protobuf}/proto-docs.mdx (100%) create mode 100644 docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx create mode 100644 docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx create mode 100644 docs/sdk/v0.53/messaging-queries/msg-services.mdx rename docs/sdk/v0.53/{learn/beginner => messaging-queries}/query-lifecycle.mdx (100%) create mode 100644 docs/sdk/v0.53/messaging-queries/query-services.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/errors.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx create mode 100644 docs/sdk/v0.53/module-anatomy-keepers/structure.mdx create mode 100644 docs/sdk/v0.53/module-reference/auth.mdx create mode 100644 docs/sdk/v0.53/module-reference/authz.mdx create mode 100644 docs/sdk/v0.53/module-reference/bank.mdx create mode 100644 docs/sdk/v0.53/module-reference/consensus.mdx create mode 100644 docs/sdk/v0.53/module-reference/crisis.mdx create mode 100644 docs/sdk/v0.53/module-reference/distribution.mdx create mode 100644 docs/sdk/v0.53/module-reference/epochs.mdx create mode 100644 docs/sdk/v0.53/module-reference/evidence.mdx create mode 100644 docs/sdk/v0.53/module-reference/feegrant.mdx create mode 100644 docs/sdk/v0.53/module-reference/gov.mdx create mode 100644 docs/sdk/v0.53/module-reference/group.mdx create mode 100644 docs/sdk/v0.53/module-reference/mint.mdx create mode 100644 docs/sdk/v0.53/module-reference/nft.mdx create mode 100644 docs/sdk/v0.53/module-reference/params.mdx create mode 100644 docs/sdk/v0.53/module-reference/protocolpool.mdx create mode 100644 docs/sdk/v0.53/module-reference/slashing.mdx create mode 100644 docs/sdk/v0.53/module-reference/staking.mdx create mode 100644 docs/sdk/v0.53/module-reference/upgrade.mdx rename docs/sdk/v0.53/{user/run-node => node-operations}/interact-node.mdx (100%) rename docs/sdk/v0.53/{user/run-node => node-operations}/keyring.mdx (100%) rename docs/sdk/v0.53/{user/run-node => node-operations}/run-node.mdx (100%) rename docs/sdk/v0.53/{user/run-node => node-operations}/run-production.mdx (100%) rename docs/sdk/v0.53/{user/run-node => node-operations}/run-testnet.mdx (100%) rename docs/sdk/v0.53/{user/run-node => node-operations}/txs.mdx (100%) rename docs/sdk/v0.53/{ => node-operations}/user.mdx (100%) create mode 100644 docs/sdk/v0.53/overview.mdx create mode 100644 docs/sdk/v0.53/release-notes.mdx create mode 100644 docs/sdk/v0.53/runtime-abci/checktx.mdx create mode 100644 docs/sdk/v0.53/runtime-abci/introduction.mdx create mode 100644 docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx create mode 100644 docs/sdk/v0.53/runtime-abci/process-proposal.mdx rename docs/sdk/v0.53/{learn/advanced => state-store}/store.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => testing-simulation}/simulation.mdx (100%) create mode 100644 docs/sdk/v0.53/testing-simulation/simulator.mdx create mode 100644 docs/sdk/v0.53/testing-simulation/testing.mdx rename docs/sdk/v0.53/{learn/beginner => transactions-fees}/gas-fees.mdx (100%) rename docs/sdk/v0.53/{learn/advanced => transactions-fees}/transactions.mdx (100%) rename docs/sdk/v0.53/{learn/beginner => transactions-fees}/tx-lifecycle.mdx (100%) create mode 100644 docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx rename docs/sdk/v0.53/{learn/advanced => upgrades-migrations}/upgrade.mdx (100%) diff --git a/docs.json b/docs.json index 6ba96321..1ea454ad 100644 --- a/docs.json +++ b/docs.json @@ -352,225 +352,202 @@ "version": "v0.53", "tabs": [ { - "tab": "Learn", - "groups": [ - { - "group": "Learn", - "pages": [ - "docs/sdk/v0.53/learn" - ] - }, - { - "group": "Introduction", - "pages": [ - "docs/sdk/v0.53/learn/intro/overview", - "docs/sdk/v0.53/learn/intro/why-app-specific", - "docs/sdk/v0.53/learn/intro/sdk-app-architecture", - "docs/sdk/v0.53/learn/intro/sdk-design" - ] - }, - { - "group": "Beginner", - "pages": [ - "docs/sdk/v0.53/learn/beginner/app-anatomy", - "docs/sdk/v0.53/learn/beginner/tx-lifecycle", - "docs/sdk/v0.53/learn/beginner/query-lifecycle", - "docs/sdk/v0.53/learn/beginner/accounts", - "docs/sdk/v0.53/learn/beginner/gas-fees" - ] - }, - { - "group": "Advanced", - "pages": [ - "docs/sdk/v0.53/learn/advanced/baseapp", - "docs/sdk/v0.53/learn/advanced/transactions", - "docs/sdk/v0.53/learn/advanced/context", - "docs/sdk/v0.53/learn/advanced/node", - "docs/sdk/v0.53/learn/advanced/store", - "docs/sdk/v0.53/learn/advanced/encoding", - "docs/sdk/v0.53/learn/advanced/grpc_rest", - "docs/sdk/v0.53/learn/advanced/cli", - "docs/sdk/v0.53/learn/advanced/events", - "docs/sdk/v0.53/learn/advanced/telemetry", - "docs/sdk/v0.53/learn/advanced/ocap", - "docs/sdk/v0.53/learn/advanced/runtx_middleware", - "docs/sdk/v0.53/learn/advanced/simulation", - "docs/sdk/v0.53/learn/advanced/proto-docs", - "docs/sdk/v0.53/learn/advanced/upgrade", - "docs/sdk/v0.53/learn/advanced/config", - "docs/sdk/v0.53/learn/advanced/autocli" - ] - } - ] - }, - { - "tab": "Build", + "tab": "Documentation", + "pages": [ + "docs/sdk/v0.53/overview" + ], "groups": [ { - "group": "Build", + "group": "Core Concepts", "pages": [ - "docs/sdk/v0.53/build" + { + "group": "Fundamentals", + "pages": [ + "docs/sdk/v0.53/core-concepts/overview", + "docs/sdk/v0.53/core-concepts/why-app-specific", + "docs/sdk/v0.53/core-concepts/sdk-app-architecture", + "docs/sdk/v0.53/core-concepts/sdk-design", + "docs/sdk/v0.53/core-concepts/app-anatomy" + ] + }, + { + "group": "Core Components", + "pages": [ + "docs/sdk/v0.53/core-concepts/accounts", + "docs/sdk/v0.53/core-concepts/context", + "docs/sdk/v0.53/core-concepts/node", + "docs/sdk/v0.53/core-concepts/events", + "docs/sdk/v0.53/core-concepts/telemetry" + ] + }, + { + "group": "Advanced Concepts", + "pages": [ + "docs/sdk/v0.53/core-concepts/ocap", + "docs/sdk/v0.53/core-concepts/config", + "docs/sdk/v0.53/core-concepts/what-is-an-oracle" + ] + } ] }, { "group": "Building Apps", "pages": [ - "docs/sdk/v0.53/build/building-apps/app-go", - "docs/sdk/v0.53/build/building-apps/runtime", - "docs/sdk/v0.53/build/building-apps/app-go-di", - "docs/sdk/v0.53/build/building-apps/app-mempool", - "docs/sdk/v0.53/build/building-apps/app-upgrade", - "docs/sdk/v0.53/build/building-apps/vote-extensions", - "docs/sdk/v0.53/build/building-apps/app-testnet" + { + "group": "App Basics", + "pages": [ + "docs/sdk/v0.53/app-wiring-runtime/app-go", + "docs/sdk/v0.53/app-wiring-runtime/runtime", + "docs/sdk/v0.53/app-wiring-runtime/app-go-di", + "docs/sdk/v0.53/app-wiring-runtime/baseapp" + ] + }, + { + "group": "Advanced Features", + "pages": [ + "docs/sdk/v0.53/app-wiring-runtime/runtx_middleware", + "docs/sdk/v0.53/app-wiring-runtime/app-mempool", + "docs/sdk/v0.53/app-wiring-runtime/app-upgrade", + "docs/sdk/v0.53/app-wiring-runtime/vote-extensions", + "docs/sdk/v0.53/app-wiring-runtime/app-testnet" + ] + } ] }, { "group": "Building Modules", "pages": [ - "docs/sdk/v0.53/build/building-modules/module-manager", - "docs/sdk/v0.53/build/building-modules/messages-and-queries", - "docs/sdk/v0.53/build/building-modules/msg-services", - "docs/sdk/v0.53/build/building-modules/query-services", - "docs/sdk/v0.53/build/building-modules/protobuf-annotations", - "docs/sdk/v0.53/build/building-modules/beginblock-endblock", - "docs/sdk/v0.53/build/building-modules/keeper", - "docs/sdk/v0.53/build/building-modules/invariants", - "docs/sdk/v0.53/build/building-modules/genesis", - "docs/sdk/v0.53/build/building-modules/module-interfaces", - "docs/sdk/v0.53/build/building-modules/structure", - "docs/sdk/v0.53/build/building-modules/errors", - "docs/sdk/v0.53/build/building-modules/upgrade", - "docs/sdk/v0.53/build/building-modules/simulator", - "docs/sdk/v0.53/build/building-modules/depinject", - "docs/sdk/v0.53/build/building-modules/testing", - "docs/sdk/v0.53/build/building-modules/preblock" - ] - }, - { - "group": "ABCI", - "pages": [ - "docs/sdk/v0.53/build/abci/introduction", - "docs/sdk/v0.53/build/abci/prepare-proposal", - "docs/sdk/v0.53/build/abci/process-proposal", - "docs/sdk/v0.53/build/abci/vote-extensions", - "docs/sdk/v0.53/build/abci/checktx" - ] - }, - { - "group": "Modules", - "pages": [ - "docs/sdk/v0.53/build/modules", { - "group": "x/auth", + "group": "Module Basics", "pages": [ - "docs/sdk/v0.53/build/modules/auth", - "docs/sdk/v0.53/build/modules/auth/vesting", - "docs/sdk/v0.53/build/modules/auth/tx" + "docs/sdk/v0.53/module-anatomy-keepers/module-manager", + "docs/sdk/v0.53/module-anatomy-keepers/module-interfaces", + "docs/sdk/v0.53/module-anatomy-keepers/structure", + "docs/sdk/v0.53/module-anatomy-keepers/keeper" ] }, - "docs/sdk/v0.53/build/modules/authz", - "docs/sdk/v0.53/build/modules/bank", - "docs/sdk/v0.53/build/modules/consensus", - "docs/sdk/v0.53/build/modules/crisis", - "docs/sdk/v0.53/build/modules/distribution", - "docs/sdk/v0.53/build/modules/epochs", - "docs/sdk/v0.53/build/modules/evidence", - "docs/sdk/v0.53/build/modules/feegrant", - "docs/sdk/v0.53/build/modules/gov", - "docs/sdk/v0.53/build/modules/group", - "docs/sdk/v0.53/build/modules/mint", - "docs/sdk/v0.53/build/modules/nft", - "docs/sdk/v0.53/build/modules/params", - "docs/sdk/v0.53/build/modules/protocolpool", - "docs/sdk/v0.53/build/modules/slashing", - "docs/sdk/v0.53/build/modules/staking", - "docs/sdk/v0.53/build/modules/upgrade", - "docs/sdk/v0.53/build/modules/circuit", - "docs/sdk/v0.53/build/modules/genutil" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/sdk/v0.53/build/migrations/intro", - "docs/sdk/v0.53/build/migrations/upgrade-reference", - "docs/sdk/v0.53/build/migrations/upgrade-guide" + { + "group": "Module Lifecycle", + "pages": [ + "docs/sdk/v0.53/module-anatomy-keepers/genesis", + "docs/sdk/v0.53/module-anatomy-keepers/invariants", + "docs/sdk/v0.53/module-anatomy-keepers/errors", + "docs/sdk/v0.53/module-anatomy-keepers/preblock" + ] + } ] }, { - "group": "Packages", + "group": "Transactions & Queries", "pages": [ - "docs/sdk/v0.53/build/packages", - "docs/sdk/v0.53/build/packages/depinject", - "docs/sdk/v0.53/build/packages/collections" + { + "group": "Transactions", + "pages": [ + "docs/sdk/v0.53/transactions-fees/tx-lifecycle", + "docs/sdk/v0.53/transactions-fees/transactions", + "docs/sdk/v0.53/transactions-fees/gas-fees" + ] + }, + { + "group": "Messages & Queries", + "pages": [ + "docs/sdk/v0.53/messaging-queries/messages-and-queries", + "docs/sdk/v0.53/messaging-queries/msg-services", + "docs/sdk/v0.53/messaging-queries/query-services", + "docs/sdk/v0.53/messaging-queries/query-lifecycle" + ] + } ] }, { - "group": "Tooling", + "group": "ABCI & State Machine", "pages": [ - "docs/sdk/v0.53/build/tooling", - "docs/sdk/v0.53/build/tooling/protobuf", - "docs/sdk/v0.53/build/tooling/cosmovisor", - "docs/sdk/v0.53/build/tooling/confix" + { + "group": "ABCI", + "pages": [ + "docs/sdk/v0.53/runtime-abci/introduction", + "docs/sdk/v0.53/runtime-abci/prepare-proposal", + "docs/sdk/v0.53/runtime-abci/process-proposal", + "docs/sdk/v0.53/runtime-abci/checktx" + ] + }, + { + "group": "State Management", + "pages": [ + "docs/sdk/v0.53/state-store/store" + ] + } ] }, { - "group": "RFC", + "group": "Encoding & Protocol", "pages": [ - "docs/sdk/v0.53/build/rfc", - "docs/sdk/v0.53/build/rfc/PROCESS", - "docs/sdk/v0.53/build/rfc/rfc-001-tx-validation", - "docs/sdk/v0.53/build/rfc/rfc-template" + "docs/sdk/v0.53/encoding-protobuf/encoding", + "docs/sdk/v0.53/encoding-protobuf/proto-docs", + "docs/sdk/v0.53/encoding-protobuf/protobuf-annotations" ] }, { - "group": "Specifications", + "group": "Testing & Upgrades", "pages": [ - "docs/sdk/v0.53/build/spec", - "docs/sdk/v0.53/build/spec/SPEC_MODULE", - "docs/sdk/v0.53/build/spec/SPEC_STANDARD", { - "group": "Addresses spec", + "group": "Testing", "pages": [ - "docs/sdk/v0.53/build/spec/addresses", - "docs/sdk/v0.53/build/spec/addresses/bech32" + "docs/sdk/v0.53/testing-simulation/simulation", + "docs/sdk/v0.53/testing-simulation/testing", + "docs/sdk/v0.53/testing-simulation/simulator" ] }, { - "group": "Store", + "group": "Upgrades", "pages": [ - "docs/sdk/v0.53/build/spec/store", - "docs/sdk/v0.53/build/spec/store/interblock-cache" + "docs/sdk/v0.53/upgrades-migrations/upgrade", + "docs/sdk/v0.53/upgrades-migrations/module-upgrade" ] } ] - } - ] - }, - { - "tab": "User Guides", - "groups": [ + }, { - "group": "User Guides", + "group": "API & CLI", "pages": [ - "docs/sdk/v0.53/user" + "docs/sdk/v0.53/apis-clients/cli", + "docs/sdk/v0.53/apis-clients/grpc_rest", + "docs/sdk/v0.53/apis-clients/autocli" ] }, { - "group": "Running a Node, API and CLI", + "group": "Node Operations", "pages": [ - "docs/sdk/v0.53/user/run-node/keyring", - "docs/sdk/v0.53/user/run-node/run-node", - "docs/sdk/v0.53/user/run-node/interact-node", - "docs/sdk/v0.53/user/run-node/txs", - "docs/sdk/v0.53/user/run-node/run-testnet", - "docs/sdk/v0.53/user/run-node/run-production" + "docs/sdk/v0.53/node-operations/user", + "docs/sdk/v0.53/node-operations/interact-node", + "docs/sdk/v0.53/node-operations/run-testnet", + "docs/sdk/v0.53/node-operations/run-node", + "docs/sdk/v0.53/node-operations/txs", + "docs/sdk/v0.53/node-operations/keyring", + "docs/sdk/v0.53/node-operations/run-production" ] }, { - "group": "User", + "group": "Module Reference", "pages": [ - "docs/sdk/v0.53/user" + "docs/sdk/v0.53/module-reference/auth", + "docs/sdk/v0.53/module-reference/authz", + "docs/sdk/v0.53/module-reference/bank", + "docs/sdk/v0.53/module-reference/consensus", + "docs/sdk/v0.53/module-reference/crisis", + "docs/sdk/v0.53/module-reference/distribution", + "docs/sdk/v0.53/module-reference/epochs", + "docs/sdk/v0.53/module-reference/evidence", + "docs/sdk/v0.53/module-reference/feegrant", + "docs/sdk/v0.53/module-reference/gov", + "docs/sdk/v0.53/module-reference/group", + "docs/sdk/v0.53/module-reference/mint", + "docs/sdk/v0.53/module-reference/nft", + "docs/sdk/v0.53/module-reference/params", + "docs/sdk/v0.53/module-reference/protocolpool", + "docs/sdk/v0.53/module-reference/slashing", + "docs/sdk/v0.53/module-reference/staking", + "docs/sdk/v0.53/module-reference/upgrade" ] } ] @@ -579,16 +556,10 @@ "tab": "Tutorials", "groups": [ { - "group": "Tutorials", - "pages": [ - "docs/sdk/v0.53/tutorials" - ] - }, - { - "group": "Vote Extensions Tutorials", + "group": "Vote Extensions", "pages": [ { - "group": "Mitigating Auction Front-Running Tutorial", + "group": "Auction Front-Running", "pages": [ "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started", "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", @@ -598,10 +569,9 @@ ] }, { - "group": "Oracle Tutorial", + "group": "Oracle", "pages": [ "docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle", "docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions", "docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle" ] @@ -609,12 +579,25 @@ ] }, { - "group": "Transaction Tutorials", + "group": "Transactions", "pages": [ "docs/sdk/v0.53/tutorials/transactions/building-a-transaction" ] } ] + }, + { + "tab": "API Reference", + "pages": [ + "docs/sdk/v0.53/apis-clients/grpc_rest", + "docs/sdk/v0.53/encoding-protobuf/proto-docs" + ] + }, + { + "tab": "Release Notes", + "pages": [ + "docs/sdk/v0.53/changelog/release-notes" + ] } ] }, @@ -885,6 +868,14 @@ ] } ] + }, + { + "tab": "API Reference", + "pages": [] + }, + { + "tab": "Release Notes", + "pages": [] } ] }, @@ -1155,6 +1146,14 @@ ] } ] + }, + { + "tab": "API Reference", + "pages": [] + }, + { + "tab": "Release Notes", + "pages": [] } ] }, @@ -1162,269 +1161,77 @@ "version": "next", "tabs": [ { - "tab": "Learn", + "tab": "Documentation", "groups": [ { - "group": "Learn", - "pages": [ - "docs/sdk/next/learn" - ] + "group": "Transactions & Fees", + "pages": [] }, { - "group": "Introduction", + "group": "Messaging & Queries", "pages": [ - "docs/sdk/next/learn/intro/overview", - "docs/sdk/next/learn/intro/why-app-specific", - "docs/sdk/next/learn/intro/sdk-app-architecture", - "docs/sdk/next/learn/intro/sdk-design" + "docs/sdk/next/build/building-modules/messaging-and-queries" ] }, { - "group": "Beginner", + "group": "Integration", "pages": [ - "docs/sdk/next/learn/beginner/app-anatomy", - "docs/sdk/next/learn/beginner/tx-lifecycle", - "docs/sdk/next/learn/beginner/query-lifecycle", - "docs/sdk/next/learn/beginner/accounts", - "docs/sdk/next/learn/beginner/gas-fees" + { "group": "App Wiring & Runtime", "pages": [] }, + { "group": "Module Wiring", "pages": [] }, + { "group": "Upgrades & Migrations", "pages": [] }, + { "group": "Messaging Integration", "pages": [] }, + { "group": "Vote Extensions (End-to-End)", "pages": [] } ] }, { - "group": "Advanced", - "pages": [ - "docs/sdk/next/learn/advanced/baseapp", - "docs/sdk/next/learn/advanced/transactions", - "docs/sdk/next/learn/advanced/context", - "docs/sdk/next/learn/advanced/node", - "docs/sdk/next/learn/advanced/store", - "docs/sdk/next/learn/advanced/encoding", - "docs/sdk/next/learn/advanced/grpc_rest", - "docs/sdk/next/learn/advanced/cli", - "docs/sdk/next/learn/advanced/events", - "docs/sdk/next/learn/advanced/telemetry", - "docs/sdk/next/learn/advanced/ocap", - "docs/sdk/next/learn/advanced/runtx_middleware", - "docs/sdk/next/learn/advanced/simulation", - "docs/sdk/next/learn/advanced/proto-docs", - "docs/sdk/next/learn/advanced/upgrade", - "docs/sdk/next/learn/advanced/config", - "docs/sdk/next/learn/advanced/autocli" - ] - } - ] - }, - { - "tab": "Build", - "groups": [ - { - "group": "Build", - "pages": [ - "docs/sdk/next/build" - ] + "group": "Module Anatomy & Keepers", + "pages": [] }, { - "group": "Building Apps", + "group": "Runtime & ABCI", "pages": [ - "docs/sdk/next/build/building-apps/app-go", - "docs/sdk/next/build/building-apps/runtime", - "docs/sdk/next/build/building-apps/app-go-di", - "docs/sdk/next/build/building-apps/app-mempool", - "docs/sdk/next/build/building-apps/app-upgrade", - "docs/sdk/next/build/building-apps/vote-extensions", - "docs/sdk/next/build/building-apps/app-testnet" + "docs/sdk/next/build/abci/index" ] }, { - "group": "Building Modules", - "pages": [ - "docs/sdk/next/build/building-modules/module-manager", - "docs/sdk/next/build/building-modules/messages-and-queries", - "docs/sdk/next/build/building-modules/msg-services", - "docs/sdk/next/build/building-modules/query-services", - "docs/sdk/next/build/building-modules/protobuf-annotations", - "docs/sdk/next/build/building-modules/beginblock-endblock", - "docs/sdk/next/build/building-modules/keeper", - "docs/sdk/next/build/building-modules/invariants", - "docs/sdk/next/build/building-modules/genesis", - "docs/sdk/next/build/building-modules/module-interfaces", - "docs/sdk/next/build/building-modules/structure", - "docs/sdk/next/build/building-modules/errors", - "docs/sdk/next/build/building-modules/upgrade", - "docs/sdk/next/build/building-modules/simulator", - "docs/sdk/next/build/building-modules/depinject", - "docs/sdk/next/build/building-modules/testing", - "docs/sdk/next/build/building-modules/preblock" - ] + "group": "State & Store", + "pages": [] }, { - "group": "ABCI", - "pages": [ - "docs/sdk/next/build/abci/introduction", - "docs/sdk/next/build/abci/prepare-proposal", - "docs/sdk/next/build/abci/process-proposal", - "docs/sdk/next/build/abci/vote-extensions", - "docs/sdk/next/build/abci/checktx" - ] + "group": "Encoding & Protobuf", + "pages": [] }, { - "group": "Modules", - "pages": [ - "docs/sdk/next/build/modules", - { - "group": "x/auth", - "pages": [ - "docs/sdk/next/build/modules/auth", - "docs/sdk/next/build/modules/auth/vesting", - "docs/sdk/next/build/modules/auth/tx" - ] - }, - "docs/sdk/next/build/modules/authz", - "docs/sdk/next/build/modules/bank", - "docs/sdk/next/build/modules/consensus", - "docs/sdk/next/build/modules/crisis", - "docs/sdk/next/build/modules/distribution", - "docs/sdk/next/build/modules/epochs", - "docs/sdk/next/build/modules/evidence", - "docs/sdk/next/build/modules/feegrant", - "docs/sdk/next/build/modules/gov", - "docs/sdk/next/build/modules/group", - "docs/sdk/next/build/modules/mint", - "docs/sdk/next/build/modules/nft", - "docs/sdk/next/build/modules/params", - "docs/sdk/next/build/modules/protocolpool", - "docs/sdk/next/build/modules/slashing", - "docs/sdk/next/build/modules/staking", - "docs/sdk/next/build/modules/upgrade", - "docs/sdk/next/build/modules/circuit", - "docs/sdk/next/build/modules/genutil" - ] + "group": "Testing & Simulation", + "pages": [] }, { - "group": "Migrations", + "group": "Core Concepts", "pages": [ - "docs/sdk/next/build/migrations/intro", - "docs/sdk/next/build/migrations/upgrade-reference", - "docs/sdk/next/build/migrations/upgrade-guide" + "docs/sdk/next/index" ] }, { - "group": "Packages", - "pages": [ - "docs/sdk/next/build/packages", - "docs/sdk/next/build/packages/depinject", - "docs/sdk/next/build/packages/collections" - ] + "group": "Node Operations", + "pages": [] }, { "group": "Tooling", - "pages": [ - "docs/sdk/next/build/tooling", - "docs/sdk/next/build/tooling/protobuf", - "docs/sdk/next/build/tooling/cosmovisor", - "docs/sdk/next/build/tooling/confix" - ] - }, - { - "group": "RFC", - "pages": [ - "docs/sdk/next/build/rfc", - "docs/sdk/next/build/rfc/PROCESS", - "docs/sdk/next/build/rfc/rfc-001-tx-validation", - "docs/sdk/next/build/rfc/rfc-template" - ] - }, - { - "group": "Specifications", - "pages": [ - "docs/sdk/next/build/spec", - "docs/sdk/next/build/spec/SPEC_MODULE", - "docs/sdk/next/build/spec/SPEC_STANDARD", - { - "group": "Addresses spec", - "pages": [ - "docs/sdk/next/build/spec/addresses", - "docs/sdk/next/build/spec/addresses/bech32" - ] - }, - { - "group": "Store", - "pages": [ - "docs/sdk/next/build/spec/store", - "docs/sdk/next/build/spec/store/interblock-cache" - ] - } - ] + "pages": [] } ] }, { - "tab": "User Guides", - "groups": [ - { - "group": "User Guides", - "pages": [ - "docs/sdk/next/user" - ] - }, - { - "group": "Running a Node, API and CLI", - "pages": [ - "docs/sdk/next/user/run-node/keyring", - "docs/sdk/next/user/run-node/run-node", - "docs/sdk/next/user/run-node/interact-node", - "docs/sdk/next/user/run-node/txs", - "docs/sdk/next/user/run-node/run-testnet", - "docs/sdk/next/user/run-node/run-production" - ] - }, - { - "group": "User", - "pages": [ - "docs/sdk/next/user" - ] - } - ] + "tab": "Module Reference", + "groups": [] }, { - "tab": "Tutorials", - "groups": [ - { - "group": "Tutorials", - "pages": [ - "docs/sdk/next/tutorials" - ] - }, - { - "group": "Vote Extensions Tutorials", - "pages": [ - { - "group": "Mitigating Auction Front-Running Tutorial", - "pages": [ - "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/getting-started", - "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", - "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", - "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", - "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running" - ] - }, - { - "group": "Oracle Tutorial", - "pages": [ - "docs/sdk/next/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/next/tutorials/vote-extensions/oracle/what-is-an-oracle", - "docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions", - "docs/sdk/next/tutorials/vote-extensions/oracle/testing-oracle" - ] - } - ] - }, - { - "group": "Transaction Tutorials", - "pages": [ - "docs/sdk/next/tutorials/transactions/building-a-transaction" - ] - } - ] + "tab": "API Reference", + "pages": [] + }, + { + "tab": "Release Notes", + "pages": [] } ] } diff --git a/docs/ibc/next/changelog/release-notes.mdx b/docs/ibc/next/changelog/release-notes.mdx index 604ed0db..7c743f40 100644 --- a/docs/ibc/next/changelog/release-notes.mdx +++ b/docs/ibc/next/changelog/release-notes.mdx @@ -5,504 +5,5 @@ mode: "custom" --- - - {/* - - Guiding Principles: - - Changelogs are for humans, not machines. - - There should be an entry for every single version. - - The same types of changes should be grouped. - - Versions and sections should be linkable. - - The latest version comes first. - - The release date of each version is displayed. - - Mention whether you follow Semantic Versioning. - - Usage: - - Change log entries are to be added to the Unreleased section under the - - appropriate stanza (see below). Each entry should ideally include a tag and - - the Github issue reference in the following format: - - * () \# message - - The issue numbers will later be link-ified during the release process so you do - - not have to worry about including a link manually, but you can if you wish. - - Types of changes (Stanzas): - - "Features" for new features. - - "Improvements" for changes in existing functionality. - - "Deprecated" for soon-to-be removed features. - - "Bug Fixes" for any bug fixes. - - "Client Breaking" for breaking CLI commands and REST routes used by end-users. - - "API Breaking" for breaking exported APIs used by developers building on SDK. - - "State Machine Breaking" for any changes that result in a different AppState given the same genesisState and txList. - - Ref: https://keepachangelog.com/en/1.0.0/ - - */} - - # Changelog - - ## [v10.3.0](https://github.com/cosmos/ibc-go/releases/tag/v10.3.0) - 2025-06-06 - - ### Features - - ### Dependencies - - * [\#8369](https://github.com/cosmos/ibc-go/pull/8369) Bump **github.com/CosmWasm/wasmvm** to **2.2.4** - - * [\#8369](https://github.com/cosmos/ibc-go/pull/8369) Bump **github.com/ethereum/go-ethereum** to **1.15.11** - - ### API Breaking - - ### State Machine Breaking - - ### Improvements - - * (core/api) [\#8303](https://github.com/cosmos/ibc-go/pull/8303) Prefix-based routing in IBCv2 Router - - - (apps/callbacks) [\#8353](https://github.com/cosmos/ibc-go/pull/8353) Add field in callbacks data for custom calldata - - ### Bug Fixes - - ### Testing API - - * [\#8371](https://github.com/cosmos/ibc-go/pull/8371) e2e: Create only necessary number of chains for e2e suite. - - * [\#8375](https://github.com/cosmos/ibc-go/pull/8375) feat: parse IBC v2 packets from ABCI events - - ## [v10.2.0](https://github.com/cosmos/ibc-go/releases/tag/v10.2.0) - 2025-04-30 - - ### Features - - * (light-clients/07-tendermint) [\#8185](https://github.com/cosmos/ibc-go/pull/8185) Allow scaling of trusting period for client upgrades - - ### Dependencies - - * [\#8254](https://github.com/cosmos/ibc-go/pull/8254) Bump **github.com/cosmos/cosmos-sdk** to **0.53.0** - - * [\#8326](https://github.com/cosmos/ibc-go/pull/8329) Bump **cosmossdk.io/x/upgrade** to **0.2.0** - - * [\#8326](https://github.com/cosmos/ibc-go/pull/8326) Bump **cosmossdk.io/api** to **0.9.2** - - * [\#8293](https://github.com/cosmos/ibc-go/pull/8293) Bump **cosmossdk.io/math** to **1.5.3** - - * [\#8254](https://github.com/cosmos/ibc-go/pull/8254) Bump **cosmossdk.io/core** to **0.11.3** - - * [\#8254](https://github.com/cosmos/ibc-go/pull/8254) Bump **cosmossdk.io/store** to **1.1.2** - - * [\#8254](https://github.com/cosmos/ibc-go/pull/8254) Bump **cosmossdk.io/x/tx** to **0.14.0** - - * [\#8253](https://github.com/cosmos/ibc-go/pull/8253) Bump **cosmossdk.io/errors** to **1.0.2** - - * [\#8253](https://github.com/cosmos/ibc-go/pull/8253) Bump **cosmossdk.io/log** to **1.5.1** - - * [\#8253](https://github.com/cosmos/ibc-go/pull/8253) Bump **github.com/cometbft/cometbft** to **0.38.17** - - * [\#8264](https://github.com/cosmos/ibc-go/pull/8264) Bump **github.com/prysmaticlabs/prysm** to **v5.3.0** - - ### Bug Fixes - - * [\#8287](https://github.com/cosmos/ibc-go/pull/8287) rename total_escrow REST query from `denoms` to `total_escrow` - - ## [v10.1.0](https://github.com/cosmos/ibc-go/releases/tag/v10.1.0) - 2025-03-14 - - ### Security Fixes - - * Fix [ISA-2025-001](https://github.com/cosmos/ibc-go/security/advisories/GHSA-4wf3-5qj9-368v) security vulnerability. - - * Fix [ASA-2025-004](https://github.com/cosmos/ibc-go/security/advisories/GHSA-jg6f-48ff-5xrw) security vulnerability. - - ### Features - - * (core) [\#7505](https://github.com/cosmos/ibc-go/pull/7505) Add IBC Eureka (IBC v2) implementation, enabling more efficient IBC packet handling without channel dependencies, bringing significant performance improvements. - - * (apps/transfer) [\#7650](https://github.com/cosmos/ibc-go/pull/7650) Add support for transfer of entire balance for vesting accounts. - - * (apps/wasm) [\#5079](https://github.com/cosmos/ibc-go/pull/5079) 08-wasm light client proxy module for wasm clients by. - - * (core/02-client) [\#7936](https://github.com/cosmos/ibc-go/pull/7936) Clientv2 module. - - * (core/04-channel) [\#7933](https://github.com/cosmos/ibc-go/pull/7933) Channel-v2 genesis. - - * (core/04-channel, core/api) [\#7934](https://github.com/cosmos/ibc-go/pull/7934) - Callbacks Eureka. - - * (light-clients/09-localhost) [\#6683](https://github.com/cosmos/ibc-go/pull/6683) Make 09-localhost stateless. - - * (core, app) [\#6902](https://github.com/cosmos/ibc-go/pull/6902) Add channel version to core app callbacks. - - ### Dependencies - - * [\#8181](https://github.com/cosmos/ibc-go/pull/8181) Bump **github.com/cosmos/cosmos-sdk** to **0.50.13** - - * [\#7932](https://github.com/cosmos/ibc-go/pull/7932) Bump **go** to **1.23** - - * [\#7330](https://github.com/cosmos/ibc-go/pull/7330) Bump **cosmossdk.io/api** to **0.7.6** - - * [\#6828](https://github.com/cosmos/ibc-go/pull/6828) Bump **cosmossdk.io/core** to **0.11.1** - - * [\#7182](https://github.com/cosmos/ibc-go/pull/7182) Bump **cosmossdk.io/log** to **1.4.1** - - * [\#7264](https://github.com/cosmos/ibc-go/pull/7264) Bump **cosmossdk.io/store** to **1.1.1** - - * [\#7585](https://github.com/cosmos/ibc-go/pull/7585) Bump **cosmossdk.io/math** to **1.4.0** - - * [\#7540](https://github.com/cosmos/ibc-go/pull/7540) Bump **github.com/cometbft/cometbft** to **0.38.15** - - * [\#6828](https://github.com/cosmos/ibc-go/pull/6828) Bump **cosmossdk.io/x/upgrade** to **0.1.4** - - * [\#8124](https://github.com/cosmos/ibc-go/pull/8124) Bump **cosmossdk.io/x/tx** to **0.13.7** - - * [\#7942](https://github.com/cosmos/ibc-go/pull/7942) Bump **github.com/cosmos/cosmos-db** to **1.1.1** - - * [\#7224](https://github.com/cosmos/ibc-go/pull/7224) Bump **github.com/cosmos/ics23/go** to **0.11.0** - - ### API Breaking - - * (core, apps) [\#7213](https://github.com/cosmos/ibc-go/pull/7213) Remove capabilities from `SendPacket`. - - * (core, apps) [\#7225](https://github.com/cosmos/ibc-go/pull/7225) Remove capabilities from `WriteAcknowledgement`. - - * (core, apps) [\#7232](https://github.com/cosmos/ibc-go/pull/7232) Remove capabilities from channel handshake methods. - - * (core, apps) [\#7270](https://github.com/cosmos/ibc-go/pull/7270) Remove remaining dependencies on capability module. - - * (core, apps) [\#4811](https://github.com/cosmos/ibc-go/pull/4811) Use expected interface for legacy params subspace - - * (core/04-channel) [\#7239](https://github.com/cosmos/ibc-go/pull/7239) Removed function `LookupModuleByChannel` - - * (core/05-port) [\#7252](https://github.com/cosmos/ibc-go/pull/7252) Removed function `LookupModuleByPort` - - * (core/24-host) [\#7239](https://github.com/cosmos/ibc-go/pull/7239) Removed function `ChannelCapabilityPath` - - * (apps/27-interchain-accounts) [\#7239](https://github.com/cosmos/ibc-go/pull/7239) The following functions have been removed: `AuthenticateCapability`, `ClaimCapability` - - * (apps/27-interchain-accounts) [\#7961](https://github.com/cosmos/ibc-go/pull/7961) Removed `absolute-timeouts` flag from `send-tx` in the ICA CLI. - - * (apps/transfer) [\#7239](https://github.com/cosmos/ibc-go/pull/7239) The following functions have been removed: `BindPort`, `AuthenticateCapability`, `ClaimCapability` - - * (capability) [\#7279](https://github.com/cosmos/ibc-go/pull/7279) The module `capability` has been removed. - - * (testing) [\#7305](https://github.com/cosmos/ibc-go/pull/7305) Added `TrustedValidators` map to `TestChain`. This removes the dependency on the `x/staking` module for retrieving trusted validator sets at a given height, and removes the `GetTrustedValidators` method from the `TestChain` struct. - - * (23-commitment) [\#7486](https://github.com/cosmos/ibc-go/pull/7486) Remove unimplemented `BatchVerifyMembership` and `BatchVerifyNonMembership` functions - - * (core/02-client, light-clients) [\#5806](https://github.com/cosmos/ibc-go/pull/5806) Decouple light client routing from their encoding structure. - - * (core/04-channel) [\#5991](https://github.com/cosmos/ibc-go/pull/5991) The client CLI `QueryLatestConsensusState` has been removed. - - * (light-clients/06-solomachine) [\#6037](https://github.com/cosmos/ibc-go/pull/6037) Remove `Initialize` function from `ClientState` and move logic to `Initialize` function of `LightClientModule`. - - * (light-clients/06-solomachine) [\#6230](https://github.com/cosmos/ibc-go/pull/6230) Remove `GetTimestampAtHeight`, `Status` and `UpdateStateOnMisbehaviour` functions from `ClientState` and move logic to functions of `LightClientModule`. - - * (core/02-client) [\#6084](https://github.com/cosmos/ibc-go/pull/6084) Removed `stakingKeeper` as an argument to `NewKeeper` and replaced with a `ConsensusHost` implementation. - - * (testing) [\#6070](https://github.com/cosmos/ibc-go/pull/6070) Remove `AssertEventsLegacy` function. - - * (core) [\#6138](https://github.com/cosmos/ibc-go/pull/6138) Remove `Router` reference from IBC core keeper and use instead the router on the existing `PortKeeper` reference. - - * (core/04-channel) [\#6023](https://github.com/cosmos/ibc-go/pull/6023) Remove emission of non-hexlified event attributes `packet_data` and `packet_ack`. - - * (core) [\#6320](https://github.com/cosmos/ibc-go/pull/6320) Remove unnecessary `Proof` interface from `exported` package. - - * (core/05-port) [\#6341](https://github.com/cosmos/ibc-go/pull/6341) Modify `UnmarshalPacketData` interface to take in the context, portID, and channelID. This allows for packet data's to be unmarshaled based on the channel version. - - * (apps/27-interchain-accounts) [\#6433](https://github.com/cosmos/ibc-go/pull/6433) Use UNORDERED as the default ordering for new ICA channels. - - * (apps/transfer) [\#6440](https://github.com/cosmos/ibc-go/pull/6440) Remove `GetPrefixedDenom`. - - * (apps/transfer) [\#6508](https://github.com/cosmos/ibc-go/pull/6508) Remove the `DenomTrace` type. - - * (apps/27-interchain-accounts) [\#6598](https://github.com/cosmos/ibc-go/pull/6598) Mark the `requests` repeated field of `MsgModuleQuerySafe` non-nullable. - - * (23-commmitment) [\#6644](https://github.com/cosmos/ibc-go/pull/6644) Introduce `commitment.v2.MerklePath` to include `repeated bytes` in favour of `repeated string`. This supports using merkle path keys which include non UTF-8 encoded runes. - - * (23-commmitment) [\#6870](https://github.com/cosmos/ibc-go/pull/6870) Remove `commitment.v1.MerklePath` in favour of `commitment.v2.MerklePath`. - - * (apps/27-interchain-accounts) [\#6749](https://github.com/cosmos/ibc-go/pull/6749) The ICA controller `NewIBCMiddleware` constructor function sets by default the auth module to nil. - - * (core, core/02-client) [\#6763](https://github.com/cosmos/ibc-go/pull/6763) Move prometheus metric labels for 02-client and core into a separate `metrics` package on core. - - * (core/02-client) [\#6777](https://github.com/cosmos/ibc-go/pull/6777) The `NewClientProposalHandler` of `02-client` has been removed. - - * (core/types) [\#6794](https://github.com/cosmos/ibc-go/pull/6794) The composite interface `QueryServer` has been removed from package `core/types`. Please use the granular `QueryServer` interfaces provided by each core submodule. - - * (light-clients/06-solomachine) [\#6888](https://github.com/cosmos/ibc-go/pull/6888) Remove `TypeClientMisbehaviour` constant and the `Type` method on `Misbehaviour`. - - * (light-clients/06-solomachine, light-clients/07-tendermint) [\#6891](https://github.com/cosmos/ibc-go/pull/6891) The `VerifyMembership` and `VerifyNonMembership` functions of solomachine's `ClientState` have been made private. The `VerifyMembership`, `VerifyNonMembership`, `GetTimestampAtHeight`, `Status` and `Initialize` functions of tendermint's `ClientState` have been made private. - - * (core/04-channel) [\#6902](https://github.com/cosmos/ibc-go/pull/6902) Add channel version to core application callbacks. - - * (core/03-connection, core/02-client) [\#6937](https://github.com/cosmos/ibc-go/pull/6937) Remove 'ConsensusHost' interface, also removing self client and consensus state validation in the connection handshake. - - * (core/24-host) [\#6882](https://github.com/cosmos/ibc-go/issues/6882) All functions ending in `Path` have been removed from 24-host in favour of their sybling functions ending in `Key`. - - * (23-commmitment) [\#6633](https://github.com/cosmos/ibc-go/pull/6633) MerklePath has been changed to use `repeated bytes` in favour of `repeated strings`. - - * (23-commmitment) [\#6644](https://github.com/cosmos/ibc-go/pull/6644) Introduce `commitment.v2.MerklePath` to include `repeated bytes` in favour of `repeated string`. This supports using merkle path keys which include non UTF-8 encoded runes. - - * (23-commmitment) [\#6870](https://github.com/cosmos/ibc-go/pull/6870) Remove `commitment.v1.MerklePath` in favour of `commitment.v2.MerklePath`. - - * [\#6923](https://github.com/cosmos/ibc-go/pull/6923) The JSON msg API for `VerifyMembershipMsg` and `VerifyNonMembershipMsg` payloads for client contract `SudoMsg` has been updated. The field `path` has been changed to `merkle_path`. This change requires updates to 08-wasm client contracts for integration. - - * (apps/callbacks) [\#7000](https://github.com/cosmos/ibc-go/pull/7000) Add base application version to contract keeper callbacks. - - * (light-clients/08-wasm) [\#5154](https://github.com/cosmos/ibc-go/pull/5154) Use bytes in wasm contract api instead of wrapped. - - * (core, core/08-wasm) [\#5397](https://github.com/cosmos/ibc-go/pull/5397) Add coordinator Setup functions to the Path type. - - * (core/05-port) [\#6341](https://github.com/cosmos/ibc-go/pull/6341) Modify `UnmarshalPacketData` interface to take in the context, portID, and channelID. This allows for packet data's to be unmarshaled based on the channel version. - - * (core/02-client) [\#6863](https://github.com/cosmos/ibc-go/pull/6863) remove ClientStoreProvider interface in favour of concrete type. - - * (core/05-port) [\#6988](https://github.com/cosmos/ibc-go/pull/6988) Modify `UnmarshalPacketData` interface to return the underlying application version. - - * (apps/27-interchain-accounts) [\#7053](https://github.com/cosmos/ibc-go/pull/7053) Remove ICS27 channel capability migration introduced in v6. - - * (apps/27-interchain-accounts) [\#8002](https://github.com/cosmos/ibc-go/issues/8002) Remove ICS-29: fee middleware. - - * (core/04-channel) [\#8053](https://github.com/cosmos/ibc-go/issues/8053) Remove channel upgradability. - - ### State Machine Breaking - - * (light-clients/06-solomachine) [\#6313](https://github.com/cosmos/ibc-go/pull/6313) Fix: No-op to avoid panicking on `UpdateState` for invalid misbehaviour submissions. - - * (apps/callbacks) [\#8014](https://github.com/cosmos/ibc-go/pull/8014) Callbacks will now return an error acknowledgement if the recvPacket callback fails. This reverts all app callback changes whereas before we only reverted the callback changes. We also error on all callbacks if the callback data is set but malformed whereas before we ignored the error and continued processing. - - * (apps/callbacks) [\#5349](https://github.com/cosmos/ibc-go/pull/5349) Check if clients params are duplicates. - - * (apps/transfer) [\#6268](https://github.com/cosmos/ibc-go/pull/6268) Use memo strings instead of JSON keys in `AllowedPacketData` of transfer authorization. - - * (light-clients/07-tendermint) Fix: No-op to avoid panicking on `UpdateState` for invalid misbehaviour submissions. - - * (light-clients/06-solomachine) [\#6313](https://github.com/cosmos/ibc-go/pull/6313) Fix: No-op to avoid panicking on `UpdateState` for invalid misbehaviour submissions. - - ### Improvements - - * (testing)[\#7430](https://github.com/cosmos/ibc-go/pull/7430) Update the block proposer in test chains for each block. - - * (apps/27-interchain-accounts) [\#5533](https://github.com/cosmos/ibc-go/pull/5533) ICA host sets the host connection ID on `OnChanOpenTry`, so that ICA controller implementations are not obliged to set the value on `OnChanOpenInit` if they are not able. - - * (core/02-client, core/03-connection, apps/27-interchain-accounts) [\#6256](https://github.com/cosmos/ibc-go/pull/6256) Add length checking of array fields in messages. - - * (light-clients/08-wasm) [\#5146](https://github.com/cosmos/ibc-go/pull/5146) Use global wasm VM instead of keeping an additional reference in keeper. - - * (core/04-channels) [\#7935](https://github.com/cosmos/ibc-go/pull/7935) Limit payload size for both v1 and v2 packet. - - * (core/runtime) [\#7601](https://github.com/cosmos/ibc-go/pull/7601) - IBC core runtime env. - - * (core/08-wasm) [\#5294](https://github.com/cosmos/ibc-go/pull/5294) Don't panic during any store operations. - - * (apps) [\#5305](https://github.com/cosmos/ibc-go/pull/5305)- Remove GetSigners from `sdk.Msg` implementations. - - * (apps) [\#/5778](https://github.com/cosmos/ibc-go/pull/5778) Use json for marshalling/unmarshalling transfer packet data. - - * (core/08-wasm) [\#5785](https://github.com/cosmos/ibc-go/pull/5785) Allow module safe queries in ICA. - - * (core/ante) [\#6278](https://github.com/cosmos/ibc-go/pull/6278) Performance: Exclude pruning from tendermint client updates in ante handler executions. - - * (core/ante) [\#6302](https://github.com/cosmos/ibc-go/pull/6302) Performance: Skip app callbacks during RecvPacket execution in checkTx within the redundant relay ante handler. - - * (core/ante) [\#6280](https://github.com/cosmos/ibc-go/pull/6280) Performance: Skip redundant proof checking in RecvPacket execution in reCheckTx within the redundant relay ante handler. - - * [\#6716](https://github.com/cosmos/ibc-go/pull/6716) Add `HasModule` to capability keeper to allow checking if a scoped module already exists. - - ### Bug Fixes - - * (apps/27-interchain-accounts) [\#7277](https://github.com/cosmos/ibc-go/pull/7277) Use `GogoResolver` when populating module query safe allow list to avoid panics from unresolvable protobuf dependencies. - - * (core/04-channel) [\#7342](https://github.com/cosmos/ibc-go/pull/7342) Read Tx cmd flags including from address to avoid Address cannot be empty error when upgrade-channels via cli. - - * (core/03-connection) [\#7397](https://github.com/cosmos/ibc-go/pull/7397) Skip the genesis validation connectionID for localhost client. - - * (apps/27-interchain-accounts) [\#6377](https://github.com/cosmos/ibc-go/pull/6377) Generate ICA simtest proposals only for provided keepers. - - ### Testing API - - * [\#7688](https://github.com/cosmos/ibc-go/pull/7688) Added `SendMsgsWithSender` to `TestChain`. - - * [\#7430](https://github.com/cosmos/ibc-go/pull/7430) Update block proposer in testing - - * [\#5493](https://github.com/cosmos/ibc-go/pull/5493) Add IBCClientHeader func for endpoint and update tests - - * [\#6685](https://github.com/cosmos/ibc-go/pull/6685) Configure relayers to watch only channels associated with an individual test - - * [\#6758](https://github.com/cosmos/ibc-go/pull/6758) Tokens are successfully forwarded from A to C through B - - ## [v8.5.0](https://github.com/cosmos/ibc-go/releases/tag/v8.5.0) - 2024-08-30 - - ### Dependencies - - * [\#6828](https://github.com/cosmos/ibc-go/pull/6828) Bump Cosmos SDK to v0.50.9. - - * [\#7222](https://github.com/cosmos/ibc-go/pull/7221) Update ics23 to v0.11.0. - - ### State Machine Breaking - - * (core/03-connection) [\#7129](https://github.com/cosmos/ibc-go/pull/7129) Remove verification of self client and consensus state from connection handshake. - - ## [v8.4.0](https://github.com/cosmos/ibc-go/releases/tag/v8.4.0) - 2024-07-29 - - ### Improvements - - * (core/04-channel) [\#6871](https://github.com/cosmos/ibc-go/pull/6871) Add channel ordering to write acknowledgement event. - - ### Features - - * (apps/transfer) [\#6877](https://github.com/cosmos/ibc-go/pull/6877) Added the possibility to transfer the entire user balance of a particular denomination by using [`UnboundedSpendLimit`](https://github.com/cosmos/ibc-go/blob/beb2d93b58835ddb9ed8e7624988f1e66b849251/modules/apps/transfer/types/token.go#L56-L58) as the token amount. - - ### Bug Fixes - - * (core/04-channel) [\#6935](https://github.com/cosmos/ibc-go/pull/6935) Check upgrade compatibility in `ChanUpgradeConfirm`. - - ## [v8.3.2](https://github.com/cosmos/ibc-go/releases/tag/v8.3.2) - 2024-06-20 - - ### Dependencies - - * [\#6614](https://github.com/cosmos/ibc-go/pull/6614) Bump Cosmos SDK to v0.50.7. - - ### Improvements - - * (apps/27-interchain-accounts) [\#6436](https://github.com/cosmos/ibc-go/pull/6436) Refactor ICA host keeper instantiation method to avoid panic related to proto files. - - ## [v8.3.1](https://github.com/cosmos/ibc-go/releases/tag/v8.3.1) - 2024-05-22 - - ### Improvements - - * (core/ante) [\#6302](https://github.com/cosmos/ibc-go/pull/6302) Performance: Skip app callbacks during RecvPacket execution in checkTx within the redundant relay ante handler. - - * (core/ante) [\#6280](https://github.com/cosmos/ibc-go/pull/6280) Performance: Skip redundant proof checking in RecvPacket execution in reCheckTx within the redundant relay ante handler. - - * (core/ante) [\#6306](https://github.com/cosmos/ibc-go/pull/6306) Performance: Skip misbehaviour checks in UpdateClient flow and skip signature checks in reCheckTx mode. - - ## [v8.3.0](https://github.com/cosmos/ibc-go/releases/tag/v8.3.0) - 2024-05-16 - - ### Dependencies - - * [\#6300](https://github.com/cosmos/ibc-go/pull/6300) Bump Cosmos SDK to v0.50.6 and CometBFT to v0.38.7. - - ### State Machine Breaking - - * (light-clients/07-tendermint) [\#6276](https://github.com/cosmos/ibc-go/pull/6276) Fix: No-op to avoid panicking on `UpdateState` for invalid misbehaviour submissions. - - ### Improvements - - * (apps/27-interchain-accounts, apps/transfer, apps/29-fee) [\#6253](https://github.com/cosmos/ibc-go/pull/6253) Allow channel handshake to succeed if fee middleware is wired up on one side, but not the other. - - * (apps/27-interchain-accounts) [\#6251](https://github.com/cosmos/ibc-go/pull/6251) Use `UNORDERED` as the default ordering for new ICA channels. - - * (apps/transfer) [\#6268](https://github.com/cosmos/ibc-go/pull/6268) Use memo strings instead of JSON keys in `AllowedPacketData` of transfer authorization. - - * (core/ante) [\#6278](https://github.com/cosmos/ibc-go/pull/6278) Performance: Exclude pruning from tendermint client updates in ante handler executions. - - * (core/ante) [\#6302](https://github.com/cosmos/ibc-go/pull/6302) Performance: Skip app callbacks during RecvPacket execution in checkTx within the redundant relay ante handler. - - * (core/ante) [\#6280](https://github.com/cosmos/ibc-go/pull/6280) Performance: Skip redundant proof checking in RecvPacket execution in reCheckTx within the redundant relay ante handler. - - ### Features - - * (core) [\#6055](https://github.com/cosmos/ibc-go/pull/6055) Introduce a new interface `ConsensusHost` used to validate an IBC `ClientState` and `ConsensusState` against the host chain's underlying consensus parameters. - - * (core/02-client) [\#5821](https://github.com/cosmos/ibc-go/pull/5821) Add rpc `VerifyMembershipProof` (querier approach for conditional clients). - - * (core/04-channel) [\#5788](https://github.com/cosmos/ibc-go/pull/5788) Add `NewErrorAcknowledgementWithCodespace` to allow codespaces in ack errors. - - * (apps/27-interchain-accounts) [\#5785](https://github.com/cosmos/ibc-go/pull/5785) Introduce a new tx message that ICA host submodule can use to query the chain (only those marked with `module_query_safe`) and write the responses to the acknowledgement. - - ### Bug Fixes - - * (apps/27-interchain-accounts) [\#6167](https://github.com/cosmos/ibc-go/pull/6167) Fixed an edge case bug where migrating params for a pre-existing ica module which implemented controller functionality only could panic when migrating params for newly added host, and align controller param migration with host. - - * (app/29-fee) [\#6255](https://github.com/cosmos/ibc-go/pull/6255) Delete refunded fees from state if some fee(s) cannot be refunded on channel closure. - - ## [v8.2.0](https://github.com/cosmos/ibc-go/releases/tag/v8.2.0) - 2024-04-05 - - ### Dependencies - - * [\#5975](https://github.com/cosmos/ibc-go/pull/5975) Bump Cosmos SDK to v0.50.5. - - ### Improvements - - * (proto) [\#5987](https://github.com/cosmos/ibc-go/pull/5987) Add wasm proto files. - - ## [v8.1.0](https://github.com/cosmos/ibc-go/releases/tag/v8.1.0) - 2024-01-31 - - ### Dependencies - - * [\#5663](https://github.com/cosmos/ibc-go/pull/5663) Bump Cosmos SDK to v0.50.3 and CometBFT to v0.38.2. - - ### State Machine Breaking - - * (apps/27-interchain-accounts) [\#5442](https://github.com/cosmos/ibc-go/pull/5442) Increase the maximum allowed length for the memo field of `InterchainAccountPacketData`. - - ### Improvements - - * (core/02-client) [\#5429](https://github.com/cosmos/ibc-go/pull/5429) Add wildcard `"*"` to allow all clients in `AllowedClients` param. - - * (core) [\#5541](https://github.com/cosmos/ibc-go/pull/5541) Enable emission of events on erroneous IBC application callbacks by appending a prefix to all event type and attribute keys. - - ### Features - - * (core/04-channel) [\#1613](https://github.com/cosmos/ibc-go/pull/1613) Channel upgradability. - - * (apps/transfer) [\#5280](https://github.com/cosmos/ibc-go/pull/5280) Add list of allowed packet data keys to `Allocation` of `TransferAuthorization`. - - * (apps/27-interchain-accounts) [\#5633](https://github.com/cosmos/ibc-go/pull/5633) Allow setting new and upgrading existing ICA (ordered) channels to use unordered ordering. - - ### Bug Fixes - - * (apps/27-interchain-accounts) [\#5343](https://github.com/cosmos/ibc-go/pull/5343) Add check if controller is enabled in `sendTx` before sending packet to host. - - * (apps/29-fee) [\#5441](https://github.com/cosmos/ibc-go/pull/5441) Allow setting the relayer address as payee. - - ## [v8.0.1](https://github.com/cosmos/ibc-go/releases/tag/v8.0.1) - 2024-01-31 - - ### Dependencies - - * [\#5718](https://github.com/cosmos/ibc-go/pull/5718) Update Cosmos SDK to v0.50.3 and CometBFT to v0.38.2. - - ### Improvements - - * (core) [\#5541](https://github.com/cosmos/ibc-go/pull/5541) Enable emission of events on erroneous IBC application callbacks by appending a prefix to all event type and attribute keys. - - ## [v8.0.0](https://github.com/cosmos/ibc-go/releases/tag/v8.0.0) - 2023-11-10 - - ### Dependencies - - * [\#5038](https://github.com/cosmos/ibc-go/pull/5038) Bump SDK v0.50.1 and cometBFT v0.38. - - * [\#4398](https://github.com/cosmos/ibc-go/pull/4398) Update all modules to go 1.21. - - ### API Breaking - - * (core) [\#4703](https://github.com/cosmos/ibc-go/pull/4703) Make `PortKeeper` field of `IBCKeeper` a pointer. - - * (core/23-commitment) [\#4459](https://github.com/cosmos/ibc-go/pull/4459) Remove `Pretty` and `String` custom implementations of `MerklePath`. - - * [\#3205](https://github.com/cosmos/ibc-go/pull/3205) Make event emission functions unexported. - - * (apps/27-interchain-accounts, apps/transfer) [\#3253](https://github.com/cosmos/ibc-go/pull/3253) Rename `IsBound` to `HasCapability`. - - * (apps/27-interchain-accounts, apps/transfer) [\#3303](https://github.com/cosmos/ibc-go/pull/3303) Make `HasCapability` private. - - * [\#3303](https://github.com/cosmos/ibc-go/pull/3856) Add missing/remove unnecessary gogoproto directive. - - * (apps/27-interchain-accounts) [\#3967](https://github.com/cosmos/ibc-go/pull/3967) Add encoding type as argument to ICA encoding/decoding functions. - - * (core) [\#3867](https://github.com/cosmos/ibc-go/pull/3867) Remove unnecessary event attribute from INIT handshake msgs. - - * (core/04-channel) [\#3806](https://github.com/cosmos/ibc-go/pull/3806) Remove unused `EventTypeTimeoutPacketOnClose`. - - * (testing) [\#4018](https://github.com/cosmos/ibc-go/pull/4018) Allow failure expectations when using `chain.SendMsgs`. - - ### State Machine Breaking - - * (apps/transfer, apps/27-interchain-accounts, app/29-fee) [\#4992](https://github.com/cosmos/ibc-go/pull/4992) Set validation for length of string fields. - - ### Improvements - - * [\#3304](https://github.com/cosmos/ibc-go/pull/3304) Remove unnecessary defer func statements. - - * (apps/29-fee) [\#3054](https://github.com/cosmos/ibc-go/pull/3054) Add page result to ics29-fee queries. - - * (apps/27-interchain-accounts, apps/transfer) [\#3077](https://github.com/cosmos/ibc-go/pull/3077) Add debug level logging for the error message which is discarded when generating a failed acknowledgement. - - * (core/03-connection) [\#3244](https://github.com/cosmos/ibc-go/pull/3244) Cleanup 03-connection msg validate basic test. - - * (core/02-client) [\#3514](https://github.com/cosmos/ibc-go/pull/3514) Add check for the client status in `CreateClient`. - - * (apps/29-fee) [\#4100](https://github.com/cosmos/ibc-go/pull/4100) Adding `MetadataFromVersion` to `29-fee` package `types`. - - * (apps/29-fee) [\#4290](https://github.com/cosmos/ibc-go/pull/4290) Use `types.MetadataFromVersion` helper function for callback handlers. - - * (core/04-channel) [\#4155](https://github.com/cosmos/ibc-go/pull/4155) Adding `IsOpen` and `IsClosed` methods to `Channel` type. - - * (core/03-connection) [\#4110](https://github.com/cosmos/ibc-go/pull/4110) Remove `Version` interface and casting functions from 03-connection. - - * (core) [\#4835](https://github.com/cosmos/ibc-go/pull/4835) Use expected interface for legacy params subspace parameter of keeper constructor functions. - - ### Features - - * (capability) [\#3097](https://github.com/cosmos/ibc-go/pull/3097) Migrate capability module from Cosmos SDK to ibc-go. - - * (core/02-client) [\#3640](https://github.com/cosmos/ibc-go/pull/3640) Migrate client params to be self managed. - - * (core/03-connection) [\#3650](https://github.com/cosmos/ibc-go/pull/3650) Migrate connection params to be self managed. - - * (apps/transfer) [\#3553](https://github.com/cosmos/ibc-go/pull/3553) Migrate transfer parameters to be self managed (#3553) - - * (apps/27-interchain-accounts) [\#3520](https://github.com/cosmos/ibc-go/pull/3590) Migrate ica/controller parameters to be self managed (#3590) - - * (apps/27-interchain-accounts) [\#3520](https://github.com/cosmos/ibc-go/pull/3520) Migrate ica/host to params to be self managed. - - * (apps/transfer) [\#3104](https://github.com/cosmos/ibc-go/pull/3104) Add metadata for IBC tokens. - - * [\#4620](https://github.com/cosmos/ibc-go/pull/4620) Migrate to gov v1 via the additions of `MsgRecoverClient` and `MsgIBCSoftwareUpgrade`. The legacy proposal types `ClientUpdateProposal` and `UpgradeProposal` have been deprecated and will be removed in the next major release. - - ### Bug Fixes - - * (apps/transfer) [\#4709](https://github.com/cosmos/ibc-go/pull/4709) Order query service RPCs to fix availability of denom traces endpoint when no args are provided. - - * (core/04-channel) [\#3357](https://github.com/cosmos/ibc-go/pull/3357) Handle unordered channels in `NextSequenceReceive` query. - - * (e2e) [\#3402](https://github.com/cosmos/ibc-go/pull/3402) Allow retries for messages signed by relayer. - - * (core/04-channel) [\#3417](https://github.com/cosmos/ibc-go/pull/3417) Add missing query for next sequence send. - - * (testing) [\#4630](https://github.com/cosmos/ibc-go/pull/4630) Update `testconfig` to use revision formatted chain IDs. - - * (core/04-channel) [\#4706](https://github.com/cosmos/ibc-go/pull/4706) Retrieve correct next send sequence for packets in unordered channels. - - * (core/02-client) [\#4746](https://github.com/cosmos/ibc-go/pull/4746) Register implementations against `govtypes.Content` interface. - - * (apps/27-interchain-accounts) [\#4944](https://github.com/cosmos/ibc-go/pull/4944) Add missing proto interface registration. - - * (core/02-client) [\#5020](https://github.com/cosmos/ibc-go/pull/5020) Fix expect pointer error when unmarshalling misbehaviour file. - - ### Documentation - - * [\#3133](https://github.com/cosmos/ibc-go/pull/3133) Add linter for markdown documents. - - * [\#4693](https://github.com/cosmos/ibc-go/pull/4693) Migrate docs to docusaurus. - - ### Testing - - * [\#3138](https://github.com/cosmos/ibc-go/pull/3138) Use `testing.TB` instead of `testing.T` to support benchmarks and fuzz tests. - - * [\#3980](https://github.com/cosmos/ibc-go/pull/3980) Change `sdk.Events` usage to `[]abci.Event` in the testing package. - - * [\#3986](https://github.com/cosmos/ibc-go/pull/3986) Add function `RelayPacketWithResults`. - - * [\#4182](https://github.com/cosmos/ibc-go/pull/4182) Return current validator set when requesting current height in `GetValsAtHeight`. - - * [\#4319](https://github.com/cosmos/ibc-go/pull/4319) Fix in `TimeoutPacket` function to use counterparty `portID`/`channelID` in `GetNextSequenceRecv` query. - - * [\#4180](https://github.com/cosmos/ibc-go/pull/4180) Remove unused function `simapp.SetupWithGenesisAccounts`. - - ### Miscellaneous Tasks - - * (apps/27-interchain-accounts) [\#4677](https://github.com/cosmos/ibc-go/pull/4677) Remove ica store key. - - * [\#4724](https://github.com/cosmos/ibc-go/pull/4724) Add `HasValidateBasic` compiler assertions to messages. - - * [\#4725](https://github.com/cosmos/ibc-go/pull/4725) Add fzf selection for config files. - - * [\#4741](https://github.com/cosmos/ibc-go/pull/4741) Panic with error. - - * [\#3186](https://github.com/cosmos/ibc-go/pull/3186) Migrate all SDK errors to the new errors go module. - - * [\#3216](https://github.com/cosmos/ibc-go/pull/3216) Modify `simapp` to fulfill the SDK `runtime.AppI` interface. - - * [\#3290](https://github.com/cosmos/ibc-go/pull/3290) Remove `gogoproto` yaml tags from proto files. - - * [\#3439](https://github.com/cosmos/ibc-go/pull/3439) Use nil pointer pattern to check for interface compliance. - - * [\#3433](https://github.com/cosmos/ibc-go/pull/3433) Add tests for `acknowledgement.Acknowledgement()`. - - * (core, apps/29-fee) [\#3462](https://github.com/cosmos/ibc-go/pull/3462) Add missing `nil` check and corresponding tests for query handlers. - - * (light-clients/07-tendermint, light-clients/06-solomachine) [\#3571](https://github.com/cosmos/ibc-go/pull/3571) Delete unused `GetProofSpecs` functions. - - * (core) [\#3616](https://github.com/cosmos/ibc-go/pull/3616) Add debug log for redundant relay. - - * (core) [\#3892](https://github.com/cosmos/ibc-go/pull/3892) Add deprecated option to `create_localhost` field. - - * (core) [\#3893](https://github.com/cosmos/ibc-go/pull/3893) Add deprecated option to `MsgSubmitMisbehaviour`. - - * (apps/transfer, apps/29-fee) [\#4570](https://github.com/cosmos/ibc-go/pull/4570) Remove `GetSignBytes` from 29-fee and transfer msgs. - - * [\#3630](https://github.com/cosmos/ibc-go/pull/3630) Add annotation to Msg service. - - ## [v7.8.0](https://github.com/cosmos/ibc-go/releases/tag/v7.8.0) - 2024-08-30 - - ### State Machine Breaking - - * (core/03-connection) [\#7128](https://github.com/cosmos/ibc-go/pull/7128) Remove verification of self client and consensus state from connection handshake. - - ## [v7.7.0](https://github.com/cosmos/ibc-go/releases/tag/v7.7.0) - 2024-07-29 - - ### Dependencies - - * [\#6943](https://github.com/cosmos/ibc-go/pull/6943) Update Cosmos SDK to v0.47.13. - - ### Features - - * (apps/transfer) [\#6877](https://github.com/cosmos/ibc-go/pull/6877) Added the possibility to transfer the entire user balance of a particular denomination by using [`UnboundedSpendLimit`](https://github.com/cosmos/ibc-go/blob/715f00eef8727da41db25fdd4763b709bdbba07e/modules/apps/transfer/types/transfer_authorization.go#L253-L255) as the token amount. - - ### Bug Fixes - - ## [v7.6.0](https://github.com/cosmos/ibc-go/releases/tag/v7.6.0) - 2024-06-20 - - ### State Machine Breaking - - * (apps/transfer, apps/27-interchain-accounts, app/29-fee) [\#4992](https://github.com/cosmos/ibc-go/pull/4992) Set validation for length of string fields. - - ## [v7.5.2](https://github.com/cosmos/ibc-go/releases/tag/v7.5.2) - 2024-06-20 - - ### Dependencies - - * [\#6613](https://github.com/cosmos/ibc-go/pull/6613) Update Cosmos SDK to v0.47.12. - - ### Improvements - - * (apps/27-interchain-accounts) [\#6436](https://github.com/cosmos/ibc-go/pull/6436) Refactor ICA host keeper instantiation method to avoid panic related to proto files. - - ## [v7.5.1](https://github.com/cosmos/ibc-go/releases/tag/v7.5.1) - 2024-05-22 - - ### Improvements - - * (core/ante) [\#6302](https://github.com/cosmos/ibc-go/pull/6302) Performance: Skip app callbacks during RecvPacket execution in checkTx within the redundant relay ante handler. - - * (core/ante) [\#6280](https://github.com/cosmos/ibc-go/pull/6280) Performance: Skip redundant proof checking in RecvPacket execution in reCheckTx within the redundant relay ante handler. - - * (core/ante) [\#6306](https://github.com/cosmos/ibc-go/pull/6306) Performance: Skip misbehaviour checks in UpdateClient flow and skip signature checks in reCheckTx mode. - - ## [v7.5.0](https://github.com/cosmos/ibc-go/releases/tag/v7.5.0) - 2024-05-14 - - ### Dependencies - - * [\#6254](https://github.com/cosmos/ibc-go/pull/6254) Update Cosmos SDK to v0.47.11 and CometBFT to v0.37.5. - - ### State Machine Breaking - - * (light-clients/07-tendermint) [\#6276](https://github.com/cosmos/ibc-go/pull/6276) Fix: No-op to avoid panicking on `UpdateState` for invalid misbehaviour submissions. - - ### Improvements - - * (apps/27-interchain-accounts) [\#6147](https://github.com/cosmos/ibc-go/pull/6147) Emit an event signalling that the host submodule is disabled. - - * (testing) [\#6180](https://github.com/cosmos/ibc-go/pull/6180) Add version to tm abci headers in ibctesting. - - * (apps/27-interchain-accounts, apps/transfer, apps/29-fee) [\#6253](https://github.com/cosmos/ibc-go/pull/6253) Allow channel handshake to succeed if fee middleware is wired up on one side, but not the other. - - * (apps/transfer) [\#6268](https://github.com/cosmos/ibc-go/pull/6268) Use memo strings instead of JSON keys in `AllowedPacketData` of transfer authorization. - - ### Features - - * (apps/27-interchain-accounts) [\#5633](https://github.com/cosmos/ibc-go/pull/5633) Allow new ICA channels to use unordered ordering. - - * (apps/27-interchain-accounts) [\#5785](https://github.com/cosmos/ibc-go/pull/5785) Introduce a new tx message that ICA host submodule can use to query the chain (only those marked with `module_query_safe`) and write the responses to the acknowledgement. - - ### Bug Fixes - - * (apps/29-fee) [\#6255](https://github.com/cosmos/ibc-go/pull/6255) Delete already refunded fees from state if some fee(s) cannot be refunded on channel closure. - - ## [v7.4.0](https://github.com/cosmos/ibc-go/releases/tag/v7.4.0) - 2024-04-05 - - ## [v7.3.2](https://github.com/cosmos/ibc-go/releases/tag/v7.3.2) - 2024-01-31 - - ### Dependencies - - * [\#5717](https://github.com/cosmos/ibc-go/pull/5717) Update Cosmos SDK to v0.47.8 and CometBFT to v0.37.4. - - ### Improvements - - * (core) [\#5541](https://github.com/cosmos/ibc-go/pull/5541) Enable emission of events on erroneous IBC application callbacks by appending a prefix to all event type and attribute keys. - - ### Bug Fixes - - * (apps/27-interchain-accounts) [\#4944](https://github.com/cosmos/ibc-go/pull/4944) Add missing proto interface registration. - - ## [v7.3.1](https://github.com/cosmos/ibc-go/releases/tag/v7.3.1) - 2023-10-20 - - ### Dependencies - - * [\#4539](https://github.com/cosmos/ibc-go/pull/4539) Update Cosmos SDK to v0.47.5. - - ### Improvements - - * (apps/27-interchain-accounts) [\#4537](https://github.com/cosmos/ibc-go/pull/4537) Add argument to `generate-packet-data` cli to choose the encoding format for the messages in the ICA packet data. - - ### Bug Fixes - - * (apps/transfer) [\#4709](https://github.com/cosmos/ibc-go/pull/4709) Order query service RPCs to fix availability of denom traces endpoint when no args are provided. - - ## [v7.3.0](https://github.com/cosmos/ibc-go/releases/tag/v7.3.0) - 2023-08-31 - - ### Dependencies - - * [\#4122](https://github.com/cosmos/ibc-go/pull/4122) Update Cosmos SDK to v0.47.4. - - ### Improvements - - * [\#4187](https://github.com/cosmos/ibc-go/pull/4187) Adds function `WithICS4Wrapper` to keepers to allow to set the middleware after the keeper's creation. - - * (light-clients/06-solomachine) [\#4429](https://github.com/cosmos/ibc-go/pull/4429) Remove IBC key from path of bytes signed by solomachine and not escape the path. - - ### Features - - * (apps/27-interchain-accounts) [\#3796](https://github.com/cosmos/ibc-go/pull/3796) Adds support for json tx encoding for interchain accounts. - - * [\#4188](https://github.com/cosmos/ibc-go/pull/4188) Adds optional `PacketDataUnmarshaler` interface that allows a middleware to request the packet data to be unmarshaled by the base application. - - * [\#4199](https://github.com/cosmos/ibc-go/pull/4199) Adds optional `PacketDataProvider` interface for retrieving custom packet data stored on behalf of another application. - - * [\#4200](https://github.com/cosmos/ibc-go/pull/4200) Adds optional `PacketData` interface which application's packet data may implement. - - ### Bug Fixes - - * (04-channel) [\#4476](https://github.com/cosmos/ibc-go/pull/4476) Use UTC time in log messages for packet timeout error. - - * (testing) [\#4483](https://github.com/cosmos/ibc-go/pull/4483) Use the correct revision height when querying trusted validator set. - - ## [v7.2.3](https://github.com/cosmos/ibc-go/releases/tag/v7.2.3) - 2024-01-31 - - ### Dependencies - - * [\#5716](https://github.com/cosmos/ibc-go/pull/5716) Update Cosmos SDK to v0.47.8 and CometBFT to v0.37.4. - - ### Improvements - - * (core) [\#5541](https://github.com/cosmos/ibc-go/pull/5541) Enable emission of events on erroneous IBC application callbacks by appending a prefix to all event type and attribute keys. - - ## [v7.2.2](https://github.com/cosmos/ibc-go/releases/tag/v7.2.2) - 2023-10-20 - - ### Dependencies - - * [\#4539](https://github.com/cosmos/ibc-go/pull/4539) Update Cosmos SDK to v0.47.5. - - ### Bug Fixes - - * (apps/transfer) [\#4709](https://github.com/cosmos/ibc-go/pull/4709) Order query service RPCs to fix availability of denom traces endpoint when no args are provided. - - ## [v7.2.1](https://github.com/cosmos/ibc-go/releases/tag/v7.2.1) - 2023-08-31 - - ### Bug Fixes - - * (04-channel) [\#4476](https://github.com/cosmos/ibc-go/pull/4476) Use UTC time in log messages for packet timeout error. - - * (testing) [\#4483](https://github.com/cosmos/ibc-go/pull/4483) Use the correct revision height when querying trusted validator set. - - ## [v7.2.0](https://github.com/cosmos/ibc-go/releases/tag/v7.2.0) - 2023-06-22 - - ### Dependencies - - * [\#3810](https://github.com/cosmos/ibc-go/pull/3810) Update Cosmos SDK to v0.47.3. - - * [\#3862](https://github.com/cosmos/ibc-go/pull/3862) Update CometBFT to v0.37.2. - - ### State Machine Breaking - - * [\#3907](https://github.com/cosmos/ibc-go/pull/3907) Re-implemented missing functions of `LegacyMsg` interface to fix transaction signing with ledger. - - ## [v7.1.0](https://github.com/cosmos/ibc-go/releases/tag/v7.1.0) - 2023-06-09 - - ### Dependencies - - * [\#3542](https://github.com/cosmos/ibc-go/pull/3542) Update Cosmos SDK to v0.47.2 and CometBFT to v0.37.1. - - * [\#3457](https://github.com/cosmos/ibc-go/pull/3457) Update to ics23 v0.10.0. - - ### Improvements - - * (apps/transfer) [\#3454](https://github.com/cosmos/ibc-go/pull/3454) Support transfer authorization unlimited spending when the max `uint256` value is provided as limit. - - ### Features - - * (light-clients/09-localhost) [\#3229](https://github.com/cosmos/ibc-go/pull/3229) Implementation of v2 of localhost loopback client. - - * (apps/transfer) [\#3019](https://github.com/cosmos/ibc-go/pull/3019) Add state entry to keep track of total amount of tokens in escrow. - - ### Bug Fixes - - * (core/04-channel) [\#3346](https://github.com/cosmos/ibc-go/pull/3346) Properly handle ordered channels in `UnreceivedPackets` query. - - * (core/04-channel) [\#3593](https://github.com/cosmos/ibc-go/pull/3593) `SendPacket` now correctly returns `ErrClientNotFound` in favour of `ErrConsensusStateNotFound`. - - ## [v7.0.1](https://github.com/cosmos/ibc-go/releases/tag/v7.0.1) - 2023-05-25 - - ### Bug Fixes - - * [\#3346](https://github.com/cosmos/ibc-go/pull/3346) Properly handle ordered channels in `UnreceivedPackets` query. - - ## [v7.0.0](https://github.com/cosmos/ibc-go/releases/tag/v7.0.0) - 2023-03-17 - - ### Dependencies - - * [\#2672](https://github.com/cosmos/ibc-go/issues/2672) Update to cosmos-sdk v0.47. - - * [\#3175](https://github.com/cosmos/ibc-go/issues/3175) Migrate to cometbft v0.37. - - ### API Breaking - - * (core) [\#2897](https://github.com/cosmos/ibc-go/pull/2897) Remove legacy migrations required for upgrading from Stargate release line to ibc-go >= v1.x.x. - - * (core/02-client) [\#2856](https://github.com/cosmos/ibc-go/pull/2856) Rename `IterateClients` to `IterateClientStates`. The function now takes a prefix argument which may be used for prefix iteration over the client store. - - * (light-clients/tendermint)[\#1768](https://github.com/cosmos/ibc-go/pull/1768) Removed `AllowUpdateAfterExpiry`, `AllowUpdateAfterMisbehaviour` booleans as they are deprecated (see ADR026) - - * (06-solomachine) [\#1679](https://github.com/cosmos/ibc-go/pull/1679) Remove `types` sub-package from `06-solomachine` lightclient directory. - - * (07-tendermint) [\#1677](https://github.com/cosmos/ibc-go/pull/1677) Remove `types` sub-package from `07-tendermint` lightclient directory. - - * (06-solomachine) [\#1687](https://github.com/cosmos/ibc-go/pull/1687) Bump `06-solomachine` protobuf version from `v2` to `v3`. - - * (06-solomachine) [\#1687](https://github.com/cosmos/ibc-go/pull/1687) Removed `DataType` enum and associated message types from `06-solomachine`. `DataType` has been removed from `SignBytes` and `SignatureAndData` in favour of `path`. - - * (02-client) [\#598](https://github.com/cosmos/ibc-go/pull/598) The client state and consensus state return value has been removed from `VerifyUpgradeAndUpdateState`. Light client implementations must update the client state and consensus state after verifying a valid client upgrade. - - * (06-solomachine) [\#1100](https://github.com/cosmos/ibc-go/pull/1100) Remove `GetClientID` function from 06-solomachine `Misbehaviour` type. - - * (06-solomachine) [\#1100](https://github.com/cosmos/ibc-go/pull/1100) Deprecate `ClientId` field in 06-solomachine `Misbehaviour` type. - - * (07-tendermint) [\#1097](https://github.com/cosmos/ibc-go/pull/1097) Remove `GetClientID` function from 07-tendermint `Misbehaviour` type. - - * (07-tendermint) [\#1097](https://github.com/cosmos/ibc-go/pull/1097) Deprecate `ClientId` field in 07-tendermint `Misbehaviour` type. - - * (modules/core/exported) [\#1107](https://github.com/cosmos/ibc-go/pull/1107) Merging the `Header` and `Misbehaviour` interfaces into a single `ClientMessage` type. - - * (06-solomachine)[\#1906](https://github.com/cosmos/ibc-go/pull/1906/files) Removed `AllowUpdateAfterProposal` boolean as it has been deprecated (see 01_concepts of the solo machine spec for more details). - - * (07-tendermint) [\#1896](https://github.com/cosmos/ibc-go/pull/1896) Remove error return from `IterateConsensusStateAscending` in `07-tendermint`. - - * (apps/27-interchain-accounts) [\#2638](https://github.com/cosmos/ibc-go/pull/2638) Interchain accounts host and controller Keepers now expects a keeper which fulfills the expected `exported.ScopedKeeper` interface for the capability keeper. - - * (06-solomachine) [\#2761](https://github.com/cosmos/ibc-go/pull/2761) Removed deprecated `ClientId` field from `Misbehaviour` and `allow_update_after_proposal` field from `ClientState`. - - * (apps) [\#3154](https://github.com/cosmos/ibc-go/pull/3154) Remove unused `ProposalContents` function. - - * (apps) [\#3149](https://github.com/cosmos/ibc-go/pull/3149) Remove legacy interface function `RandomizedParams`, which is no longer used. - - * (light-clients/06-solomachine) [\#2941](https://github.com/cosmos/ibc-go/pull/2941) Remove solomachine header sequence. - - * (core) [\#2982](https://github.com/cosmos/ibc-go/pull/2982) Moved the ibc module name into the exported package. - - ### State Machine Breaking - - * (06-solomachine) [\#2744](https://github.com/cosmos/ibc-go/pull/2744) `Misbehaviour.ValidateBasic()` now only enforces that signature data does not match when the signature paths are different. - - * (06-solomachine) [\#2748](https://github.com/cosmos/ibc-go/pull/2748) Adding sentinel value for header path in 06-solomachine. - - * (apps/29-fee) [\#2942](https://github.com/cosmos/ibc-go/pull/2942) Check `x/bank` send enabled before escrowing fees. - - * (core/04-channel) [\#3009](https://github.com/cosmos/ibc-go/pull/3009) Change check to disallow optimistic sends. - - ### Improvements - - * (core) [\#3082](https://github.com/cosmos/ibc-go/pull/3082) Add `HasConnection` and `HasChannel` methods. - - * (tests) [\#2926](https://github.com/cosmos/ibc-go/pull/2926) Lint tests - - * (apps/transfer) [\#2643](https://github.com/cosmos/ibc-go/pull/2643) Add amount, denom, and memo to transfer event emission. - - * (core) [\#2746](https://github.com/cosmos/ibc-go/pull/2746) Allow proof height to be zero for all core IBC `sdk.Msg` types that contain proofs. - - * (light-clients/06-solomachine) [\#2746](https://github.com/cosmos/ibc-go/pull/2746) Discard proofHeight for solo machines and use the solo machine sequence instead. - - * (modules/light-clients/07-tendermint) [\#1713](https://github.com/cosmos/ibc-go/pull/1713) Allow client upgrade proposals to update `TrustingPeriod`. See ADR-026 for context. - - * (modules/core/02-client) [\#1188](https://github.com/cosmos/ibc-go/pull/1188/files) Routing `MsgSubmitMisbehaviour` to `UpdateClient` keeper function. Deprecating `SubmitMisbehaviour` endpoint. - - * (modules/core/02-client) [\#1208](https://github.com/cosmos/ibc-go/pull/1208) Replace `CheckHeaderAndUpdateState` usage in 02-client with calls to `VerifyClientMessage`, `CheckForMisbehaviour`, `UpdateStateOnMisbehaviour` and `UpdateState`. - - * (modules/light-clients/09-localhost) [\#1187](https://github.com/cosmos/ibc-go/pull/1187/) Removing localhost light client implementation as it is not functional. An upgrade handler is provided in `modules/migrations/v5` to prune `09-localhost` clients and consensus states from the store. - - * (modules/core/02-client) [\#1186](https://github.com/cosmos/ibc-go/pull/1186) Removing `GetRoot` function from ConsensusState interface in `02-client`. `GetRoot` is unused by core IBC. - - * (modules/core/02-client) [\#1196](https://github.com/cosmos/ibc-go/pull/1196) Adding VerifyClientMessage to ClientState interface. - - * (modules/core/02-client) [\#1198](https://github.com/cosmos/ibc-go/pull/1198) Adding UpdateStateOnMisbehaviour to ClientState interface. - - * (modules/core/02-client) [\#1170](https://github.com/cosmos/ibc-go/pull/1170) Updating `ClientUpdateProposal` to set client state in lightclient implementations `CheckSubstituteAndUpdateState` methods. - - * (modules/core/02-client) [\#1197](https://github.com/cosmos/ibc-go/pull/1197) Adding `CheckForMisbehaviour` to `ClientState` interface. - - * (modules/core/02-client) [\#1210](https://github.com/cosmos/ibc-go/pull/1210) Removing `CheckHeaderAndUpdateState` from `ClientState` interface & associated light client implementations. - - * (modules/core/02-client) [\#1212](https://github.com/cosmos/ibc-go/pull/1212) Removing `CheckMisbehaviourAndUpdateState` from `ClientState` interface & associated light client implementations. - - * (modules/core/exported) [\#1206](https://github.com/cosmos/ibc-go/pull/1206) Adding new method `UpdateState` to `ClientState` interface. - - * (modules/core/02-client) [\#1741](https://github.com/cosmos/ibc-go/pull/1741) Emitting a new `upgrade_chain` event upon setting upgrade consensus state. - - * (client) [\#724](https://github.com/cosmos/ibc-go/pull/724) `IsRevisionFormat` and `IsClientIDFormat` have been updated to disallow newlines before the dash used to separate the chainID and revision number, and the client type and client sequence. - - * (02-client/cli) [\#897](https://github.com/cosmos/ibc-go/pull/897) Remove `GetClientID()` from `Misbehaviour` interface. Submit client misbehaviour cli command requires an explicit client id now. - - * (06-solomachine) [\#1972](https://github.com/cosmos/ibc-go/pull/1972) Solo machine implementation of `ZeroCustomFields` fn now panics as the fn is only used for upgrades which solo machine does not support. - - * (light-clients/06-solomachine) Moving `verifyMisbehaviour` function from update.go to misbehaviour_handle.go. - - * [\#2434](https://github.com/cosmos/ibc-go/pull/2478) Removed all `TypeMsg` constants - - * (modules/core/exported) [\#2539](https://github.com/cosmos/ibc-go/pull/2539) Removing `GetVersions` from `ConnectionI` interface. - - * (core/02-connection) [\#2419](https://github.com/cosmos/ibc-go/pull/2419) Add optional proof data to proto definitions of `MsgConnectionOpenTry` and `MsgConnectionOpenAck` for host state machines that are unable to introspect their own consensus state. - - * (light-clients/07-tendermint) [\#3046](https://github.com/cosmos/ibc-go/pull/3046) Moved non-verification misbehaviour checks to `CheckForMisbehaviour`. - - * (apps/29-fee) [\#2975](https://github.com/cosmos/ibc-go/pull/2975) Adding distribute fee events to ics29. - - * (light-clients/07-tendermint) [\#2965](https://github.com/cosmos/ibc-go/pull/2965) Prune expired `07-tendermint` consensus states on duplicate header updates. - - * (light-clients) [\#2736](https://github.com/cosmos/ibc-go/pull/2736) Updating `VerifyMembership` and `VerifyNonMembership` methods to use `Path` interface. - - * (light-clients) [\#3113](https://github.com/cosmos/ibc-go/pull/3113) Align light client module names. - - ### Features - - * (apps/transfer) [\#3079](https://github.com/cosmos/ibc-go/pull/3079) Added authz support for ics20. - - * (core/02-client) [\#2824](https://github.com/cosmos/ibc-go/pull/2824) Add genesis migrations for v6 to v7. The migration migrates the solo machine client state definition, removes all solo machine consensus states and removes the localhost client. - - * (core/24-host) [\#2856](https://github.com/cosmos/ibc-go/pull/2856) Add `PrefixedClientStorePath` and `PrefixedClientStoreKey` functions to 24-host - - * (core/02-client) [\#2819](https://github.com/cosmos/ibc-go/pull/2819) Add automatic in-place store migrations to remove the localhost client and migrate existing solo machine definitions. - - * (light-clients/06-solomachine) [\#2826](https://github.com/cosmos/ibc-go/pull/2826) Add `AppModuleBasic` for the 06-solomachine client and remove solo machine type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. - - * (light-clients/07-tendermint) [\#2825](https://github.com/cosmos/ibc-go/pull/2825) Add `AppModuleBasic` for the 07-tendermint client and remove tendermint type registration from core IBC. Chains must register the `AppModuleBasic` of light clients. - - * (light-clients/07-tendermint) [\#2800](https://github.com/cosmos/ibc-go/pull/2800) Add optional in-place store migration function to prune all expired tendermint consensus states. - - * (core/24-host) [\#2820](https://github.com/cosmos/ibc-go/pull/2820) Add `MustParseClientStatePath` which parses the clientID from a client state key path. - - * (testing/simapp) [\#2842](https://github.com/cosmos/ibc-go/pull/2842) Adding the new upgrade handler for v6 -> v7 to simapp which prunes expired Tendermint consensus states. - - * (testing) [\#2829](https://github.com/cosmos/ibc-go/pull/2829) Add `AssertEvents` which asserts events against expected event map. - - ### Bug Fixes - - * (testing) [\#3295](https://github.com/cosmos/ibc-go/pull/3295) The function `SetupWithGenesisValSet` will set the baseapp chainID before running `InitChain` - - * (light-clients/solomachine) [\#1839](https://github.com/cosmos/ibc-go/pull/1839) Fixed usage of the new diversifier in validation of changing diversifiers for the solo machine. The current diversifier must sign over the new diversifier. - - * (light-clients/07-tendermint) [\#1674](https://github.com/cosmos/ibc-go/pull/1674) Submitted ClientState is zeroed out before checking the proof in order to prevent the proposal from containing information governance is not actually voting on. - - * (modules/core/02-client)[\#1676](https://github.com/cosmos/ibc-go/pull/1676) ClientState must be zeroed out for `UpgradeProposals` to pass validation. This prevents a proposal containing information governance is not actually voting on. - - * (core/02-client) [\#2510](https://github.com/cosmos/ibc-go/pull/2510) Fix client ID validation regex to conform closer to spec. - - * (apps/transfer) [\#3045](https://github.com/cosmos/ibc-go/pull/3045) Allow value with slashes in URL template. - - * (apps/27-interchain-accounts) [\#2601](https://github.com/cosmos/ibc-go/pull/2601) Remove bech32 check from owner address on ICA controller msgs RegisterInterchainAccount and SendTx. - - * (apps/transfer) [\#2651](https://github.com/cosmos/ibc-go/pull/2651) Skip emission of unpopulated memo field in ics20. - - * (apps/27-interchain-accounts) [\#2682](https://github.com/cosmos/ibc-go/pull/2682) Avoid race conditions in ics27 handshakes. - - * (light-clients/06-solomachine) [\#2741](https://github.com/cosmos/ibc-go/pull/2741) Added check for empty path in 06-solomachine. - - * (light-clients/07-tendermint) [\#3022](https://github.com/cosmos/ibc-go/pull/3022) Correctly close iterator in `07-tendermint` store. - - * (core/02-client) [\#3010](https://github.com/cosmos/ibc-go/pull/3010) Update `Paginate` to use `FilterPaginate` in `ClientStates` and `ConnectionChannels` grpc queries. - - ## [v6.3.0](https://github.com/cosmos/ibc-go/releases/tag/v6.3.0) - 2024-04-05 + - Placeholder release notes diff --git a/docs/sdk/proposed-nav-next.json b/docs/sdk/proposed-nav-next.json new file mode 100644 index 00000000..f1fa84cf --- /dev/null +++ b/docs/sdk/proposed-nav-next.json @@ -0,0 +1,37 @@ +{ + "version": "next", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { "group": "Transactions & Fees", "pages": [] }, + { "group": "Messaging & Queries", "pages": [ + "docs/sdk/next/build/building-modules/messaging-and-queries" + ]}, + { "group": "Integration", "groups": [ + { "group": "App Wiring & Runtime", "pages": [] }, + { "group": "Module Wiring", "pages": [] }, + { "group": "Upgrades & Migrations", "pages": [] }, + { "group": "Messaging Integration", "pages": [] }, + { "group": "Vote Extensions (End-to-End)", "pages": [] } + ]}, + { "group": "Module Anatomy & Keepers", "pages": [] }, + { "group": "Runtime & ABCI", "pages": [ + "docs/sdk/next/build/abci/index" + ]}, + { "group": "State & Store", "pages": [] }, + { "group": "Encoding & Protobuf", "pages": [] }, + { "group": "Testing & Simulation", "pages": [] }, + { "group": "Core Concepts", "pages": [ + "docs/sdk/next/index" + ]}, + { "group": "Node Operations", "pages": [] }, + { "group": "Tooling", "pages": [] } + ] + }, + { "tab": "Module Reference", "groups": [] }, + { "tab": "API Reference", "pages": [] }, + { "tab": "Release Notes", "pages": [] } + ] +} + diff --git a/docs/sdk/proposed-nav-v0.47.json b/docs/sdk/proposed-nav-v0.47.json new file mode 100644 index 00000000..d811b8a7 --- /dev/null +++ b/docs/sdk/proposed-nav-v0.47.json @@ -0,0 +1,8 @@ +{ + "version": "v0.47", + "tabs": [ + { "tab": "API Reference", "pages": [] }, + { "tab": "Release Notes", "pages": [] } + ] +} + diff --git a/docs/sdk/proposed-nav-v0.50.json b/docs/sdk/proposed-nav-v0.50.json new file mode 100644 index 00000000..d47d6173 --- /dev/null +++ b/docs/sdk/proposed-nav-v0.50.json @@ -0,0 +1,8 @@ +{ + "version": "v0.50", + "tabs": [ + { "tab": "API Reference", "pages": [] }, + { "tab": "Release Notes", "pages": [] } + ] +} + diff --git a/docs/sdk/proposed-nav-v0.53.json b/docs/sdk/proposed-nav-v0.53.json new file mode 100644 index 00000000..1b118103 --- /dev/null +++ b/docs/sdk/proposed-nav-v0.53.json @@ -0,0 +1,224 @@ +{ + "version": "v0.53", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "Runtime & ABCI", + "pages": [ + "docs/sdk/v0.53/build/abci/introduction", + "docs/sdk/v0.53/build/abci/prepare-proposal", + "docs/sdk/v0.53/build/abci/process-proposal", + "docs/sdk/v0.53/build/abci/checktx" + ] + }, + { + "group": "Transactions & Fees", + "pages": [ + "docs/sdk/v0.53/learn/beginner/tx-lifecycle", + "docs/sdk/v0.53/learn/advanced/transactions", + "docs/sdk/v0.53/learn/beginner/gas-fees" + ] + }, + { + "group": "Integration", + "groups": [ + { + "group": "App Wiring & Runtime", + "pages": [ + "docs/sdk/v0.53/build/building-apps/app-go", + "docs/sdk/v0.53/build/building-apps/runtime", + "docs/sdk/v0.53/build/building-apps/app-go-di", + "docs/sdk/v0.53/build/building-apps/app-mempool", + "docs/sdk/v0.53/build/building-apps/app-upgrade", + "docs/sdk/v0.53/build/building-apps/app-testnet" + ] + }, + { + "group": "Module Wiring", + "pages": [ + "docs/sdk/v0.53/build/building-modules/module-manager", + "docs/sdk/v0.53/build/building-modules/module-interfaces", + "docs/sdk/v0.53/build/building-modules/structure", + "docs/sdk/v0.53/build/building-modules/keeper", + "docs/sdk/v0.53/build/building-modules/genesis", + "docs/sdk/v0.53/build/building-modules/invariants", + "docs/sdk/v0.53/build/building-modules/errors", + "docs/sdk/v0.53/build/building-modules/preblock", + "docs/sdk/v0.53/build/building-modules/depinject" + ] + }, + { + "group": "Messaging Integration", + "pages": [ + "docs/sdk/v0.53/build/building-modules/messages-and-queries", + "docs/sdk/v0.53/build/building-modules/msg-services", + "docs/sdk/v0.53/build/building-modules/query-services" + ] + }, + { + "group": "Upgrades & Migrations", + "pages": [ + "docs/sdk/v0.53/build/building-apps/app-upgrade", + "docs/sdk/v0.53/build/building-modules/upgrade", + "docs/sdk/v0.53/learn/advanced/upgrade" + ] + }, + { + "group": "Vote Extensions (End-to-End)", + "pages": [ + "docs/sdk/v0.53/build/abci/vote-extensions", + "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started", + "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", + "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", + "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", + "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running", + "docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started", + "docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions", + "docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle" + ] + } + ] + }, + { + "group": "State & Store", + "pages": [ + "docs/sdk/v0.53/learn/advanced/store" + ] + }, + { + "group": "Encoding & Protobuf", + "pages": [ + "docs/sdk/v0.53/learn/advanced/encoding", + "docs/sdk/v0.53/build/building-modules/protobuf-annotations" + ] + }, + { + "group": "Testing & Simulation", + "pages": [ + "docs/sdk/v0.53/build/building-modules/testing", + "docs/sdk/v0.53/build/building-modules/simulator" + ] + }, + { + "group": "Tooling", + "pages": [ + "docs/sdk/v0.53/learn/advanced/cli" + ] + }, + { + "group": "Core Concepts", + "pages": [ + "docs/sdk/v0.53/learn/intro/overview", + "docs/sdk/v0.53/learn/intro/why-app-specific", + "docs/sdk/v0.53/learn/intro/sdk-app-architecture", + "docs/sdk/v0.53/learn/intro/sdk-design", + "docs/sdk/v0.53/learn/beginner/accounts", + "docs/sdk/v0.53/learn/advanced/context", + "docs/sdk/v0.53/learn/advanced/node", + "docs/sdk/v0.53/learn/advanced/events", + "docs/sdk/v0.53/learn/advanced/telemetry", + "docs/sdk/v0.53/learn/advanced/ocap", + "docs/sdk/v0.53/learn/advanced/config", + "docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle" + ] + }, + { + "group": "Node Operations", + "pages": [ + "docs/sdk/v0.53/user", + "docs/sdk/v0.53/user/run-node/interact-node", + "docs/sdk/v0.53/user/run-node/run-testnet", + "docs/sdk/v0.53/user/run-node/run-node", + "docs/sdk/v0.53/user/run-node/txs", + "docs/sdk/v0.53/user/run-node/keyring", + "docs/sdk/v0.53/user/run-node/run-production" + ] + } + ] + }, + { + "tab": "Module Reference", + "groups": [ + { + "group": "x/auth", + "pages": [ + "docs/sdk/v0.53/build/modules/auth", + "docs/sdk/v0.53/build/modules/auth/vesting", + "docs/sdk/v0.53/build/modules/auth/tx" + ] + }, + { + "group": "x/authz & feegrant", + "pages": [ + "docs/sdk/v0.53/build/modules/authz", + "docs/sdk/v0.53/build/modules/feegrant" + ] + }, + { + "group": "x/bank & mint", + "pages": [ + "docs/sdk/v0.53/build/modules/bank", + "docs/sdk/v0.53/build/modules/mint" + ] + }, + { + "group": "x/gov & group", + "pages": [ + "docs/sdk/v0.53/build/modules/gov", + "docs/sdk/v0.53/build/modules/group" + ] + }, + { + "group": "x/staking suite", + "pages": [ + "docs/sdk/v0.53/build/modules/staking", + "docs/sdk/v0.53/build/modules/slashing", + "docs/sdk/v0.53/build/modules/distribution" + ] + }, + { + "group": "x/consensus & evidence", + "pages": [ + "docs/sdk/v0.53/build/modules/consensus", + "docs/sdk/v0.53/build/modules/evidence" + ] + }, + { + "group": "x/params & upgrade", + "pages": [ + "docs/sdk/v0.53/build/modules/params", + "docs/sdk/v0.53/build/modules/upgrade" + ] + }, + { + "group": "x/protocolpool", + "pages": [ + "docs/sdk/v0.53/build/modules/protocolpool" + ] + }, + { + "group": "x/nft & epochs", + "pages": [ + "docs/sdk/v0.53/build/modules/nft", + "docs/sdk/v0.53/build/modules/epochs" + ] + } + ] + }, + { + "tab": "API Reference", + "pages": [ + "docs/sdk/v0.53/learn/advanced/grpc_rest", + "docs/sdk/v0.53/learn/advanced/proto-docs" + ] + }, + { + "tab": "Release Notes", + "pages": [ + "docs/sdk/v0.53/changelog/release-notes" + ] + } + ] +} diff --git a/docs/sdk/sdk-categorization.json b/docs/sdk/sdk-categorization.json new file mode 100644 index 00000000..d1109aff --- /dev/null +++ b/docs/sdk/sdk-categorization.json @@ -0,0 +1,210 @@ +{ + "v0.53": { + "Runtime & ABCI": [ + "docs/sdk/v0.53/build/abci/introduction", + "docs/sdk/v0.53/build/abci/prepare-proposal", + "docs/sdk/v0.53/build/abci/process-proposal", + "docs/sdk/v0.53/build/abci/checktx" + ], + "Transactions & Fees": [ + "docs/sdk/v0.53/learn/beginner/tx-lifecycle", + "docs/sdk/v0.53/learn/advanced/transactions", + "docs/sdk/v0.53/learn/beginner/gas-fees" + ], + "Messaging & Queries": [ + "docs/sdk/v0.53/build/building-modules/messages-and-queries", + "docs/sdk/v0.53/build/building-modules/msg-services", + "docs/sdk/v0.53/build/building-modules/query-services" + ], + "Module Anatomy & Keepers": [ + "docs/sdk/v0.53/build/building-modules/module-manager", + "docs/sdk/v0.53/build/building-modules/module-interfaces", + "docs/sdk/v0.53/build/building-modules/structure", + "docs/sdk/v0.53/build/building-modules/keeper", + "docs/sdk/v0.53/build/building-modules/genesis", + "docs/sdk/v0.53/build/building-modules/invariants", + "docs/sdk/v0.53/build/building-modules/errors", + "docs/sdk/v0.53/build/building-modules/preblock" + ], + "App Wiring & Runtime": [ + "docs/sdk/v0.53/build/building-apps/app-go", + "docs/sdk/v0.53/build/building-apps/runtime", + "docs/sdk/v0.53/build/building-apps/app-go-di", + "docs/sdk/v0.53/build/building-apps/app-mempool", + "docs/sdk/v0.53/build/building-apps/app-upgrade", + "docs/sdk/v0.53/build/building-apps/vote-extensions" + ], + "State & Store": [ + "docs/sdk/v0.53/learn/advanced/store" + ], + "Encoding & Protobuf": [ + "docs/sdk/v0.53/learn/advanced/encoding", + "docs/sdk/v0.53/learn/advanced/proto-docs", + "docs/sdk/v0.53/build/building-modules/protobuf-annotations" + ], + "Upgrades & Migrations": [ + "docs/sdk/v0.53/build/building-apps/app-upgrade", + "docs/sdk/v0.53/build/building-modules/upgrade", + "docs/sdk/v0.53/learn/advanced/upgrade" + ], + "Testing & Simulation": [ + "docs/sdk/v0.53/build/building-modules/testing", + "docs/sdk/v0.53/build/building-modules/simulator" + ], + "APIs & Clients": [ + "docs/sdk/v0.53/learn/advanced/cli", + "docs/sdk/v0.53/learn/advanced/grpc_rest" + ], + "Core Concepts": [ + "docs/sdk/v0.53/learn/intro/overview", + "docs/sdk/v0.53/learn/intro/why-app-specific", + "docs/sdk/v0.53/learn/intro/sdk-app-architecture", + "docs/sdk/v0.53/learn/intro/sdk-design", + "docs/sdk/v0.53/learn/beginner/accounts", + "docs/sdk/v0.53/learn/advanced/context", + "docs/sdk/v0.53/learn/advanced/node", + "docs/sdk/v0.53/learn/advanced/events", + "docs/sdk/v0.53/learn/advanced/telemetry", + "docs/sdk/v0.53/learn/advanced/ocap", + "docs/sdk/v0.53/learn/advanced/config", + "docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle" + ], + "Node Operations": [ + "docs/sdk/v0.53/user", + "docs/sdk/v0.53/user/run-node/interact-node", + "docs/sdk/v0.53/user/run-node/run-testnet", + "docs/sdk/v0.53/user/run-node/run-node", + "docs/sdk/v0.53/user/run-node/txs", + "docs/sdk/v0.53/user/run-node/keyring", + "docs/sdk/v0.53/user/run-node/run-production" + ], + "Module Reference (x/*)": [ + "docs/sdk/v0.53/build/modules/auth", + "docs/sdk/v0.53/build/modules/auth/vesting", + "docs/sdk/v0.53/build/modules/auth/tx", + "docs/sdk/v0.53/build/modules/authz", + "docs/sdk/v0.53/build/modules/feegrant", + "docs/sdk/v0.53/build/modules/bank", + "docs/sdk/v0.53/build/modules/mint", + "docs/sdk/v0.53/build/modules/gov", + "docs/sdk/v0.53/build/modules/group", + "docs/sdk/v0.53/build/modules/staking", + "docs/sdk/v0.53/build/modules/slashing", + "docs/sdk/v0.53/build/modules/distribution", + "docs/sdk/v0.53/build/modules/consensus", + "docs/sdk/v0.53/build/modules/evidence", + "docs/sdk/v0.53/build/modules/params", + "docs/sdk/v0.53/build/modules/upgrade", + "docs/sdk/v0.53/build/modules/protocolpool", + "docs/sdk/v0.53/build/modules/nft", + "docs/sdk/v0.53/build/modules/epochs" + ] + }, + "v0.50": { + "Runtime & ABCI": [], + "Transactions & Fees": [ + "docs/sdk/v0.50/learn/beginner/tx-lifecycle", + "docs/sdk/v0.50/learn/advanced/transactions", + "docs/sdk/v0.50/learn/beginner/gas-fees" + ], + "Messaging & Queries": [ + "docs/sdk/v0.50/learn/advanced/baseapp" + ], + "Module Anatomy & Keepers": [], + "App Wiring & Runtime": [], + "State & Store": [ + "docs/sdk/v0.50/learn/advanced/store" + ], + "Encoding & Protobuf": [ + "docs/sdk/v0.50/learn/advanced/encoding", + "docs/sdk/v0.50/learn/advanced/proto-docs" + ], + "Upgrades & Migrations": [ + "docs/sdk/v0.50/learn/advanced/upgrade" + ], + "Testing & Simulation": [ + "docs/sdk/v0.50/learn/advanced/simulation" + ], + "APIs & Clients": [ + "docs/sdk/v0.50/learn/advanced/cli", + "docs/sdk/v0.50/learn/advanced/grpc_rest" + ], + "Core Concepts": [ + "docs/sdk/v0.50/learn/intro/overview", + "docs/sdk/v0.50/learn/intro/why-app-specific", + "docs/sdk/v0.50/learn/intro/sdk-app-architecture", + "docs/sdk/v0.50/learn/intro/sdk-design", + "docs/sdk/v0.50/learn/beginner/accounts", + "docs/sdk/v0.50/learn/advanced/events", + "docs/sdk/v0.50/learn/advanced/ocap", + "docs/sdk/v0.50/learn/advanced/config", + "docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle" + ], + "Node Operations": [ + "docs/sdk/v0.50/user", + "docs/sdk/v0.50/user/run-node/interact-node", + "docs/sdk/v0.50/user/run-node/run-testnet", + "docs/sdk/v0.50/user/run-node/run-node", + "docs/sdk/v0.50/user/run-node/txs", + "docs/sdk/v0.50/user/run-node/keyring", + "docs/sdk/v0.50/user/run-node/rosetta", + "docs/sdk/v0.50/user/run-node/run-production" + ] + }, + "v0.47": { + "Runtime & ABCI": [], + "Transactions & Fees": [ + "docs/sdk/v0.47/learn/beginner/tx-lifecycle", + "docs/sdk/v0.47/learn/advanced/transactions", + "docs/sdk/v0.47/learn/beginner/gas-fees" + ], + "Messaging & Queries": [ + "docs/sdk/v0.47/learn/advanced/baseapp" + ], + "Module Anatomy & Keepers": [], + "App Wiring & Runtime": [], + "State & Store": [ + "docs/sdk/v0.47/learn/advanced/store", + "docs/sdk/v0.47/learn/advanced/interblock-cache" + ], + "Encoding & Protobuf": [ + "docs/sdk/v0.47/learn/advanced/encoding", + "docs/sdk/v0.47/learn/advanced/proto-docs" + ], + "Upgrades & Migrations": [ + "docs/sdk/v0.47/learn/advanced/upgrade" + ], + "Testing & Simulation": [ + "docs/sdk/v0.47/learn/advanced/simulation" + ], + "APIs & Clients": [ + "docs/sdk/v0.47/learn/advanced/cli", + "docs/sdk/v0.47/learn/advanced/grpc_rest" + ], + "Core Concepts": [ + "docs/sdk/v0.47/learn/intro/overview", + "docs/sdk/v0.47/learn/intro/why-app-specific", + "docs/sdk/v0.47/learn/intro/sdk-app-architecture", + "docs/sdk/v0.47/learn/intro/sdk-design", + "docs/sdk/v0.47/learn/beginner/accounts", + "docs/sdk/v0.47/learn/advanced/context", + "docs/sdk/v0.47/learn/advanced/node", + "docs/sdk/v0.47/learn/advanced/events", + "docs/sdk/v0.47/learn/advanced/telemetry", + "docs/sdk/v0.47/learn/advanced/ocap", + "docs/sdk/v0.47/learn/advanced/config" + ], + "Node Operations": [ + "docs/sdk/v0.47/user", + "docs/sdk/v0.47/user/run-node/interact-node", + "docs/sdk/v0.47/user/run-node/multisig-guide", + "docs/sdk/v0.47/user/run-node/run-testnet", + "docs/sdk/v0.47/user/run-node/run-node", + "docs/sdk/v0.47/user/run-node/rosetta", + "docs/sdk/v0.47/user/run-node/txs", + "docs/sdk/v0.47/user/run-node/keyring", + "docs/sdk/v0.47/user/run-node/run-production" + ] + } +} + diff --git a/docs/sdk/v0.47/changelog/release-notes.mdx b/docs/sdk/v0.47/changelog/release-notes.mdx new file mode 100644 index 00000000..b34f815e --- /dev/null +++ b/docs/sdk/v0.47/changelog/release-notes.mdx @@ -0,0 +1,407 @@ +--- +title: "Release Notes" +description: "Cosmos SDK release notes and changelog" +mode: "custom" +--- + + + - {/* + - Guiding Principles: + - Changelogs are for humans, not machines. + - There should be an entry for every single version. + - The same types of changes should be grouped. + - Versions and sections should be linkable. + - The latest version comes first. + - The release date of each version is displayed. + - Mention whether you follow Semantic Versioning. + - Usage: + - Change log entries are to be added to the Unreleased section under the + - appropriate stanza (see below). Each entry should ideally include a tag and + - the Github issue reference in the following format: + - * () \# message + - The issue numbers will later be link-ified during the release process so you do + - not have to worry about including a link manually, but you can if you wish. + - Types of changes (Stanzas): + - "Features" for new features. + - "Improvements" for changes in existing functionality. + - "Deprecated" for soon-to-be removed features. + - "Bug Fixes" for any bug fixes. + - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. + - "CLI Breaking" for breaking CLI commands. + - "API Breaking" for breaking exported APIs used by developers building on SDK. + - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. + - Ref: https://keepachangelog.com/en/1.0.0/ + - */} + - # Changelog + - ## [Unreleased] + - ## [v0.47.17](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.17) - 2025-02-12 + - ### Bug Fixes + - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker + - ## [v0.47.16](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.16) - 2025-02-20 + - ### Bug Fixes + - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal + - ## [v0.47.15](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.15) - 2024-12-16 + - ### Bug Fixes + - * Bump `cosmossdk.io/math` to v1.4. + - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any + - ## [v0.47.14](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.14) - 2024-09-20 + - ### Improvements + - * [#21295](https://github.com/cosmos/cosmos-sdk/pull/21295) Bump to gogoproto v1.7.0. + - * [#21295](https://github.com/cosmos/cosmos-sdk/pull/21295) Remove usage of `slices.SortFunc` due to API break in used versions. + - ## [v0.47.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.13) - 2024-07-15 + - ### Bug Fixes + - * (client) [#20912](https://github.com/cosmos/cosmos-sdk/pull/20912) Fix `math.LegacyDec` type deserialization in GRPC queries. + - * (x/group) [#20750](https://github.com/cosmos/cosmos-sdk/pull/20750) x/group shouldn't claim "orm" error codespace. This prevents any chain Cosmos SDK `v0.47` chain to use the ORM module. + - ## [v0.47.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.12) - 2024-06-10 + - ## Improvements + - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. + - ### Bug Fixes + - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. + - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. + - ## [v0.47.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.11) - 2024-04-22 + - ### Bug Fixes + - * (x/feegrant,x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m). The same issue was found in `x/feegrant` and `x/authz` modules. + - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. + - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from `proposal.FinalTallyResult` in the gprc query. + - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19746) Throw an error when signing with incorrect Ledger. + - ## [v0.47.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.10) - 2024-02-27 + - ### Bug Fixes + - * (x/staking) Fix a possible bypass of delagator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) + - * (server) [#19573](https://github.com/cosmos/cosmos-sdk/pull/19573) Use proper `db_backend` type when reading chain-id + - ## [v0.47.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.9) - 2024-02-19 + - ### Bug Fixes + - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. + - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. + - ## [v0.47.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.8) - 2024-01-22 + - ### Improvements + - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. + - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1. + - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 + - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. + - ### Bug Fixes + - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. + - * (server) [#18920](https://github.com/cosmos/cosmos-sdk/pull/18920) Fixes consensus failure while restart node with wrong `chainId` in genesis. + - ## [v0.47.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.7) - 2023-12-20 + - ### Improvements + - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. + - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. + - ### Bug Fixes + - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after BeginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. + - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. + - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. + - ## [v0.47.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.6) - 2023-11-14 + - ### Features + - * (server) [#18110](https://github.com/cosmos/cosmos-sdk/pull/18110) Start gRPC & API server in standalone mode. + - ### Improvements + - * (baseapp) [#17954](https://github.com/cosmos/cosmos-sdk/issues/17954) Add `Mempool()` method on `BaseApp` to allow access to the mempool. + - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. + - ### Bug Fixes + - * (server) [#18254](https://github.com/cosmos/cosmos-sdk/pull/18254) Don't hardcode gRPC address to localhost. + - * (server) [#18251](https://github.com/cosmos/cosmos-sdk/pull/18251) Call `baseapp.Close()` when app started as grpc only. + - * (baseapp) [#17769](https://github.com/cosmos/cosmos-sdk/pull/17769) Ensure we respect block size constraints in the `DefaultProposalHandler`'s `PrepareProposal` handler when a nil or no-op mempool is used. We provide a `TxSelector` type to assist in making transaction selection generalized. We also fix a comparison bug in tx selection when `req.maxTxBytes` is reached. + - * (config) [#17649](https://github.com/cosmos/cosmos-sdk/pull/17649) Fix `mempool.max-txs` configuration is invalid in `app.config`. + - * (mempool) [#17668](https://github.com/cosmos/cosmos-sdk/pull/17668) Fix `PriorityNonceIterator.Next()` nil pointer ref for min priority at the end of iteration. + - * (x/auth) [#17902](https://github.com/cosmos/cosmos-sdk/pull/17902) Remove tip posthandler. + - * (x/bank) [#18107](https://github.com/cosmos/cosmos-sdk/pull/18107) Add missing keypair of SendEnabled to restore legacy param set before migration. + - ### Client Breaking Changes + - * (x/gov) [#17910](https://github.com/cosmos/cosmos-sdk/pull/17910) Remove telemetry for counting votes and proposals. It was incorrectly counting votes. Use alternatives, such as state streaming. + - ## [v0.47.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.5) - 2023-09-01 + - ### Features + - * (client/rpc) [#17274](https://github.com/cosmos/cosmos-sdk/pull/17274) Add `QueryEventForTxCmd` cmd to subscribe and wait event for transaction by hash. + - * (keyring) [#17424](https://github.com/cosmos/cosmos-sdk/pull/17424) Allows to import private keys encoded in hex. + - ### Improvements + - * (x/gov) [#17387](https://github.com/cosmos/cosmos-sdk/pull/17387) Add `MsgSubmitProposal` `SetMsgs` method. + - * (x/gov) [#17354](https://github.com/cosmos/cosmos-sdk/issues/17354) Emit `VoterAddr` in `proposal_vote` event. + - * (x/group, x/gov) [#17220](https://github.com/cosmos/cosmos-sdk/pull/17220) Add `--skip-metadata` flag in `draft-proposal` to skip metadata prompt. + - * (x/genutil) [#17296](https://github.com/cosmos/cosmos-sdk/pull/17296) Add `MigrateHandler` to allow reuse migrate genesis related function. + - * In v0.46, v0.47 this function is additive to the `genesis migrate` command. However in v0.50+, adding custom migrations to the `genesis migrate` command is directly possible. + - ### Bug Fixes + - * (server) [#17181](https://github.com/cosmos/cosmos-sdk/pull/17181) Fix `db_backend` lookup fallback from `config.toml`. + - * (runtime) [#17284](https://github.com/cosmos/cosmos-sdk/pull/17284) Properly allow to combine depinject-enabled modules and non-depinject-enabled modules in app v2. + - * (baseapp) [#17159](https://github.com/cosmos/cosmos-sdk/pull/17159) Validators can propose blocks that exceed the gas limit. + - * (baseapp) [#16547](https://github.com/cosmos/cosmos-sdk/pull/16547) Ensure a transaction's gas limit cannot exceed the block gas limit. + - * (x/gov,x/group) [#17220](https://github.com/cosmos/cosmos-sdk/pull/17220) Do not try validate `msgURL` as web URL in `draft-proposal` command. + - * (cli) [#17188](https://github.com/cosmos/cosmos-sdk/pull/17188) Fix `--output-document` flag in `tx multi-sign`. + - * (x/auth) [#17209](https://github.com/cosmos/cosmos-sdk/pull/17209) Internal error on AccountInfo when account's public key is not set. + - ## [v0.47.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.4) - 2023-07-17 + - ### Features + - * (sims) [#16656](https://github.com/cosmos/cosmos-sdk/pull/16656) Add custom max gas for block for sim config with unlimited as default. + - ### Improvements + - * (cli) [#16856](https://github.com/cosmos/cosmos-sdk/pull/16856) Improve `simd prune` UX by using the app default home directory and set pruning method as first variable argument (defaults to default). `pruning.PruningCmd` rest unchanged for API compability, use `pruning.Cmd` instead. + - * (testutil) [#16704](https://github.com/cosmos/cosmos-sdk/pull/16704) Make app config configurator for testing configurable with external modules. + - * (deps) [#16565](https://github.com/cosmos/cosmos-sdk/pull/16565) Bump CometBFT to [v0.37.2](https://github.com/cometbft/cometbft/blob/v0.37.2/CHANGELOG.md). + - ### Bug Fixes + - * (x/auth) [#16994](https://github.com/cosmos/cosmos-sdk/pull/16994) Fix regression where querying transactions events with `<=` or `>=` would not work. + - * (server) [#16827](https://github.com/cosmos/cosmos-sdk/pull/16827) Properly use `--trace` flag (before it was setting the trace level instead of displaying the stacktraces). + - * (x/auth) [#16554](https://github.com/cosmos/cosmos-sdk/pull/16554) `ModuleAccount.Validate` now reports a nil `.BaseAccount` instead of panicking. + - * [#16588](https://github.com/cosmos/cosmos-sdk/pull/16588) Propogate snapshotter failures to the caller, (it would create an empty snapshot silently before). + - * (x/slashing) [#16784](https://github.com/cosmos/cosmos-sdk/pull/16784) Emit event with the correct reason in `SlashWithInfractionReason`. + - ## [v0.47.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.3) - 2023-06-08 + - ### Features + - * (baseapp) [#16290](https://github.com/cosmos/cosmos-sdk/pull/16290) Add circuit breaker setter in baseapp. + - * (x/group) [#16191](https://github.com/cosmos/cosmos-sdk/pull/16191) Add EventProposalPruned event to group module whenever a proposal is pruned. + - * (tx) [#15992](https://github.com/cosmos/cosmos-sdk/pull/15992) Add `WithExtensionOptions` in tx Factory to allow `SetExtensionOptions` with given extension options. + - ### Improvements + - * (baseapp) [#16407](https://github.com/cosmos/cosmos-sdk/pull/16407) Make `DefaultProposalHandler.ProcessProposalHandler` return a ProcessProposal NoOp when using none or a NoOp mempool. + - * (deps) [#16083](https://github.com/cosmos/cosmos-sdk/pull/16083) Bumps `proto-builder` image to 0.13.0. + - * (client) [#16075](https://github.com/cosmos/cosmos-sdk/pull/16075) Partly revert [#15953](https://github.com/cosmos/cosmos-sdk/issues/15953) and `factory.Prepare` now does nothing in offline mode. + - * (server) [#15984](https://github.com/cosmos/cosmos-sdk/pull/15984) Use `cosmossdk.io/log` package for logging instead of CometBFT logger. NOTE: v0.45 and v0.46 were not using CometBFT logger either. This keeps the same underlying logger (zerolog) as in v0.45.x+ and v0.46.x+ but now properly supporting filtered logging. + - * (gov) [#15979](https://github.com/cosmos/cosmos-sdk/pull/15979) Improve gov error message when failing to convert v1 proposal to v1beta1. + - * (store) [#16067](https://github.com/cosmos/cosmos-sdk/pull/16067) Add local snapshots management commands. + - * (server) [#16061](https://github.com/cosmos/cosmos-sdk/pull/16061) Add Comet bootstrap command. + - * (snapshots) [#16060](https://github.com/cosmos/cosmos-sdk/pull/16060) Support saving and restoring snapshot locally. + - * (x/staking) [#16068](https://github.com/cosmos/cosmos-sdk/pull/16068) Update simulation to allow non-EOA accounts to stake. + - * (server) [#16142](https://github.com/cosmos/cosmos-sdk/pull/16142) Remove JSON Indentation from the GRPC to REST gateway's responses. (Saving bandwidth) + - * (types) [#16145](https://github.com/cosmos/cosmos-sdk/pull/16145) Rename interface `ExtensionOptionI` back to `TxExtensionOptionI` to avoid breaking change. + - * (baseapp) [#16193](https://github.com/cosmos/cosmos-sdk/pull/16193) Add `Close` method to `BaseApp` for custom app to cleanup resource in graceful shutdown. + - ### Bug Fixes + - * Fix [barberry](https://forum.cosmos.network/t/cosmos-sdk-security-advisory-barberry/10825) security vulnerability. + - * (server) [#16395](https://github.com/cosmos/cosmos-sdk/pull/16395) Do not override some Comet config is purposely set differently in `InterceptConfigsPreRunHandler`. + - * (store) [#16449](https://github.com/cosmos/cosmos-sdk/pull/16449) Fix StateSync Restore by excluding memory store. + - * (cli) [#16312](https://github.com/cosmos/cosmos-sdk/pull/16312) Allow any addresses in `client.ValidatePromptAddress`. + - * (x/group) [#16017](https://github.com/cosmos/cosmos-sdk/pull/16017) Correctly apply account number in group v2 migration. + - ### API Breaking Changes + - * (testutil) [#14991](https://github.com/cosmos/cosmos-sdk/pull/14991) The `testutil/testdata_pulsar` package has moved to `testutil/testdata/testpb`. Chains will not notice this breaking change as this package contains testing utilities only used by the SDK internally. + - ## [v0.47.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.2) - 2023-04-27 + - ### Improvements + - * (x/evidence) [#15908](https://github.com/cosmos/cosmos-sdk/pull/15908) Update the equivocation handler to work with ICS by removing a pubkey check that was performing a no-op for consumer chains. + - * (x/slashing) [#15908](https://github.com/cosmos/cosmos-sdk/pull/15908) Remove the validators' pubkey check in the signature handler in order to work with ICS. + - * (deps) [#15957](https://github.com/cosmos/cosmos-sdk/pull/15957) Bump CometBFT to [v0.37.1](https://github.com/cometbft/cometbft/blob/v0.37.1/CHANGELOG.md#v0371). + - * (store) [#15683](https://github.com/cosmos/cosmos-sdk/pull/15683) `rootmulti.Store.CacheMultiStoreWithVersion` now can handle loading archival states that don't persist any of the module stores the current state has. + - * [#15448](https://github.com/cosmos/cosmos-sdk/pull/15448) Automatically populate the block timestamp for historical queries. In contexts where the block timestamp is needed for previous states, the timestamp will now be set. Note, when querying against a node it must be re-synced in order to be able to automatically populate the block timestamp. Otherwise, the block timestamp will be populated for heights going forward once upgraded. + - * [#14019](https://github.com/cosmos/cosmos-sdk/issues/14019) Remove the interface casting to allow other implementations of a `CommitMultiStore`. + - * (simtestutil) [#15903](https://github.com/cosmos/cosmos-sdk/pull/15903) Add `AppStateFnWithExtendedCbs` with moduleStateCb callback function to allow access moduleState. + - ### Bug Fixes + - * (baseapp) [#15789](https://github.com/cosmos/cosmos-sdk/pull/15789) Ensure `PrepareProposal` and `ProcessProposal` respect `InitialHeight` set by CometBFT when set to a value greater than 1. + - * (types) [#15433](https://github.com/cosmos/cosmos-sdk/pull/15433) Allow disabling of account address caches (for printing bech32 account addresses). + - * (client/keys) [#15876](https://github.com/cosmos/cosmos-sdk/pull/15876) Fix the JSON output ` keys list --output json` when there are no keys. + - ## [v0.47.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.1) - 2023-03-23 + - ### Features + - * (x/bank) [#15265](https://github.com/cosmos/cosmos-sdk/pull/15265) Update keeper interface to include `GetAllDenomMetaData`. + - * (x/groups) [#14879](https://github.com/cosmos/cosmos-sdk/pull/14879) Add `Query/Groups` query to get all the groups. + - * (x/gov,cli) [#14718](https://github.com/cosmos/cosmos-sdk/pull/14718) Added `AddGovPropFlagsToCmd` and `ReadGovPropFlags` functions. + - * (cli) [#14655](https://github.com/cosmos/cosmos-sdk/pull/14655) Add a new command to list supported algos. + - * (x/genutil,cli) [#15147](https://github.com/cosmos/cosmos-sdk/pull/15147) Add `--initial-height` flag to cli init cmd to provide `genesis.json` with user-defined initial block height. + - ### Improvements + - * (x/distribution) [#15462](https://github.com/cosmos/cosmos-sdk/pull/15462) Add delegator address to the event for withdrawing delegation rewards. + - * [#14609](https://github.com/cosmos/cosmos-sdk/pull/14609) Add `RetryForBlocks` method to use in tests that require waiting for a transaction to be included in a block. + - ### Bug Fixes + - * (baseapp) [#15487](https://github.com/cosmos/cosmos-sdk/pull/15487) Reset state before calling PrepareProposal and ProcessProposal. + - * (cli) [#15123](https://github.com/cosmos/cosmos-sdk/pull/15123) Fix the CLI `offline` mode behavior to be really offline. The API of `clienttx.NewFactoryCLI` is updated to return an error. + - ### Deprecated + - * (x/genutil) [#15316](https://github.com/cosmos/cosmos-sdk/pull/15316) Remove requirement on node & IP being included in a gentx. + - ## [v0.47.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.0) - 2023-03-14 + - ### Features + - * (x/gov) [#15151](https://github.com/cosmos/cosmos-sdk/pull/15151) Add `burn_vote_quorum`, `burn_proposal_deposit_prevote` and `burn_vote_veto` params to allow applications to decide if they would like to burn deposits + - * (client) [#14509](https://github.com/cosmos/cosmos-sdk/pull/#14509) Added `AddKeyringFlags` function. + - * (x/bank) [#14045](https://github.com/cosmos/cosmos-sdk/pull/14045) Add CLI command `spendable-balances`, which also accepts the flag `--denom`. + - * (x/slashing, x/staking) [#14363](https://github.com/cosmos/cosmos-sdk/pull/14363) Add the infraction a validator commited type as an argument to a `SlashWithInfractionReason` keeper method. + - * (client) [#14051](https://github.com/cosmos/cosmos-sdk/pull/14051) Add `--grpc` client option. + - * (x/genutil) [#14149](https://github.com/cosmos/cosmos-sdk/pull/14149) Add `genutilcli.GenesisCoreCommand` command, which contains all genesis-related sub-commands. + - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) Add new proto field `hash` of type `string` to `QueryEvidenceRequest` which helps to decode the hash properly while using query API. + - * (core) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add a `FormatCoins` function to in `core/coins` to format sdk Coins following the Value Renderers spec. + - * (math) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add `FormatInt` and `FormatDec` functiosn in `math` to format integers and decimals following the Value Renderers spec. + - * (x/staking) [#13122](https://github.com/cosmos/cosmos-sdk/pull/13122) Add `UnbondingCanComplete` and `PutUnbondingOnHold` to `x/staking` module. + - * [#13437](https://github.com/cosmos/cosmos-sdk/pull/13437) Add new flag `--modules-to-export` in `simd export` command to export only selected modules. + - * [#13298](https://github.com/cosmos/cosmos-sdk/pull/13298) Add `AddGenesisAccount` helper func in x/auth module which helps adding accounts to genesis state. + - * (x/authz) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) Add an allow list, an optional list of addresses allowed to receive bank assets via authz MsgSend grant. + - * (sdk.Coins) [#12627](https://github.com/cosmos/cosmos-sdk/pull/12627) Make a Denoms method on sdk.Coins. + - * (testutil) [#12973](https://github.com/cosmos/cosmos-sdk/pull/12973) Add generic `testutil.RandSliceElem` function which selects a random element from the list. + - * (client) [#12936](https://github.com/cosmos/cosmos-sdk/pull/12936) Add capability to preprocess transactions before broadcasting from a higher level chain. + - * (cli) [#13064](https://github.com/cosmos/cosmos-sdk/pull/13064) Add `debug prefixes` to list supported HRP prefixes via . + - * (ledger) [#12935](https://github.com/cosmos/cosmos-sdk/pull/12935) Generalize Ledger integration to allow for different apps or keytypes that use SECP256k1. + - * (x/bank) [#11981](https://github.com/cosmos/cosmos-sdk/pull/11981) Create the `SetSendEnabled` endpoint for managing the bank's SendEnabled settings. + - * (x/auth) [#13210](https://github.com/cosmos/cosmos-sdk/pull/13210) Add `Query/AccountInfo` endpoint for simplified access to basic account info. + - * (x/consensus) [#12905](https://github.com/cosmos/cosmos-sdk/pull/12905) Create a new `x/consensus` module that is now responsible for maintaining Tendermint consensus parameters instead of `x/param`. Legacy types remain in order to facilitate parameter migration from the deprecated `x/params`. App developers should ensure that they execute `baseapp.MigrateParams` during their chain upgrade. These legacy types will be removed in a future release. + - * (client/tx) [#13670](https://github.com/cosmos/cosmos-sdk/pull/13670) Add validation in `BuildUnsignedTx` to prevent simple inclusion of valid mnemonics + - ### Improvements + - * [#14995](https://github.com/cosmos/cosmos-sdk/pull/14995) Allow unknown fields in `ParseTypedEvent`. + - * (store) [#14931](https://github.com/cosmos/cosmos-sdk/pull/14931) Exclude in-memory KVStores, i.e. `StoreTypeMemory`, from CommitInfo commitments. + - * (cli) [#14919](https://github.com/cosmos/cosmos-sdk/pull/14919) Fix never assigned error when write validators. + - * (x/group) [#14923](https://github.com/cosmos/cosmos-sdk/pull/14923) Fix error while using pagination in `x/group` from CLI. + - * (types/coin) [#14715](https://github.com/cosmos/cosmos-sdk/pull/14715) `sdk.Coins.Add` now returns an empty set of coins `sdk.Coins{}` if both coins set are empty. + - * This is a behavior change, as previously `sdk.Coins.Add` would return `nil` in this case. + - * (reflection) [#14838](https://github.com/cosmos/cosmos-sdk/pull/14838) We now require that all proto files' import path (i.e. the OS path) matches their fully-qualified package name. For example, proto files with package name `cosmos.my.pkg.v1` should live in the folder `cosmos/my/pkg/v1/*.proto` relatively to the protoc import root folder (usually the root `proto/` folder). + - * (baseapp) [#14505](https://github.com/cosmos/cosmos-sdk/pull/14505) PrepareProposal and ProcessProposal now use deliverState for the first block in order to access changes made in InitChain. + - * (x/group) [#14527](https://github.com/cosmos/cosmos-sdk/pull/14527) Fix wrong address set in `EventUpdateGroupPolicy`. + - * (cli) [#14509](https://github.com/cosmos/cosmos-sdk/pull/14509) Added missing options to keyring-backend flag usage. + - * (server) [#14441](https://github.com/cosmos/cosmos-sdk/pull/14441) Fix `--log_format` flag not working. + - * (ante) [#14448](https://github.com/cosmos/cosmos-sdk/pull/14448) Return anteEvents when postHandler fail. + - * (baseapp) [#13983](https://github.com/cosmos/cosmos-sdk/pull/13983) Don't emit duplicate ante-handler events when a post-handler is defined. + - * (x/staking) [#14064](https://github.com/cosmos/cosmos-sdk/pull/14064) Set all fields in `redelegation.String()`. + - * (x/upgrade) [#13936](https://github.com/cosmos/cosmos-sdk/pull/13936) Make downgrade verification work again. + - * (x/group) [#13742](https://github.com/cosmos/cosmos-sdk/pull/13742) Fix `validate-genesis` when group policy accounts exist. + - * (store) [#13516](https://github.com/cosmos/cosmos-sdk/pull/13516) Fix state listener that was observing writes at wrong time. + - * (simstestutil) [#15305](https://github.com/cosmos/cosmos-sdk/pull/15305) Add `AppStateFnWithExtendedCb` with callback function to extend rawState. + - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. + - * (cli) [#14953](https://github.com/cosmos/cosmos-sdk/pull/14953) Enable profiling block replay during abci handshake with `--cpu-profile`. + - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. + - * (store) [#14189](https://github.com/cosmos/cosmos-sdk/pull/14189) Add config `iavl-lazy-loading` to enable lazy loading of iavl store, to improve start up time of archive nodes, add method `SetLazyLoading` to `CommitMultiStore` interface. + - * (deps) [#14830](https://github.com/cosmos/cosmos-sdk/pull/14830) Bump to IAVL `v0.19.5-rc.1`. + - * (tools) [#14793](https://github.com/cosmos/cosmos-sdk/pull/14793) Dockerfile optimization. + - * (x/gov) [#13010](https://github.com/cosmos/cosmos-sdk/pull/13010) Partial cherry-pick of this issue for adding proposer migration. + - * [#14691](https://github.com/cosmos/cosmos-sdk/pull/14691) Change behavior of `sdk.StringifyEvents` to not flatten events attributes by events type. + - * This change only affects ABCI message logs, and not the events field. + - * [#14692](https://github.com/cosmos/cosmos-sdk/pull/14692) Improve RPC queries error message when app is at height 0. + - * [#14017](https://github.com/cosmos/cosmos-sdk/pull/14017) Simplify ADR-028 and `address.Module`. + - * This updates the [ADR-028](https://docs.cosmos.network/main/architecture/adr-028-public-key-addresses) and enhance the `address.Module` API to support module addresses and sub-module addresses in a backward compatible way. + - * (snapshots) [#14608](https://github.com/cosmos/cosmos-sdk/pull/14608/) Deprecate unused structs `SnapshotKVItem` and `SnapshotSchema`. + - * [#15243](https://github.com/cosmos/cosmos-sdk/pull/15243) `LatestBlockResponse` & `BlockByHeightResponse` types' field `sdk_block` was incorrectly cast `proposer_address` bytes to validator operator address, now to consensus address + - * (x/group, x/gov) [#14483](https://github.com/cosmos/cosmos-sdk/pull/14483) Add support for `[]string` and `[]int` in `draft-proposal` prompt. + - * (protobuf) [#14476](https://github.com/cosmos/cosmos-sdk/pull/14476) Clean up protobuf annotations `{accepts,implements}_interface`. + - * (x/gov, x/group) [#14472](https://github.com/cosmos/cosmos-sdk/pull/14472) The recommended metadata format for x/gov and x/group proposals now uses an array of strings (instead of a single string) for the `authors` field. + - * (crypto) [#14460](https://github.com/cosmos/cosmos-sdk/pull/14460) Check the signature returned by a ledger device against the public key in the keyring. + - * [#14356](https://github.com/cosmos/cosmos-sdk/pull/14356) Add `events.GetAttributes` and `event.GetAttribute` methods to simplify the retrieval of an attribute from event(s). + - * (types) [#14332](https://github.com/cosmos/cosmos-sdk/issues/14332) Reduce state export time by 50%. + - * (types) [#14163](https://github.com/cosmos/cosmos-sdk/pull/14163) Refactor `(coins Coins) Validate()` to avoid unnecessary map. + - * [#13881](https://github.com/cosmos/cosmos-sdk/pull/13881) Optimize iteration on nested cached KV stores and other operations in general. + - * (x/gov) [#14347](https://github.com/cosmos/cosmos-sdk/pull/14347) Support `v1.Proposal` message in `v1beta1.Proposal.Content`. + - * [#13882](https://github.com/cosmos/cosmos-sdk/pull/13882) Add tx `encode` and `decode` endpoints to amino tx service. + - > Note: These endpoints encodes and decodes only amino txs. + - * (config) [#13894](https://github.com/cosmos/cosmos-sdk/pull/13894) Support state streaming configuration in `app.toml` template and default configuration. + - * (x/nft) [#13836](https://github.com/cosmos/cosmos-sdk/pull/13836) Remove the validation for `classID` and `nftID` from the NFT module. + - * [#13789](https://github.com/cosmos/cosmos-sdk/pull/13789) Add tx `encode` and `decode` endpoints to tx service. + - > Note: These endpoints will only encode and decode proto messages, Amino encoding and decoding is not supported. + - * [#13619](https://github.com/cosmos/cosmos-sdk/pull/13619) Add new function called LogDeferred to report errors in defers. Use the function in x/bank files. + - * (deps) [#13397](https://github.com/cosmos/cosmos-sdk/pull/13397) Bump Go version minimum requirement to `1.19`. + - * [#13070](https://github.com/cosmos/cosmos-sdk/pull/13070) Migrate from `gogo/protobuf` to `cosmos/gogoproto`. + - * [#12995](https://github.com/cosmos/cosmos-sdk/pull/12995) Add `FormatTime` and `ParseTimeString` methods. + - * [#12952](https://github.com/cosmos/cosmos-sdk/pull/12952) Replace keyring module to Cosmos fork. + - * [#12352](https://github.com/cosmos/cosmos-sdk/pull/12352) Move the `RegisterSwaggerAPI` logic into a separate helper function in the server package. + - * [#12876](https://github.com/cosmos/cosmos-sdk/pull/12876) Remove proposer-based rewards. + - * [#12846](https://github.com/cosmos/cosmos-sdk/pull/12846) Remove `RandomizedParams` from the `AppModuleSimulation` interface which is no longer needed. + - * (ci) [#12854](https://github.com/cosmos/cosmos-sdk/pull/12854) Use ghcr.io to host the proto builder image. Update proto builder image to go 1.19 + - * (x/bank) [#12706](https://github.com/cosmos/cosmos-sdk/pull/12706) Added the `chain-id` flag to the `AddTxFlagsToCmd` API. There is no longer a need to explicitly register this flag on commands whens `AddTxFlagsToCmd` is already called. + - * [#12717](https://github.com/cosmos/cosmos-sdk/pull/12717) Use injected encoding params in simapp. + - * [#12634](https://github.com/cosmos/cosmos-sdk/pull/12634) Move `sdk.Dec` to math package. + - * [#12187](https://github.com/cosmos/cosmos-sdk/pull/12187) Add batch operation for x/nft module. + - * [#12455](https://github.com/cosmos/cosmos-sdk/pull/12455) Show attempts count in error for signing. + - * [#13101](https://github.com/cosmos/cosmos-sdk/pull/13101) Remove weights from `simapp/params` and `testutil/sims`. They are now in their respective modules. + - * [#12398](https://github.com/cosmos/cosmos-sdk/issues/12398) Refactor all `x` modules to unit-test via mocks and decouple `simapp`. + - * [#13144](https://github.com/cosmos/cosmos-sdk/pull/13144) Add validator distribution info grpc gateway get endpoint. + - * [#13168](https://github.com/cosmos/cosmos-sdk/pull/13168) Migrate tendermintdev/proto-builder to ghcr.io. New image `ghcr.io/cosmos/proto-builder:0.8` + - * [#13178](https://github.com/cosmos/cosmos-sdk/pull/13178) Add `cosmos.msg.v1.service` protobuf annotation to allow tooling to distinguish between Msg and Query services via reflection. + - * [#13236](https://github.com/cosmos/cosmos-sdk/pull/13236) Integrate Filter Logging + - * [#13528](https://github.com/cosmos/cosmos-sdk/pull/13528) Update `ValidateMemoDecorator` to only check memo against `MaxMemoCharacters` param when a memo is present. + - * [#13651](https://github.com/cosmos/cosmos-sdk/pull/13651) Update `server/config/config.GetConfig` function. + - * [#13781](https://github.com/cosmos/cosmos-sdk/pull/13781) Remove `client/keys.KeysCdc`. + - * [#13802](https://github.com/cosmos/cosmos-sdk/pull/13802) Add --output-document flag to the export CLI command to allow writing genesis state to a file. + - * [#13794](https://github.com/cosmos/cosmos-sdk/pull/13794) `types/module.Manager` now supports the + - `cosmossdk.io/core/appmodule.AppModule` API via the new `NewManagerFromMap` constructor. + - * [#14175](https://github.com/cosmos/cosmos-sdk/pull/14175) Add `server.DefaultBaseappOptions(appopts)` function to reduce boiler plate in root.go. + - ### State Machine Breaking + - * (baseapp, x/auth/posthandler) [#13940](https://github.com/cosmos/cosmos-sdk/pull/13940) Update `PostHandler` to receive the `runTx` success boolean. + - * (store) [#14378](https://github.com/cosmos/cosmos-sdk/pull/14378) The `CacheKV` store is thread-safe again, which includes improved iteration and deletion logic. Iteration is on a strictly isolated view now, which is breaking from previous behavior. + - * (x/bank) [#14538](https://github.com/cosmos/cosmos-sdk/pull/14538) Validate denom in bank balances GRPC queries. + - * (x/group) [#14465](https://github.com/cosmos/cosmos-sdk/pull/14465) Add title and summary to proposal struct. + - * (x/gov) [#14390](https://github.com/cosmos/cosmos-sdk/pull/14390) Add title, proposer and summary to proposal struct. + - * (x/group) [#14071](https://github.com/cosmos/cosmos-sdk/pull/14071) Don't re-tally proposal after voting period end if they have been marked as ACCEPTED or REJECTED. + - * (x/group) [#13742](https://github.com/cosmos/cosmos-sdk/pull/13742) Migrate group policy account from module accounts to base account. + - * (x/auth)[#13780](https://github.com/cosmos/cosmos-sdk/pull/13780) `id` (type of int64) in `AccountAddressByID` grpc query is now deprecated, update to account-id(type of uint64) to use `AccountAddressByID`. + - * (codec) [#13307](https://github.com/cosmos/cosmos-sdk/pull/13307) Register all modules' `Msg`s with group's ModuleCdc so that Amino sign bytes are correctly generated.* (x/gov) + - * (codec) [#13196](https://github.com/cosmos/cosmos-sdk/pull/13196) Register all modules' `Msg`s with gov's ModuleCdc so that Amino sign bytes are correctly generated. + - * (group) [#13592](https://github.com/cosmos/cosmos-sdk/pull/13592) Fix group types registration with Amino. + - * (x/distribution) [#12852](https://github.com/cosmos/cosmos-sdk/pull/12852) Deprecate `CommunityPoolSpendProposal`. Please execute a `MsgCommunityPoolSpend` message via the new v1 `x/gov` module instead. This message can be used to directly fund the `x/gov` module account. + - * (x/bank) [#12610](https://github.com/cosmos/cosmos-sdk/pull/12610) `MsgMultiSend` now allows only a single input. + - * (x/bank) [#12630](https://github.com/cosmos/cosmos-sdk/pull/12630) Migrate `x/bank` to self-managed parameters and deprecate its usage of `x/params`. + - * (x/auth) [#12475](https://github.com/cosmos/cosmos-sdk/pull/12475) Migrate `x/auth` to self-managed parameters and deprecate its usage of `x/params`. + - * (x/slashing) [#12399](https://github.com/cosmos/cosmos-sdk/pull/12399) Migrate `x/slashing` to self-managed parameters and deprecate its usage of `x/params`. + - * (x/mint) [#12363](https://github.com/cosmos/cosmos-sdk/pull/12363) Migrate `x/mint` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/distribution) [#12434](https://github.com/cosmos/cosmos-sdk/pull/12434) Migrate `x/distribution` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/crisis) [#12445](https://github.com/cosmos/cosmos-sdk/pull/12445) Migrate `x/crisis` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) Migrate `x/gov` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/staking) [#12409](https://github.com/cosmos/cosmos-sdk/pull/12409) Migrate `x/staking` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) Move the SendEnabled information out of the Params and into the state store directly. + - * (x/gov) [#12771](https://github.com/cosmos/cosmos-sdk/pull/12771) Initial deposit requirement for proposals at submission time. + - * (x/staking) [#12967](https://github.com/cosmos/cosmos-sdk/pull/12967) `unbond` now creates only one unbonding delegation entry when multiple unbondings exist at a single height (e.g. through multiple messages in a transaction). + - * (x/auth/vesting) [#13502](https://github.com/cosmos/cosmos-sdk/pull/13502) Add Amino Msg registration for `MsgCreatePeriodicVestingAccount`. + - ### API Breaking Changes + - * Migrate to CometBFT. Follow the migration instructions in the [upgrade guide](./UPGRADING.md#migration-to-cometbft-part-1). + - * (simulation) [#14728](https://github.com/cosmos/cosmos-sdk/pull/14728) Rename the `ParamChanges` field to `LegacyParamChange` and `Contents` to `LegacyProposalContents` in `simulation.SimulationState`. Additionally it adds a `ProposalMsgs` field to `simulation.SimulationState`. + - * (x/gov) [#14782](https://github.com/cosmos/cosmos-sdk/pull/14782) Move the `metadata` argument in `govv1.NewProposal` alongside `title` and `summary`. + - * (x/upgrade) [#14216](https://github.com/cosmos/cosmos-sdk/pull/14216) Change upgrade keeper receiver to upgrade keeper pointers. + - * (x/auth) [#13780](https://github.com/cosmos/cosmos-sdk/pull/13780) Querying with `id` (type of int64) in `AccountAddressByID` grpc query now throws error, use account-id(type of uint64) instead. + - * (store) [#13516](https://github.com/cosmos/cosmos-sdk/pull/13516) Update State Streaming APIs: + - * Add method `ListenCommit` to `ABCIListener` + - * Move `ListeningEnabled` and `AddListener` methods to `CommitMultiStore` + - * Remove `CacheWrapWithListeners` from `CacheWrap` and `CacheWrapper` interfaces + - * Remove listening APIs from the caching layer (it should only listen to the `rootmulti.Store`) + - * Add three new options to file streaming service constructor. + - * Modify `ABCIListener` such that any error from any method will always halt the app via `panic` + - * (x/auth) [#13877](https://github.com/cosmos/cosmos-sdk/pull/13877) Rename `AccountKeeper`'s `GetNextAccountNumber` to `NextAccountNumber`. + - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) The `NewQueryEvidenceRequest` function now takes `hash` as a HEX encoded `string`. + - * (server) [#13485](https://github.com/cosmos/cosmos-sdk/pull/13485) The `Application` service now requires the `RegisterNodeService` method to be implemented. + - * [#13437](https://github.com/cosmos/cosmos-sdk/pull/13437) Add a list of modules to export argument in `ExportAppStateAndValidators`. + - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move simulation flags to `x/simulation/client/cli`. + - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move simulation helpers functions (`SetupSimulation`, `SimulationOperations`, `CheckExportSimulation`, `PrintStats`, `GetSimulationLog`) to `testutil/sims`. + - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move `testutil/rest` package to `testutil`. + - * (types) [#13380](https://github.com/cosmos/cosmos-sdk/pull/13380) Remove deprecated `sdk.NewLevelDB`. + - * (simapp) [#13378](https://github.com/cosmos/cosmos-sdk/pull/13378) Move `simapp.App` to `runtime.AppI`. + - * (tx) [#12659](https://github.com/cosmos/cosmos-sdk/pull/12659) Remove broadcast mode `block`. + - * (simapp) [#12747](https://github.com/cosmos/cosmos-sdk/pull/12747) Remove `simapp.MakeTestEncodingConfig`. Please use `moduletestutil.MakeTestEncodingConfig` (`types/module/testutil`) in tests instead. + - * (x/bank) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) `NewSendAuthorization` takes a new argument of an optional list of addresses allowed to receive bank assests via authz MsgSend grant. You can pass `nil` for the same behavior as before, i.e. any recipient is allowed. + - * (x/bank) [#12593](https://github.com/cosmos/cosmos-sdk/pull/12593) Add `SpendableCoin` method to `BaseViewKeeper` + - * (x/slashing) [#12581](https://github.com/cosmos/cosmos-sdk/pull/12581) Remove `x/slashing` legacy querier. + - * (types) [#12355](https://github.com/cosmos/cosmos-sdk/pull/12355) Remove the compile-time `types.DBbackend` variable. Removes usage of the same in server/util.go + - * (x/gov) [#12368](https://github.com/cosmos/cosmos-sdk/pull/12369) Gov keeper is now passed by reference instead of copy to make post-construction mutation of Hooks and Proposal Handlers possible at a framework level. + - * (simapp) [#12270](https://github.com/cosmos/cosmos-sdk/pull/12270) Remove `invCheckPeriod uint` attribute from `SimApp` struct as per migration of `x/crisis` to app wiring + - * (simapp) [#12334](https://github.com/cosmos/cosmos-sdk/pull/12334) Move `simapp.ConvertAddrsToValAddrs` and `simapp.CreateTestPubKeys ` to respectively `simtestutil.ConvertAddrsToValAddrs` and `simtestutil.CreateTestPubKeys` (`testutil/sims`) + - * (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Move `simapp.EmptyAppOptions` to `simtestutil.EmptyAppOptions` (`testutil/sims`) + - * (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Remove `skipUpgradeHeights map[int64]bool` and `homePath string` from `NewSimApp` constructor as per migration of `x/upgrade` to app-wiring. + - * (testutil) [#12278](https://github.com/cosmos/cosmos-sdk/pull/12278) Move all functions from `simapp/helpers` to `testutil/sims` + - * (testutil) [#12233](https://github.com/cosmos/cosmos-sdk/pull/12233) Move `simapp.TestAddr` to `simtestutil.TestAddr` (`testutil/sims`) + - * (x/staking) [#12102](https://github.com/cosmos/cosmos-sdk/pull/12102) Staking keeper now is passed by reference instead of copy. Keeper's SetHooks no longer returns keeper. It updates the keeper in place instead. + - * (linting) [#12141](https://github.com/cosmos/cosmos-sdk/pull/12141) Fix usability related linting for database. This means removing the infix Prefix from `prefix.NewPrefixWriter` and such so that it is `prefix.NewWriter` and making `db.DBConnection` and such into `db.Connection` + - * (x/distribution) [#12434](https://github.com/cosmos/cosmos-sdk/pull/12434) `x/distribution` module `SetParams` keeper method definition is now updated to return `error`. + - * (x/staking) [#12409](https://github.com/cosmos/cosmos-sdk/pull/12409) `x/staking` module `SetParams` keeper method definition is now updated to return `error`. + - * (x/crisis) [#12445](https://github.com/cosmos/cosmos-sdk/pull/12445) `x/crisis` module `SetConstantFee` keeper method definition is now updated to return `error`. + - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) `x/gov` module refactored to use `Params` as single struct instead of `DepositParams`, `TallyParams` & `VotingParams`. + - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) Migrate `x/gov` to self-managed parameters and deprecate it's usage of `x/params`. + - * (x/bank) [#12630](https://github.com/cosmos/cosmos-sdk/pull/12630) `x/bank` module `SetParams` keeper method definition is now updated to return `error`. + - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) Move the SendEnabled information out of the Params and into the state store directly. + - The information can now be accessed using the BankKeeper. + - Setting can be done using MsgSetSendEnabled as a governance proposal. + - A SendEnabled query has been added to both GRPC and CLI. + - * (appModule) Remove `Route`, `QuerierRoute` and `LegacyQuerierHandler` from AppModule Interface. + - * (x/modules) Remove all LegacyQueries and related code from modules + - * (store) [#11825](https://github.com/cosmos/cosmos-sdk/pull/11825) Make extension snapshotter interface safer to use, renamed the util function `WriteExtensionItem` to `WriteExtensionPayload`. + - * (x/genutil)[#12956](https://github.com/cosmos/cosmos-sdk/pull/12956) `genutil.AppModuleBasic` has a new attribute: genesis transaction validation function. The existing validation logic is implemented in `genutiltypes.DefaultMessageValidator`. Use `genutil.NewAppModuleBasic` to create a new genutil Module Basic. + - * (codec) [#12964](https://github.com/cosmos/cosmos-sdk/pull/12964) `ProtoCodec.MarshalInterface` now returns an error when serializing unregistered types and a subsequent `ProtoCodec.UnmarshalInterface` would fail. + - * (x/staking) [#12973](https://github.com/cosmos/cosmos-sdk/pull/12973) Removed `stakingkeeper.RandomValidator`. Use `testutil.RandSliceElem(r, sk.GetAllValidators(ctx))` instead. + - * (x/gov) [#13160](https://github.com/cosmos/cosmos-sdk/pull/13160) Remove custom marshaling of proposl and voteoption. + - * (types) [#13430](https://github.com/cosmos/cosmos-sdk/pull/13430) Remove unused code `ResponseCheckTx` and `ResponseDeliverTx` + - * (store) [#13529](https://github.com/cosmos/cosmos-sdk/pull/13529) Add method `LatestVersion` to `MultiStore` interface, add method `SetQueryMultiStore` to baesapp to support alternative `MultiStore` implementation for query service. + - * (pruning) [#13609](https://github.com/cosmos/cosmos-sdk/pull/13609) Move pruning package to be under store package + - * [#13794](https://github.com/cosmos/cosmos-sdk/pull/13794) Most methods on `types/module.AppModule` have been moved to + - extension interfaces. `module.Manager.Modules` is now of type `map[string]interface{}` to support in parallel the new + - `cosmossdk.io/core/appmodule.AppModule` API. + - ### CLI Breaking Changes + - * (genesis) [#14149](https://github.com/cosmos/cosmos-sdk/pull/14149) Add `simd genesis` command, which contains all genesis-related sub-commands. + - * (x/genutil) [#13535](https://github.com/cosmos/cosmos-sdk/pull/13535) Replace in `simd init`, the `--staking-bond-denom` flag with `--default-denom` which is used for all default denomination in the genesis, instead of only staking. + - ### Bug Fixes + - * (x/auth/vesting) [#15373](https://github.com/cosmos/cosmos-sdk/pull/15373) Add extra checks when creating a periodic vesting account. + - * (x/auth) [#13838](https://github.com/cosmos/cosmos-sdk/pull/13838) Fix calling `String()` and `MarshalYAML` panics when pubkey is set on a `BaseAccount``. + - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) Fix evidence query API to decode the hash properly. + - * (bank) [#13691](https://github.com/cosmos/cosmos-sdk/issues/13691) Fix unhandled error for vesting account transfers, when total vesting amount exceeds total balance. + - * [#13553](https://github.com/cosmos/cosmos-sdk/pull/13553) Ensure all parameter validation for decimal types handles nil decimal values. + - * [#13145](https://github.com/cosmos/cosmos-sdk/pull/13145) Fix panic when calling `String()` to a Record struct type. + - * [#13116](https://github.com/cosmos/cosmos-sdk/pull/13116) Fix a dead-lock in the `Group-TotalWeight` `x/group` invariant. + - * (types) [#12154](https://github.com/cosmos/cosmos-sdk/pull/12154) Add `baseAccountGetter` to avoid invalid account error when create vesting account. + - * (x/staking) [#12303](https://github.com/cosmos/cosmos-sdk/pull/12303) Use bytes instead of string comparison in delete validator queue + - * (store/rootmulti) [#12487](https://github.com/cosmos/cosmos-sdk/pull/12487) Fix non-deterministic map iteration. + - * (sdk/dec_coins) [#12903](https://github.com/cosmos/cosmos-sdk/pull/12903) Fix nil `DecCoin` creation when converting `Coins` to `DecCoins` + - * (store) [#12945](https://github.com/cosmos/cosmos-sdk/pull/12945) Fix nil end semantics in store/cachekv/iterator when iterating a dirty cache. + - * (x/gov) [#13051](https://github.com/cosmos/cosmos-sdk/pull/13051) In SubmitPropsal, when a legacy msg fails it's handler call, wrap the error as ErrInvalidProposalContent (instead of ErrNoProposalHandlerExists). + - * (snapshot) [#13400](https://github.com/cosmos/cosmos-sdk/pull/13400) Fix snapshot checksum issue in golang 1.19. + - * (server) [#13778](https://github.com/cosmos/cosmos-sdk/pull/13778) Set Cosmos SDK default endpoints to localhost to avoid unknown exposure of endpoints. + - * (x/auth) [#13877](https://github.com/cosmos/cosmos-sdk/pull/13877) Handle missing account numbers during `InitGenesis`. + - * (x/gov) [#13918](https://github.com/cosmos/cosmos-sdk/pull/13918) Propagate message errors when executing a proposal. + - ### Deprecated + - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) The `evidence_hash` field of `QueryEvidenceRequest` has been deprecated and now contains a new field `hash` with type `string`. + - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) The Params.SendEnabled field is deprecated and unusable. + - The information can now be accessed using the BankKeeper. + - Setting can be done using MsgSetSendEnabled as a governance proposal. + - A SendEnabled query has been added to both GRPC and CLI. + - ## Previous Versions + - [CHANGELOG of previous versions](https://github.com/cosmos/cosmos-sdk/blob/main/CHANGELOG.md#v0460---2022-07-26). + \ No newline at end of file diff --git a/docs/sdk/v0.50/changelog/release-notes.mdx b/docs/sdk/v0.50/changelog/release-notes.mdx new file mode 100644 index 00000000..741fb657 --- /dev/null +++ b/docs/sdk/v0.50/changelog/release-notes.mdx @@ -0,0 +1,508 @@ +--- +title: "Release Notes" +description: "Cosmos SDK release notes and changelog" +mode: "custom" +--- + + + - {/* + - Guiding Principles: + - Changelogs are for humans, not machines. + - There should be an entry for every single version. + - The same types of changes should be grouped. + - Versions and sections should be linkable. + - The latest version comes first. + - The release date of each version is displayed. + - Mention whether you follow Semantic Versioning. + - Usage: + - Change log entries are to be added to the Unreleased section under the + - appropriate stanza (see below). Each entry is required to include a tag and + - the Github issue reference in the following format: + - * () \# message + - The tag should consist of where the change is being made ex. (x/staking), (store) + - The issue numbers will later be link-ified during the release process so you do + - not have to worry about including a link manually, but you can if you wish. + - Types of changes (Stanzas): + - "Features" for new features. + - "Improvements" for changes in existing functionality. + - "Deprecated" for soon-to-be removed features. + - "Bug Fixes" for any bug fixes. + - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. + - "CLI Breaking" for breaking CLI commands. + - "API Breaking" for breaking exported APIs used by developers building on SDK. + - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. + - Ref: https://keepachangelog.com/en/1.0.0/ + - */} + - # Changelog + - ## [Unreleased] + - ### Improvements + - * (x/gov) [#24386](https://github.com/cosmos/cosmos-sdk/pull/24386) Improve helpers to easily create governance proposals from CLI. + - ### Bug Fixes + - * (baseapp) [#23879](https://github.com/cosmos/cosmos-sdk/pull/23879) Ensure finalize block response is not empty in the defer check of FinalizeBlock to avoid panic by nil pointer. + - * (query) [#23884](https://github.com/cosmos/cosmos-sdk/pull/23884) Fix NPE in query pagination. + - ## [v0.50.14](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.14) - 2025-07-08 + - ### Bug Fixes + - * [GHSA-p22h-3m2v-cmgh](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-p22h-3m2v-cmgh) Fix x/distribution can halt when historical rewards overflow. + - ## [v0.50.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.13) - 2025-03-12 + - ### Bug Fixes + - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker + - ## [v0.50.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.12) - 2025-02-20 + - ### Bug Fixes + - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal + - ## [v0.50.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.11) - 2024-12-16 + - ### Features + - * (crypto/keyring) [#21653](https://github.com/cosmos/cosmos-sdk/pull/21653) New Linux-only backend that adds Linux kernel's `keyctl` support. + - ### Improvements + - * (server) [#21941](https://github.com/cosmos/cosmos-sdk/pull/21941) Regenerate addrbook.json for in place testnet. + - ### Bug Fixes + - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any + - * (server) [#22564](https://github.com/cosmos/cosmos-sdk/pull/22564) Fix fallback genesis path in server + - * (x/group) [#22425](https://github.com/cosmos/cosmos-sdk/pull/22425) Proper address rendering in error + - * (sims) [#21906](https://github.com/cosmos/cosmos-sdk/pull/21906) Skip sims test when running dry on validators + - * (cli) [#21919](https://github.com/cosmos/cosmos-sdk/pull/21919) Query address-by-acc-num by account_id instead of id. + - * (x/group) [#22229](https://github.com/cosmos/cosmos-sdk/pull/22229) Accept `1` and `try` in CLI for group proposal exec. + - ## [v0.50.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.10) - 2024-09-20 + - ### Features + - * (cli) [#20779](https://github.com/cosmos/cosmos-sdk/pull/20779) Added `module-hash-by-height` command to query and retrieve module hashes at a specified blockchain height, enhancing debugging capabilities. + - * (cli) [#21372](https://github.com/cosmos/cosmos-sdk/pull/21372) Added a `bulk-add-genesis-account` genesis command to add many genesis accounts at once. + - * (types/collections) [#21724](https://github.com/cosmos/cosmos-sdk/pull/21724) Added `LegacyDec` collection value. + - ### Improvements + - * (x/bank) [#21460](https://github.com/cosmos/cosmos-sdk/pull/21460) Added `Sender` attribute in `MsgMultiSend` event. + - * (genutil) [#21701](https://github.com/cosmos/cosmos-sdk/pull/21701) Improved error messages for genesis validation. + - * (testutil/integration) [#21816](https://github.com/cosmos/cosmos-sdk/pull/21816) Allow to pass baseapp options in `NewIntegrationApp`. + - ### Bug Fixes + - * (runtime) [#21769](https://github.com/cosmos/cosmos-sdk/pull/21769) Fix baseapp options ordering to avoid overwriting options set by modules. + - * (x/consensus) [#21493](https://github.com/cosmos/cosmos-sdk/pull/21493) Fix regression that prevented to upgrade to > v0.50.7 without consensus version params. + - * (baseapp) [#21256](https://github.com/cosmos/cosmos-sdk/pull/21256) Halt height will not commit the block indicated, meaning that if halt-height is set to 10, only blocks until 9 (included) will be committed. This is to go back to the original behavior before a change was introduced in v0.50.0. + - * (baseapp) [#21444](https://github.com/cosmos/cosmos-sdk/pull/21444) Follow-up, Return PreBlocker events in FinalizeBlockResponse. + - * (baseapp) [#21413](https://github.com/cosmos/cosmos-sdk/pull/21413) Fix data race in sdk mempool. + - ## [v0.50.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.9) - 2024-08-07 + - ## Bug Fixes + - * (baseapp) [#21159](https://github.com/cosmos/cosmos-sdk/pull/21159) Return PreBlocker events in FinalizeBlockResponse. + - * [#20939](https://github.com/cosmos/cosmos-sdk/pull/20939) Fix collection reverse iterator to include `pagination.key` in the result. + - * (client/grpc) [#20969](https://github.com/cosmos/cosmos-sdk/pull/20969) Fix `node.NewQueryServer` method not setting `cfg`. + - * (testutil/integration) [#21006](https://github.com/cosmos/cosmos-sdk/pull/21006) Fix `NewIntegrationApp` method not writing default genesis to state. + - * (runtime) [#21080](https://github.com/cosmos/cosmos-sdk/pull/21080) Fix `app.yaml` / `app.json` incompatibility with `depinject v1.0.0`. + - ## [v0.50.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.8) - 2024-07-15 + - ## Features + - * (client) [#20690](https://github.com/cosmos/cosmos-sdk/pull/20690) Import mnemonic from file + - ## Improvements + - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. + - * [#20631](https://github.com/cosmos/cosmos-sdk/pull/20631) Fix json parsing in the wait-tx command. + - * (x/auth) [#20438](https://github.com/cosmos/cosmos-sdk/pull/20438) Add `--skip-signature-verification` flag to multisign command to allow nested multisigs. + - ## Bug Fixes + - * (simulation) [#17911](https://github.com/cosmos/cosmos-sdk/pull/17911) Fix all problems with executing command `make test-sim-custom-genesis-fast` for simulation test. + - * (simulation) [#18196](https://github.com/cosmos/cosmos-sdk/pull/18196) Fix the problem of `validator set is empty after InitGenesis` in simulation test. + - ## [v0.50.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.7) - 2024-06-04 + - ### Improvements + - * (debug) [#20328](https://github.com/cosmos/cosmos-sdk/pull/20328) Add consensus address for debug cmd. + - * (runtime) [#20264](https://github.com/cosmos/cosmos-sdk/pull/20264) Expose grpc query router via depinject. + - * (x/consensus) [#20381](https://github.com/cosmos/cosmos-sdk/pull/20381) Use Comet utility for consensus module consensus param updates. + - * (client) [#20356](https://github.com/cosmos/cosmos-sdk/pull/20356) Overwrite client context when available in `SetCmdClientContext`. + - ### Bug Fixes + - * (baseapp) [#20346](https://github.com/cosmos/cosmos-sdk/pull/20346) Correctly assign `execModeSimulate` to context for `simulateTx`. + - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. + - * (baseapp) [#20107](https://github.com/cosmos/cosmos-sdk/pull/20107) Avoid header height overwrite block height. + - * (cli) [#20020](https://github.com/cosmos/cosmos-sdk/pull/20020) Make bootstrap-state command support both new and legacy genesis format. + - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. + - ## [v0.50.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.6) - 2024-04-22 + - ### Features + - * (types) [#19759](https://github.com/cosmos/cosmos-sdk/pull/19759) Align SignerExtractionAdapter in PriorityNonceMempool Remove. + - * (client) [#19870](https://github.com/cosmos/cosmos-sdk/pull/19870) Add new query command `wait-tx`. Alias `event-query-tx-for` to `wait-tx` for backward compatibility. + - ### Improvements + - * (telemetry) [#19903](https://github.com/cosmos/cosmos-sdk/pull/19903) Conditionally emit metrics based on enablement. + - * **Introduction of `Now` Function**: Added a new function called `Now` to the telemetry package. It returns the current system time if telemetry is enabled, or a zero time if telemetry is not enabled. + - * **Atomic Global Variable**: Implemented an atomic global variable to manage the state of telemetry's enablement. This ensures thread safety for the telemetry state. + - * **Conditional Telemetry Emission**: All telemetry functions have been updated to emit metrics only when telemetry is enabled. They perform a check with `isTelemetryEnabled()` and return early if telemetry is disabled, minimizing unnecessary operations and overhead. + - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Upgrade prometheus version and fix API breaking change due to prometheus bump. + - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Bump `cosmossdk.io/store` to v1.1.0. + - * (server) [#19884](https://github.com/cosmos/cosmos-sdk/pull/19884) Add start customizability to start command options. + - * (x/gov) [#19853](https://github.com/cosmos/cosmos-sdk/pull/19853) Emit `depositor` in `EventTypeProposalDeposit`. + - * (x/gov) [#19844](https://github.com/cosmos/cosmos-sdk/pull/19844) Emit the proposer of governance proposals. + - * (baseapp) [#19616](https://github.com/cosmos/cosmos-sdk/pull/19616) Don't share gas meter in tx execution. + - ## Bug Fixes + - * (x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m) for `x/authz`. + - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19745) Fix tx sign doesn't throw an error when incorrect Ledger is used. + - * (baseapp) [#19970](https://github.com/cosmos/cosmos-sdk/pull/19970) Fix default config values to use no-op mempool as default. + - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. + - * (x/bank) [#20028](https://github.com/cosmos/cosmos-sdk/pull/20028) Align query with multi denoms for send-enabled. + - ## [v0.50.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.5) - 2024-03-12 + - ### Features + - * (baseapp) [#19626](https://github.com/cosmos/cosmos-sdk/pull/19626) Add `DisableBlockGasMeter` option to `BaseApp`, which removes the block gas meter during transaction execution. + - ### Improvements + - * (x/distribution) [#19707](https://github.com/cosmos/cosmos-sdk/pull/19707) Add autocli config for `DelegationTotalRewards` for CLI consistency with `q rewards` commands in previous versions. + - * (x/auth) [#19651](https://github.com/cosmos/cosmos-sdk/pull/19651) Allow empty public keys in `GetSignBytesAdapter`. + - ### Bug Fixes + - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from proposal.FinalTallyResult in the gprc query. + - * (types) [#19709](https://github.com/cosmos/cosmos-sdk/pull/19709) Fix skip staking genesis export when using `CoreAppModuleAdaptor` / `CoreAppModuleBasicAdaptor` for it. + - * (x/auth) [#19549](https://github.com/cosmos/cosmos-sdk/pull/19549) Accept custom get signers when injecting `x/auth/tx`. + - * (x/staking) Fix a possible bypass of delegator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) + - * (baseapp) Fix a bug in `baseapp.ValidateVoteExtensions` helper ([GHSA-95rx-m9m5-m94v](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-95rx-m9m5-m94v)). The helper has been fixed and for avoiding API breaking changes `currentHeight` and `chainID` arguments are ignored. Those arguments are removed from the helper in v0.51+. + - ## [v0.50.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.4) - 2024-02-19 + - ### Features + - * (server) [#19280](https://github.com/cosmos/cosmos-sdk/pull/19280) Adds in-place testnet CLI command. + - ### Improvements + - * (client) [#19393](https://github.com/cosmos/cosmos-sdk/pull/19393/) Add `ReadDefaultValuesFromDefaultClientConfig` to populate the default values from the default client config in client.Context without creating a app folder. + - ### Bug Fixes + - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. + - * (baseapp) [#19338](https://github.com/cosmos/cosmos-sdk/pull/19338) Set HeaderInfo in context when calling `setState`. + - * (baseapp): [#19200](https://github.com/cosmos/cosmos-sdk/pull/19200) Ensure that sdk side ve math matches cometbft. + - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. + - * (baseapp) [#19198](https://github.com/cosmos/cosmos-sdk/pull/19198) Remove usage of pointers in logs in all optimistic execution goroutines. + - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. + - * (crypto) [#19371](https://github.com/cosmos/cosmos-sdk/pull/19371) Avoid CLI redundant log in stdout, log to stderr instead. + - ## [v0.50.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.3) - 2024-01-15 + - ### Features + - * (types) [#18991](https://github.com/cosmos/cosmos-sdk/pull/18991) Add SignerExtractionAdapter to PriorityNonceMempool/Config and provide Default implementation matching existing behavior. + - * (gRPC) [#19043](https://github.com/cosmos/cosmos-sdk/pull/19043) Add `halt_height` to the gRPC `/cosmos/base/node/v1beta1/config` request. + - ### Improvements + - * (x/bank) [#18956](https://github.com/cosmos/cosmos-sdk/pull/18956) Introduced a new `DenomOwnersByQuery` query method for `DenomOwners`, which accepts the denom value as a query string parameter, resolving issues with denoms containing slashes. + - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. + - * (x/auth/tx) [#18772](https://github.com/cosmos/cosmos-sdk/pull/18772) Remove misleading gas wanted from tx simulation failure log. + - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. + - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 + - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 + - * (baseapp) [#18915](https://github.com/cosmos/cosmos-sdk/pull/18915) Add a new `ExecModeVerifyVoteExtension` exec mode and ensure it's populated in the `Context` during `VerifyVoteExtension` execution. + - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. + - ### Bug Fixes + - * (baseapp) [#19058](https://github.com/cosmos/cosmos-sdk/pull/19058) Fix baseapp posthandler branch would fail if the `runMsgs` had returned an error. + - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after module's beginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. + - * (baseapp) [#18895](https://github.com/cosmos/cosmos-sdk/pull/18895) Fix de-duplicating vote extensions during validation in ValidateVoteExtensions. + - ## [v0.50.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.2) - 2023-12-11 + - ### Features + - * (debug) [#18219](https://github.com/cosmos/cosmos-sdk/pull/18219) Add debug commands for application codec types. + - * (client/keys) [#17639](https://github.com/cosmos/cosmos-sdk/pull/17639) Allows using and saving public keys encoded as base64. + - * (server) [#17094](https://github.com/cosmos/cosmos-sdk/pull/17094) Add a `shutdown-grace` flag for waiting a given time before exit. + - ### Improvements + - * (telemetry) [#18646] (https://github.com/cosmos/cosmos-sdk/pull/18646) Enable statsd and dogstatsd telemetry sinks. + - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. + - * (x/gov) [#18025](https://github.com/cosmos/cosmos-sdk/pull/18025) Improve ` q gov proposer` by querying directly a proposal instead of tx events. It is an alias of `q gov proposal` as the proposer is a field of the proposal. + - * (version) [#18063](https://github.com/cosmos/cosmos-sdk/pull/18063) Allow to define extra info to be displayed in ` version --long` command. + - * (codec/unknownproto)[#18541](https://github.com/cosmos/cosmos-sdk/pull/18541) Remove the use of "protoc-gen-gogo/descriptor" in favour of using the official protobuf descriptorpb types inside unknownproto. + - ### Bug Fixes + - * (x/auth) [#18564](https://github.com/cosmos/cosmos-sdk/pull/18564) Fix total fees calculation when batch signing. + - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. + - * [#18531](https://github.com/cosmos/cosmos-sdk/pull/18531) Baseapp's `GetConsensusParams` returns an empty struct instead of panicking if no params are found. + - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. + - * (baseapp) [#18486](https://github.com/cosmos/cosmos-sdk/pull/18486) Fixed FinalizeBlock calls not being passed to ABCIListeners. + - * (baseapp) [#18627](https://github.com/cosmos/cosmos-sdk/pull/18627) Post handlers are run on non successful transaction executions too. + - * (baseapp) [#18654](https://github.com/cosmos/cosmos-sdk/pull/18654) Fixes an issue in which `gogoproto.Merge` does not work with gogoproto messages with custom types. + - ## [v0.50.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.1) - 2023-11-07 + - > v0.50.0 has been retracted due to a mistake in tagging the release. Please use v0.50.1 instead. + - ### Features + - * (baseapp) [#18071](https://github.com/cosmos/cosmos-sdk/pull/18071) Add hybrid handlers to `MsgServiceRouter`. + - * (server) [#18162](https://github.com/cosmos/cosmos-sdk/pull/18162) Start gRPC & API server in standalone mode. + - * (baseapp & types) [#17712](https://github.com/cosmos/cosmos-sdk/pull/17712) Introduce `PreBlock`, which runs before begin blocker other modules, and allows to modify consensus parameters, and the changes are visible to the following state machine logics. Additionally it can be used for vote extensions. + - * (genutil) [#17571](https://github.com/cosmos/cosmos-sdk/pull/17571) Allow creation of `AppGenesis` without a file lookup. + - * (codec) [#17042](https://github.com/cosmos/cosmos-sdk/pull/17042) Add `CollValueV2` which supports encoding of protov2 messages in collections. + - * (x/gov) [#16976](https://github.com/cosmos/cosmos-sdk/pull/16976) Add `failed_reason` field to `Proposal` under `x/gov` to indicate the reason for a failed proposal. Referenced from [#238](https://github.com/bnb-chain/greenfield-cosmos-sdk/pull/238) under `bnb-chain/greenfield-cosmos-sdk`. + - * (baseapp) [#16898](https://github.com/cosmos/cosmos-sdk/pull/16898) Add `preFinalizeBlockHook` to allow vote extensions persistence. + - * (cli) [#16887](https://github.com/cosmos/cosmos-sdk/pull/16887) Add two new CLI commands: ` tx simulate` for simulating a transaction; ` query block-results` for querying CometBFT RPC for block results. + - * (x/bank) [#16852](https://github.com/cosmos/cosmos-sdk/pull/16852) Add `DenomMetadataByQueryString` query in bank module to support metadata query by query string. + - * (baseapp) [#16581](https://github.com/cosmos/cosmos-sdk/pull/16581) Implement Optimistic Execution as an experimental feature (not enabled by default). + - * (types) [#16257](https://github.com/cosmos/cosmos-sdk/pull/16257) Allow setting the base denom in the denom registry. + - * (baseapp) [#16239](https://github.com/cosmos/cosmos-sdk/pull/16239) Add Gas Limits to allow node operators to resource bound queries. + - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Make `StartCmd` more customizable. + - * (types/simulation) [#16074](https://github.com/cosmos/cosmos-sdk/pull/16074) Add generic SimulationStoreDecoder for modules using collections. + - * (genutil) [#16046](https://github.com/cosmos/cosmos-sdk/pull/16046) Add "module-name" flag to genutil `add-genesis-account` to enable intializing module accounts at genesis.* [#15970](https://github.com/cosmos/cosmos-sdk/pull/15970) Enable SIGN_MODE_TEXTUAL. + - * (types) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Add `module.NewBasicManagerFromManager` for creating a basic module manager from a module manager. + - * (types/module) [#15829](https://github.com/cosmos/cosmos-sdk/pull/15829) Add new endblocker interface to handle valset updates. + - * (runtime) [#15818](https://github.com/cosmos/cosmos-sdk/pull/15818) Provide logger through `depinject` instead of appBuilder. + - * (types) [#15735](https://github.com/cosmos/cosmos-sdk/pull/15735) Make `ValidateBasic() error` method of `Msg` interface optional. Modules should validate messages directly in their message handlers ([RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation)). + - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) Allow applications to specify a custom genesis migration function for the `genesis migrate` command. + - * (telemetry) [#15657](https://github.com/cosmos/cosmos-sdk/pull/15657) Emit more data (go version, sdk version, upgrade height) in prom metrics. + - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) Add status endpoint for clients. + - * (testutil/integration) [#15556](https://github.com/cosmos/cosmos-sdk/pull/15556) Introduce `testutil/integration` package for module integration testing. + - * (runtime) [#15547](https://github.com/cosmos/cosmos-sdk/pull/15547) Allow runtime to pass event core api service to modules. + - * (client) [#15458](https://github.com/cosmos/cosmos-sdk/pull/15458) Add a `CmdContext` field to client.Context initialized to cobra command's context. + - * (x/genutil) [#15301](https://github.com/cosmos/cosmos-sdk/pull/15031) Add application genesis. The genesis is now entirely managed by the application and passed to CometBFT at note instantiation. Functions that were taking a `cmttypes.GenesisDoc{}` now takes a `genutiltypes.AppGenesis{}`. + - * (core) [#15133](https://github.com/cosmos/cosmos-sdk/pull/15133) Implement RegisterServices in the module manager. + - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Return a human readable denomination for IBC vouchers when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest` and `--resolve-denom` flag to `GetBalancesCmd()`. + - * (core) [#14860](https://github.com/cosmos/cosmos-sdk/pull/14860) Add `Precommit` and `PrepareCheckState` AppModule callbacks. + - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Upstream expedited proposals from Osmosis. + - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by events with queries directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. + - * (x/auth) [#14650](https://github.com/cosmos/cosmos-sdk/pull/14650) Add Textual SignModeHandler. Enable `SIGN_MODE_TEXTUAL` by following the [UPGRADING.md](./UPGRADING.md) instructions. + - * (x/crisis) [#14588](https://github.com/cosmos/cosmos-sdk/pull/14588) Use CacheContext() in AssertInvariants(). + - * (mempool) [#14484](https://github.com/cosmos/cosmos-sdk/pull/14484) Add priority nonce mempool option for transaction replacement. + - * (query) [#14468](https://github.com/cosmos/cosmos-sdk/pull/14468) Implement pagination for collections. + - * (x/gov) [#14373](https://github.com/cosmos/cosmos-sdk/pull/14373) Add new proto field `constitution` of type `string` to gov module genesis state, which allows chain builders to lay a strong foundation by specifying purpose. + - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) Add ` config` command is now a sub-command, for setting, getting and migrating Cosmos SDK configuration files. + - * (x/distribution) [#14322](https://github.com/cosmos/cosmos-sdk/pull/14322) Introduce a new gRPC message handler, `DepositValidatorRewardsPool`, that allows explicit funding of a validator's reward pool. + - * (x/bank) [#14224](https://github.com/cosmos/cosmos-sdk/pull/14224) Allow injection of restrictions on transfers using `AppendSendRestriction` or `PrependSendRestriction`. + - ### Improvements + - * (x/gov) [#18189](https://github.com/cosmos/cosmos-sdk/pull/18189) Limit the accepted deposit coins for a proposal to the minimum proposal deposit denoms. + - * (x/staking) [#18049](https://github.com/cosmos/cosmos-sdk/pull/18049) Return early if Slash encounters zero tokens to burn. + - * (x/staking) [#18035](https://github.com/cosmos/cosmos-sdk/pull/18035) Hoisted out of the redelegation loop, the non-changing validator and delegator addresses parsing. + - * (keyring) [#17913](https://github.com/cosmos/cosmos-sdk/pull/17913) Add `NewAutoCLIKeyring` for creating an AutoCLI keyring from a SDK keyring. + - * (x/consensus) [#18041](https://github.com/cosmos/cosmos-sdk/pull/18041) Let `ToProtoConsensusParams()` return an error. + - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. + - * (baseapp) [#17667](https://github.com/cosmos/cosmos-sdk/pull/17667) Close databases opened by SDK in `baseApp.Close()`. + - * (types/module) [#17554](https://github.com/cosmos/cosmos-sdk/pull/17554) Introduce `HasABCIGenesis` which is implemented by a module only when a validatorset update needs to be returned. + - * (cli) [#17389](https://github.com/cosmos/cosmos-sdk/pull/17389) gRPC CometBFT commands have been added under ` q consensus comet`. CometBFT commands placement in the SDK has been simplified. See the exhaustive list below. + - * `client/rpc.StatusCommand()` is now at `server.StatusCommand()` + - * (testutil) [#17216](https://github.com/cosmos/cosmos-sdk/issues/17216) Add `DefaultContextWithKeys` to `testutil` package. + - * (cli) [#17187](https://github.com/cosmos/cosmos-sdk/pull/17187) Do not use `ctx.PrintObjectLegacy` in commands anymore. + - * ` q gov proposer [proposal-id]` now returns a proposal id as int instead of string. + - * (x/staking) [#17164](https://github.com/cosmos/cosmos-sdk/pull/17164) Add `BondedTokensAndPubKeyByConsAddr` to the keeper to enable vote extension verification. + - * (x/group, x/gov) [#17109](https://github.com/cosmos/cosmos-sdk/pull/17109) Let proposal summary be 40x longer than metadata limit. + - * (version) [#17096](https://github.com/cosmos/cosmos-sdk/pull/17096) Improve `getSDKVersion()` to handle module replacements. + - * (types) [#16890](https://github.com/cosmos/cosmos-sdk/pull/16890) Remove `GetTxCmd() *cobra.Command` and `GetQueryCmd() *cobra.Command` from `module.AppModuleBasic` interface. + - * (x/authz) [#16869](https://github.com/cosmos/cosmos-sdk/pull/16869) Improve error message when grant not found. + - * (all) [#16497](https://github.com/cosmos/cosmos-sdk/pull/16497) Removed all exported vestiges of `sdk.MustSortJSON` and `sdk.SortJSON`. + - * (server) [#16238](https://github.com/cosmos/cosmos-sdk/pull/16238) Don't setup p2p node keys if starting a node in GRPC only mode. + - * (cli) [#16206](https://github.com/cosmos/cosmos-sdk/pull/16206) Make ABCI handshake profileable. + - * (types) [#16076](https://github.com/cosmos/cosmos-sdk/pull/16076) Optimize `ChainAnteDecorators`/`ChainPostDecorators` to instantiate the functions once instead of on every invocation of the returned `AnteHandler`/`PostHandler`. + - * (server) [#16071](https://github.com/cosmos/cosmos-sdk/pull/16071) When `mempool.max-txs` is set to a negative value, use a no-op mempool (effectively disable the app mempool). + - * (types/query) [#16041](https://github.com/cosmos/cosmos-sdk/pull/16041) Change pagination max limit to a variable in order to be modifed by application devs. + - * (simapp) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Refactor SimApp for removing the global basic manager. + - * (all modules) [#15901](https://github.com/cosmos/cosmos-sdk/issues/15901) All core Cosmos SDK modules query commands have migrated to [AutoCLI](https://docs.cosmos.network/main/core/autocli), ensuring parity between gRPC and CLI queries. + - * (x/auth) [#15867](https://github.com/cosmos/cosmos-sdk/pull/15867) Support better logging for signature verification failure. + - * (store/cachekv) [#15767](https://github.com/cosmos/cosmos-sdk/pull/15767) Reduce peak RAM usage during and after `InitGenesis`. + - * (x/bank) [#15764](https://github.com/cosmos/cosmos-sdk/pull/15764) Speedup x/bank `InitGenesis`. + - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) Refactor the validator's missed block signing window to be a chunked bitmap instead of a "logical" bitmap, significantly reducing the storage footprint. + - * (x/gov) [#15554](https://github.com/cosmos/cosmos-sdk/pull/15554) Add proposal result log in `active_proposal` event. When a proposal passes but fails to execute, the proposal result is logged in the `active_proposal` event. + - * (x/consensus) [#15553](https://github.com/cosmos/cosmos-sdk/pull/15553) Migrate consensus module to use collections. + - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Add `server.InterceptConfigsAndCreateContext` as alternative to `server.InterceptConfigsPreRunHandler` which does not set the server context and the default SDK logger. + - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) Improve the `PriorityNonceMempool`: + - * Support generic transaction prioritization, instead of `ctx.Priority()` + - * Improve construction through the use of a single `PriorityNonceMempoolConfig` instead of option functions + - * (x/authz) [#15164](https://github.com/cosmos/cosmos-sdk/pull/15164) Add `MsgCancelUnbondingDelegation` to staking authorization. + - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Remove unnecessary sleeps from gRPC and API server initiation. The servers will start and accept requests as soon as they're ready. + - * (baseapp) [#15023](https://github.com/cosmos/cosmos-sdk/pull/15023) & [#15213](https://github.com/cosmos/cosmos-sdk/pull/15213) Add `MessageRouter` interface to baseapp and pass it to authz, gov and groups instead of concrete type. + - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) Introduce `cosmossdk.io/log` package to provide a consistent logging interface through the SDK. CometBFT logger is now replaced by `cosmossdk.io/log.Logger`. + - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. + - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Allow transaction event queries to directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. + - * (x/evidence) [#14757](https://github.com/cosmos/cosmos-sdk/pull/14757) Evidence messages do not need to implement a `.Type()` anymore. + - * (x/auth/tx) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove `.Type()` and `Route()` methods from all msgs and `legacytx.LegacyMsg` interface. + - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by either height/hash ` q block --type=height|hash `. + - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) Return undelegate amount in MsgUndelegateResponse. + - * [#14529](https://github.com/cosmos/cosmos-sdk/pull/14529) Add new property `BondDenom` to `SimulationState` struct. + - * (store) [#14439](https://github.com/cosmos/cosmos-sdk/pull/14439) Remove global metric gatherer from store. + - * By default store has a no op metric gatherer, the application developer must set another metric gatherer or us the provided one in `store/metrics`. + - * (store) [#14438](https://github.com/cosmos/cosmos-sdk/pull/14438) Pass logger from baseapp to store. + - * (baseapp) [#14417](https://github.com/cosmos/cosmos-sdk/pull/14417) The store package no longer has a dependency on baseapp. + - * (module) [#14415](https://github.com/cosmos/cosmos-sdk/pull/14415) Loosen assertions in SetOrderBeginBlockers() and SetOrderEndBlockers(). + - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. + - * [#14406](https://github.com/cosmos/cosmos-sdk/issues/14406) Migrate usage of `types/store.go` to `store/types/..`. + - * (context)[#14384](https://github.com/cosmos/cosmos-sdk/pull/14384) Refactor(context): Pass EventManager to the context as an interface. + - * (types) [#14354](https://github.com/cosmos/cosmos-sdk/pull/14354) Improve performance on Context.KVStore and Context.TransientStore by 40%. + - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` + - * (signing) [#14087](https://github.com/cosmos/cosmos-sdk/pull/14087) Add SignModeHandlerWithContext interface with a new `GetSignBytesWithContext` to get the sign bytes using `context.Context` as an argument to access state. + - * (server) [#14062](https://github.com/cosmos/cosmos-sdk/pull/14062) Remove rosetta from server start. + - * (crypto) [#3129](https://github.com/cosmos/cosmos-sdk/pull/3129) New armor and keyring key derivation uses aead and encryption uses chacha20poly. + - ### State Machine Breaking + - * (x/gov) [#18146](https://github.com/cosmos/cosmos-sdk/pull/18146) Add denom check to reject denoms outside of those listed in `MinDeposit`. A new `MinDepositRatio` param is added (with a default value of `0.001`) and now deposits are required to be at least `MinDepositRatio*MinDeposit` to be accepted. + - * (x/group,x/gov) [#16235](https://github.com/cosmos/cosmos-sdk/pull/16235) A group and gov proposal is rejected if the proposal metadata title and summary do not match the proposal title and summary. + - * (baseapp) [#15930](https://github.com/cosmos/cosmos-sdk/pull/15930) change vote info provided by prepare and process proposal to the one in the block. + - * (x/staking) [#15731](https://github.com/cosmos/cosmos-sdk/pull/15731) Introducing a new index to retrieve the delegations by validator efficiently. + - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) The `HistoricalInfoKey` has been updated to use a binary format. + - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) The validator slashing window now stores "chunked" bitmap entries for each validator's signing window instead of a single boolean entry per signing window index. + - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. + - * (x/feegrant) [#14294](https://github.com/cosmos/cosmos-sdk/pull/14294) Moved the logic of rejecting duplicate grant from `msg_server` to `keeper` method. + - ### API Breaking Changes + - * (x/auth) [#17787](https://github.com/cosmos/cosmos-sdk/pull/17787) Remove Tip functionality. + - * (types) `module.EndBlockAppModule` has been replaced by Core API `appmodule.HasEndBlocker` or `module.HasABCIEndBlock` when needing validator updates. + - * (types) `module.BeginBlockAppModule` has been replaced by Core API `appmodule.HasBeginBlocker`. + - * (types) [#17358](https://github.com/cosmos/cosmos-sdk/pull/17358) Remove deprecated `sdk.Handler`, use `baseapp.MsgServiceHandler` instead. + - * (client) [#17197](https://github.com/cosmos/cosmos-sdk/pull/17197) `keys.Commands` does not take a home directory anymore. It is inferred from the root command. + - * (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. + - * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address + - * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. + - * `FromABCIEvidence` & `GetConsensusAddress(consAc address.Codec)` now take a consensus address codec to be able to decode the incoming address. + - * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function + - * (x/staking) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgCreateValidator`, `NewValidator`, `NewMsgCancelUnbondingDelegation`, `NewMsgUndelegate`, `NewMsgBeginRedelegate`, `NewMsgDelegate` and `NewMsgEditValidator` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`: + - * `NewRedelegation` and `NewUnbondingDelegation` takes a validatorAddressCodec and a delegatorAddressCodec in order to decode the addresses. + - * `NewRedelegationResponse` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. + - * `NewMsgCreateValidator.Validate()` takes an address codec in order to decode the address. + - * `BuildCreateValidatorMsg` takes a ValidatorAddressCodec in order to decode addresses. + - * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` + - * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses. + - * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. + - * (x/staking) [#16959](https://github.com/cosmos/cosmos-sdk/pull/16959) Add validator and consensus address codec as staking keeper arguments. + - * (x/staking) [#16958](https://github.com/cosmos/cosmos-sdk/pull/16958) DelegationI interface `GetDelegatorAddr` & `GetValidatorAddr` have been migrated to return string instead of sdk.AccAddress and sdk.ValAddress respectively. stakingtypes.NewDelegation takes a string instead of sdk.AccAddress and sdk.ValAddress. + - * (testutil) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) The *cli testutil* `QueryBalancesExec` has been removed. Use the gRPC or REST query instead. + - * (x/staking) [#16795](https://github.com/cosmos/cosmos-sdk/pull/16795) `DelegationToDelegationResponse`, `DelegationsToDelegationResponses`, `RedelegationsToRedelegationResponses` are no longer exported. + - * (x/auth/vesting) [#16741](https://github.com/cosmos/cosmos-sdk/pull/16741) Vesting account constructor now return an error with the result of their validate function. + - * (x/auth) [#16650](https://github.com/cosmos/cosmos-sdk/pull/16650) The *cli testutil* `QueryAccountExec` has been removed. Use the gRPC or REST query instead. + - * (x/auth) [#16621](https://github.com/cosmos/cosmos-sdk/pull/16621) Pass address codec to auth new keeper constructor. + - * (x/auth) [#16423](https://github.com/cosmos/cosmos-sdk/pull/16423) `helpers.AddGenesisAccount` has been moved to `x/genutil` to remove the cyclic dependency between `x/auth` and `x/genutil`. + - * (baseapp) [#16342](https://github.com/cosmos/cosmos-sdk/pull/16342) NewContext was renamed to NewContextLegacy. The replacement (NewContext) now does not take a header, instead you should set the header via `WithHeaderInfo` or `WithBlockHeight`. Note that `WithBlockHeight` will soon be depreacted and its recommneded to use `WithHeaderInfo`. + - * (x/mint) [#16329](https://github.com/cosmos/cosmos-sdk/pull/16329) Use collections for state management: + - * Removed: keeper `GetParams`, `SetParams`, `GetMinter`, `SetMinter`. + - * (x/crisis) [#16328](https://github.com/cosmos/cosmos-sdk/pull/16328) Use collections for state management: + - * Removed: keeper `GetConstantFee`, `SetConstantFee` + - * (x/staking) [#16324](https://github.com/cosmos/cosmos-sdk/pull/16324) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. Notable changes: + - * `Validator` method now returns `types.ErrNoValidatorFound` instead of `nil` when not found. + - * (x/distribution) [#16302](https://github.com/cosmos/cosmos-sdk/pull/16302) Use collections for FeePool state management. + - * Removed: keeper `GetFeePool`, `SetFeePool`, `GetFeePoolCommunityCoins` + - * (types) [#16272](https://github.com/cosmos/cosmos-sdk/pull/16272) `FeeGranter` in the `FeeTx` interface returns `[]byte` instead of `string`. + - * (x/gov) [#16268](https://github.com/cosmos/cosmos-sdk/pull/16268) Use collections for proposal state management (part 2): + - * this finalizes the gov collections migration + - * Removed: types all the key related functions + - * Removed: keeper `InsertActiveProposalsQueue`, `RemoveActiveProposalsQueue`, `InsertInactiveProposalsQueue`, `RemoveInactiveProposalsQueue`, `IterateInactiveProposalsQueue`, `IterateActiveProposalsQueue`, `ActiveProposalsQueueIterator`, `InactiveProposalsQueueIterator` + - * (x/slashing) [#16246](https://github.com/cosmos/cosmos-sdk/issues/16246) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. `GetValidatorSigningInfo` now returns an error instead of a `found bool`, the error can be `nil` (found), `ErrNoSigningInfoFound` (not found) and any other error. + - * (module) [#16227](https://github.com/cosmos/cosmos-sdk/issues/16227) `manager.RunMigrations()` now take a `context.Context` instead of a `sdk.Context`. + - * (x/crisis) [#16216](https://github.com/cosmos/cosmos-sdk/issues/16216) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` instead of panicking. + - * (x/distribution) [#16211](https://github.com/cosmos/cosmos-sdk/pull/16211) Use collections for params state management. + - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Add API `StartCmdWithOptions` to create customized start command. + - * (x/mint) [#16179](https://github.com/cosmos/cosmos-sdk/issues/16179) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. + - * (x/gov) [#16171](https://github.com/cosmos/cosmos-sdk/pull/16171) Use collections for proposal state management (part 1): + - * Removed: keeper: `GetProposal`, `UnmarshalProposal`, `MarshalProposal`, `IterateProposal`, `GetProposal`, `GetProposalFiltered`, `GetProposals`, `GetProposalID`, `SetProposalID` + - * Removed: errors unused errors + - * (x/gov) [#16164](https://github.com/cosmos/cosmos-sdk/pull/16164) Use collections for vote state management: + - * Removed: types `VoteKey`, `VoteKeys` + - * Removed: keeper `IterateVotes`, `IterateAllVotes`, `GetVotes`, `GetVote`, `SetVote` + - * (sims) [#16155](https://github.com/cosmos/cosmos-sdk/pull/16155) + - * `simulation.NewOperationMsg` now marshals the operation msg as proto bytes instead of legacy amino JSON bytes. + - * `simulation.NewOperationMsg` is now 2-arity instead of 3-arity with the obsolete argument `codec.ProtoCodec` removed. + - * The field `OperationMsg.Msg` is now of type `[]byte` instead of `json.RawMessage`. + - * (x/gov) [#16127](https://github.com/cosmos/cosmos-sdk/pull/16127) Use collections for deposit state management: + - * The following methods are removed from the gov keeper: `GetDeposit`, `GetAllDeposits`, `IterateAllDeposits`. + - * The following functions are removed from the gov types: `DepositKey`, `DepositsKey`. + - * (x/gov) [#16118](https://github.com/cosmos/cosmos-sdk/pull/16118/) Use collections for constituion and params state management. + - * (x/gov) [#16106](https://github.com/cosmos/cosmos-sdk/pull/16106) Remove gRPC query methods from gov keeper. + - * (x/*all*) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetSignBytes` implementations on messages and global legacy amino codec definitions have been removed from all modules. + - * (sims) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetOrGenerate` no longer requires a codec argument is now 4-arity instead of 5-arity. + - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16798) Remove aliases in `types/math.go` (part 2). + - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16040) Remove aliases in `types/math.go` (part 1). + - * (x/auth) [#16016](https://github.com/cosmos/cosmos-sdk/pull/16016) Use collections for accounts state management: + - * removed: keeper `HasAccountByID`, `AccountAddressByID`, `SetParams + - * (x/genutil) [#15999](https://github.com/cosmos/cosmos-sdk/pull/15999) Genutil now takes the `GenesisTxHanlder` interface instead of deliverTx. The interface is implemented on baseapp + - * (x/gov) [#15988](https://github.com/cosmos/cosmos-sdk/issues/15988) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` (instead of panicking or returning a `found bool`). Iterators callback functions now return an error instead of a `bool`. + - * (x/auth) [#15985](https://github.com/cosmos/cosmos-sdk/pull/15985) The `AccountKeeper` does not expose the `QueryServer` and `MsgServer` APIs anymore. + - * (x/authz) [#15962](https://github.com/cosmos/cosmos-sdk/issues/15962) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. The `Authorization` interface's `Accept` method now takes a `context.Context` instead of a `sdk.Context`. + - * (x/distribution) [#15948](https://github.com/cosmos/cosmos-sdk/issues/15948) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Keeper methods also now return an `error`. + - * (x/bank) [#15891](https://github.com/cosmos/cosmos-sdk/issues/15891) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Also `FundAccount` and `FundModuleAccount` from the `testutil` package accept a `context.Context` instead of a `sdk.Context`, and it's position was moved to the first place. + - * (x/slashing) [#15875](https://github.com/cosmos/cosmos-sdk/pull/15875) `x/slashing.NewAppModule` now requires an `InterfaceRegistry` parameter. + - * (x/crisis) [#15852](https://github.com/cosmos/cosmos-sdk/pull/15852) Crisis keeper now takes a instance of the address codec to be able to decode user addresses + - * (x/auth) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The type of struct field `ante.HandlerOptions.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. + - * (client) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The return type of the interface method `TxConfig.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. + - * The signature of `VerifySignature` has been changed to accept a `x/tx/signing.HandlerMap` and other structs from `x/tx` as arguments. + - * The signature of `NewTxConfigWithTextual` has been deprecated and its signature changed to accept a `SignModeOptions`. + - * The signature of `NewSigVerificationDecorator` has been changed to accept a `x/tx/signing.HandlerMap`. + - * (x/bank) [#15818](https://github.com/cosmos/cosmos-sdk/issues/15818) `BaseViewKeeper`'s `Logger` method now doesn't require a context. `NewBaseKeeper`, `NewBaseSendKeeper` and `NewBaseViewKeeper` now also require a `log.Logger` to be passed in. + - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) `MigrateGenesisCmd` now takes a `MigrationMap` instead of having the SDK genesis migration hardcoded. + - * (client) [#15673](https://github.com/cosmos/cosmos-sdk/pull/15673) Move `client/keys.OutputFormatJSON` and `client/keys.OutputFormatText` to `client/flags` package. + - * (x/*all*) [#15648](https://github.com/cosmos/cosmos-sdk/issues/15648) Make `SetParams` consistent across all modules and validate the params at the message handling instead of `SetParams` method. + - * (codec) [#15600](https://github.com/cosmos/cosmos-sdk/pull/15600) [#15873](https://github.com/cosmos/cosmos-sdk/pull/15873) add support for getting signers to `codec.Codec` and `InterfaceRegistry`: + - * `InterfaceRegistry` is has unexported methods and implements `protodesc.Resolver` plus the `RangeFiles` and `SigningContext` methods. All implementations of `InterfaceRegistry` by other users must now embed the official implementation. + - * `Codec` has new methods `InterfaceRegistry`, `GetMsgAnySigners`, `GetMsgV1Signers`, and `GetMsgV2Signers` as well as unexported methods. All implementations of `Codec` by other users must now embed an official implementation from the `codec` package. + - * `AminoCodec` is marked as deprecated and no longer implements `Codec. + - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) `RegisterNodeService` now requires a config parameter. + - * (x/nft) [#15588](https://github.com/cosmos/cosmos-sdk/pull/15588) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. + - * (baseapp) [#15568](https://github.com/cosmos/cosmos-sdk/pull/15568) `SetIAVLLazyLoading` is removed from baseapp. + - * (x/genutil) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `CollectGenTxsCmd` & `GenTxCmd` takes a address.Codec to be able to decode addresses. + - * (x/bank) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `GenesisBalance.GetAddress` now returns a string instead of `sdk.AccAddress` + - * `MsgSendExec` test helper function now takes a address.Codec + - * (x/auth) [#15520](https://github.com/cosmos/cosmos-sdk/pull/15520) `NewAccountKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) `runTxMode`s were renamed to `execMode`. `ModeDeliver` as changed to `ModeFinalize` and a new `ModeVoteExtension` was added for vote extensions. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Writing of state to the multistore was moved to `FinalizeBlock`. `Commit` still handles the committing values to disk. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Calls to BeginBlock and EndBlock have been replaced with core api beginblock & endblock. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock and EndBlock are now internal to baseapp. For testing, user must call `FinalizeBlock`. BeginBlock and EndBlock calls are internal to Baseapp. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) All calls to ABCI methods now accept a pointer of the abci request and response types + - * (x/consensus) [#15517](https://github.com/cosmos/cosmos-sdk/pull/15517) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`. + - * (x/bank) [#15477](https://github.com/cosmos/cosmos-sdk/pull/15477) `banktypes.NewMsgMultiSend` and `keeper.InputOutputCoins` only accept one input. + - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Remove `server.ErrorCode` that was not used anywhere. + - * (x/capability) [#15344](https://github.com/cosmos/cosmos-sdk/pull/15344) Capability module was removed and is now housed in [IBC-GO](https://github.com/cosmos/ibc-go). + - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) The `PriorityNonceMempool` is now generic over type `C comparable` and takes a single `PriorityNonceMempoolConfig[C]` argument. See `DefaultPriorityNonceMempoolConfig` for how to construct the configuration and a `TxPriority` type. + - * [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `StdTx` transaction and signing APIs. No SDK version has actually supported `StdTx` since before Stargate. + - * [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) + - * (x/gov) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. + - * (x/authx) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. + - * `types/tx.Tx` no longer implements `sdk.Tx`. + - * `sdk.Tx` now requires a new method `GetMsgsV2()`. + - * `sdk.Msg.GetSigners` was deprecated and is no longer supported. Use the `cosmos.msg.v1.signer` protobuf annotation instead. + - * `TxConfig` has a new method `SigningContext() *signing.Context`. + - * `SigVerifiableTx.GetSigners()` now returns `([][]byte, error)` instead of `[]sdk.AccAddress`. + - * `AccountKeeper` now has an `AddressCodec() address.Codec` method and the expected `AccountKeeper` for `x/auth/ante` expects this method. + - * [#15211](https://github.com/cosmos/cosmos-sdk/pull/15211) Remove usage of `github.com/cometbft/cometbft/libs/bytes.HexBytes` in favor of `[]byte` thorough the SDK. + - * (crypto) [#15070](https://github.com/cosmos/cosmos-sdk/pull/15070) `GenerateFromPassword` and `Cost` from `bcrypt.go` now take a `uint32` instead of a `int` type. + - * (types) [#15067](https://github.com/cosmos/cosmos-sdk/pull/15067) Remove deprecated alias from `types/errors`. Use `cosmossdk.io/errors` instead. + - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Refactor how gRPC and API servers are started to remove unnecessary sleeps: + - * `api.Server#Start` now accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the API server can gracefully exit. The caller does not need to stop the server. + - * To start the gRPC server you must first create the server via `NewGRPCServer`, after which you can start the gRPC server via `StartGRPCServer` which accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the gRPC server can gracefully exit. The caller does not need to stop the server. + - * Rename `WaitForQuitSignals` to `ListenForQuitSignals`. Note, this function is no longer blocking. Thus the caller is expected to provide a `context.CancelFunc` which indicates that when a signal is caught, that any spawned processes can gracefully exit. + - * Remove `ServerStartTime` constant. + - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) All functions that were taking a CometBFT logger, now take `cosmossdk.io/log.Logger` instead. + - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. + - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Allow a human readable denomination for coins when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest`. + - * [#14847](https://github.com/cosmos/cosmos-sdk/pull/14847) App and ModuleManager methods `InitGenesis`, `ExportGenesis`, `BeginBlock` and `EndBlock` now also return an error. + - * (x/upgrade) [#14764](https://github.com/cosmos/cosmos-sdk/pull/14764) The `x/upgrade` module is extracted to have a separate go.mod file which allows it to be a standalone module. + - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Refactor transaction searching: + - * Refactor `QueryTxsByEvents` to accept a `query` of type `string` instead of `events` of type `[]string` + - * Refactor CLI methods to accept `--query` flag instead of `--events` + - * Pass `prove=false` to Tendermint's `TxSearch` RPC method + - * (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct. + - * (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`. + - * (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`. + - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Add an expedited field in the gov v1 proposal and `MsgNewMsgProposal`. + - * (x/feegrant) [#14649](https://github.com/cosmos/cosmos-sdk/pull/14649) Extract Feegrant in its own go.mod and rename the package to `cosmossdk.io/x/feegrant`. + - * (tx) [#14634](https://github.com/cosmos/cosmos-sdk/pull/14634) Move the `tx` go module to `x/tx`. + - * (store/streaming)[#14603](https://github.com/cosmos/cosmos-sdk/pull/14603) `StoreDecoderRegistry` moved from store to `types/simulations` this breaks the `AppModuleSimulation` interface. + - * (snapshots) [#14597](https://github.com/cosmos/cosmos-sdk/pull/14597) Move `snapshots` to `store/snapshots`, rename and bump proto package to v1. + - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. + - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` + - * (baseapp) [#14050](https://github.com/cosmos/cosmos-sdk/pull/14050) Refactor `ABCIListener` interface to accept Go contexts. + - * (x/auth) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850/) Remove `MarshalYAML` methods from module (`x/...`) types. + - * (modules) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850) and [#14046](https://github.com/cosmos/cosmos-sdk/pull/14046) Remove gogoproto stringer annotations. This removes the custom `String()` methods on all types that were using the annotations. + - * (x/evidence) [14724](https://github.com/cosmos/cosmos-sdk/pull/14724) Extract Evidence in its own go.mod and rename the package to `cosmossdk.io/x/evidence`. + - * (crypto/keyring) [#13734](https://github.com/cosmos/cosmos-sdk/pull/13834) The keyring's `Sign` method now takes a new `signMode` argument. It is only used if the signing key is a Ledger hardware device. You can set it to 0 in all other cases. + - * (snapshots) [14048](https://github.com/cosmos/cosmos-sdk/pull/14048) Move the Snapshot package to the store package. This is done in an effort group all storage related logic under one package. + - * (signing) [#13701](https://github.com/cosmos/cosmos-sdk/pull/) Add `context.Context` as an argument `x/auth/signing.VerifySignature`. + - * (store) [#11825](https://github.com/cosmos/cosmos-sdk/pull/11825) Make extension snapshotter interface safer to use, renamed the util function `WriteExtensionItem` to `WriteExtensionPayload`. + - ### Client Breaking Changes + - * (x/gov) [#17910](https://github.com/cosmos/cosmos-sdk/pull/17910) Remove telemetry for counting votes and proposals. It was incorrectly counting votes. Use alternatives, such as state streaming. + - * (abci) [#15845](https://github.com/cosmos/cosmos-sdk/pull/15845) Remove duplicating events in `logs`. + - * (abci) [#15845](https://github.com/cosmos/cosmos-sdk/pull/15845) Add `msg_index` to all event attributes to associate events and messages. + - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) `HistoricalInfoKey` now has a binary format. + - * (store/streaming) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) State Streaming removed emitting of beginblock, endblock and delivertx in favour of emitting FinalizeBlock. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock & EndBlock events have begin or endblock in the events in order to identify which stage they are emitted from since they are returned to comet as FinalizeBlock events. + - * (grpc-web) [#14652](https://github.com/cosmos/cosmos-sdk/pull/14652) Use same port for gRPC-Web and the API server. + - ### CLI Breaking Changes + - * (all) The migration of modules to [AutoCLI](https://docs.cosmos.network/main/core/autocli) led to no changes in UX but a [small change in CLI outputs](https://github.com/cosmos/cosmos-sdk/issues/16651) where results can be nested. + - * (all) Query pagination flags have been renamed with the migration to AutoCLI: + - * `--reverse` -> `--page-reverse` + - * `--offset` -> `--page-offset` + - * `--limit` -> `--page-limit` + - * `--count-total` -> `--page-count-total` + - * (cli) [#17184](https://github.com/cosmos/cosmos-sdk/pull/17184) All json keys returned by the `status` command are now snake case instead of pascal case. + - * (server) [#17177](https://github.com/cosmos/cosmos-sdk/pull/17177) Remove `iavl-lazy-loading` configuration. + - * (x/gov) [#16987](https://github.com/cosmos/cosmos-sdk/pull/16987) In ` query gov proposals` the proposal status flag have renamed from `--status` to `--proposal-status`. Additionally, that flags now uses the ENUM values: `PROPOSAL_STATUS_DEPOSIT_PERIOD`, `PROPOSAL_STATUS_VOTING_PERIOD`, `PROPOSAL_STATUS_PASSED`, `PROPOSAL_STATUS_REJECTED`, `PROPOSAL_STATUS_FAILED`. + - * (x/bank) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) With the migration to AutoCLI some bank commands have been split in two: + - * Use `total-supply` (or `total`) for querying the total supply and `total-supply-of` for querying the supply of a specific denom. + - * Use `denoms-metadata` for querying all denom metadata and `denom-metadata` for querying a specific denom metadata. + - * (rosetta) [#16276](https://github.com/cosmos/cosmos-sdk/issues/16276) Rosetta migration to standalone repo. + - * (cli) [#15826](https://github.com/cosmos/cosmos-sdk/pull/15826) Remove ` q account` command. Use ` q auth account` instead. + - * (cli) [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `--amino` flag from `sign` and `multi-sign` commands. Amino `StdTx` has been deprecated for a while. Amino JSON signing still works as expected. + - * (x/gov) [#14880](https://github.com/cosmos/cosmos-sdk/pull/14880) Remove ` tx gov submit-legacy-proposal cancel-software-upgrade` and `software-upgrade` commands. These commands are now in the `x/upgrade` module and using gov v1. Use `tx upgrade software-upgrade` instead. + - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. + - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) ` q block ` is removed as it just output json. The new command allows either height/hash and is ` q block --type=height|hash `. + - * (grpc-web) [#14652](https://github.com/cosmos/cosmos-sdk/pull/14652) Remove `grpc-web.address` flag. + - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) ` config` command is now a sub-command using Confix. Use ` config --help` to learn more. + - ### Bug Fixes + - * (server) [#18254](https://github.com/cosmos/cosmos-sdk/pull/18254) Don't hardcode gRPC address to localhost. + - * (x/gov) [#18173](https://github.com/cosmos/cosmos-sdk/pull/18173) Gov hooks now return an error and are *blocking* when they fail. Expect for `AfterProposalFailedMinDeposit` and `AfterProposalVotingPeriodEnded` which log the error and continue. + - * (x/gov) [#17873](https://github.com/cosmos/cosmos-sdk/pull/17873) Fail any inactive and active proposals that cannot be decoded. + - * (x/slashing) [#18016](https://github.com/cosmos/cosmos-sdk/pull/18016) Fixed builder function for missed blocks key (`validatorMissedBlockBitArrayPrefixKey`) in slashing/migration/v4. + - * (x/bank) [#18107](https://github.com/cosmos/cosmos-sdk/pull/18107) Add missing keypair of SendEnabled to restore legacy param set before migration. + - * (baseapp) [#17769](https://github.com/cosmos/cosmos-sdk/pull/17769) Ensure we respect block size constraints in the `DefaultProposalHandler`'s `PrepareProposal` handler when a nil or no-op mempool is used. We provide a `TxSelector` type to assist in making transaction selection generalized. We also fix a comparison bug in tx selection when `req.maxTxBytes` is reached. + - * (mempool) [#17668](https://github.com/cosmos/cosmos-sdk/pull/17668) Fix `PriorityNonceIterator.Next()` nil pointer ref for min priority at the end of iteration. + - * (config) [#17649](https://github.com/cosmos/cosmos-sdk/pull/17649) Fix `mempool.max-txs` configuration is invalid in `app.config`. + - * (baseapp) [#17518](https://github.com/cosmos/cosmos-sdk/pull/17518) Utilizing voting power from vote extensions (CometBFT) instead of the current bonded tokens (x/staking) to determine if a set of vote extensions are valid. + - * (baseapp) [#17251](https://github.com/cosmos/cosmos-sdk/pull/17251) VerifyVoteExtensions and ExtendVote initialize their own contexts/states, allowing VerifyVoteExtensions being called without ExtendVote. + - * (x/distribution) [#17236](https://github.com/cosmos/cosmos-sdk/pull/17236) Using "validateCommunityTax" in "Params.ValidateBasic", preventing panic when field "CommunityTax" is nil. + - * (x/bank) [#17170](https://github.com/cosmos/cosmos-sdk/pull/17170) Avoid empty spendable error message on send coins. + - * (x/group) [#17146](https://github.com/cosmos/cosmos-sdk/pull/17146) Rename x/group legacy ORM package's error codespace from "orm" to "legacy_orm", preventing collisions with ORM's error codespace "orm". + - * (types/query) [#16905](https://github.com/cosmos/cosmos-sdk/pull/16905) Collections Pagination now applies proper count when filtering results. + - * (x/bank) [#16841](https://github.com/cosmos/cosmos-sdk/pull/16841) Correctly process legacy `DenomAddressIndex` values. + - * (x/auth/vesting) [#16733](https://github.com/cosmos/cosmos-sdk/pull/16733) Panic on overflowing and negative EndTimes when creating a PeriodicVestingAccount. + - * (x/consensus) [#16713](https://github.com/cosmos/cosmos-sdk/pull/16713) Add missing ABCI param in `MsgUpdateParams`. + - * (baseapp) [#16700](https://github.com/cosmos/cosmos-sdk/pull/16700) Fix consensus failure in returning no response to malformed transactions. + - * [#16639](https://github.com/cosmos/cosmos-sdk/pull/16639) Make sure we don't execute blocks beyond the halt height. + - * (baseapp) [#16613](https://github.com/cosmos/cosmos-sdk/pull/16613) Ensure each message in a transaction has a registered handler, otherwise `CheckTx` will fail. + - * (baseapp) [#16596](https://github.com/cosmos/cosmos-sdk/pull/16596) Return error during `ExtendVote` and `VerifyVoteExtension` if the request height is earlier than `VoteExtensionsEnableHeight`. + - * (baseapp) [#16259](https://github.com/cosmos/cosmos-sdk/pull/16259) Ensure the `Context` block height is correct after `InitChain` and prior to the second block. + - * (x/gov) [#16231](https://github.com/cosmos/cosmos-sdk/pull/16231) Fix Rawlog JSON formatting of proposal_vote option field.* (cli) [#16138](https://github.com/cosmos/cosmos-sdk/pull/16138) Fix snapshot commands panic if snapshot don't exists. + - * (x/staking) [#16043](https://github.com/cosmos/cosmos-sdk/pull/16043) Call `AfterUnbondingInitiated` hook for new unbonding entries only and fix `UnbondingDelegation` entries handling. This is a behavior change compared to Cosmos SDK v0.47.x, now the hook is called only for new unbonding entries. + - * (types) [#16010](https://github.com/cosmos/cosmos-sdk/pull/16010) Let `module.CoreAppModuleBasicAdaptor` fallback to legacy genesis handling. + \ No newline at end of file diff --git a/docs/sdk/v0.50/release-notes.mdx b/docs/sdk/v0.50/release-notes.mdx new file mode 100644 index 00000000..46a6d471 --- /dev/null +++ b/docs/sdk/v0.50/release-notes.mdx @@ -0,0 +1,38 @@ +--- +title: "Release Notes" +description: "Cosmos SDK v0.50 release notes and changelog" +--- + +## Overview + +This page provides release notes and changelog information for Cosmos SDK v0.50. + + +For the most up-to-date and detailed changelog, please refer to the official Cosmos SDK repository. + + +## Resources + +- [Full Changelog on GitHub](https://github.com/cosmos/cosmos-sdk/blob/release/v0.50.x/CHANGELOG.md) +- [Release Notes](https://github.com/cosmos/cosmos-sdk/releases?q=v0.50&expanded=true) +- [Migration Guide](https://github.com/cosmos/cosmos-sdk/blob/release/v0.50.x/UPGRADING.md) + +## Major Changes in v0.50 + +### Key Features +- Introduction of ABCI 2.0 +- AutoCLI for automatic CLI generation +- Enhanced module system +- Improved performance and efficiency + +### Breaking Changes +- Updated to CometBFT consensus +- Module API changes +- Store improvements + +### Module Updates +- Core modules have been updated with new features +- Enhanced security and performance +- Better developer experience + +For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.50.x/CHANGELOG.md). \ No newline at end of file diff --git a/docs/sdk/v0.53/learn/advanced/autocli.mdx b/docs/sdk/v0.53/apis-clients/autocli.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/autocli.mdx rename to docs/sdk/v0.53/apis-clients/autocli.mdx diff --git a/docs/sdk/v0.53/learn/advanced/cli.mdx b/docs/sdk/v0.53/apis-clients/cli.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/cli.mdx rename to docs/sdk/v0.53/apis-clients/cli.mdx diff --git a/docs/sdk/v0.53/learn/advanced/grpc_rest.mdx b/docs/sdk/v0.53/apis-clients/grpc_rest.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/grpc_rest.mdx rename to docs/sdk/v0.53/apis-clients/grpc_rest.mdx diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx new file mode 100644 index 00000000..a296bb5e --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx @@ -0,0 +1,169 @@ +--- +title: "Overview of `app_di.go`" + +--- + +--- + +--- + + +**Synopsis** + +The Cosmos SDK allows much easier wiring of an `app.go` thanks to [runtime](./00-runtime.md) and app wiring. +Learn more about the rationale of App Wiring in [ADR-057](../architecture/adr-057-app-wiring.md). + + + + +**Pre-requisite Readings** + +* [What is `runtime`?](./00-runtime.md) +* [Depinject documentation](../packages/01-depinject.md) +* [Modules depinject-ready](../building-modules/15-depinject.md) +* [ADR 057: App Wiring](../architecture/adr-057-app-wiring.md) + + + +This section is intended to provide an overview of the `SimApp` `app_di.go` file with App Wiring. + +## `app_config.go` + +The `app_config.go` file is the single place to configure all modules parameters. + +1. Create the `AppConfig` variable: + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L289-L303 + ``` + + Where the `appConfig` combines the [runtime](/docs/sdk/v0.53/00-runtime.md) configuration and the (extra) modules configuration. + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_di.go#L113-L161 + ``` + +2. Configure the `runtime` module: + + In this configuration, the order at which the modules are defined in PreBlockers, BeginBlocks, and EndBlockers is important. + They are named in the order they should be executed by the module manager. + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L103-L188 + ``` + +3. Wire the other modules: + + Next to runtime, the other (depinject-enabled) modules are wired in the `AppConfig`: + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L103-L286 + ``` + + Note: the `tx` isn't a module, but a configuration. It should be wired in the `AppConfig` as well. + + ```go reference + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L222-L227 + ``` + +See the complete `app_config.go` file for `SimApp` [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go). + +### Alternative formats + +```go +``` + +The example above shows how to create an `AppConfig` using Go. However, it is also possible to create an `AppConfig` using YAML, or JSON. +The configuration can then be embed with `go:embed` and read with [`appconfig.LoadYAML`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadYAML), or [`appconfig.LoadJSON`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadJSON), in `app_di.go`. + +//go:embed app_config.yaml +var ( + appConfigYaml []byte + appConfig = appconfig.LoadYAML(appConfigYaml) +) + + + +```yaml +modules: + - name: runtime + config: + "@type": cosmos.app.runtime.v1alpha1.Module + app_name: SimApp + begin_blockers: [staking, auth, bank] + end_blockers: [bank, auth, staking] + init_genesis: [bank, auth, staking] + - name: auth + config: + "@type": cosmos.auth.module.v1.Module + bech32_prefix: cosmos + - name: bank + config: + "@type": cosmos.bank.module.v1.Module + - name: staking + config: + "@type": cosmos.staking.module.v1.Module + - name: tx + config: + "@type": cosmos.tx.module.v1.Module +``` + +A more complete example of `app.yaml` can be found [here](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/simapp/example_app.yaml). + +## `app_di.go` + +`app_di.go` is the place where `SimApp` is constructed. `depinject.Inject` automatically wires the app modules and keepers when provided with an application configuration (`AppConfig`). `SimApp` is constructed upon calling the injected `*runtime.AppBuilder` with `appBuilder.Build(...)`. +In short `depinject` and the [`runtime` package](/docs/sdk/v0.53/00-runtime.md) abstract the wiring of the app, and the `AppBuilder` is the place where the app is constructed. [`runtime`](/docs/sdk/v0.53/00-runtime.md) takes care of registering the codecs, KV store, subspaces and instantiating `baseapp`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_di.go#L100-L270 +``` + + +When using `depinject.Inject`, the injected types must be pointers. + + +### Advanced Configuration + +In advanced cases, it is possible to inject extra (module) configuration in a way that is not (yet) supported by `AppConfig`. +In this case, use `depinject.Configs` for combining the extra configuration, and `AppConfig` and `depinject.Supply` for providing the extra configuration. +More information on how `depinject.Configs` and `depinject.Supply` function can be found in the [`depinject` documentation](https://pkg.go.dev/cosmossdk.io/depinject). + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_di.go#L114-L162 +``` + +### Registering non app wiring modules + +It is possible to combine app wiring / depinject enabled modules with non-app wiring modules. +To do so, use the `app.RegisterModules` method to register the modules on your app, as well as `app.RegisterStores` for registering the extra stores needed. + +```go +// .... +app.App = appBuilder.Build(db, traceStore, baseAppOptions...) + +// register module manually +app.RegisterStores(storetypes.NewKVStoreKey(example.ModuleName)) +app.ExampleKeeper = examplekeeper.NewKeeper(app.appCodec, app.AccountKeeper.AddressCodec(), runtime.NewKVStoreService(app.GetKey(example.ModuleName)), authtypes.NewModuleAddress(govtypes.ModuleName).String()) +exampleAppModule := examplemodule.NewAppModule(app.ExampleKeeper) +if err := app.RegisterModules(&exampleAppModule); err != nil { + panic(err) +} + +// .... +``` + + +When using AutoCLI and combining app wiring and non-app wiring modules. The AutoCLI options should be manually constructed instead of injected. +Otherwise it will miss the non depinject modules and not register their CLI. + + +### Complete `app_di.go` + + +Note that in the complete `SimApp` `app_di.go` file, testing utilities are also defined, but they could as well be defined in a separate file. + + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_di.go +``` diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx new file mode 100644 index 00000000..89c90504 --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx @@ -0,0 +1,17 @@ +--- +title: "Overview of `app.go`" + +--- + +--- + +--- + +This section is intended to provide an overview of the `SimApp` `app.go` file and is still a work in progress. +For now please instead read the [tutorials](https://tutorials.cosmos.network) for a deep dive on how to build a chain. + +## Complete `app.go` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/simapp/app.go +``` diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx new file mode 100644 index 00000000..9fffbb29 --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx @@ -0,0 +1,99 @@ +--- +title: "Application Mempool" + +--- + +--- + +--- + + +**Synopsis** +This section describes how the app-side mempool can be used and replaced. + + +Since `v0.47` the application has its own mempool to allow much more granular +block building than previous versions. This change was enabled by +[ABCI 1.0](https://github.com/cometbft/cometbft/blob/v0.37.0/spec/abci). +Notably it introduces the `PrepareProposal` and `ProcessProposal` steps of ABCI++. + + +**Pre-requisite Readings** + +* [BaseApp](../../learn/advanced/00-baseapp.md) +* [ABCI](../abci/00-introduction.md) + + + +## Mempool + +There are countless designs that an application developer can write for a mempool, the SDK opted to provide only simple mempool implementations. +Namely, the SDK provides the following mempools: + +* [No-op Mempool](#no-op-mempool) +* [Sender Nonce Mempool](#sender-nonce-mempool) +* [Priority Nonce Mempool](#priority-nonce-mempool) + +By default, the SDK uses the [No-op Mempool](#no-op-mempool), but it can be replaced by the application developer in [`app.go`](/docs/sdk/v0.53/01-app-go-di.md): + +```go +nonceMempool := mempool.NewSenderNonceMempool() +mempoolOpt := baseapp.SetMempool(nonceMempool) +baseAppOptions = append(baseAppOptions, mempoolOpt) +``` + +### No-op Mempool + +A no-op mempool is a mempool where transactions are completely discarded and ignored when BaseApp interacts with the mempool. +When this mempool is used, it is assumed that an application will rely on CometBFT's transaction ordering defined in `RequestPrepareProposal`, +which is FIFO-ordered by default. + +> Note: If a NoOp mempool is used, PrepareProposal and ProcessProposal both should be aware of this as +> PrepareProposal could include transactions that could fail verification in ProcessProposal. + +### Sender Nonce Mempool + +The nonce mempool is a mempool that keeps transactions from an sorted by nonce in order to avoid the issues with nonces. +It works by storing the transaction in a list sorted by the transaction nonce. When the proposer asks for transactions to be included in a block it randomly selects a sender and gets the first transaction in the list. It repeats this until the mempool is empty or the block is full. + +It is configurable with the following parameters: + +#### MaxTxs + +It is an integer value that sets the mempool in one of three modes, *bounded*, *unbounded*, or *disabled*. + +* **negative**: Disabled, mempool does not insert new transaction and return early. +* **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. +* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` + +#### Seed + +Set the seed for the random number generator used to select transactions from the mempool. + +### Priority Nonce Mempool + +The [priority nonce mempool](https://github.com/cosmos/cosmos-sdk/blob/main/types/mempool/priority_nonce_spec.md) is a mempool implementation that stores txs in a partially ordered set by 2 dimensions: + +* priority +* sender-nonce (sequence number) + +Internally it uses one priority ordered [skip list](https://pkg.go.dev/github.com/huandu/skiplist) and one skip list per sender ordered by sender-nonce (sequence number). When there are multiple txs from the same sender, they are not always comparable by priority to other sender txs and must be partially ordered by both sender-nonce and priority. + +It is configurable with the following parameters: + +#### MaxTxs + +It is an integer value that sets the mempool in one of three modes, *bounded*, *unbounded*, or *disabled*. + +* **negative**: Disabled, mempool does not insert new transaction and return early. +* **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. +* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` + +#### Callback + +The priority nonce mempool provides mempool options allowing the application sets callback(s). + +* **OnRead**: Set a callback to be called when a transaction is read from the mempool. +* **TxReplacement**: Sets a callback to be called when duplicated transaction nonce detected during mempool insert. Application can define a transaction replacement rule based on tx priority or certain transaction fields. + +More information on the SDK mempool implementation can be found in the [godocs](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/types/mempool). diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx new file mode 100644 index 00000000..afe051c7 --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx @@ -0,0 +1,237 @@ +--- +title: "Application Testnets" + +--- + +--- + +--- + +Building an application is complicated and requires a lot of testing. The Cosmos SDK provides a way to test your application in a real-world environment: a testnet. + +We allow developers to take the state from their mainnet and run tests against the state. This is useful for testing upgrade migrations, or for testing the application in a real-world environment. + +## Testnet Setup + +We will be breaking down the steps to create a testnet from mainnet state. + +```go + // InitSimAppForTestnet is broken down into two sections: + // Required Changes: Changes that, if not made, will cause the testnet to halt or panic + // Optional Changes: Changes to customize the testnet to one's liking (lower vote times, fund accounts, etc) + func InitSimAppForTestnet(app *SimApp, newValAddr bytes.HexBytes, newValPubKey crypto.PubKey, newOperatorAddress, upgradeToTrigger string) *SimApp { + ... + } +``` + +### Required Changes + +#### Staking + +When creating a testnet the important part is migrate the validator set from many validators to one or a few. This allows developers to spin up the chain without needing to replace validator keys. + +```go + ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) + pubkey := &ed25519.PubKey{Key: newValPubKey.Bytes()} + pubkeyAny, err := types.NewAnyWithValue(pubkey) + if err != nil { + tmos.Exit(err.Error()) + } + + // STAKING + // + + // Create Validator struct for our new validator. + _, bz, err := bech32.DecodeAndConvert(newOperatorAddress) + if err != nil { + tmos.Exit(err.Error()) + } + bech32Addr, err := bech32.ConvertAndEncode("simvaloper", bz) + if err != nil { + tmos.Exit(err.Error()) + } + newVal := stakingtypes.Validator{ + OperatorAddress: bech32Addr, + ConsensusPubkey: pubkeyAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: sdk.NewInt(900000000000000), + DelegatorShares: sdk.MustNewDecFromStr("10000000"), + Description: stakingtypes.Description{ + Moniker: "Testnet Validator", + }, + Commission: stakingtypes.Commission{ + CommissionRates: stakingtypes.CommissionRates{ + Rate: sdk.MustNewDecFromStr("0.05"), + MaxRate: sdk.MustNewDecFromStr("0.1"), + MaxChangeRate: sdk.MustNewDecFromStr("0.05"), + }, + }, + MinSelfDelegation: sdk.OneInt(), + } + + // Remove all validators from power store + stakingKey := app.GetKey(stakingtypes.ModuleName) + stakingStore := ctx.KVStore(stakingKey) + iterator := app.StakingKeeper.ValidatorsPowerStoreIterator(ctx) + for ; iterator.Valid(); iterator.Next() { + stakingStore.Delete(iterator.Key()) + } + iterator.Close() + + // Remove all validators from last validators store + iterator = app.StakingKeeper.LastValidatorsIterator(ctx) + for ; iterator.Valid(); iterator.Next() { + app.StakingKeeper.LastValidatorPower.Delete(iterator.Key()) + } + iterator.Close() + + // Add our validator to power and last validators store + app.StakingKeeper.SetValidator(ctx, newVal) + err = app.StakingKeeper.SetValidatorByConsAddr(ctx, newVal) + if err != nil { + panic(err) + } + app.StakingKeeper.SetValidatorByPowerIndex(ctx, newVal) + app.StakingKeeper.SetLastValidatorPower(ctx, newVal.GetOperator(), 0) + if err := app.StakingKeeper.Hooks().AfterValidatorCreated(ctx, newVal.GetOperator()); err != nil { + panic(err) + } +``` + +#### Distribution + +Since the validator set has changed, we need to update the distribution records for the new validator. + +```go + // Initialize records for this validator across all distribution stores + app.DistrKeeper.ValidatorHistoricalRewards.Set(ctx, newVal.GetOperator(), 0, distrtypes.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) + app.DistrKeeper.ValidatorCurrentRewards.Set(ctx, newVal.GetOperator(), distrtypes.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) + app.DistrKeeper.ValidatorAccumulatedCommission.Set(ctx, newVal.GetOperator(), distrtypes.InitialValidatorAccumulatedCommission()) + app.DistrKeeper.ValidatorOutstandingRewards.Set(ctx, newVal.GetOperator(), distrtypes.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) +``` + +#### Slashing + +We also need to set the validator signing info for the new validator. + +```go + // SLASHING + // + + // Set validator signing info for our new validator. + newConsAddr := sdk.ConsAddress(newValAddr.Bytes()) + newValidatorSigningInfo := slashingtypes.ValidatorSigningInfo{ + Address: newConsAddr.String(), + StartHeight: app.LastBlockHeight() - 1, + Tombstoned: false, + } + app.SlashingKeeper.ValidatorSigningInfo.Set(ctx, newConsAddr, newValidatorSigningInfo) +``` + +#### Bank + +It is useful to create new accounts for your testing purposes. This avoids the need to have the same key as you may have on mainnet. + +```go + // BANK + // + + defaultCoins := sdk.NewCoins(sdk.NewInt64Coin("ustake", 1000000000000)) + + localSimAppAccounts := []sdk.AccAddress{ + sdk.MustAccAddressFromBech32("cosmos12smx2wdlyttvyzvzg54y2vnqwq2qjateuf7thj"), + sdk.MustAccAddressFromBech32("cosmos1cyyzpxplxdzkeea7kwsydadg87357qnahakaks"), + sdk.MustAccAddressFromBech32("cosmos18s5lynnmx37hq4wlrw9gdn68sg2uxp5rgk26vv"), + sdk.MustAccAddressFromBech32("cosmos1qwexv7c6sm95lwhzn9027vyu2ccneaqad4w8ka"), + sdk.MustAccAddressFromBech32("cosmos14hcxlnwlqtq75ttaxf674vk6mafspg8xwgnn53"), + sdk.MustAccAddressFromBech32("cosmos12rr534cer5c0vj53eq4y32lcwguyy7nndt0u2t"), + sdk.MustAccAddressFromBech32("cosmos1nt33cjd5auzh36syym6azgc8tve0jlvklnq7jq"), + sdk.MustAccAddressFromBech32("cosmos10qfrpash5g2vk3hppvu45x0g860czur8ff5yx0"), + sdk.MustAccAddressFromBech32("cosmos1f4tvsdukfwh6s9swrc24gkuz23tp8pd3e9r5fa"), + sdk.MustAccAddressFromBech32("cosmos1myv43sqgnj5sm4zl98ftl45af9cfzk7nhjxjqh"), + sdk.MustAccAddressFromBech32("cosmos14gs9zqh8m49yy9kscjqu9h72exyf295afg6kgk"), + sdk.MustAccAddressFromBech32("cosmos1jllfytsz4dryxhz5tl7u73v29exsf80vz52ucc")} + + // Fund localSimApp accounts + for _, account := range localSimAppAccounts { + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, defaultCoins) + if err != nil { + tmos.Exit(err.Error()) + } + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, account, defaultCoins) + if err != nil { + tmos.Exit(err.Error()) + } + } +``` + +#### Upgrade + +If you would like to schedule an upgrade the below can be used. + +```go + // UPGRADE + // + + if upgradeToTrigger != "" { + upgradePlan := upgradetypes.Plan{ + Name: upgradeToTrigger, + Height: app.LastBlockHeight(), + } + err = app.UpgradeKeeper.ScheduleUpgrade(ctx, upgradePlan) + if err != nil { + panic(err) + } + } +``` + +### Optional Changes + +If you have custom modules that rely on specific state from the above modules and/or you would like to test your custom module, you will need to update the state of your custom module to reflect your needs + +## Running the Testnet + +Before we can run the testnet we must plug everything together. + +in `root.go`, in the `initRootCmd` function we add: + +```diff + server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, createSimAppAndExport, addModuleInitFlags) + ++ server.AddTestnetCreatorCommand(rootCmd, simapp.DefaultNodeHome, newTestnetApp, addModuleInitFlags) +``` + +Next we will add a newTestnetApp helper function: + +```diff +// newTestnetApp starts by running the normal newApp method. From there, the app interface returned is modified in order +// for a testnet to be created from the provided app. +func newTestnetApp(logger log.Logger, db cometbftdb.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { + // Create an app and type cast to an SimApp + app := newApp(logger, db, traceStore, appOpts) + simApp, ok := app.(*simapp.SimApp) + if !ok { + panic("app created from newApp is not of type simApp") + } + + newValAddr, ok := appOpts.Get(server.KeyNewValAddr).(bytes.HexBytes) + if !ok { + panic("newValAddr is not of type bytes.HexBytes") + } + newValPubKey, ok := appOpts.Get(server.KeyUserPubKey).(crypto.PubKey) + if !ok { + panic("newValPubKey is not of type crypto.PubKey") + } + newOperatorAddress, ok := appOpts.Get(server.KeyNewOpAddr).(string) + if !ok { + panic("newOperatorAddress is not of type string") + } + upgradeToTrigger, ok := appOpts.Get(server.KeyTriggerTestnetUpgrade).(string) + if !ok { + panic("upgradeToTrigger is not of type string") + } + + // Make modifications to the normal SimApp required to run the network locally + return simapp.InitSimAppForTestnet(simApp, newValAddr, newValPubKey, newOperatorAddress, upgradeToTrigger) +} +``` diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx new file mode 100644 index 00000000..66e77b3e --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx @@ -0,0 +1,222 @@ +--- +title: "Application Upgrade" + +--- + +--- + +--- + + +This document describes how to upgrade your application. If you are looking specifically for the changes to perform between SDK versions, see the [SDK migrations documentation](https://docs.cosmos.network/main/migrations/intro). + + + +This section is currently incomplete. Track the progress of this document [here](https://github.com/cosmos/cosmos-sdk/issues/11504). + + + +**Pre-requisite Readings** + +* [`x/upgrade` Documentation](https://docs.cosmos.network/main/modules/upgrade) + + + +## General Workflow + +Let's assume we are running v0.38.0 of our software in our testnet and want to upgrade to v0.40.0. +How would this look in practice? First, we want to finalize the v0.40.0 release candidate +and then install a specially named upgrade handler (eg. "testnet-v2" or even "v0.40.0"). An upgrade +handler should be defined in a new version of the software to define what migrations +to run to migrate from the older version of the software. Naturally, this is app-specific rather +than module specific, and must be defined in `app.go`, even if it imports logic from various +modules to perform the actions. You can register them with `upgradeKeeper.SetUpgradeHandler` +during the app initialization (before starting the abci server), and they serve not only to +perform a migration, but also to identify if this is the old or new version (eg. presence of +a handler registered for the named upgrade). + +Once the release candidate along with an appropriate upgrade handler is frozen, +we can have a governance vote to approve this upgrade at some future block height (e.g. 200000). +This is known as an upgrade.Plan. The v0.38.0 code will not know of this handler, but will +continue to run until block 200000, when the plan kicks in at `BeginBlock`. It will check +for the existence of the handler, and finding it missing, know that it is running the obsolete software, +and gracefully exit. + +Generally the application binary will restart on exit, but then will execute this BeginBlocker +again and exit, causing a restart loop. Either the operator can manually install the new software, +or you can make use of an external watcher daemon to possibly download and then switch binaries, +also potentially doing a backup. The SDK tool for doing such, is called [Cosmovisor](/docs/sdk/v0.53/tooling/cosmovisor). + +When the binary restarts with the upgraded version (here v0.40.0), it will detect we have registered the +"testnet-v2" upgrade handler in the code, and realize it is the new version. It then will run the upgrade handler +and *migrate the database in-place*. Once finished, it marks the upgrade as done, and continues processing +the rest of the block as normal. Once 2/3 of the voting power has upgraded, the blockchain will immediately +resume the consensus mechanism. If the majority of operators add a custom `do-upgrade` script, this should +be a matter of minutes and not even require them to be awake at that time. + +## Integrating With An App + + +The following is not required for users using `depinject`, this is abstracted for them. + + +In addition to basic module wiring, setup the upgrade Keeper for the app and then define a `PreBlocker` that calls the upgrade +keeper's PreBlocker method: + +```go +func (app *myApp) PreBlocker(ctx sdk.Context, req req.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { + // For demonstration sake, the app PreBlocker only returns the upgrade module pre-blocker. + // In a real app, the module manager should call all pre-blockers + // return app.ModuleManager.PreBlock(ctx, req) + return app.upgradeKeeper.PreBlocker(ctx, req) +} +``` + +The app must then integrate the upgrade keeper with its governance module as appropriate. The governance module +should call ScheduleUpgrade to schedule an upgrade and ClearUpgradePlan to cancel a pending upgrade. + +## Performing Upgrades + +Upgrades can be scheduled at a predefined block height. Once this block height is reached, the +existing software will cease to process ABCI messages and a new version with code that handles the upgrade must be deployed. +All upgrades are coordinated by a unique upgrade name that cannot be reused on the same blockchain. In order for the upgrade +module to know that the upgrade has been safely applied, a handler with the name of the upgrade must be installed. +Here is an example handler for an upgrade named "my-fancy-upgrade": + +```go +app.upgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx context.Context, plan upgrade.Plan) { + // Perform any migrations of the state store needed for this upgrade +}) +``` + +This upgrade handler performs the dual function of alerting the upgrade module that the named upgrade has been applied, +as well as providing the opportunity for the upgraded software to perform any necessary state migrations. Both the halt +(with the old binary) and applying the migration (with the new binary) are enforced in the state machine. Actually +switching the binaries is an ops task and not handled inside the sdk / abci app. + +Here is a sample code to set store migrations with an upgrade: + +```go +// this configures a no-op upgrade handler for the "my-fancy-upgrade" upgrade +app.UpgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx context.Context, plan upgrade.Plan) { + // upgrade changes here +}) +upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() +if err != nil { + // handle error +} +if upgradeInfo.Name == "my-fancy-upgrade" && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + storeUpgrades := store.StoreUpgrades{ + Renamed: []store.StoreRename{{ + OldKey: "foo", + NewKey: "bar", + }}, + Deleted: []string{}, + } + // configure store loader that checks if version == upgradeHeight and applies store upgrades + app.SetStoreLoader(upgrade.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) +} +``` + +## Halt Behavior + +Before halting the ABCI state machine in the BeginBlocker method, the upgrade module will log an error +that looks like: + +```text + UPGRADE "" NEEDED at height : +``` + +where `Name` and `Info` are the values of the respective fields on the upgrade Plan. + +To perform the actual halt of the blockchain, the upgrade keeper simply panics which prevents the ABCI state machine +from proceeding but doesn't actually exit the process. Exiting the process can cause issues for other nodes that start +to lose connectivity with the exiting nodes, thus this module prefers to just halt but not exit. + +## Automation + +Read more about [Cosmovisor](/docs/sdk/v0.53/tooling/cosmovisor), the tool for automating upgrades. + +## Canceling Upgrades + +There are two ways to cancel a planned upgrade - with on-chain governance or off-chain social consensus. +For the first one, there is a `CancelSoftwareUpgrade` governance proposal, which can be voted on and will +remove the scheduled upgrade plan. Of course this requires that the upgrade was known to be a bad idea +well before the upgrade itself, to allow time for a vote. If you want to allow such a possibility, you +should set the upgrade height to be `2 * (votingperiod + depositperiod) + (safety delta)` from the beginning of +the first upgrade proposal. Safety delta is the time available from the success of an upgrade proposal +and the realization it was a bad idea (due to external testing). You can also start a `CancelSoftwareUpgrade` +proposal while the original `SoftwareUpgrade` proposal is still being voted upon, as long as the voting +period ends after the `SoftwareUpgrade` proposal. + +However, let's assume that we don't realize the upgrade has a bug until shortly before it will occur +(or while we try it out - hitting some panic in the migration). It would seem the blockchain is stuck, +but we need to allow an escape for social consensus to overrule the planned upgrade. To do so, there's +a `--unsafe-skip-upgrades` flag to the start command, which will cause the node to mark the upgrade +as done upon hitting the planned upgrade height(s), without halting and without actually performing a migration. +If over two-thirds run their nodes with this flag on the old binary, it will allow the chain to continue through +the upgrade with a manual override. (This must be well-documented for anyone syncing from genesis later on). + +Example: + +```shell + start --unsafe-skip-upgrades ... +``` + +## Pre-Upgrade Handling + +Cosmovisor supports custom pre-upgrade handling. Use pre-upgrade handling when you need to implement application config changes that are required in the newer version before you perform the upgrade. + +Using Cosmovisor pre-upgrade handling is optional. If pre-upgrade handling is not implemented, the upgrade continues. + +For example, make the required new-version changes to `app.toml` settings during the pre-upgrade handling. The pre-upgrade handling process means that the file does not have to be manually updated after the upgrade. + +Before the application binary is upgraded, Cosmovisor calls a `pre-upgrade` command that can be implemented by the application. + +The `pre-upgrade` command does not take in any command-line arguments and is expected to terminate with the following exit codes: + +| Exit status code | How it is handled in Cosmosvisor | +|------------------|---------------------------------------------------------------------------------------------------------------------| +| `0` | Assumes `pre-upgrade` command executed successfully and continues the upgrade. | +| `1` | Default exit code when `pre-upgrade` command has not been implemented. | +| `30` | `pre-upgrade` command was executed but failed. This fails the entire upgrade. | +| `31` | `pre-upgrade` command was executed but failed. But the command is retried until exit code `1` or `30` are returned. | + +## Sample + +Here is a sample structure of the `pre-upgrade` command: + +```go +func preUpgradeCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "pre-upgrade", + Short: "Pre-upgrade command", + Long: "Pre-upgrade command to implement custom pre-upgrade handling", + Run: func(cmd *cobra.Command, args []string) { + + err := HandlePreUpgrade() + + if err != nil { + os.Exit(30) + } + + os.Exit(0) + + }, + } + + return cmd +} +``` + +Ensure that the pre-upgrade command has been registered in the application: + +```go +rootCmd.AddCommand( + // .. + preUpgradeCommand(), + // .. + ) +``` + +When not using Cosmovisor, ensure to run ` pre-upgrade` before starting the application binary. diff --git a/docs/sdk/v0.53/learn/advanced/baseapp.mdx b/docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/baseapp.mdx rename to docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx diff --git a/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx new file mode 100644 index 00000000..841c7e52 --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx @@ -0,0 +1,155 @@ +--- +title: "What is `runtime`?" + +--- + +--- + +--- + +The `runtime` package in the Cosmos SDK provides a flexible framework for configuring and managing blockchain applications. It serves as the foundation for creating modular blockchain applications using a declarative configuration approach. + +## Overview + +The runtime package acts as a wrapper around the `BaseApp` and `ModuleManager`, offering a hybrid approach where applications can be configured both declaratively through configuration files and programmatically through traditional methods. +It is a layer of abstraction between `baseapp` and the application modules that simplifies the process of building a Cosmos SDK application. + +## Core Components + +### App Structure + +The runtime App struct contains several key components: + +```go +type App struct { + *baseapp.BaseApp + ModuleManager *module.Manager + configurator module.Configurator + config *runtimev1alpha1.Module + storeKeys []storetypes.StoreKey + // ... other fields +} +``` + +Cosmos SDK applications should embed the `*runtime.App` struct to leverage the runtime module. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app_di.go#L60-L61 +``` + +### Configuration + +The runtime module is configured using App Wiring. The main configuration object is the [`Module` message](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/proto/cosmos/app/runtime/v1alpha1/module.proto), which supports the following key settings: + +* `app_name`: The name of the application +* `begin_blockers`: List of module names to call during BeginBlock +* `end_blockers`: List of module names to call during EndBlock +* `init_genesis`: Order of module initialization during genesis +* `export_genesis`: Order for exporting module genesis data +* `pre_blockers`: Modules to execute before block processing + +Learn more about wiring `runtime` in the [next section](/docs/sdk/v0.53/01-app-go-di.md). + +#### Store Configuration + +By default, the runtime module uses the module name as the store key. +However it provides a flexible store key configuration through: + +* `override_store_keys`: Allows customizing module store keys +* `skip_store_keys`: Specifies store keys to skip during keeper construction + +Example configuration: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app_config.go#L133-L138 +``` + +## Key Features + +### 1. BaseApp and other Core SDK components integration + +The runtime module integrates with the `BaseApp` and other core SDK components to provide a seamless experience for developers. + +The developer only needs to embed the `runtime.App` struct in their application to leverage the runtime module. +The configuration of the module manager and other core components is handled internally via the [`AppBuilder`](#4-application-building). + +### 2. Module Registration + +Runtime has built-in support for [`depinject`-enabled modules](../building-modules/15-depinject.md). +Such modules can be registered through the configuration file (often named `app_config.go`), with no additional code required. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app_config.go#L210-L216 +``` + +Additionally, the runtime package facilitates manual module registration through the `RegisterModules` method. This is the primary integration point for modules not registered via configuration. + + +Even when using manual registration, the module should still be configured in the `Module` message in AppConfig. + + +```go +func (a *App) RegisterModules(modules ...module.AppModule) error +``` + +The SDK recommends using the declarative approach with `depinject` for module registration whenever possible. + +### 3. Service Registration + +Runtime registers all [core services](https://pkg.go.dev/cosmossdk.io/core) required by modules. +These services include `store`, `event manager`, `context`, and `logger`. +Runtime ensures that services are scoped to their respective modules during the wiring process. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/module.go#L201-L235 +``` + +Additionally, runtime provides automatic registration of other essential (i.e., gRPC routes) services available to the App: + +* AutoCLI Query Service +* Reflection Service +* Custom module services + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/builder.go#L52-L54 +``` + +### 4. Application Building + +The `AppBuilder` type provides a structured way to build applications: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/builder.go#L14-L19 +``` + +Key building steps: + +1. Configuration loading +2. Module registration +3. Service setup +4. Store mounting +5. Router configuration + +An application only needs to call `AppBuilder.Build` to create a fully configured application (`runtime.App`). + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/builder.go#L26-L57 +``` + +More information on building applications can be found in the [next section](/docs/sdk/v0.53/02-app-building.md). + +## Best Practices + +1. **Module Order**: Carefully consider the order of modules in begin_blockers, end_blockers, and pre_blockers. +2. **Store Keys**: Use override_store_keys only when necessary to maintain clarity +3. **Genesis Order**: Maintain correct initialization order in init_genesis +4. **Migration Management**: Use order_migrations to control upgrade paths + +### Migration Considerations + +When upgrading between versions: + +1. Review the migration order specified in `order_migrations` +2. Ensure all required modules are included in the configuration +3. Validate store key configurations +4. Test the upgrade path thoroughly diff --git a/docs/sdk/v0.53/learn/advanced/runtx_middleware.mdx b/docs/sdk/v0.53/app-wiring-runtime/runtx_middleware.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/runtx_middleware.mdx rename to docs/sdk/v0.53/app-wiring-runtime/runtx_middleware.mdx diff --git a/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx new file mode 100644 index 00000000..27920d03 --- /dev/null +++ b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx @@ -0,0 +1,125 @@ +--- +title: "Vote Extensions" + +--- + +--- + +--- + + +**Synopsis** +This section describes how the application can define and use vote extensions +defined in ABCI++. + + +## Extend Vote + +ABCI++ allows an application to extend a pre-commit vote with arbitrary data. This +process does NOT have to be deterministic, and the data returned can be unique to the +validator process. The Cosmos SDK defines `baseapp.ExtendVoteHandler`: + +```go +type ExtendVoteHandler func(Context, *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) +``` + +An application can set this handler in `app.go` via the `baseapp.SetExtendVoteHandler` +`BaseApp` option function. The `sdk.ExtendVoteHandler`, if defined, is called during +the `ExtendVote` ABCI method. Note, if an application decides to implement +`baseapp.ExtendVoteHandler`, it MUST return a non-nil `VoteExtension`. However, the vote +extension can be empty. See [here](https://github.com/cometbft/cometbft/blob/v0.38.0-rc1/spec/abci/abci++_methods.md#extendvote) +for more details. + +There are many decentralized censorship-resistant use cases for vote extensions. +For example, a validator may want to submit prices for a price oracle or encryption +shares for an encrypted transaction mempool. Note, an application should be careful +to consider the size of the vote extensions as they could increase latency in block +production. See [here](https://github.com/cometbft/cometbft/blob/v0.38.0-rc1/docs/qa/CometBFT-QA-38.md#vote-extensions-testbed) +for more details. + +## Verify Vote Extension + +Similar to extending a vote, an application can also verify vote extensions from +other validators when validating their pre-commits. For a given vote extension, +this process MUST be deterministic. The Cosmos SDK defines `sdk.VerifyVoteExtensionHandler`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/abci.go#L26-L27 +``` + +An application can set this handler in `app.go` via the `baseapp.SetVerifyVoteExtensionHandler` +`BaseApp` option function. The `sdk.VerifyVoteExtensionHandler`, if defined, is called +during the `VerifyVoteExtension` ABCI method. If an application defines a vote +extension handler, it should also define a verification handler. Note, not all +validators will share the same view of what vote extensions they verify depending +on how votes are propagated. See [here](https://github.com/cometbft/cometbft/blob/v0.38.0-rc1/spec/abci/abci++_methods.md#verifyvoteextension) +for more details. + +## Vote Extension Propagation + +The agreed upon vote extensions at height `H` are provided to the proposing validator +at height `H+1` during `PrepareProposal`. As a result, the vote extensions are +not natively provided or exposed to the remaining validators during `ProcessProposal`. +As a result, if an application requires that the agreed upon vote extensions from +height `H` are available to all validators at `H+1`, the application must propagate +these vote extensions manually in the block proposal itself. This can be done by +"injecting" them into the block proposal, since the `Txs` field in `PrepareProposal` +is just a slice of byte slices. + +`FinalizeBlock` will ignore any byte slice that doesn't implement an `sdk.Tx`, so +any injected vote extensions will safely be ignored in `FinalizeBlock`. For more +details on propagation, see the [ABCI++ 2.0 ADR](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-064-abci-2.0.md#vote-extension-propagation--verification). + +### Recovery of injected Vote Extensions + +As stated before, vote extensions can be injected into a block proposal (along with +other transactions in the `Txs` field). The Cosmos SDK provides a pre-FinalizeBlock +hook to allow applications to recover vote extensions, perform any necessary +computation on them, and then store the results in the cached store. These results +will be available to the application during the subsequent `FinalizeBlock` call. + +An example of how a pre-FinalizeBlock hook could look like is shown below: + +```go +app.SetPreBlocker(func(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { + allVEs := []VE{} // store all parsed vote extensions here + for _, tx := range req.Txs { + // define a custom function that tries to parse the tx as a vote extension + ve, ok := parseVoteExtension(tx) + if !ok { + continue + } + + allVEs = append(allVEs, ve) + } + + // perform any necessary computation on the vote extensions and store the result + // in the cached store + result := compute(allVEs) + err := storeVEResult(ctx, result) + if err != nil { + return err + } + + return nil +}) + +``` + +Then, in an app's module, the application can retrieve the result of the computation +of vote extensions from the cached store: + +```go +func (k Keeper) BeginBlocker(ctx context.Context) error { + // retrieve the result of the computation of vote extensions from the cached store + result, err := k.GetVEResult(ctx) + if err != nil { + return err + } + + // use the result of the computation of vote extensions + k.setSomething(result) + + return nil +} +``` diff --git a/docs/sdk/v0.53/changelog/release-notes.mdx b/docs/sdk/v0.53/changelog/release-notes.mdx new file mode 100644 index 00000000..36a1e130 --- /dev/null +++ b/docs/sdk/v0.53/changelog/release-notes.mdx @@ -0,0 +1,508 @@ +--- +title: "Release Notes" +description: "Cosmos SDK release notes and changelog" +mode: "custom" +--- + + + - {/* + - Guiding Principles: + - Changelogs are for humans, not machines. + - There should be an entry for every single version. + - The same types of changes should be grouped. + - Versions and sections should be linkable. + - The latest version comes first. + - The release date of each version is displayed. + - Mention whether you follow Semantic Versioning. + - Usage: + - Change log entries are to be added to the Unreleased section under the + - appropriate stanza (see below). Each entry is required to include a tag and + - the Github issue reference in the following format: + - * () \# message + - The tag should consist of where the change is being made ex. (x/staking), (store) + - The issue numbers will later be link-ified during the release process so you do + - not have to worry about including a link manually, but you can if you wish. + - Types of changes (Stanzas): + - "Features" for new features. + - "Improvements" for changes in existing functionality. + - "Deprecated" for soon-to-be removed features. + - "Bug Fixes" for any bug fixes. + - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. + - "CLI Breaking" for breaking CLI commands. + - "API Breaking" for breaking exported APIs used by developers building on SDK. + - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. + - Ref: https://keepachangelog.com/en/1.0.0/ + - */} + - # Changelog + - ## [v0.53.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.3) - 2025-07-25 + - This patch update also includes minor dependency bumps. + - ### Features + - * (abci_utils) [#25008](https://github.com/cosmos/cosmos-sdk/pull/24861) add the ability to assign a custom signer extraction adapter in `DefaultProposalHandler`. + - ## [v0.53.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.3) - 2025-07-08 + - ### Bug Fixes + - * [GHSA-p22h-3m2v-cmgh](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-p22h-3m2v-cmgh) Fix x/distribution can halt when historical rewards overflow. + - ## [v0.53.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.2) - 2025-06-02 + - This patch update also includes minor dependency bumps. + - ### Bug Fixes + - * (x/epochs) [#24770](https://github.com/cosmos/cosmos-sdk/pull/24770) Fix register of epoch hooks in `InvokeSetHooks`. + - ## [v0.53.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.0) - 2025-04-29 + - ### Features + - * (simsx) [#24062](https://github.com/cosmos/cosmos-sdk/pull/24062) [#24145](https://github.com/cosmos/cosmos-sdk/pull/24145) Add new simsx framework on top of simulations for better module dev experience. + - * (baseapp) [#24069](https://github.com/cosmos/cosmos-sdk/pull/24069) Create CheckTxHandler to allow extending the logic of CheckTx. + - * (types) [#24093](https://github.com/cosmos/cosmos-sdk/pull/24093) Added a new method, `IsGT`, for `types.Coin`. This method is used to check if a `types.Coin` is greater than another `types.Coin`. + - * (client/keys) [#24071](https://github.com/cosmos/cosmos-sdk/pull/24071) Add support for importing hex key using standard input. + - * (types) [#23780](https://github.com/cosmos/cosmos-sdk/pull/23780) Add a ValueCodec for the math.Uint type that can be used in collections maps. + - * (perf)[#24045](https://github.com/cosmos/cosmos-sdk/pull/24045) Sims: Replace runsim command with Go stdlib testing. CLI: `Commit` default true, `Lean`, `SimulateEveryOperation`, `PrintAllInvariants`, `DBBackend` params removed + - * (crypto/keyring) [#24040](https://github.com/cosmos/cosmos-sdk/pull/24040) Expose the db keyring used in the keystore. + - * (types) [#23919](https://github.com/cosmos/cosmos-sdk/pull/23919) Add MustValAddressFromBech32 function. + - * (all) [#23708](https://github.com/cosmos/cosmos-sdk/pull/23708) Add unordered transaction support. + - * Adds a `--timeout-timestamp` flag that allows users to specify a block time at which the unordered transactions should expire from the mempool. + - * (x/epochs) [#23815](https://github.com/cosmos/cosmos-sdk/pull/23815) Upstream `x/epochs` from Osmosis + - * (client) [#23811](https://github.com/cosmos/cosmos-sdk/pull/23811) Add auto cli for node service. + - * (genutil) [#24018](https://github.com/cosmos/cosmos-sdk/pull/24018) Allow manually setting the consensus key type in genesis + - * (client) [#18557](https://github.com/cosmos/cosmos-sdk/pull/18557) Add `--qrcode` flag to `keys show` command to support displaying keys address QR code. + - * (x/auth) [#24030](https://github.com/cosmos/cosmos-sdk/pull/24030) Allow usage of ed25519 keys for transaction signing. + - * (baseapp) [#24163](https://github.com/cosmos/cosmos-sdk/pull/24163) Add `StreamingManager` to baseapp to extend the abci listeners. + - * (x/protocolpool) [#23933](https://github.com/cosmos/cosmos-sdk/pull/23933) Add x/protocolpool module. + - * x/distribution can now utilize an externally managed community pool. NOTE: this will make the message handlers for FundCommunityPool and CommunityPoolSpend error, as well as the query handler for CommunityPool. + - * (client) [#18101](https://github.com/cosmos/cosmos-sdk/pull/18101) Add a `keyring-default-keyname` in `client.toml` for specifying a default key name, and skip the need to use the `--from` flag when signing transactions. + - * (x/gov) [#24355](https://github.com/cosmos/cosmos-sdk/pull/24355) Allow users to set a custom CalculateVoteResultsAndVotingPower function to be used in govkeeper.Tally. + - * (x/mint) [#24436](https://github.com/cosmos/cosmos-sdk/pull/24436) Allow users to set a custom minting function used in the `x/mint` begin blocker. + - * The `InflationCalculationFn` argument to `mint.NewAppModule()` is now ignored and must be nil. To set a custom `InflationCalculationFn` on the default minter, use `mintkeeper.WithMintFn(mintkeeper.DefaultMintFn(customInflationFn))`. + - * (api) [#24428](https://github.com/cosmos/cosmos-sdk/pull/24428) Add block height to response headers + - ### Improvements + - * (client) [#24561](https://github.com/cosmos/cosmos-sdk/pull/24561) TimeoutTimestamp flag has been changed to TimeoutDuration, which now sets the timeout timestamp of unordered transactions to the current time + duration passed. + - * (telemetry) [#24541](https://github.com/cosmos/cosmos-sdk/pull/24541) Telemetry now includes a pre_blocker metric key. x/upgrade should migrate to this key in v0.54.0. + - * (x/auth) [#24541](https://github.com/cosmos/cosmos-sdk/pull/24541) x/auth's PreBlocker now emits telemetry under the pre_blocker metric key. + - * (x/bank) [#24431](https://github.com/cosmos/cosmos-sdk/pull/24431) Reduce the number of `ValidateDenom` calls in `bank.SendCoins` and `Coin`. + - * The `AmountOf()` method on`sdk.Coins` no longer will `panic` if given an invalid denom and will instead return a zero value. + - * (x/staking) [#24391](https://github.com/cosmos/cosmos-sdk/pull/24391) Replace panics with error results; more verbose error messages + - * (x/staking) [#24354](https://github.com/cosmos/cosmos-sdk/pull/24354) Optimize validator endblock by reducing bech32 conversions, resulting in significant performance improvement + - * (client/keys) [#18950](https://github.com/cosmos/cosmos-sdk/pull/18950) Improve ` keys add`, ` keys import` and ` keys rename` by checking name validation. + - * (client/keys) [#18703](https://github.com/cosmos/cosmos-sdk/pull/18703) Improve ` keys add` and ` keys show` by checking whether there are duplicate keys in the multisig case. + - * (client/keys) [#18745](https://github.com/cosmos/cosmos-sdk/pull/18745) Improve ` keys export` and ` keys mnemonic` by adding --yes option to skip interactive confirmation. + - * (x/bank) [#24106](https://github.com/cosmos/cosmos-sdk/pull/24106) `SendCoins` now checks for `SendRestrictions` before instead of after deducting coins using `subUnlockedCoins`. + - * (crypto/ledger) [#24036](https://github.com/cosmos/cosmos-sdk/pull/24036) Improve error message when deriving paths using index > 100 + - * (gRPC) [#23844](https://github.com/cosmos/cosmos-sdk/pull/23844) Add debug log prints for each gRPC request. + - * (gRPC) [#24073](https://github.com/cosmos/cosmos-sdk/pull/24073) Adds error handling for out-of-gas panics in grpc query handlers. + - * (server) [#24072](https://github.com/cosmos/cosmos-sdk/pull/24072) Return BlockHeader by shallow copy in server Context. + - * (x/bank) [#24053](https://github.com/cosmos/cosmos-sdk/pull/24053) Resolve a foot-gun by swapping send restrictions check in `InputOutputCoins` before coin deduction. + - * (codec/types) [#24336](https://github.com/cosmos/cosmos-sdk/pull/24336) Most types definitions were moved to `github.com/cosmos/gogoproto/types/any` with aliases to these left in `codec/types` so that there should be no breakage to existing code. This allows protobuf generated code to optionally reference the SDK's custom `Any` type without a direct dependency on the SDK. This can be done by changing the `protoc` `M` parameter for `any.proto` to `Mgoogle/protobuf/any.proto=github.com/cosmos/gogoproto/types/any`. + - ### Bug Fixes + - * (x/gov)[#24460](https://github.com/cosmos/cosmos-sdk/pull/24460) Do not call Remove during Walk in defaultCalculateVoteResultsAndVotingPower. + - * (baseapp) [24261](https://github.com/cosmos/cosmos-sdk/pull/24261) Fix post handler error always results in code 1 + - * (server) [#24068](https://github.com/cosmos/cosmos-sdk/pull/24068) Allow align block header with skip check header in grpc server. + - * (x/gov) [#24044](https://github.com/cosmos/cosmos-sdk/pull/24044) Fix some places in which we call Remove inside a Walk (x/gov). + - * (baseapp) [#24042](https://github.com/cosmos/cosmos-sdk/pull/24042) Fixed a data race inside BaseApp.getContext, found by end-to-end (e2e) tests. + - * (client/server) [#24059](https://github.com/cosmos/cosmos-sdk/pull/24059) Consistently set viper prefix in client and server. It defaults for the binary name for both client and server. + - * (client/keys) [#24041](https://github.com/cosmos/cosmos-sdk/pull/24041) `keys delete` won't terminate when a key is not found, but will log the error. + - * (baseapp) [#24027](https://github.com/cosmos/cosmos-sdk/pull/24027) Ensure that `BaseApp.Init` checks that the commit multistore is set to protect against nil dereferences. + - * (x/group) [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker + - * (x/distribution) [#23934](https://github.com/cosmos/cosmos-sdk/pull/23934) Fix vulnerability in `incrementReferenceCount` in distribution. + - * (baseapp) [#23879](https://github.com/cosmos/cosmos-sdk/pull/23879) Ensure finalize block response is not empty in the defer check of FinalizeBlock to avoid panic by nil pointer. + - * (query) [#23883](https://github.com/cosmos/cosmos-sdk/pull/23883) Fix NPE in query pagination. + - * (client) [#23860](https://github.com/cosmos/cosmos-sdk/pull/23860) Add missing `unordered` field for legacy amino signing of tx body. + - * (x/bank) [#23836](https://github.com/cosmos/cosmos-sdk/pull/23836) Fix `DenomMetadata` rpc allow value with slashes. + - * (query) [87d3a43](https://github.com/cosmos/cosmos-sdk/commit/87d3a432af95f4cf96aa02351ed5fcc51cca6e7b) Fix collection filtered pagination. + - * (sims) [#23952](https://github.com/cosmos/cosmos-sdk/pull/23952) Use liveness matrix for validator sign status in sims + - * (baseapp) [#24055](https://github.com/cosmos/cosmos-sdk/pull/24055) Align block header when query with latest height. + - * (baseapp) [#24074](https://github.com/cosmos/cosmos-sdk/pull/24074) Use CometBFT's ComputeProtoSizeForTxs in defaultTxSelector.SelectTxForProposal for consistency. + - * (cli) [#24090](https://github.com/cosmos/cosmos-sdk/pull/24090) Prune cmd should disable async pruning. + - * (x/auth) [#19239](https://github.com/cosmos/cosmos-sdk/pull/19239) Sets from flag in multi-sign command to avoid no key name provided error. + - * (x/auth) [#23741](https://github.com/cosmos/cosmos-sdk/pull/23741) Support legacy global AccountNumber for legacy compatibility. + - * (baseapp) [#24526](https://github.com/cosmos/cosmos-sdk/pull/24526) Fix incorrect retention height when `commitHeight` equals `minRetainBlocks`. + - * (x/protocolpool) [#24594](https://github.com/cosmos/cosmos-sdk/pull/24594) Fix NPE when initializing module via depinject. + - * (x/epochs) [#24610](https://github.com/cosmos/cosmos-sdk/pull/24610) Fix semantics of `CurrentEpochStartHeight` being set before epoch has started. + - ## [v0.50.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.13) - 2025-03-12 + - ### Bug Fixes + - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker + - ## [v0.50.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.12) - 2025-02-20 + - ### Bug Fixes + - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal. + - ## [v0.50.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.11) - 2024-12-16 + - ### Features + - * (crypto/keyring) [#21653](https://github.com/cosmos/cosmos-sdk/pull/21653) New Linux-only backend that adds Linux kernel's `keyctl` support. + - ### Improvements + - * (server) [#21941](https://github.com/cosmos/cosmos-sdk/pull/21941) Regenerate addrbook.json for in place testnet. + - ### Bug Fixes + - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any + - * (server) [#22564](https://github.com/cosmos/cosmos-sdk/pull/22564) Fix fallback genesis path in server + - * (x/group) [#22425](https://github.com/cosmos/cosmos-sdk/pull/22425) Proper address rendering in error + - * (sims) [#21906](https://github.com/cosmos/cosmos-sdk/pull/21906) Skip sims test when running dry on validators + - * (cli) [#21919](https://github.com/cosmos/cosmos-sdk/pull/21919) Query address-by-acc-num by account_id instead of id. + - * (x/group) [#22229](https://github.com/cosmos/cosmos-sdk/pull/22229) Accept `1` and `try` in CLI for group proposal exec. + - ## [v0.50.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.10) - 2024-09-20 + - ### Features + - * (cli) [#20779](https://github.com/cosmos/cosmos-sdk/pull/20779) Added `module-hash-by-height` command to query and retrieve module hashes at a specified blockchain height, enhancing debugging capabilities. + - * (cli) [#21372](https://github.com/cosmos/cosmos-sdk/pull/21372) Added a `bulk-add-genesis-account` genesis command to add many genesis accounts at once. + - * (types/collections) [#21724](https://github.com/cosmos/cosmos-sdk/pull/21724) Added `LegacyDec` collection value. + - ### Improvements + - * (x/bank) [#21460](https://github.com/cosmos/cosmos-sdk/pull/21460) Added `Sender` attribute in `MsgMultiSend` event. + - * (genutil) [#21701](https://github.com/cosmos/cosmos-sdk/pull/21701) Improved error messages for genesis validation. + - * (testutil/integration) [#21816](https://github.com/cosmos/cosmos-sdk/pull/21816) Allow to pass baseapp options in `NewIntegrationApp`. + - ### Bug Fixes + - * (runtime) [#21769](https://github.com/cosmos/cosmos-sdk/pull/21769) Fix baseapp options ordering to avoid overwriting options set by modules. + - * (x/consensus) [#21493](https://github.com/cosmos/cosmos-sdk/pull/21493) Fix regression that prevented to upgrade to > v0.50.7 without consensus version params. + - * (baseapp) [#21256](https://github.com/cosmos/cosmos-sdk/pull/21256) Halt height will not commit the block indicated, meaning that if halt-height is set to 10, only blocks until 9 (included) will be committed. This is to go back to the original behavior before a change was introduced in v0.50.0. + - * (baseapp) [#21444](https://github.com/cosmos/cosmos-sdk/pull/21444) Follow-up, Return PreBlocker events in FinalizeBlockResponse. + - * (baseapp) [#21413](https://github.com/cosmos/cosmos-sdk/pull/21413) Fix data race in sdk mempool. + - ## [v0.50.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.9) - 2024-08-07 + - ## Bug Fixes + - * (baseapp) [#21159](https://github.com/cosmos/cosmos-sdk/pull/21159) Return PreBlocker events in FinalizeBlockResponse. + - * [#20939](https://github.com/cosmos/cosmos-sdk/pull/20939) Fix collection reverse iterator to include `pagination.key` in the result. + - * (client/grpc) [#20969](https://github.com/cosmos/cosmos-sdk/pull/20969) Fix `node.NewQueryServer` method not setting `cfg`. + - * (testutil/integration) [#21006](https://github.com/cosmos/cosmos-sdk/pull/21006) Fix `NewIntegrationApp` method not writing default genesis to state. + - * (runtime) [#21080](https://github.com/cosmos/cosmos-sdk/pull/21080) Fix `app.yaml` / `app.json` incompatibility with `depinject v1.0.0`. + - ## [v0.50.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.8) - 2024-07-15 + - ## Features + - * (client) [#20690](https://github.com/cosmos/cosmos-sdk/pull/20690) Import mnemonic from file + - ## Improvements + - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. + - * [#20631](https://github.com/cosmos/cosmos-sdk/pull/20631) Fix json parsing in the wait-tx command. + - * (x/auth) [#20438](https://github.com/cosmos/cosmos-sdk/pull/20438) Add `--skip-signature-verification` flag to multisign command to allow nested multisigs. + - ## Bug Fixes + - * (simulation) [#17911](https://github.com/cosmos/cosmos-sdk/pull/17911) Fix all problems with executing command `make test-sim-custom-genesis-fast` for simulation test. + - * (simulation) [#18196](https://github.com/cosmos/cosmos-sdk/pull/18196) Fix the problem of `validator set is empty after InitGenesis` in simulation test. + - ## [v0.50.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.7) - 2024-06-04 + - ### Improvements + - * (debug) [#20328](https://github.com/cosmos/cosmos-sdk/pull/20328) Add consensus address for debug cmd. + - * (runtime) [#20264](https://github.com/cosmos/cosmos-sdk/pull/20264) Expose grpc query router via depinject. + - * (x/consensus) [#20381](https://github.com/cosmos/cosmos-sdk/pull/20381) Use Comet utility for consensus module consensus param updates. + - * (client) [#20356](https://github.com/cosmos/cosmos-sdk/pull/20356) Overwrite client context when available in `SetCmdClientContext`. + - ### Bug Fixes + - * (baseapp) [#20346](https://github.com/cosmos/cosmos-sdk/pull/20346) Correctly assign `execModeSimulate` to context for `simulateTx`. + - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. + - * (baseapp) [#20107](https://github.com/cosmos/cosmos-sdk/pull/20107) Avoid header height overwrite block height. + - * (cli) [#20020](https://github.com/cosmos/cosmos-sdk/pull/20020) Make bootstrap-state command support both new and legacy genesis format. + - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. + - ## [v0.50.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.6) - 2024-04-22 + - ### Features + - * (types) [#19759](https://github.com/cosmos/cosmos-sdk/pull/19759) Align SignerExtractionAdapter in PriorityNonceMempool Remove. + - * (client) [#19870](https://github.com/cosmos/cosmos-sdk/pull/19870) Add new query command `wait-tx`. Alias `event-query-tx-for` to `wait-tx` for backward compatibility. + - ### Improvements + - * (telemetry) [#19903](https://github.com/cosmos/cosmos-sdk/pull/19903) Conditionally emit metrics based on enablement. + - * **Introduction of `Now` Function**: Added a new function called `Now` to the telemetry package. It returns the current system time if telemetry is enabled, or a zero time if telemetry is not enabled. + - * **Atomic Global Variable**: Implemented an atomic global variable to manage the state of telemetry's enablement. This ensures thread safety for the telemetry state. + - * **Conditional Telemetry Emission**: All telemetry functions have been updated to emit metrics only when telemetry is enabled. They perform a check with `isTelemetryEnabled()` and return early if telemetry is disabled, minimizing unnecessary operations and overhead. + - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Upgrade prometheus version and fix API breaking change due to prometheus bump. + - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Bump `cosmossdk.io/store` to v1.1.0. + - * (server) [#19884](https://github.com/cosmos/cosmos-sdk/pull/19884) Add start customizability to start command options. + - * (x/gov) [#19853](https://github.com/cosmos/cosmos-sdk/pull/19853) Emit `depositor` in `EventTypeProposalDeposit`. + - * (x/gov) [#19844](https://github.com/cosmos/cosmos-sdk/pull/19844) Emit the proposer of governance proposals. + - * (baseapp) [#19616](https://github.com/cosmos/cosmos-sdk/pull/19616) Don't share gas meter in tx execution. + - ## Bug Fixes + - * (x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m) for `x/authz`. + - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19745) Fix tx sign doesn't throw an error when incorrect Ledger is used. + - * (baseapp) [#19970](https://github.com/cosmos/cosmos-sdk/pull/19970) Fix default config values to use no-op mempool as default. + - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. + - * (x/bank) [#20028](https://github.com/cosmos/cosmos-sdk/pull/20028) Align query with multi denoms for send-enabled. + - ## [v0.50.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.5) - 2024-03-12 + - ### Features + - * (baseapp) [#19626](https://github.com/cosmos/cosmos-sdk/pull/19626) Add `DisableBlockGasMeter` option to `BaseApp`, which removes the block gas meter during transaction execution. + - ### Improvements + - * (x/distribution) [#19707](https://github.com/cosmos/cosmos-sdk/pull/19707) Add autocli config for `DelegationTotalRewards` for CLI consistency with `q rewards` commands in previous versions. + - * (x/auth) [#19651](https://github.com/cosmos/cosmos-sdk/pull/19651) Allow empty public keys in `GetSignBytesAdapter`. + - ### Bug Fixes + - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from proposal.FinalTallyResult in the gprc query. + - * (types) [#19709](https://github.com/cosmos/cosmos-sdk/pull/19709) Fix skip staking genesis export when using `CoreAppModuleAdaptor` / `CoreAppModuleBasicAdaptor` for it. + - * (x/auth) [#19549](https://github.com/cosmos/cosmos-sdk/pull/19549) Accept custom get signers when injecting `x/auth/tx`. + - * (x/staking) Fix a possible bypass of delegator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) + - * (baseapp) Fix a bug in `baseapp.ValidateVoteExtensions` helper ([GHSA-95rx-m9m5-m94v](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-95rx-m9m5-m94v)). The helper has been fixed and for avoiding API breaking changes `currentHeight` and `chainID` arguments are ignored. Those arguments are removed from the helper in v0.51+. + - ## [v0.50.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.4) - 2024-02-19 + - ### Features + - * (server) [#19280](https://github.com/cosmos/cosmos-sdk/pull/19280) Adds in-place testnet CLI command. + - ### Improvements + - * (client) [#19393](https://github.com/cosmos/cosmos-sdk/pull/19393/) Add `ReadDefaultValuesFromDefaultClientConfig` to populate the default values from the default client config in client.Context without creating a app folder. + - ### Bug Fixes + - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. + - * (baseapp) [#19338](https://github.com/cosmos/cosmos-sdk/pull/19338) Set HeaderInfo in context when calling `setState`. + - * (baseapp): [#19200](https://github.com/cosmos/cosmos-sdk/pull/19200) Ensure that sdk side ve math matches cometbft. + - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. + - * (baseapp) [#19198](https://github.com/cosmos/cosmos-sdk/pull/19198) Remove usage of pointers in logs in all optimistic execution goroutines. + - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. + - * (crypto) [#19371](https://github.com/cosmos/cosmos-sdk/pull/19371) Avoid CLI redundant log in stdout, log to stderr instead. + - ## [v0.50.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.3) - 2024-01-15 + - ### Features + - * (types) [#18991](https://github.com/cosmos/cosmos-sdk/pull/18991) Add SignerExtractionAdapter to PriorityNonceMempool/Config and provide Default implementation matching existing behavior. + - * (gRPC) [#19043](https://github.com/cosmos/cosmos-sdk/pull/19043) Add `halt_height` to the gRPC `/cosmos/base/node/v1beta1/config` request. + - ### Improvements + - * (x/bank) [#18956](https://github.com/cosmos/cosmos-sdk/pull/18956) Introduced a new `DenomOwnersByQuery` query method for `DenomOwners`, which accepts the denom value as a query string parameter, resolving issues with denoms containing slashes. + - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. + - * (x/auth/tx) [#18772](https://github.com/cosmos/cosmos-sdk/pull/18772) Remove misleading gas wanted from tx simulation failure log. + - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. + - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 + - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 + - * (baseapp) [#18915](https://github.com/cosmos/cosmos-sdk/pull/18915) Add a new `ExecModeVerifyVoteExtension` exec mode and ensure it's populated in the `Context` during `VerifyVoteExtension` execution. + - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. + - ### Bug Fixes + - * (baseapp) [#19058](https://github.com/cosmos/cosmos-sdk/pull/19058) Fix baseapp posthandler branch would fail if the `runMsgs` had returned an error. + - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after module's beginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. + - * (baseapp) [#18895](https://github.com/cosmos/cosmos-sdk/pull/18895) Fix de-duplicating vote extensions during validation in ValidateVoteExtensions. + - ## [v0.50.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.2) - 2023-12-11 + - ### Features + - * (debug) [#18219](https://github.com/cosmos/cosmos-sdk/pull/18219) Add debug commands for application codec types. + - * (client/keys) [#17639](https://github.com/cosmos/cosmos-sdk/pull/17639) Allows using and saving public keys encoded as base64. + - * (server) [#17094](https://github.com/cosmos/cosmos-sdk/pull/17094) Add a `shutdown-grace` flag for waiting a given time before exit. + - ### Improvements + - * (telemetry) [#18646] (https://github.com/cosmos/cosmos-sdk/pull/18646) Enable statsd and dogstatsd telemetry sinks. + - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. + - * (x/gov) [#18025](https://github.com/cosmos/cosmos-sdk/pull/18025) Improve ` q gov proposer` by querying directly a proposal instead of tx events. It is an alias of `q gov proposal` as the proposer is a field of the proposal. + - * (version) [#18063](https://github.com/cosmos/cosmos-sdk/pull/18063) Allow to define extra info to be displayed in ` version --long` command. + - * (codec/unknownproto)[#18541](https://github.com/cosmos/cosmos-sdk/pull/18541) Remove the use of "protoc-gen-gogo/descriptor" in favour of using the official protobuf descriptorpb types inside unknownproto. + - ### Bug Fixes + - * (x/auth) [#18564](https://github.com/cosmos/cosmos-sdk/pull/18564) Fix total fees calculation when batch signing. + - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. + - * [#18531](https://github.com/cosmos/cosmos-sdk/pull/18531) Baseapp's `GetConsensusParams` returns an empty struct instead of panicking if no params are found. + - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. + - * (baseapp) [#18486](https://github.com/cosmos/cosmos-sdk/pull/18486) Fixed FinalizeBlock calls not being passed to ABCIListeners. + - * (baseapp) [#18627](https://github.com/cosmos/cosmos-sdk/pull/18627) Post handlers are run on non successful transaction executions too. + - * (baseapp) [#18654](https://github.com/cosmos/cosmos-sdk/pull/18654) Fixes an issue in which `gogoproto.Merge` does not work with gogoproto messages with custom types. + - ## [v0.50.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.1) - 2023-11-07 + - > v0.50.0 has been retracted due to a mistake in tagging the release. Please use v0.50.1 instead. + - ### Features + - * (baseapp) [#18071](https://github.com/cosmos/cosmos-sdk/pull/18071) Add hybrid handlers to `MsgServiceRouter`. + - * (server) [#18162](https://github.com/cosmos/cosmos-sdk/pull/18162) Start gRPC & API server in standalone mode. + - * (baseapp & types) [#17712](https://github.com/cosmos/cosmos-sdk/pull/17712) Introduce `PreBlock`, which runs before begin blocker other modules, and allows to modify consensus parameters, and the changes are visible to the following state machine logics. Additionally it can be used for vote extensions. + - * (genutil) [#17571](https://github.com/cosmos/cosmos-sdk/pull/17571) Allow creation of `AppGenesis` without a file lookup. + - * (codec) [#17042](https://github.com/cosmos/cosmos-sdk/pull/17042) Add `CollValueV2` which supports encoding of protov2 messages in collections. + - * (x/gov) [#16976](https://github.com/cosmos/cosmos-sdk/pull/16976) Add `failed_reason` field to `Proposal` under `x/gov` to indicate the reason for a failed proposal. Referenced from [#238](https://github.com/bnb-chain/greenfield-cosmos-sdk/pull/238) under `bnb-chain/greenfield-cosmos-sdk`. + - * (baseapp) [#16898](https://github.com/cosmos/cosmos-sdk/pull/16898) Add `preFinalizeBlockHook` to allow vote extensions persistence. + - * (cli) [#16887](https://github.com/cosmos/cosmos-sdk/pull/16887) Add two new CLI commands: ` tx simulate` for simulating a transaction; ` query block-results` for querying CometBFT RPC for block results. + - * (x/bank) [#16852](https://github.com/cosmos/cosmos-sdk/pull/16852) Add `DenomMetadataByQueryString` query in bank module to support metadata query by query string. + - * (baseapp) [#16581](https://github.com/cosmos/cosmos-sdk/pull/16581) Implement Optimistic Execution as an experimental feature (not enabled by default). + - * (types) [#16257](https://github.com/cosmos/cosmos-sdk/pull/16257) Allow setting the base denom in the denom registry. + - * (baseapp) [#16239](https://github.com/cosmos/cosmos-sdk/pull/16239) Add Gas Limits to allow node operators to resource bound queries. + - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Make `StartCmd` more customizable. + - * (types/simulation) [#16074](https://github.com/cosmos/cosmos-sdk/pull/16074) Add generic SimulationStoreDecoder for modules using collections. + - * (genutil) [#16046](https://github.com/cosmos/cosmos-sdk/pull/16046) Add "module-name" flag to genutil `add-genesis-account` to enable intializing module accounts at genesis.* [#15970](https://github.com/cosmos/cosmos-sdk/pull/15970) Enable SIGN_MODE_TEXTUAL. + - * (types) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Add `module.NewBasicManagerFromManager` for creating a basic module manager from a module manager. + - * (types/module) [#15829](https://github.com/cosmos/cosmos-sdk/pull/15829) Add new endblocker interface to handle valset updates. + - * (runtime) [#15818](https://github.com/cosmos/cosmos-sdk/pull/15818) Provide logger through `depinject` instead of appBuilder. + - * (types) [#15735](https://github.com/cosmos/cosmos-sdk/pull/15735) Make `ValidateBasic() error` method of `Msg` interface optional. Modules should validate messages directly in their message handlers ([RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation)). + - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) Allow applications to specify a custom genesis migration function for the `genesis migrate` command. + - * (telemetry) [#15657](https://github.com/cosmos/cosmos-sdk/pull/15657) Emit more data (go version, sdk version, upgrade height) in prom metrics. + - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) Add status endpoint for clients. + - * (testutil/integration) [#15556](https://github.com/cosmos/cosmos-sdk/pull/15556) Introduce `testutil/integration` package for module integration testing. + - * (runtime) [#15547](https://github.com/cosmos/cosmos-sdk/pull/15547) Allow runtime to pass event core api service to modules. + - * (client) [#15458](https://github.com/cosmos/cosmos-sdk/pull/15458) Add a `CmdContext` field to client.Context initialized to cobra command's context. + - * (x/genutil) [#15301](https://github.com/cosmos/cosmos-sdk/pull/15031) Add application genesis. The genesis is now entirely managed by the application and passed to CometBFT at note instantiation. Functions that were taking a `cmttypes.GenesisDoc{}` now takes a `genutiltypes.AppGenesis{}`. + - * (core) [#15133](https://github.com/cosmos/cosmos-sdk/pull/15133) Implement RegisterServices in the module manager. + - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Return a human readable denomination for IBC vouchers when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest` and `--resolve-denom` flag to `GetBalancesCmd()`. + - * (core) [#14860](https://github.com/cosmos/cosmos-sdk/pull/14860) Add `Precommit` and `PrepareCheckState` AppModule callbacks. + - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Upstream expedited proposals from Osmosis. + - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by events with queries directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. + - * (x/auth) [#14650](https://github.com/cosmos/cosmos-sdk/pull/14650) Add Textual SignModeHandler. Enable `SIGN_MODE_TEXTUAL` by following the [UPGRADING.md](./UPGRADING.md) instructions. + - * (x/crisis) [#14588](https://github.com/cosmos/cosmos-sdk/pull/14588) Use CacheContext() in AssertInvariants(). + - * (mempool) [#14484](https://github.com/cosmos/cosmos-sdk/pull/14484) Add priority nonce mempool option for transaction replacement. + - * (query) [#14468](https://github.com/cosmos/cosmos-sdk/pull/14468) Implement pagination for collections. + - * (x/gov) [#14373](https://github.com/cosmos/cosmos-sdk/pull/14373) Add new proto field `constitution` of type `string` to gov module genesis state, which allows chain builders to lay a strong foundation by specifying purpose. + - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) Add ` config` command is now a sub-command, for setting, getting and migrating Cosmos SDK configuration files. + - * (x/distribution) [#14322](https://github.com/cosmos/cosmos-sdk/pull/14322) Introduce a new gRPC message handler, `DepositValidatorRewardsPool`, that allows explicit funding of a validator's reward pool. + - * (x/bank) [#14224](https://github.com/cosmos/cosmos-sdk/pull/14224) Allow injection of restrictions on transfers using `AppendSendRestriction` or `PrependSendRestriction`. + - ### Improvements + - * (x/gov) [#18189](https://github.com/cosmos/cosmos-sdk/pull/18189) Limit the accepted deposit coins for a proposal to the minimum proposal deposit denoms. + - * (x/staking) [#18049](https://github.com/cosmos/cosmos-sdk/pull/18049) Return early if Slash encounters zero tokens to burn. + - * (x/staking) [#18035](https://github.com/cosmos/cosmos-sdk/pull/18035) Hoisted out of the redelegation loop, the non-changing validator and delegator addresses parsing. + - * (keyring) [#17913](https://github.com/cosmos/cosmos-sdk/pull/17913) Add `NewAutoCLIKeyring` for creating an AutoCLI keyring from a SDK keyring. + - * (x/consensus) [#18041](https://github.com/cosmos/cosmos-sdk/pull/18041) Let `ToProtoConsensusParams()` return an error. + - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. + - * (baseapp) [#17667](https://github.com/cosmos/cosmos-sdk/pull/17667) Close databases opened by SDK in `baseApp.Close()`. + - * (types/module) [#17554](https://github.com/cosmos/cosmos-sdk/pull/17554) Introduce `HasABCIGenesis` which is implemented by a module only when a validatorset update needs to be returned. + - * (cli) [#17389](https://github.com/cosmos/cosmos-sdk/pull/17389) gRPC CometBFT commands have been added under ` q consensus comet`. CometBFT commands placement in the SDK has been simplified. See the exhaustive list below. + - * `client/rpc.StatusCommand()` is now at `server.StatusCommand()` + - * (testutil) [#17216](https://github.com/cosmos/cosmos-sdk/issues/17216) Add `DefaultContextWithKeys` to `testutil` package. + - * (cli) [#17187](https://github.com/cosmos/cosmos-sdk/pull/17187) Do not use `ctx.PrintObjectLegacy` in commands anymore. + - * ` q gov proposer [proposal-id]` now returns a proposal id as int instead of string. + - * (x/staking) [#17164](https://github.com/cosmos/cosmos-sdk/pull/17164) Add `BondedTokensAndPubKeyByConsAddr` to the keeper to enable vote extension verification. + - * (x/group, x/gov) [#17109](https://github.com/cosmos/cosmos-sdk/pull/17109) Let proposal summary be 40x longer than metadata limit. + - * (version) [#17096](https://github.com/cosmos/cosmos-sdk/pull/17096) Improve `getSDKVersion()` to handle module replacements. + - * (types) [#16890](https://github.com/cosmos/cosmos-sdk/pull/16890) Remove `GetTxCmd() *cobra.Command` and `GetQueryCmd() *cobra.Command` from `module.AppModuleBasic` interface. + - * (x/authz) [#16869](https://github.com/cosmos/cosmos-sdk/pull/16869) Improve error message when grant not found. + - * (all) [#16497](https://github.com/cosmos/cosmos-sdk/pull/16497) Removed all exported vestiges of `sdk.MustSortJSON` and `sdk.SortJSON`. + - * (server) [#16238](https://github.com/cosmos/cosmos-sdk/pull/16238) Don't setup p2p node keys if starting a node in GRPC only mode. + - * (cli) [#16206](https://github.com/cosmos/cosmos-sdk/pull/16206) Make ABCI handshake profileable. + - * (types) [#16076](https://github.com/cosmos/cosmos-sdk/pull/16076) Optimize `ChainAnteDecorators`/`ChainPostDecorators` to instantiate the functions once instead of on every invocation of the returned `AnteHandler`/`PostHandler`. + - * (server) [#16071](https://github.com/cosmos/cosmos-sdk/pull/16071) When `mempool.max-txs` is set to a negative value, use a no-op mempool (effectively disable the app mempool). + - * (types/query) [#16041](https://github.com/cosmos/cosmos-sdk/pull/16041) Change pagination max limit to a variable in order to be modifed by application devs. + - * (simapp) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Refactor SimApp for removing the global basic manager. + - * (all modules) [#15901](https://github.com/cosmos/cosmos-sdk/issues/15901) All core Cosmos SDK modules query commands have migrated to [AutoCLI](https://docs.cosmos.network/main/core/autocli), ensuring parity between gRPC and CLI queries. + - * (x/auth) [#15867](https://github.com/cosmos/cosmos-sdk/pull/15867) Support better logging for signature verification failure. + - * (store/cachekv) [#15767](https://github.com/cosmos/cosmos-sdk/pull/15767) Reduce peak RAM usage during and after `InitGenesis`. + - * (x/bank) [#15764](https://github.com/cosmos/cosmos-sdk/pull/15764) Speedup x/bank `InitGenesis`. + - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) Refactor the validator's missed block signing window to be a chunked bitmap instead of a "logical" bitmap, significantly reducing the storage footprint. + - * (x/gov) [#15554](https://github.com/cosmos/cosmos-sdk/pull/15554) Add proposal result log in `active_proposal` event. When a proposal passes but fails to execute, the proposal result is logged in the `active_proposal` event. + - * (x/consensus) [#15553](https://github.com/cosmos/cosmos-sdk/pull/15553) Migrate consensus module to use collections. + - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Add `server.InterceptConfigsAndCreateContext` as alternative to `server.InterceptConfigsPreRunHandler` which does not set the server context and the default SDK logger. + - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) Improve the `PriorityNonceMempool`: + - * Support generic transaction prioritization, instead of `ctx.Priority()` + - * Improve construction through the use of a single `PriorityNonceMempoolConfig` instead of option functions + - * (x/authz) [#15164](https://github.com/cosmos/cosmos-sdk/pull/15164) Add `MsgCancelUnbondingDelegation` to staking authorization. + - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Remove unnecessary sleeps from gRPC and API server initiation. The servers will start and accept requests as soon as they're ready. + - * (baseapp) [#15023](https://github.com/cosmos/cosmos-sdk/pull/15023) & [#15213](https://github.com/cosmos/cosmos-sdk/pull/15213) Add `MessageRouter` interface to baseapp and pass it to authz, gov and groups instead of concrete type. + - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) Introduce `cosmossdk.io/log` package to provide a consistent logging interface through the SDK. CometBFT logger is now replaced by `cosmossdk.io/log.Logger`. + - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. + - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Allow transaction event queries to directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. + - * (x/evidence) [#14757](https://github.com/cosmos/cosmos-sdk/pull/14757) Evidence messages do not need to implement a `.Type()` anymore. + - * (x/auth/tx) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove `.Type()` and `Route()` methods from all msgs and `legacytx.LegacyMsg` interface. + - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by either height/hash ` q block --type=height|hash `. + - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) Return undelegate amount in MsgUndelegateResponse. + - * [#14529](https://github.com/cosmos/cosmos-sdk/pull/14529) Add new property `BondDenom` to `SimulationState` struct. + - * (store) [#14439](https://github.com/cosmos/cosmos-sdk/pull/14439) Remove global metric gatherer from store. + - * By default store has a no op metric gatherer, the application developer must set another metric gatherer or us the provided one in `store/metrics`. + - * (store) [#14438](https://github.com/cosmos/cosmos-sdk/pull/14438) Pass logger from baseapp to store. + - * (baseapp) [#14417](https://github.com/cosmos/cosmos-sdk/pull/14417) The store package no longer has a dependency on baseapp. + - * (module) [#14415](https://github.com/cosmos/cosmos-sdk/pull/14415) Loosen assertions in SetOrderBeginBlockers() and SetOrderEndBlockers(). + - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. + - * [#14406](https://github.com/cosmos/cosmos-sdk/issues/14406) Migrate usage of `types/store.go` to `store/types/..`. + - * (context)[#14384](https://github.com/cosmos/cosmos-sdk/pull/14384) Refactor(context): Pass EventManager to the context as an interface. + - * (types) [#14354](https://github.com/cosmos/cosmos-sdk/pull/14354) Improve performance on Context.KVStore and Context.TransientStore by 40%. + - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` + - * (signing) [#14087](https://github.com/cosmos/cosmos-sdk/pull/14087) Add SignModeHandlerWithContext interface with a new `GetSignBytesWithContext` to get the sign bytes using `context.Context` as an argument to access state. + - * (server) [#14062](https://github.com/cosmos/cosmos-sdk/pull/14062) Remove rosetta from server start. + - * (crypto) [#3129](https://github.com/cosmos/cosmos-sdk/pull/3129) New armor and keyring key derivation uses aead and encryption uses chacha20poly. + - ### State Machine Breaking + - * (x/gov) [#18146](https://github.com/cosmos/cosmos-sdk/pull/18146) Add denom check to reject denoms outside of those listed in `MinDeposit`. A new `MinDepositRatio` param is added (with a default value of `0.001`) and now deposits are required to be at least `MinDepositRatio*MinDeposit` to be accepted. + - * (x/group,x/gov) [#16235](https://github.com/cosmos/cosmos-sdk/pull/16235) A group and gov proposal is rejected if the proposal metadata title and summary do not match the proposal title and summary. + - * (baseapp) [#15930](https://github.com/cosmos/cosmos-sdk/pull/15930) change vote info provided by prepare and process proposal to the one in the block. + - * (x/staking) [#15731](https://github.com/cosmos/cosmos-sdk/pull/15731) Introducing a new index to retrieve the delegations by validator efficiently. + - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) The `HistoricalInfoKey` has been updated to use a binary format. + - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) The validator slashing window now stores "chunked" bitmap entries for each validator's signing window instead of a single boolean entry per signing window index. + - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. + - * (x/feegrant) [#14294](https://github.com/cosmos/cosmos-sdk/pull/14294) Moved the logic of rejecting duplicate grant from `msg_server` to `keeper` method. + - ### API Breaking Changes + - * (x/auth) [#17787](https://github.com/cosmos/cosmos-sdk/pull/17787) Remove Tip functionality. + - * (types) `module.EndBlockAppModule` has been replaced by Core API `appmodule.HasEndBlocker` or `module.HasABCIEndBlock` when needing validator updates. + - * (types) `module.BeginBlockAppModule` has been replaced by Core API `appmodule.HasBeginBlocker`. + - * (types) [#17358](https://github.com/cosmos/cosmos-sdk/pull/17358) Remove deprecated `sdk.Handler`, use `baseapp.MsgServiceHandler` instead. + - * (client) [#17197](https://github.com/cosmos/cosmos-sdk/pull/17197) `keys.Commands` does not take a home directory anymore. It is inferred from the root command. + - * (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. + - * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address + - * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. + - * `FromABCIEvidence` & `GetConsensusAddress(consAc address.Codec)` now take a consensus address codec to be able to decode the incoming address. + - * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function + - * (x/staking) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgCreateValidator`, `NewValidator`, `NewMsgCancelUnbondingDelegation`, `NewMsgUndelegate`, `NewMsgBeginRedelegate`, `NewMsgDelegate` and `NewMsgEditValidator` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`: + - * `NewRedelegation` and `NewUnbondingDelegation` takes a validatorAddressCodec and a delegatorAddressCodec in order to decode the addresses. + - * `NewRedelegationResponse` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. + - * `NewMsgCreateValidator.Validate()` takes an address codec in order to decode the address. + - * `BuildCreateValidatorMsg` takes a ValidatorAddressCodec in order to decode addresses. + - * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` + - * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses. + - * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. + - * (x/staking) [#16959](https://github.com/cosmos/cosmos-sdk/pull/16959) Add validator and consensus address codec as staking keeper arguments. + - * (x/staking) [#16958](https://github.com/cosmos/cosmos-sdk/pull/16958) DelegationI interface `GetDelegatorAddr` & `GetValidatorAddr` have been migrated to return string instead of sdk.AccAddress and sdk.ValAddress respectively. stakingtypes.NewDelegation takes a string instead of sdk.AccAddress and sdk.ValAddress. + - * (testutil) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) The *cli testutil* `QueryBalancesExec` has been removed. Use the gRPC or REST query instead. + - * (x/staking) [#16795](https://github.com/cosmos/cosmos-sdk/pull/16795) `DelegationToDelegationResponse`, `DelegationsToDelegationResponses`, `RedelegationsToRedelegationResponses` are no longer exported. + - * (x/auth/vesting) [#16741](https://github.com/cosmos/cosmos-sdk/pull/16741) Vesting account constructor now return an error with the result of their validate function. + - * (x/auth) [#16650](https://github.com/cosmos/cosmos-sdk/pull/16650) The *cli testutil* `QueryAccountExec` has been removed. Use the gRPC or REST query instead. + - * (x/auth) [#16621](https://github.com/cosmos/cosmos-sdk/pull/16621) Pass address codec to auth new keeper constructor. + - * (x/auth) [#16423](https://github.com/cosmos/cosmos-sdk/pull/16423) `helpers.AddGenesisAccount` has been moved to `x/genutil` to remove the cyclic dependency between `x/auth` and `x/genutil`. + - * (baseapp) [#16342](https://github.com/cosmos/cosmos-sdk/pull/16342) NewContext was renamed to NewContextLegacy. The replacement (NewContext) now does not take a header, instead you should set the header via `WithHeaderInfo` or `WithBlockHeight`. Note that `WithBlockHeight` will soon be depreacted and its recommneded to use `WithHeaderInfo`. + - * (x/mint) [#16329](https://github.com/cosmos/cosmos-sdk/pull/16329) Use collections for state management: + - * Removed: keeper `GetParams`, `SetParams`, `GetMinter`, `SetMinter`. + - * (x/crisis) [#16328](https://github.com/cosmos/cosmos-sdk/pull/16328) Use collections for state management: + - * Removed: keeper `GetConstantFee`, `SetConstantFee` + - * (x/staking) [#16324](https://github.com/cosmos/cosmos-sdk/pull/16324) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. Notable changes: + - * `Validator` method now returns `types.ErrNoValidatorFound` instead of `nil` when not found. + - * (x/distribution) [#16302](https://github.com/cosmos/cosmos-sdk/pull/16302) Use collections for FeePool state management. + - * Removed: keeper `GetFeePool`, `SetFeePool`, `GetFeePoolCommunityCoins` + - * (types) [#16272](https://github.com/cosmos/cosmos-sdk/pull/16272) `FeeGranter` in the `FeeTx` interface returns `[]byte` instead of `string`. + - * (x/gov) [#16268](https://github.com/cosmos/cosmos-sdk/pull/16268) Use collections for proposal state management (part 2): + - * this finalizes the gov collections migration + - * Removed: types all the key related functions + - * Removed: keeper `InsertActiveProposalsQueue`, `RemoveActiveProposalsQueue`, `InsertInactiveProposalsQueue`, `RemoveInactiveProposalsQueue`, `IterateInactiveProposalsQueue`, `IterateActiveProposalsQueue`, `ActiveProposalsQueueIterator`, `InactiveProposalsQueueIterator` + - * (x/slashing) [#16246](https://github.com/cosmos/cosmos-sdk/issues/16246) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. `GetValidatorSigningInfo` now returns an error instead of a `found bool`, the error can be `nil` (found), `ErrNoSigningInfoFound` (not found) and any other error. + - * (module) [#16227](https://github.com/cosmos/cosmos-sdk/issues/16227) `manager.RunMigrations()` now take a `context.Context` instead of a `sdk.Context`. + - * (x/crisis) [#16216](https://github.com/cosmos/cosmos-sdk/issues/16216) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` instead of panicking. + - * (x/distribution) [#16211](https://github.com/cosmos/cosmos-sdk/pull/16211) Use collections for params state management. + - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Add API `StartCmdWithOptions` to create customized start command. + - * (x/mint) [#16179](https://github.com/cosmos/cosmos-sdk/issues/16179) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. + - * (x/gov) [#16171](https://github.com/cosmos/cosmos-sdk/pull/16171) Use collections for proposal state management (part 1): + - * Removed: keeper: `GetProposal`, `UnmarshalProposal`, `MarshalProposal`, `IterateProposal`, `GetProposal`, `GetProposalFiltered`, `GetProposals`, `GetProposalID`, `SetProposalID` + - * Removed: errors unused errors + - * (x/gov) [#16164](https://github.com/cosmos/cosmos-sdk/pull/16164) Use collections for vote state management: + - * Removed: types `VoteKey`, `VoteKeys` + - * Removed: keeper `IterateVotes`, `IterateAllVotes`, `GetVotes`, `GetVote`, `SetVote` + - * (sims) [#16155](https://github.com/cosmos/cosmos-sdk/pull/16155) + - * `simulation.NewOperationMsg` now marshals the operation msg as proto bytes instead of legacy amino JSON bytes. + - * `simulation.NewOperationMsg` is now 2-arity instead of 3-arity with the obsolete argument `codec.ProtoCodec` removed. + - * The field `OperationMsg.Msg` is now of type `[]byte` instead of `json.RawMessage`. + - * (x/gov) [#16127](https://github.com/cosmos/cosmos-sdk/pull/16127) Use collections for deposit state management: + - * The following methods are removed from the gov keeper: `GetDeposit`, `GetAllDeposits`, `IterateAllDeposits`. + - * The following functions are removed from the gov types: `DepositKey`, `DepositsKey`. + - * (x/gov) [#16118](https://github.com/cosmos/cosmos-sdk/pull/16118/) Use collections for constituion and params state management. + - * (x/gov) [#16106](https://github.com/cosmos/cosmos-sdk/pull/16106) Remove gRPC query methods from gov keeper. + - * (x/*all*) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetSignBytes` implementations on messages and global legacy amino codec definitions have been removed from all modules. + - * (sims) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetOrGenerate` no longer requires a codec argument is now 4-arity instead of 5-arity. + - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16798) Remove aliases in `types/math.go` (part 2). + - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16040) Remove aliases in `types/math.go` (part 1). + - * (x/auth) [#16016](https://github.com/cosmos/cosmos-sdk/pull/16016) Use collections for accounts state management: + - * removed: keeper `HasAccountByID`, `AccountAddressByID`, `SetParams + - * (x/genutil) [#15999](https://github.com/cosmos/cosmos-sdk/pull/15999) Genutil now takes the `GenesisTxHanlder` interface instead of deliverTx. The interface is implemented on baseapp + - * (x/gov) [#15988](https://github.com/cosmos/cosmos-sdk/issues/15988) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` (instead of panicking or returning a `found bool`). Iterators callback functions now return an error instead of a `bool`. + - * (x/auth) [#15985](https://github.com/cosmos/cosmos-sdk/pull/15985) The `AccountKeeper` does not expose the `QueryServer` and `MsgServer` APIs anymore. + - * (x/authz) [#15962](https://github.com/cosmos/cosmos-sdk/issues/15962) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. The `Authorization` interface's `Accept` method now takes a `context.Context` instead of a `sdk.Context`. + - * (x/distribution) [#15948](https://github.com/cosmos/cosmos-sdk/issues/15948) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Keeper methods also now return an `error`. + - * (x/bank) [#15891](https://github.com/cosmos/cosmos-sdk/issues/15891) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Also `FundAccount` and `FundModuleAccount` from the `testutil` package accept a `context.Context` instead of a `sdk.Context`, and it's position was moved to the first place. + - * (x/slashing) [#15875](https://github.com/cosmos/cosmos-sdk/pull/15875) `x/slashing.NewAppModule` now requires an `InterfaceRegistry` parameter. + - * (x/crisis) [#15852](https://github.com/cosmos/cosmos-sdk/pull/15852) Crisis keeper now takes a instance of the address codec to be able to decode user addresses + - * (x/auth) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The type of struct field `ante.HandlerOptions.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. + - * (client) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The return type of the interface method `TxConfig.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. + - * The signature of `VerifySignature` has been changed to accept a `x/tx/signing.HandlerMap` and other structs from `x/tx` as arguments. + - * The signature of `NewTxConfigWithTextual` has been deprecated and its signature changed to accept a `SignModeOptions`. + - * The signature of `NewSigVerificationDecorator` has been changed to accept a `x/tx/signing.HandlerMap`. + - * (x/bank) [#15818](https://github.com/cosmos/cosmos-sdk/issues/15818) `BaseViewKeeper`'s `Logger` method now doesn't require a context. `NewBaseKeeper`, `NewBaseSendKeeper` and `NewBaseViewKeeper` now also require a `log.Logger` to be passed in. + - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) `MigrateGenesisCmd` now takes a `MigrationMap` instead of having the SDK genesis migration hardcoded. + - * (client) [#15673](https://github.com/cosmos/cosmos-sdk/pull/15673) Move `client/keys.OutputFormatJSON` and `client/keys.OutputFormatText` to `client/flags` package. + - * (x/*all*) [#15648](https://github.com/cosmos/cosmos-sdk/issues/15648) Make `SetParams` consistent across all modules and validate the params at the message handling instead of `SetParams` method. + - * (codec) [#15600](https://github.com/cosmos/cosmos-sdk/pull/15600) [#15873](https://github.com/cosmos/cosmos-sdk/pull/15873) add support for getting signers to `codec.Codec` and `InterfaceRegistry`: + - * `InterfaceRegistry` is has unexported methods and implements `protodesc.Resolver` plus the `RangeFiles` and `SigningContext` methods. All implementations of `InterfaceRegistry` by other users must now embed the official implementation. + - * `Codec` has new methods `InterfaceRegistry`, `GetMsgAnySigners`, `GetMsgV1Signers`, and `GetMsgV2Signers` as well as unexported methods. All implementations of `Codec` by other users must now embed an official implementation from the `codec` package. + - * `AminoCodec` is marked as deprecated and no longer implements `Codec. + - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) `RegisterNodeService` now requires a config parameter. + - * (x/nft) [#15588](https://github.com/cosmos/cosmos-sdk/pull/15588) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. + - * (baseapp) [#15568](https://github.com/cosmos/cosmos-sdk/pull/15568) `SetIAVLLazyLoading` is removed from baseapp. + - * (x/genutil) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `CollectGenTxsCmd` & `GenTxCmd` takes a address.Codec to be able to decode addresses. + - * (x/bank) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `GenesisBalance.GetAddress` now returns a string instead of `sdk.AccAddress` + - * `MsgSendExec` test helper function now takes a address.Codec + - * (x/auth) [#15520](https://github.com/cosmos/cosmos-sdk/pull/15520) `NewAccountKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) `runTxMode`s were renamed to `execMode`. `ModeDeliver` as changed to `ModeFinalize` and a new `ModeVoteExtension` was added for vote extensions. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Writing of state to the multistore was moved to `FinalizeBlock`. `Commit` still handles the committing values to disk. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Calls to BeginBlock and EndBlock have been replaced with core api beginblock & endblock. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock and EndBlock are now internal to baseapp. For testing, user must call `FinalizeBlock`. BeginBlock and EndBlock calls are internal to Baseapp. + - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) All calls to ABCI methods now accept a pointer of the abci request and response types + - * (x/consensus) [#15517](https://github.com/cosmos/cosmos-sdk/pull/15517) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`. + - * (x/bank) [#15477](https://github.com/cosmos/cosmos-sdk/pull/15477) `banktypes.NewMsgMultiSend` and `keeper.InputOutputCoins` only accept one input. + - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Remove `server.ErrorCode` that was not used anywhere. + - * (x/capability) [#15344](https://github.com/cosmos/cosmos-sdk/pull/15344) Capability module was removed and is now housed in [IBC-GO](https://github.com/cosmos/ibc-go). + - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) The `PriorityNonceMempool` is now generic over type `C comparable` and takes a single `PriorityNonceMempoolConfig[C]` argument. See `DefaultPriorityNonceMempoolConfig` for how to construct the configuration and a `TxPriority` type. + - * [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `StdTx` transaction and signing APIs. No SDK version has actually supported `StdTx` since before Stargate. + - * [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) + - * (x/gov) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. + - * (x/authx) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. + - * `types/tx.Tx` no longer implements `sdk.Tx`. + - * `sdk.Tx` now requires a new method `GetMsgsV2()`. + - * `sdk.Msg.GetSigners` was deprecated and is no longer supported. Use the `cosmos.msg.v1.signer` protobuf annotation instead. + - * `TxConfig` has a new method `SigningContext() *signing.Context`. + - * `SigVerifiableTx.GetSigners()` now returns `([][]byte, error)` instead of `[]sdk.AccAddress`. + - * `AccountKeeper` now has an `AddressCodec() address.Codec` method and the expected `AccountKeeper` for `x/auth/ante` expects this method. + - * [#15211](https://github.com/cosmos/cosmos-sdk/pull/15211) Remove usage of `github.com/cometbft/cometbft/libs/bytes.HexBytes` in favor of `[]byte` thorough the SDK. + - * (crypto) [#15070](https://github.com/cosmos/cosmos-sdk/pull/15070) `GenerateFromPassword` and `Cost` from `bcrypt.go` now take a `uint32` instead of a `int` type. + - * (types) [#15067](https://github.com/cosmos/cosmos-sdk/pull/15067) Remove deprecated alias from `types/errors`. Use `cosmossdk.io/errors` instead. + - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Refactor how gRPC and API servers are started to remove unnecessary sleeps: + - * `api.Server#Start` now accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the API server can gracefully exit. The caller does not need to stop the server. + - * To start the gRPC server you must first create the server via `NewGRPCServer`, after which you can start the gRPC server via `StartGRPCServer` which accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the gRPC server can gracefully exit. The caller does not need to stop the server. + - * Rename `WaitForQuitSignals` to `ListenForQuitSignals`. Note, this function is no longer blocking. Thus the caller is expected to provide a `context.CancelFunc` which indicates that when a signal is caught, that any spawned processes can gracefully exit. + - * Remove `ServerStartTime` constant. + - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) All functions that were taking a CometBFT logger, now take `cosmossdk.io/log.Logger` instead. + - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. + - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Allow a human readable denomination for coins when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest`. + - * [#14847](https://github.com/cosmos/cosmos-sdk/pull/14847) App and ModuleManager methods `InitGenesis`, `ExportGenesis`, `BeginBlock` and `EndBlock` now also return an error. + - * (x/upgrade) [#14764](https://github.com/cosmos/cosmos-sdk/pull/14764) The `x/upgrade` module is extracted to have a separate go.mod file which allows it to be a standalone module. + - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Refactor transaction searching: + - * Refactor `QueryTxsByEvents` to accept a `query` of type `string` instead of `events` of type `[]string` + - * Refactor CLI methods to accept `--query` flag instead of `--events` + - * Pass `prove=false` to Tendermint's `TxSearch` RPC method + - * (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct. + - * (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`. + - * (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`. + \ No newline at end of file diff --git a/docs/sdk/v0.53/learn/beginner/accounts.mdx b/docs/sdk/v0.53/core-concepts/accounts.mdx similarity index 100% rename from docs/sdk/v0.53/learn/beginner/accounts.mdx rename to docs/sdk/v0.53/core-concepts/accounts.mdx diff --git a/docs/sdk/v0.53/learn/beginner/app-anatomy.mdx b/docs/sdk/v0.53/core-concepts/app-anatomy.mdx similarity index 100% rename from docs/sdk/v0.53/learn/beginner/app-anatomy.mdx rename to docs/sdk/v0.53/core-concepts/app-anatomy.mdx diff --git a/docs/sdk/v0.53/learn/advanced/config.mdx b/docs/sdk/v0.53/core-concepts/config.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/config.mdx rename to docs/sdk/v0.53/core-concepts/config.mdx diff --git a/docs/sdk/v0.53/learn/advanced/context.mdx b/docs/sdk/v0.53/core-concepts/context.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/context.mdx rename to docs/sdk/v0.53/core-concepts/context.mdx diff --git a/docs/sdk/v0.53/learn/advanced/events.mdx b/docs/sdk/v0.53/core-concepts/events.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/events.mdx rename to docs/sdk/v0.53/core-concepts/events.mdx diff --git a/docs/sdk/v0.53/learn/advanced/node.mdx b/docs/sdk/v0.53/core-concepts/node.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/node.mdx rename to docs/sdk/v0.53/core-concepts/node.mdx diff --git a/docs/sdk/v0.53/learn/advanced/ocap.mdx b/docs/sdk/v0.53/core-concepts/ocap.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/ocap.mdx rename to docs/sdk/v0.53/core-concepts/ocap.mdx diff --git a/docs/sdk/v0.53/learn/intro/overview.mdx b/docs/sdk/v0.53/core-concepts/overview.mdx similarity index 100% rename from docs/sdk/v0.53/learn/intro/overview.mdx rename to docs/sdk/v0.53/core-concepts/overview.mdx diff --git a/docs/sdk/v0.53/learn/intro/sdk-app-architecture.mdx b/docs/sdk/v0.53/core-concepts/sdk-app-architecture.mdx similarity index 100% rename from docs/sdk/v0.53/learn/intro/sdk-app-architecture.mdx rename to docs/sdk/v0.53/core-concepts/sdk-app-architecture.mdx diff --git a/docs/sdk/v0.53/learn/intro/sdk-design.mdx b/docs/sdk/v0.53/core-concepts/sdk-design.mdx similarity index 100% rename from docs/sdk/v0.53/learn/intro/sdk-design.mdx rename to docs/sdk/v0.53/core-concepts/sdk-design.mdx diff --git a/docs/sdk/v0.53/learn/advanced/telemetry.mdx b/docs/sdk/v0.53/core-concepts/telemetry.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/telemetry.mdx rename to docs/sdk/v0.53/core-concepts/telemetry.mdx diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx b/docs/sdk/v0.53/core-concepts/what-is-an-oracle.mdx similarity index 100% rename from docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx rename to docs/sdk/v0.53/core-concepts/what-is-an-oracle.mdx diff --git a/docs/sdk/v0.53/learn/intro/why-app-specific.mdx b/docs/sdk/v0.53/core-concepts/why-app-specific.mdx similarity index 100% rename from docs/sdk/v0.53/learn/intro/why-app-specific.mdx rename to docs/sdk/v0.53/core-concepts/why-app-specific.mdx diff --git a/docs/sdk/v0.53/learn/advanced/encoding.mdx b/docs/sdk/v0.53/encoding-protobuf/encoding.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/encoding.mdx rename to docs/sdk/v0.53/encoding-protobuf/encoding.mdx diff --git a/docs/sdk/v0.53/learn/advanced/proto-docs.mdx b/docs/sdk/v0.53/encoding-protobuf/proto-docs.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/proto-docs.mdx rename to docs/sdk/v0.53/encoding-protobuf/proto-docs.mdx diff --git a/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx b/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx new file mode 100644 index 00000000..9b2b0b2d --- /dev/null +++ b/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx @@ -0,0 +1,136 @@ +--- +title: "ProtocolBuffer Annotations" + +--- + +--- + +--- + +This document explains the various protobuf scalars that have been added to make working with protobuf easier for Cosmos SDK application developers + +## Signer + +Signer specifies which field should be used to determine the signer of a message for the Cosmos SDK. This field can be used for clients as well to infer which field should be used to determine the signer of a message. + +Read more about the signer field [here](/docs/sdk/v0.53/02-messages-and-queries.md). + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/e6848d99b55a65d014375b295bdd7f9641aac95e/proto/cosmos/bank/v1beta1/tx.proto#L40 +``` + +```proto +option (cosmos.msg.v1.signer) = "from_address"; +``` + +## Scalar + +The scalar type defines a way for clients to understand how to construct protobuf messages according to what is expected by the module and sdk. + +```proto +(cosmos_proto.scalar) = "cosmos.AddressString" +``` + +Example of account address string scalar: + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e6848d99b55a65d014375b295bdd7f9641aac95e/proto/cosmos/bank/v1beta1/tx.proto#L46 +``` + +Example of validator address string scalar: + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/distribution/v1beta1/query.proto#L87 +``` + +Example of Decimals scalar: + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/distribution/v1beta1/distribution.proto#L26 +``` + +Example of Int scalar: + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/gov/v1/gov.proto#L137 +``` + +There are a few options for what can be provided as a scalar: `cosmos.AddressString`, `cosmos.ValidatorAddressString`, `cosmos.ConsensusAddressString`, `cosmos.Int`, `cosmos.Dec`. + +## Implements_Interface + +Implement interface is used to provide information to client tooling like [telescope](https://github.com/cosmology-tech/telescope) on how to encode and decode protobuf messages. + +```proto +option (cosmos_proto.implements_interface) = "cosmos.auth.v1beta1.AccountI"; +``` + +## Method,Field,Message Added In + +`method_added_in`, `field_added_in` and `message_added_in` are annotations to denotate to clients that a field has been supported in a later version. This is useful when new methods or fields are added in later versions and that the client needs to be aware of what it can call. + +The annotation should be worded as follow: + +```proto +option (cosmos_proto.method_added_in) = "cosmos-sdk v0.50.1"; +option (cosmos_proto.method_added_in) = "x/epochs v1.0.0"; +option (cosmos_proto.method_added_in) = "simapp v24.0.0"; +``` + +## Amino + +The amino codec was removed in `v0.50+`, this means there is not a need register `legacyAminoCodec`. To replace the amino codec, Amino protobuf annotations are used to provide information to the amino codec on how to encode and decode protobuf messages. + + +Amino annotations are only used for backwards compatibility with amino. New modules are not required use amino annotations. + + +The below annotations are used to provide information to the amino codec on how to encode and decode protobuf messages in a backwards compatible manner. + +### Name + +Name specifies the amino name that would show up for the user in order for them see which message they are signing. + +```proto +option (amino.name) = "cosmos-sdk/BaseAccount"; +``` + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/bank/v1beta1/tx.proto#L41 +``` + +### Field_Name + +Field name specifies the amino name that would show up for the user in order for them see which field they are signing. + +```proto +uint64 height = 1 [(amino.field_name) = "public_key"]; +``` + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/distribution/v1beta1/distribution.proto#L166 +``` + +### Dont_OmitEmpty + +Dont omitempty specifies that the field should not be omitted when encoding to amino. + +```proto +repeated cosmos.base.v1beta1.Coin amount = 3 [(amino.dont_omitempty) = true]; +``` + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/bank/v1beta1/bank.proto#L56 +``` + +### Encoding + +Encoding instructs the amino json marshaler how to encode certain fields that may differ from the standard encoding behaviour. The most common example of this is how `repeated cosmos.base.v1beta1.Coin` is encoded when using the amino json encoding format. The `legacy_coins` option tells the json marshaler [how to encode a null slice](https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/x/tx/signing/aminojson/json_marshal.go#L65) of `cosmos.base.v1beta1.Coin`. + +```proto +(amino.encoding) = "legacy_coins", +``` + +```proto reference +https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9d6/proto/cosmos/bank/v1beta1/genesis.proto#L23 +``` diff --git a/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx new file mode 100644 index 00000000..86e53729 --- /dev/null +++ b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx @@ -0,0 +1,140 @@ +--- +title: "Messages and Queries" + +--- + +--- + +--- + + +**Synopsis** +`Msg`s and `Queries` are the two primary objects handled by modules. Most of the core components defined in a module, like `Msg` services, `keeper`s and `Query` services, exist to process `message`s and `queries`. + + + +**Pre-requisite Readings** + +* [Introduction to Cosmos SDK Modules](./00-intro.md) + + + +## Messages + +`Msg`s are objects whose end-goal is to trigger state-transitions. They are wrapped in [transactions](../../learn/advanced/01-transactions.md), which may contain one or more of them. + +When a transaction is relayed from the underlying consensus engine to the Cosmos SDK application, it is first decoded by [`BaseApp`](../../learn/advanced/00-baseapp.md). Then, each message contained in the transaction is extracted and routed to the appropriate module via `BaseApp`'s `MsgServiceRouter` so that it can be processed by the module's [`Msg` service](/docs/sdk/v0.53/03-msg-services.md). For a more detailed explanation of the lifecycle of a transaction, click [here](../../learn/beginner/01-tx-lifecycle.md). + +### `Msg` Services + +Defining Protobuf `Msg` services is the recommended way to handle messages. A Protobuf `Msg` service should be created for each module, typically in `tx.proto` (see more info about [conventions and naming](../../learn/advanced/05-encoding.md#faq)). It must have an RPC service method defined for each message in the module. + +Each `Msg` service method must have exactly one argument, which must implement the `sdk.Msg` interface, and a Protobuf response. The naming convention is to call the RPC argument `Msg` and the RPC response `MsgResponse`. For example: + +```protobuf + rpc Send(MsgSend) returns (MsgSendResponse); +``` + +See an example of a `Msg` service definition from `x/bank` module: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/bank/v1beta1/tx.proto#L13-L36 +``` + +### `sdk.Msg` Interface + +`sdk.Msg` is a alias of `proto.Message`. + +To attach a `ValidateBasic()` method to a message then you must add methods to the type adhereing to the `HasValidateBasic`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/9c1e8b247cd47b5d3decda6e86fbc3bc996ee5d7/types/tx_msg.go#L84-L88 +``` + +In 0.50+ signers from the `GetSigners()` call is automated via a protobuf annotation. + +Read more about the signer field [here](/docs/sdk/v0.53/05-protobuf-annotations.md). + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/e6848d99b55a65d014375b295bdd7f9641aac95e/proto/cosmos/bank/v1beta1/tx.proto#L40 +``` + +If there is a need for custom signers then there is an alternative path which can be taken. A function which returns `signing.CustomGetSigner` for a specific message can be defined. + +```go +func ProvideBankSendTransactionGetSigners() signing.CustomGetSigner { + + // Extract the signer from the signature. + signer, err := coretypes.LatestSigner(Tx).Sender(ethTx) + if err != nil { + return nil, err + } + + // Return the signer in the required format. + return [][]byte{signer.Bytes()}, nil +} +``` + +When using dependency injection (depinject) this can be provided to the application via the provide method. + +```go +depinject.Provide(banktypes.ProvideBankSendTransactionGetSigners) +``` + +The Cosmos SDK uses Protobuf definitions to generate client and server code: + +* `MsgServer` interface defines the server API for the `Msg` service and its implementation is described as part of the [`Msg` services](/docs/sdk/v0.53/03-msg-services.md) documentation. +* Structures are generated for all RPC request and response types. + +A `RegisterMsgServer` method is also generated and should be used to register the module's `MsgServer` implementation in `RegisterServices` method from the [`AppModule` interface](/docs/sdk/v0.53/01-module-manager.md#appmodule). + +In order for clients (CLI and grpc-gateway) to have these URLs registered, the Cosmos SDK provides the function `RegisterMsgServiceDesc(registry codectypes.InterfaceRegistry, sd *grpc.ServiceDesc)` that should be called inside module's [`RegisterInterfaces`](01-module-manager.md#appmodulebasic) method, using the proto-generated `&_Msg_serviceDesc` as `*grpc.ServiceDesc` argument. + +## Queries + +A `query` is a request for information made by end-users of applications through an interface and processed by a full-node. A `query` is received by a full-node through its consensus engine and relayed to the application via the ABCI. It is then routed to the appropriate module via `BaseApp`'s `QueryRouter` so that it can be processed by the module's query service (./04-query-services.md). For a deeper look at the lifecycle of a `query`, click [here](../../learn/beginner/02-query-lifecycle.md). + +### gRPC Queries + +Queries should be defined using [Protobuf services](https://developers.google.com/protocol-buffers/docs/proto#services). A `Query` service should be created per module in `query.proto`. This service lists endpoints starting with `rpc`. + +Here's an example of such a `Query` service definition: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/auth/v1beta1/query.proto#L14-L89 +``` + +As `proto.Message`s, generated `Response` types implement by default `String()` method of [`fmt.Stringer`](https://pkg.go.dev/fmt#Stringer). + +A `RegisterQueryServer` method is also generated and should be used to register the module's query server in the `RegisterServices` method from the [`AppModule` interface](/docs/sdk/v0.53/01-module-manager.md#appmodule). + +### Legacy Queries + +Before the introduction of Protobuf and gRPC in the Cosmos SDK, there was usually no specific `query` object defined by module developers, contrary to `message`s. Instead, the Cosmos SDK took the simpler approach of using a simple `path` to define each `query`. The `path` contains the `query` type and all the arguments needed to process it. For most module queries, the `path` should look like the following: + +```text +queryCategory/queryRoute/queryType/arg1/arg2/... +``` + +where: + +* `queryCategory` is the category of the `query`, typically `custom` for module queries. It is used to differentiate between different kinds of queries within `BaseApp`'s [`Query` method](../../learn/advanced/00-baseapp.md#query). +* `queryRoute` is used by `BaseApp`'s [`queryRouter`](../../learn/advanced/00-baseapp.md#query-routing) to map the `query` to its module. Usually, `queryRoute` should be the name of the module. +* `queryType` is used by the module's [`querier`](/docs/sdk/v0.53/04-query-services.md#legacy-queriers) to map the `query` to the appropriate `querier function` within the module. +* `args` are the actual arguments needed to process the `query`. They are filled out by the end-user. Note that for bigger queries, you might prefer passing arguments in the `Data` field of the request `req` instead of the `path`. + +The `path` for each `query` must be defined by the module developer in the module's [command-line interface file](/docs/sdk/v0.53/09-module-interfaces.md#query-commands).Overall, there are 3 mains components module developers need to implement in order to make the subset of the state defined by their module queryable: + +* A [`querier`](/docs/sdk/v0.53/04-query-services.md#legacy-queriers), to process the `query` once it has been [routed to the module](../../learn/advanced/00-baseapp.md#query-routing). +* [Query commands](/docs/sdk/v0.53/09-module-interfaces.md#query-commands) in the module's CLI file, where the `path` for each `query` is specified. +* `query` return types. Typically defined in a file `types/querier.go`, they specify the result type of each of the module's `queries`. These custom types must implement the `String()` method of [`fmt.Stringer`](https://pkg.go.dev/fmt#Stringer). + +### Store Queries + +Store queries query directly for store keys. They use `clientCtx.QueryABCI(req abci.RequestQuery)` to return the full `abci.ResponseQuery` with inclusion Merkle proofs. + +See following examples: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/baseapp/abci.go#L864-L894 +``` diff --git a/docs/sdk/v0.53/messaging-queries/msg-services.mdx b/docs/sdk/v0.53/messaging-queries/msg-services.mdx new file mode 100644 index 00000000..b885d58b --- /dev/null +++ b/docs/sdk/v0.53/messaging-queries/msg-services.mdx @@ -0,0 +1,124 @@ +--- +title: "`Msg` Services" + +--- + +--- + +--- + + +**Synopsis** +A Protobuf `Msg` service processes [messages](./02-messages-and-queries.md#messages). Protobuf `Msg` services are specific to the module in which they are defined, and only process messages defined within the said module. They are called from `BaseApp` during [`DeliverTx`](../../learn/advanced/00-baseapp.md#delivertx). + + + +**Pre-requisite Readings** + +* [Module Manager](./01-module-manager.md) +* [Messages and Queries](./02-messages-and-queries.md) + + + +## Implementation of a module `Msg` service + +Each module should define a Protobuf `Msg` service, which will be responsible for processing requests (implementing `sdk.Msg`) and returning responses. + +As further described in [ADR 031](../architecture/adr-031-msg-service.md), this approach has the advantage of clearly specifying return types and generating server and client code. + +Protobuf generates a `MsgServer` interface based on a definition of `Msg` service. It is the role of the module developer to implement this interface, by implementing the state transition logic that should happen upon receival of each `sdk.Msg`. As an example, here is the generated `MsgServer` interface for `x/bank`, which exposes two `sdk.Msg`s: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/types/tx.pb.go#L550-L568 +``` + +When possible, the existing module's [`Keeper`](/docs/sdk/v0.53/06-keeper.md) should implement `MsgServer`, otherwise a `msgServer` struct that embeds the `Keeper` can be created, typically in `./keeper/msg_server.go`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/msg_server.go#L17-L19 +``` + +`msgServer` methods can retrieve the `context.Context` from the `context.Context` parameter method using the `sdk.UnwrapSDKContext`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/msg_server.go#L56 +``` + +`sdk.Msg` processing usually follows these 3 steps: + +### Validation + +The message server must perform all validation required (both *stateful* and *stateless*) to make sure the `message` is valid. +The `signer` is charged for the gas cost of this validation. + +For example, a `msgServer` method for a `transfer` message should check that the sending account has enough funds to actually perform the transfer. + +It is recommended to implement all validation checks in a separate function that passes state values as arguments. This implementation simplifies testing. As expected, expensive validation functions charge additional gas. Example: + +```go +ValidateMsgA(msg MsgA, now Time, gm GasMeter) error { + if now.Before(msg.Expire) { + return sdkerrrors.ErrInvalidRequest.Wrap("msg expired") + } + gm.ConsumeGas(1000, "signature verification") + return signatureVerificaton(msg.Prover, msg.Data) +} +``` + + +Previously, the `ValidateBasic` method was used to perform simple and stateless validation checks. +This way of validating is deprecated, this means the `msgServer` must perform all validation checks. + + +### State Transition + +After the validation is successful, the `msgServer` method uses the [`keeper`](/docs/sdk/v0.53/06-keeper.md) functions to access the state and perform a state transition. + +### Events + +Before returning, `msgServer` methods generally emit one or more [events](../../learn/advanced/08-events.md) by using the `EventManager` held in the `ctx`. Use the new `EmitTypedEvent` function that uses protobuf-based event types: + +```go +ctx.EventManager().EmitTypedEvent( + &group.EventABC{Key1: Value1, Key2, Value2}) +``` + +or the older `EmitEvent` function: + +```go +ctx.EventManager().EmitEvent( + sdk.NewEvent( + eventType, // e.g. sdk.EventTypeMessage for a message, types.CustomEventType for a custom event defined in the module + sdk.NewAttribute(key1, value1), + sdk.NewAttribute(key2, value2), + ), +) +``` + +These events are relayed back to the underlying consensus engine and can be used by service providers to implement services around the application. Click [here](../../learn/advanced/08-events.md) to learn more about events. + +The invoked `msgServer` method returns a `proto.Message` response and an `error`. These return values are then wrapped into an `*sdk.Result` or an `error` using `sdk.WrapServiceResult(ctx context.Context, res proto.Message, err error)`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/baseapp/msg_service_router.go#L160 +``` + +This method takes care of marshaling the `res` parameter to protobuf and attaching any events on the `ctx.EventManager()` to the `sdk.Result`. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/base/abci/v1beta1/abci.proto#L93-L113 +``` + +This diagram shows a typical structure of a Protobuf `Msg` service, and how the message propagates through the module. + +![Transaction flow](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/transaction_flow.svg) + +## Telemetry + +New [telemetry metrics](../../learn/advanced/09-telemetry.md) can be created from `msgServer` methods when handling messages. + +This is an example from the `x/auth/vesting` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/vesting/msg_server.go#L76-L88 +``` diff --git a/docs/sdk/v0.53/learn/beginner/query-lifecycle.mdx b/docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx similarity index 100% rename from docs/sdk/v0.53/learn/beginner/query-lifecycle.mdx rename to docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx diff --git a/docs/sdk/v0.53/messaging-queries/query-services.mdx b/docs/sdk/v0.53/messaging-queries/query-services.mdx new file mode 100644 index 00000000..15f45e2e --- /dev/null +++ b/docs/sdk/v0.53/messaging-queries/query-services.mdx @@ -0,0 +1,62 @@ +--- +title: "Query Services" + +--- + +--- + +--- + + +**Synopsis** +A Protobuf Query service processes [`queries`](./02-messages-and-queries.md#queries). Query services are specific to the module in which they are defined, and only process `queries` defined within said module. They are called from `BaseApp`'s [`Query` method](../../learn/advanced/00-baseapp.md#query). + + + +**Pre-requisite Readings** + +* [Module Manager](./01-module-manager.md) +* [Messages and Queries](./02-messages-and-queries.md) + + + +## Implementation of a module query service + +### gRPC Service + +When defining a Protobuf `Query` service, a `QueryServer` interface is generated for each module with all the service methods: + +```go +type QueryServer interface { + QueryBalance(context.Context, *QueryBalanceParams) (*types.Coin, error) + QueryAllBalances(context.Context, *QueryAllBalancesParams) (*QueryAllBalancesResponse, error) +} +``` + +These custom queries methods should be implemented by a module's keeper, typically in `./keeper/grpc_query.go`. The first parameter of these methods is a generic `context.Context`. Therefore, the Cosmos SDK provides a function `sdk.UnwrapSDKContext` to retrieve the `context.Context` from the provided +`context.Context`. + +Here's an example implementation for the bank module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/grpc_query.go +``` + +### Calling queries from the State Machine + +The Cosmos SDK v0.47 introduces a new `cosmos.query.v1.module_query_safe` Protobuf annotation which is used to state that a query that is safe to be called from within the state machine, for example: + +* a Keeper's query function can be called from another module's Keeper, +* ADR-033 intermodule query calls, +* CosmWasm contracts can also directly interact with these queries. + +If the `module_query_safe` annotation set to `true`, it means: + +* The query is deterministic: given a block height it will return the same response upon multiple calls, and doesn't introduce any state-machine breaking changes across SDK patch versions. +* Gas consumption never fluctuates across calls and across patch versions. + +If you are a module developer and want to use `module_query_safe` annotation for your own query, you have to ensure the following things: + +* the query is deterministic and won't introduce state-machine-breaking changes without coordinated upgrades +* it has its gas tracked, to avoid the attack vector where no gas is accounted for + on potentially high-computation queries. diff --git a/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx new file mode 100644 index 00000000..a42546c3 --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx @@ -0,0 +1,60 @@ +--- +title: "Errors" + +--- + +--- + +--- + + +**Synopsis** +This document outlines the recommended usage and APIs for error handling in Cosmos SDK modules. + + +Modules are encouraged to define and register their own errors to provide better +context on failed message or handler execution. Typically, these errors should be +common or general errors which can be further wrapped to provide additional specific +execution context. + +## Registration + +Modules should define and register their custom errors in `x/{module}/errors.go`. +Registration of errors is handled via the [`errors` package](https://github.com/cosmos/cosmos-sdk/blob/main/errors/errors.go). + +Example: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/distribution/types/errors.go +``` + +Each custom module error must provide the codespace, which is typically the module name +(e.g. "distribution") and is unique per module, and a uint32 code. Together, the codespace and code +provide a globally unique Cosmos SDK error. Typically, the code is monotonically increasing but does not +necessarily have to be. The only restrictions on error codes are the following: + +* Must be greater than one, as a code value of one is reserved for internal errors. +* Must be unique within the module. + +Note, the Cosmos SDK provides a core set of *common* errors. These errors are defined in [`types/errors/errors.go`](https://github.com/cosmos/cosmos-sdk/blob/main/types/errors/errors.go). + +## Wrapping + +The custom module errors can be returned as their concrete type as they already fulfill the `error` +interface. However, module errors can be wrapped to provide further context and meaning to failed +execution. + +Example: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/keeper.go#L141-L182 +``` + +Regardless if an error is wrapped or not, the Cosmos SDK's `errors` package provides a function to determine if +an error is of a particular kind via `Is`. + +## ABCI + +If a module error is registered, the Cosmos SDK `errors` package allows ABCI information to be extracted +through the `ABCIInfo` function. The package also provides `ResponseCheckTx` and `ResponseDeliverTx` as +auxiliary functions to automatically get `CheckTx` and `DeliverTx` responses from an error. diff --git a/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx b/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx new file mode 100644 index 00000000..5ca509a6 --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx @@ -0,0 +1,83 @@ +--- +title: "Module Genesis" + +--- + +--- + +--- + + +**Synopsis** +Modules generally handle a subset of the state and, as such, they need to define the related subset of the genesis file as well as methods to initialize, verify and export it. + + + +**Pre-requisite Readings** + +* [Module Manager](./01-module-manager.md) +* [Keepers](./06-keeper.md) + + + +## Type Definition + +The subset of the genesis state defined from a given module is generally defined in a `genesis.proto` file ([more info](../../learn/advanced/05-encoding.md#gogoproto) on how to define protobuf messages). The struct defining the module's subset of the genesis state is usually called `GenesisState` and contains all the module-related values that need to be initialized during the genesis process. + +See an example of `GenesisState` protobuf message definition from the `auth` module: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/auth/v1beta1/genesis.proto +``` + +Next we present the main genesis-related methods that need to be implemented by module developers in order for their module to be used in Cosmos SDK applications. + +### `DefaultGenesis` + +The `DefaultGenesis()` method is a simple method that calls the constructor function for `GenesisState` with the default value for each parameter. See an example from the `auth` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/module.go#L63-L67 +``` + +### `ValidateGenesis` + +The `ValidateGenesis(data GenesisState)` method is called to verify that the provided `genesisState` is correct. It should perform validity checks on each of the parameters listed in `GenesisState`. See an example from the `auth` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/types/genesis.go#L62-L75 +``` + +## Other Genesis Methods + +Other than the methods related directly to `GenesisState`, module developers are expected to implement two other methods as part of the [`AppModuleGenesis` interface](/docs/sdk/v0.53/01-module-manager.md#appmodulegenesis) (only if the module needs to initialize a subset of state in genesis). These methods are [`InitGenesis`](#initgenesis) and [`ExportGenesis`](#exportgenesis). + +### `InitGenesis` + +The `InitGenesis` method is executed during [`InitChain`](../../learn/advanced/00-baseapp.md#initchain) when the application is first started. Given a `GenesisState`, it initializes the subset of the state managed by the module by using the module's [`keeper`](/docs/sdk/v0.53/06-keeper.md) setter function on each parameter within the `GenesisState`. + +The [module manager](/docs/sdk/v0.53/01-module-manager.md#manager) of the application is responsible for calling the `InitGenesis` method of each of the application's modules in order. This order is set by the application developer via the manager's `SetOrderGenesisMethod`, which is called in the [application's constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). + +See an example of `InitGenesis` from the `auth` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/keeper/genesis.go#L8-L35 +``` + +### `ExportGenesis` + +The `ExportGenesis` method is executed whenever an export of the state is made. It takes the latest known version of the subset of the state managed by the module and creates a new `GenesisState` out of it. This is mainly used when the chain needs to be upgraded via a hard fork. + +See an example of `ExportGenesis` from the `auth` module. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/keeper/genesis.go#L37-L49 +``` + +### GenesisTxHandler + +`GenesisTxHandler` is a way for modules to submit state transitions prior to the first block. This is used by `x/genutil` to submit the genesis transactions for the validators to be added to staking. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/core/genesis/txhandler.go#L3-L6 +``` diff --git a/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx new file mode 100644 index 00000000..21ab3d11 --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx @@ -0,0 +1,95 @@ +--- +title: "Invariants" + +--- + +--- + +--- + + +**Synopsis** +An invariant is a property of the application that should always be true. In the context of the Cosmos SDK, an `Invariant` is a function that checks for a particular invariant. These functions are useful to detect bugs early on and act upon them to limit their potential consequences (e.g. by halting the chain). They are also useful in the development process of the application to detect bugs via simulations. + + + +**Pre-requisite Readings** + +* [Keepers](./06-keeper.md) + + + +## Implementing `Invariant`s + +An `Invariant` is a function that checks for a particular invariant within a module. Module `Invariant`s must follow the `Invariant` type: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/invariant.go#L9 +``` + +The `string` return value is the invariant message, which can be used when printing logs, and the `bool` return value is the actual result of the invariant check. + +In practice, each module implements `Invariant`s in a `keeper/invariants.go` file within the module's folder. The standard is to implement one `Invariant` function per logical grouping of invariants with the following model: + +```go +// Example for an Invariant that checks balance-related invariants + +func BalanceInvariants(k Keeper) sdk.Invariant { + return func(ctx context.Context) (string, bool) { + // Implement checks for balance-related invariants + } +} +``` + +Additionally, module developers should generally implement an `AllInvariants` function that runs all the `Invariant`s functions of the module: + +```go +// AllInvariants runs all invariants of the module. +// In this example, the module implements two Invariants: BalanceInvariants and DepositsInvariants + +func AllInvariants(k Keeper) sdk.Invariant { + + return func(ctx context.Context) (string, bool) { + res, stop := BalanceInvariants(k)(ctx) + if stop { + return res, stop + } + + return DepositsInvariant(k)(ctx) + } +} +``` + +Finally, module developers need to implement the `RegisterInvariants` method as part of the [`AppModule` interface](/docs/sdk/v0.53/01-module-manager.md#appmodule). Indeed, the `RegisterInvariants` method of the module, implemented in the `module/module.go` file, typically only defers the call to a `RegisterInvariants` method implemented in the `keeper/invariants.go` file. The `RegisterInvariants` method registers a route for each `Invariant` function in the [`InvariantRegistry`](#invariant-registry): + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/staking/keeper/invariants.go#L12-L22 +``` + +For more, see an example of [`Invariant`s implementation from the `staking` module](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/staking/keeper/invariants.go). + +## Invariant Registry + +The `InvariantRegistry` is a registry where the `Invariant`s of all the modules of an application are registered. There is only one `InvariantRegistry` per **application**, meaning module developers need not implement their own `InvariantRegistry` when building a module. **All module developers need to do is to register their modules' invariants in the `InvariantRegistry`, as explained in the section above**. The rest of this section gives more information on the `InvariantRegistry` itself, and does not contain anything directly relevant to module developers. + +At its core, the `InvariantRegistry` is defined in the Cosmos SDK as an interface: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/invariant.go#L14-L17 +``` + +Typically, this interface is implemented in the `keeper` of a specific module. The most used implementation of an `InvariantRegistry` can be found in the `crisis` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/crisis/keeper/keeper.go#L48-L50 +``` + +The `InvariantRegistry` is therefore typically instantiated by instantiating the `keeper` of the `crisis` module in the [application's constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). + +`Invariant`s can be checked manually via [`message`s](/docs/sdk/v0.53/02-messages-and-queries.md), but most often they are checked automatically at the end of each block. Here is an example from the `crisis` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/crisis/abci.go#L13-L23 +``` + +In both cases, if one of the `Invariant`s returns false, the `InvariantRegistry` can trigger special logic (e.g. have the application panic and print the `Invariant`s message in the log). diff --git a/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx new file mode 100644 index 00000000..a3c903a2 --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx @@ -0,0 +1,97 @@ +--- +title: "Keepers" + +--- + +--- + +--- + + +**Synopsis** +`Keeper`s refer to a Cosmos SDK abstraction whose role is to manage access to the subset of the state defined by various modules. `Keeper`s are module-specific, i.e. the subset of state defined by a module can only be accessed by a `keeper` defined in said module. If a module needs to access the subset of state defined by another module, a reference to the second module's internal `keeper` needs to be passed to the first one. This is done in `app.go` during the instantiation of module keepers. + + + +**Pre-requisite Readings** + +* [Introduction to Cosmos SDK Modules](./00-intro.md) + + + +## Motivation + +The Cosmos SDK is a framework that makes it easy for developers to build complex decentralized applications from scratch, mainly by composing modules together. As the ecosystem of open-source modules for the Cosmos SDK expands, it will become increasingly likely that some of these modules contain vulnerabilities, as a result of the negligence or malice of their developer. + +The Cosmos SDK adopts an [object-capabilities-based approach](../../learn/advanced/10-ocap.md) to help developers better protect their application from unwanted inter-module interactions, and `keeper`s are at the core of this approach. A `keeper` can be considered quite literally to be the gatekeeper of a module's store(s). Each store (typically an [`IAVL` Store](../../learn/advanced/04-store.md#iavl-store)) defined within a module comes with a `storeKey`, which grants unlimited access to it. The module's `keeper` holds this `storeKey` (which should otherwise remain unexposed), and defines [methods](#implementing-methods) for reading and writing to the store(s). + +The core idea behind the object-capabilities approach is to only reveal what is necessary to get the work done. In practice, this means that instead of handling permissions of modules through access-control lists, module `keeper`s are passed a reference to the specific instance of the other modules' `keeper`s that they need to access (this is done in the [application's constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function)). As a consequence, a module can only interact with the subset of state defined in another module via the methods exposed by the instance of the other module's `keeper`. This is a great way for developers to control the interactions that their own module can have with modules developed by external developers. + +## Type Definition + +`keeper`s are generally implemented in a `/keeper/keeper.go` file located in the module's folder. By convention, the type `keeper` of a module is simply named `Keeper` and usually follows the following structure: + +```go +type Keeper struct { + // External keepers, if any + + // Store key(s) + + // codec + + // authority +} +``` + +For example, here is the type definition of the `keeper` from the `staking` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/staking/keeper/keeper.go#L23-L31 +``` + +Let us go through the different parameters: + +* An expected `keeper` is a `keeper` external to a module that is required by the internal `keeper` of said module. External `keeper`s are listed in the internal `keeper`'s type definition as interfaces. These interfaces are themselves defined in an `expected_keepers.go` file in the root of the module's folder. In this context, interfaces are used to reduce the number of dependencies, as well as to facilitate the maintenance of the module itself. +* `storeKey`s grant access to the store(s) of the [multistore](../../learn/advanced/04-store.md) managed by the module. They should always remain unexposed to external modules. +* `cdc` is the [codec](../../learn/advanced/05-encoding.md) used to marshall and unmarshall structs to/from `[]byte`. The `cdc` can be any of `codec.BinaryCodec`, `codec.JSONCodec` or `codec.Codec` based on your requirements. It can be either a proto or amino codec as long as they implement these interfaces. +* The authority listed is a module account or user account that has the right to change module level parameters. Previously this was handled by the param module, which has been deprecated. + +Of course, it is possible to define different types of internal `keeper`s for the same module (e.g. a read-only `keeper`). Each type of `keeper` comes with its own constructor function, which is called from the [application's constructor function](../../learn/beginner/00-app-anatomy.md). This is where `keeper`s are instantiated, and where developers make sure to pass correct instances of modules' `keeper`s to other modules that require them. + +## Implementing Methods + +`Keeper`s primarily expose getter and setter methods for the store(s) managed by their module. These methods should remain as simple as possible and strictly be limited to getting or setting the requested value, as validity checks should have already been performed by the [`Msg` server](/docs/sdk/v0.53/03-msg-services.md) when `keeper`s' methods are called. + +Typically, a *getter* method will have the following signature + +```go +func (k Keeper) Get(ctx context.Context, key string) returnType +``` + +and the method will go through the following steps: + +1. Retrieve the appropriate store from the `ctx` using the `storeKey`. This is done through the `KVStore(storeKey sdk.StoreKey)` method of the `ctx`. Then it's preferred to use the `prefix.Store` to access only the desired limited subset of the store for convenience and safety. +2. If it exists, get the `[]byte` value stored at location `[]byte(key)` using the `Get(key []byte)` method of the store. +3. Unmarshall the retrieved value from `[]byte` to `returnType` using the codec `cdc`. Return the value. + +Similarly, a *setter* method will have the following signature + +```go +func (k Keeper) Set(ctx context.Context, key string, value valueType) +``` + +and the method will go through the following steps: + +1. Retrieve the appropriate store from the `ctx` using the `storeKey`. This is done through the `KVStore(storeKey sdk.StoreKey)` method of the `ctx`. It's preferred to use the `prefix.Store` to access only the desired limited subset of the store for convenience and safety. +2. Marshal `value` to `[]byte` using the codec `cdc`. +3. Set the encoded value in the store at location `key` using the `Set(key []byte, value []byte)` method of the store. + +For more, see an example of `keeper`'s [methods implementation from the `staking` module](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/staking/keeper/keeper.go). + +The [module `KVStore`](../../learn/advanced/04-store.md#kvstore-and-commitkvstore-interfaces) also provides an `Iterator()` method which returns an `Iterator` object to iterate over a domain of keys. + +This is an example from the `auth` module to iterate accounts: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/keeper/account.go +``` diff --git a/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx new file mode 100644 index 00000000..777311bd --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx @@ -0,0 +1,169 @@ +--- +title: "Module Interfaces" + +--- + +--- + +--- + + +**Synopsis** +This document details how to build CLI and REST interfaces for a module. Examples from various Cosmos SDK modules are included. + + + +**Pre-requisite Readings** + +* [Building Modules Intro](./00-intro.md) + + + +## CLI + +One of the main interfaces for an application is the [command-line interface](../../learn/advanced/07-cli.md). This entrypoint adds commands from the application's modules enabling end-users to create [**messages**](/docs/sdk/v0.53/02-messages-and-queries.md#messages) wrapped in transactions and [**queries**](/docs/sdk/v0.53/02-messages-and-queries.md#queries). The CLI files are typically found in the module's `./client/cli` folder. + +### Transaction Commands + +In order to create messages that trigger state changes, end-users must create [transactions](../../learn/advanced/01-transactions.md) that wrap and deliver the messages. A transaction command creates a transaction that includes one or more messages. + +Transaction commands typically have their own `tx.go` file that lives within the module's `./client/cli` folder. The commands are specified in getter functions and the name of the function should include the name of the command. + +Here is an example from the `x/bank` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/client/cli/tx.go#L37-L76 +``` + +In the example, `NewSendTxCmd()` creates and returns the transaction command for a transaction that wraps and delivers `MsgSend`. `MsgSend` is the message used to send tokens from one account to another. + +In general, the getter function does the following: + +* **Constructs the command:** Read the [Cobra Documentation](https://pkg.go.dev/github.com/spf13/cobra) for more detailed information on how to create commands. + * **Use:** Specifies the format of the user input required to invoke the command. In the example above, `send` is the name of the transaction command and `[from_key_or_address]`, `[to_address]`, and `[amount]` are the arguments. + * **Args:** The number of arguments the user provides. In this case, there are exactly three: `[from_key_or_address]`, `[to_address]`, and `[amount]`. + * **Short and Long:** Descriptions for the command. A `Short` description is expected. A `Long` description can be used to provide additional information that is displayed when a user adds the `--help` flag. + * **RunE:** Defines a function that can return an error. This is the function that is called when the command is executed. This function encapsulates all of the logic to create a new transaction. + * The function typically starts by getting the `clientCtx`, which can be done with `client.GetClientTxContext(cmd)`. The `clientCtx` contains information relevant to transaction handling, including information about the user. In this example, the `clientCtx` is used to retrieve the address of the sender by calling `clientCtx.GetFromAddress()`. + * If applicable, the command's arguments are parsed. In this example, the arguments `[to_address]` and `[amount]` are both parsed. + * A [message](/docs/sdk/v0.53/02-messages-and-queries.md) is created using the parsed arguments and information from the `clientCtx`. The constructor function of the message type is called directly. In this case, `types.NewMsgSend(fromAddr, toAddr, amount)`. Its good practice to call, if possible, the necessary [message validation methods](../building-modules/03-msg-services.md#Validation) before broadcasting the message. + * Depending on what the user wants, the transaction is either generated offline or signed and broadcasted to the preconfigured node using `tx.GenerateOrBroadcastTxCLI(clientCtx, flags, msg)`. +* **Adds transaction flags:** All transaction commands must add a set of transaction [flags](#flags). The transaction flags are used to collect additional information from the user (e.g. the amount of fees the user is willing to pay). The transaction flags are added to the constructed command using `AddTxFlagsToCmd(cmd)`. +* **Returns the command:** Finally, the transaction command is returned. + +Each module can implement `NewTxCmd()`, which aggregates all of the transaction commands of the module. Here is an example from the `x/bank` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/client/cli/tx.go#L20-L35 +``` + +Each module then can also implement a `GetTxCmd()` method that simply returns `NewTxCmd()`. This allows the root command to easily aggregate all of the transaction commands for each module. Here is an example: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/module.go#L84-L86 +``` + +### Query Commands + + +This section is being rewritten. Refer to [AutoCLI](https://docs.cosmos.network/main/core/autocli) while this section is being updated. + + + + +## gRPC + +[gRPC](https://grpc.io/) is a Remote Procedure Call (RPC) framework. RPC is the preferred way for external clients like wallets and exchanges to interact with a blockchain. + +In addition to providing an ABCI query pathway, the Cosmos SDK provides a gRPC proxy server that routes gRPC query requests to ABCI query requests. + +In order to do that, modules must implement `RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux)` on `AppModuleBasic` to wire the client gRPC requests to the correct handler inside the module. + +Here's an example from the `x/auth` module: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/module.go#L71-L76 +``` + +## gRPC-gateway REST + +Applications need to support web services that use HTTP requests (e.g. a web wallet like [Keplr](https://keplr.app)). [grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway) translates REST calls into gRPC calls, which might be useful for clients that do not use gRPC. + +Modules that want to expose REST queries should add `google.api.http` annotations to their `rpc` methods, such as in the example below from the `x/auth` module: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/auth/v1beta1/query.proto#L14-L89 +``` + +gRPC gateway is started in-process along with the application and CometBFT. It can be enabled or disabled by setting gRPC Configuration `enable` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). + +The Cosmos SDK provides a command for generating [Swagger](https://swagger.io/) documentation (`protoc-gen-swagger`). Setting `swagger` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) defines if swagger documentation should be automatically registered. diff --git a/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx b/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx new file mode 100644 index 00000000..9527587c --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx @@ -0,0 +1,333 @@ +--- +title: "Module Manager" + +--- + +--- + +--- + + +**Synopsis** +Cosmos SDK modules need to implement the [`AppModule` interfaces](#application-module-interfaces), in order to be managed by the application's [module manager](#module-manager). The module manager plays an important role in [`message` and `query` routing](../../learn/advanced/00-baseapp.md#routing), and allows application developers to set the order of execution of a variety of functions like [`PreBlocker`](../../learn/beginner/00-app-anatomy#preblocker) and [`BeginBlocker` and `EndBlocker`](../../learn/beginner/00-app-anatomy.md#begingblocker-and-endblocker). + + + +**Pre-requisite Readings** + +* [Introduction to Cosmos SDK Modules](./00-intro.md) + + + +## Application Module Interfaces + +Application module interfaces exist to facilitate the composition of modules together to form a functional Cosmos SDK application. + + + +It is recommended to implement interfaces from the [Core API](https://docs.cosmos.network/main/architecture/adr-063-core-module-api) `appmodule` package. This makes modules less dependent on the SDK. +For legacy reason modules can still implement interfaces from the SDK `module` package. + + +There are 2 main application module interfaces: + +* [`appmodule.AppModule` / `module.AppModule`](#appmodule) for inter-dependent module functionalities (except genesis-related functionalities). +* (legacy) [`module.AppModuleBasic`](#appmodulebasic) for independent module functionalities. New modules can use `module.CoreAppModuleBasicAdaptor` instead. + +The above interfaces are mostly embedding smaller interfaces (extension interfaces), that defines specific functionalities: + +* (legacy) `module.HasName`: Allows the module to provide its own name for legacy purposes. +* (legacy) [`module.HasGenesisBasics`](#modulehasgenesisbasics): The legacy interface for stateless genesis methods. +* [`module.HasGenesis`](#modulehasgenesis) for inter-dependent genesis-related module functionalities. +* [`module.HasABCIGenesis`](#modulehasabcigenesis) for inter-dependent genesis-related module functionalities. +* [`appmodule.HasGenesis` / `module.HasGenesis`](#appmodulehasgenesis): The extension interface for stateful genesis methods. +* [`appmodule.HasPreBlocker`](#haspreblocker): The extension interface that contains information about the `AppModule` and `PreBlock`. +* [`appmodule.HasBeginBlocker`](#hasbeginblocker): The extension interface that contains information about the `AppModule` and `BeginBlock`. +* [`appmodule.HasEndBlocker`](#hasendblocker): The extension interface that contains information about the `AppModule` and `EndBlock`. +* [`appmodule.HasPrecommit`](#hasprecommit): The extension interface that contains information about the `AppModule` and `Precommit`. +* [`appmodule.HasPrepareCheckState`](#haspreparecheckstate): The extension interface that contains information about the `AppModule` and `PrepareCheckState`. +* [`appmodule.HasService` / `module.HasServices`](#hasservices): The extension interface for modules to register services. +* [`module.HasABCIEndBlock`](#hasabciendblock): The extension interface that contains information about the `AppModule`, `EndBlock` and returns an updated validator set. +* (legacy) [`module.HasInvariants`](#hasinvariants): The extension interface for registering invariants. +* (legacy) [`module.HasConsensusVersion`](#hasconsensusversion): The extension interface for declaring a module consensus version. + +The `AppModuleBasic` interface exists to define independent methods of the module, i.e. those that do not depend on other modules in the application. This allows for the construction of the basic application structure early in the application definition, generally in the `init()` function of the [main application file](../../learn/beginner/00-app-anatomy.md#core-application-file). + +The `AppModule` interface exists to define inter-dependent module methods. Many modules need to interact with other modules, typically through [`keeper`s](/docs/sdk/v0.53/06-keeper.md), which means there is a need for an interface where modules list their `keeper`s and other methods that require a reference to another module's object. `AppModule` interface extension, such as `HasBeginBlocker` and `HasEndBlocker`, also enables the module manager to set the order of execution between module's methods like `BeginBlock` and `EndBlock`, which is important in cases where the order of execution between modules matters in the context of the application. + +The usage of extension interfaces allows modules to define only the functionalities they need. For example, a module that does not need an `EndBlock` does not need to define the `HasEndBlocker` interface and thus the `EndBlock` method. `AppModule` and `AppModuleGenesis` are voluntarily small interfaces, that can take advantage of the `Module` patterns without having to define many placeholder functions. + +### `AppModuleBasic` + + +Use `module.CoreAppModuleBasicAdaptor` instead for creating an `AppModuleBasic` from an `appmodule.AppModule`. + + +The `AppModuleBasic` interface defines the independent methods modules need to implement. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L56-L61 +``` + +* `RegisterLegacyAminoCodec(*codec.LegacyAmino)`: Registers the `amino` codec for the module, which is used to marshal and unmarshal structs to/from `[]byte` in order to persist them in the module's `KVStore`. +* `RegisterInterfaces(codectypes.InterfaceRegistry)`: Registers a module's interface types and their concrete implementations as `proto.Message`. +* `RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux)`: Registers gRPC routes for the module. + +All the `AppModuleBasic` of an application are managed by the [`BasicManager`](#basicmanager). + +### `HasName` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L66-L68 +``` + +* `HasName` is an interface that has a method `Name()`. This method returns the name of the module as a `string`. + +### Genesis + + +For easily creating an `AppModule` that only has genesis functionalities, use `module.GenesisOnlyAppModule`. + + +#### `module.HasGenesisBasics` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L71-L74 +``` + +Let us go through the methods: + +* `DefaultGenesis(codec.JSONCodec)`: Returns a default [`GenesisState`](/docs/sdk/v0.53/08-genesis.md#genesisstate) for the module, marshalled to `json.RawMessage`. The default `GenesisState` need to be defined by the module developer and is primarily used for testing. +* `ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`: Used to validate the `GenesisState` defined by a module, given in its `json.RawMessage` form. It will usually unmarshall the `json` before running a custom [`ValidateGenesis`](/docs/sdk/v0.53/08-genesis.md#validategenesis) function defined by the module developer. + +#### `module.HasGenesis` + +`HasGenesis` is an extension interface for allowing modules to implement genesis functionalities. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/6ce2505/types/module/module.go#L184-L189 +``` + +#### `module.HasABCIGenesis` + +`HasABCIGenesis` is an extension interface for allowing modules to implement genesis functionalities and returns validator set updates. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/6ce2505/types/module/module.go#L191-L196 +``` + +#### `appmodule.HasGenesis` + + +`appmodule.HasGenesis` is experimental and should be considered unstable, it is recommended to not use this interface at this time. + + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/6ce2505/core/appmodule/genesis.go#L8-L25 +``` + +### `AppModule` + +The `AppModule` interface defines a module. Modules can declare their functionalities by implementing extensions interfaces. +`AppModule`s are managed by the [module manager](#manager), which checks which extension interfaces are implemented by the module. + +#### `appmodule.AppModule` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/6afece6/core/appmodule/module.go#L11-L20 +``` + +#### `module.AppModule` + + +Previously the `module.AppModule` interface was containing all the methods that are defined in the extensions interfaces. This was leading to much boilerplate for modules that did not need all the functionalities. + + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L199-L206 +``` + +### `HasInvariants` + +This interface defines one method. It allows to checks if a module can register invariants. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L211-L214 +``` + +* `RegisterInvariants(sdk.InvariantRegistry)`: Registers the [`invariants`](/docs/sdk/v0.53/07-invariants.md) of the module. If an invariant deviates from its predicted value, the [`InvariantRegistry`](/docs/sdk/v0.53/07-invariants.md#registry) triggers appropriate logic (most often the chain will be halted). + +### `HasServices` + +This interface defines one method. It allows to checks if a module can register invariants. + +#### `appmodule.HasService` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/6afece6/core/appmodule/module.go#L22-L40 +``` + +#### `module.HasServices` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L217-L220 +``` + +* `RegisterServices(Configurator)`: Allows a module to register services. + +### `HasConsensusVersion` + +This interface defines one method for checking a module consensus version. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L223-L229 +``` + +* `ConsensusVersion() uint64`: Returns the consensus version of the module. + +### `HasPreBlocker` + +The `HasPreBlocker` is an extension interface from `appmodule.AppModule`. All modules that have an `PreBlock` method implement this interface. + +### `HasBeginBlocker` + +The `HasBeginBlocker` is an extension interface from `appmodule.AppModule`. All modules that have an `BeginBlock` method implement this interface. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L73-L80 +``` + +* `BeginBlock(context.Context) error`: This method gives module developers the option to implement logic that is automatically triggered at the beginning of each block. + +### `HasEndBlocker` + +The `HasEndBlocker` is an extension interface from `appmodule.AppModule`. All modules that have an `EndBlock` method implement this interface. If a module need to return validator set updates (staking), they can use `HasABCIEndBlock` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L83-L89 +``` + +* `EndBlock(context.Context) error`: This method gives module developers the option to implement logic that is automatically triggered at the end of each block. + +### `HasABCIEndBlock` + +The `HasABCIEndBlock` is an extension interface from `module.AppModule`. All modules that have an `EndBlock` which return validator set updates implement this interface. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L236-L239 +``` + +* `EndBlock(context.Context) ([]abci.ValidatorUpdate, error)`: This method gives module developers the option to inform the underlying consensus engine of validator set changes (e.g. the `staking` module). + +### `HasPrecommit` + +`HasPrecommit` is an extension interface from `appmodule.AppModule`. All modules that have a `Precommit` method implement this interface. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L50-L53 +``` + +* `Precommit(context.Context)`: This method gives module developers the option to implement logic that is automatically triggered during [`Commit'](../../learn/advanced/00-baseapp.md#commit) of each block using the [`finalizeblockstate`](../../learn/advanced/00-baseapp.md#state-updates) of the block to be committed. Implement empty if no logic needs to be triggered during `Commit` of each block for this module. + +### `HasPrepareCheckState` + +`HasPrepareCheckState` is an extension interface from `appmodule.AppModule`. All modules that have a `PrepareCheckState` method implement this interface. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L44-L47 +``` + +* `PrepareCheckState(context.Context)`: This method gives module developers the option to implement logic that is automatically triggered during [`Commit'](../../learn/advanced/00-baseapp.md#commit) of each block using the [`checkState`](../../learn/advanced/00-baseapp.md#state-updates) of the next block. Implement empty if no logic needs to be triggered during `Commit` of each block for this module. + +### Implementing the Application Module Interfaces + +Typically, the various application module interfaces are implemented in a file called `module.go`, located in the module's folder (e.g. `./x/module/module.go`). + +Almost every module needs to implement the `AppModuleBasic` and `AppModule` interfaces. If the module is only used for genesis, it will implement `AppModuleGenesis` instead of `AppModule`. The concrete type that implements the interface can add parameters that are required for the implementation of the various methods of the interface. For example, the `Route()` function often calls a `NewMsgServerImpl(k keeper)` function defined in `keeper/msg_server.go` and therefore needs to pass the module's [`keeper`](/docs/sdk/v0.53/06-keeper.md) as a parameter. + +```go +// example +type AppModule struct { + AppModuleBasic + keeper Keeper +} +``` + +In the example above, you can see that the `AppModule` concrete type references an `AppModuleBasic`, and not an `AppModuleGenesis`. That is because `AppModuleGenesis` only needs to be implemented in modules that focus on genesis-related functionalities. In most modules, the concrete `AppModule` type will have a reference to an `AppModuleBasic` and implement the two added methods of `AppModuleGenesis` directly in the `AppModule` type. + +If no parameter is required (which is often the case for `AppModuleBasic`), just declare an empty concrete type like so: + +```go +type AppModuleBasic struct{} +``` + +## Module Managers + +Module managers are used to manage collections of `AppModuleBasic` and `AppModule`. + +### `BasicManager` + +The `BasicManager` is a structure that lists all the `AppModuleBasic` of an application: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L77 +``` + +It implements the following methods: + +* `NewBasicManager(modules ...AppModuleBasic)`: Constructor function. It takes a list of the application's `AppModuleBasic` and builds a new `BasicManager`. This function is generally called in the `init()` function of [`app.go`](../../learn/beginner/00-app-anatomy.md#core-application-file) to quickly initialize the independent elements of the application's modules (click [here](https://github.com/cosmos/gaia/blob/main/app/app.go#L59-L74) to see an example). +* `NewBasicManagerFromManager(manager *Manager, customModuleBasics map[string]AppModuleBasic)`: Contructor function. It creates a new `BasicManager` from a `Manager`. The `BasicManager` will contain all `AppModuleBasic` from the `AppModule` manager using `CoreAppModuleBasicAdaptor` whenever possible. Module's `AppModuleBasic` can be overridden by passing a custom AppModuleBasic map +* `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)`: Registers the [`codec.LegacyAmino`s](../../learn/advanced/05-encoding.md#amino) of each of the application's `AppModuleBasic`. This function is usually called early on in the [application's construction](../../learn/beginner/00-app-anatomy.md#constructor). +* `RegisterInterfaces(registry codectypes.InterfaceRegistry)`: Registers interface types and implementations of each of the application's `AppModuleBasic`. +* `DefaultGenesis(cdc codec.JSONCodec)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONCodec)`](/docs/sdk/v0.53/08-genesis.md#defaultgenesis) function of each module. It only calls the modules that implements the `HasGenesisBasics` interfaces. +* `ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`](/docs/sdk/v0.53/08-genesis.md#validategenesis) function of modules implementing the `HasGenesisBasics` interface. +* `RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux)`: Registers gRPC routes for modules. +* `AddTxCommands(rootTxCmd *cobra.Command)`: Adds modules' transaction commands (defined as `GetTxCmd() *cobra.Command`) to the application's [`rootTxCommand`](../../learn/advanced/07-cli.md#transaction-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../../learn/advanced/07-cli.md). +* `AddQueryCommands(rootQueryCmd *cobra.Command)`: Adds modules' query commands (defined as `GetQueryCmd() *cobra.Command`) to the application's [`rootQueryCommand`](../../learn/advanced/07-cli.md#query-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../../learn/advanced/07-cli.md). + +### `Manager` + +The `Manager` is a structure that holds all the `AppModule` of an application, and defines the order of execution between several key components of these modules: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L278-L288 +``` + +The module manager is used throughout the application whenever an action on a collection of modules is required. It implements the following methods: + +* `NewManager(modules ...AppModule)`: Constructor function. It takes a list of the application's `AppModule`s and builds a new `Manager`. It is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderInitGenesis(moduleNames ...string)`: Sets the order in which the [`InitGenesis`](/docs/sdk/v0.53/08-genesis.md#initgenesis) function of each module will be called when the application is first started. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). + To initialize modules successfully, module dependencies should be considered. For example, the `genutil` module must occur after `staking` module so that the pools are properly initialized with tokens from genesis accounts, the `genutils` module must also occur after `auth` so that it can access the params from auth, IBC's `capability` module should be initialized before all other modules so that it can initialize any capabilities. +* `SetOrderExportGenesis(moduleNames ...string)`: Sets the order in which the [`ExportGenesis`](/docs/sdk/v0.53/08-genesis.md#exportgenesis) function of each module will be called in case of an export. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderPreBlockers(moduleNames ...string)`: Sets the order in which the `PreBlock()` function of each module will be called before `BeginBlock()` of all modules. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderBeginBlockers(moduleNames ...string)`: Sets the order in which the `BeginBlock()` function of each module will be called at the beginning of each block. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderEndBlockers(moduleNames ...string)`: Sets the order in which the `EndBlock()` function of each module will be called at the end of each block. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderPrecommiters(moduleNames ...string)`: Sets the order in which the `Precommit()` function of each module will be called during commit of each block. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderPrepareCheckStaters(moduleNames ...string)`: Sets the order in which the `PrepareCheckState()` function of each module will be called during commit of each block. This function is generally called from the application's main [constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function). +* `SetOrderMigrations(moduleNames ...string)`: Sets the order of migrations to be run. If not set then migrations will be run with an order defined in `DefaultMigrationsOrder`. +* `RegisterInvariants(ir sdk.InvariantRegistry)`: Registers the [invariants](/docs/sdk/v0.53/07-invariants.md) of module implementing the `HasInvariants` interface. +* `RegisterServices(cfg Configurator)`: Registers the services of modules implementing the `HasServices` interface. +* `InitGenesis(ctx context.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](/docs/sdk/v0.53/08-genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. +* `ExportGenesis(ctx context.Context, cdc codec.JSONCodec)`: Calls the [`ExportGenesis`](/docs/sdk/v0.53/08-genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. +* `ExportGenesisForModules(ctx context.Context, cdc codec.JSONCodec, modulesToExport []string)`: Behaves the same as `ExportGenesis`, except takes a list of modules to export. +* `BeginBlock(ctx context.Context) error`: At the beginning of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#beginblock) and, in turn, calls the [`BeginBlock`](/docs/sdk/v0.53/06-beginblock-endblock.md) function of each modules implementing the `appmodule.HasBeginBlocker` interface, in the order defined in `OrderBeginBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from each modules. +* `EndBlock(ctx context.Context) error`: At the end of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#endblock) and, in turn, calls the [`EndBlock`](/docs/sdk/v0.53/06-beginblock-endblock.md) function of each modules implementing the `appmodule.HasEndBlocker` interface, in the order defined in `OrderEndBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from all modules. The function returns an `abci` which contains the aforementioned events, as well as validator set updates (if any). +* `EndBlock(context.Context) ([]abci.ValidatorUpdate, error)`: At the end of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#endblock) and, in turn, calls the [`EndBlock`](/docs/sdk/v0.53/06-beginblock-endblock.md) function of each modules implementing the `module.HasABCIEndBlock` interface, in the order defined in `OrderEndBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from all modules. The function returns an `abci` which contains the aforementioned events, as well as validator set updates (if any). +* `Precommit(ctx context.Context)`: During [`Commit`](../../learn/advanced/00-baseapp.md#commit), this function is called from `BaseApp` immediately before the [`deliverState`](../../learn/advanced/00-baseapp.md#state-updates) is written to the underlying [`rootMultiStore`](../../learn/advanced/04-store.md#commitmultistore) and, in turn calls the `Precommit` function of each modules implementing the `HasPrecommit` interface, in the order defined in `OrderPrecommiters`. It creates a child [context](../../learn/advanced/02-context.md) where the underlying `CacheMultiStore` is that of the newly committed block's [`finalizeblockstate`](../../learn/advanced/00-baseapp.md#state-updates). +* `PrepareCheckState(ctx context.Context)`: During [`Commit`](../../learn/advanced/00-baseapp.md#commit), this function is called from `BaseApp` immediately after the [`deliverState`](../../learn/advanced/00-baseapp.md#state-updates) is written to the underlying [`rootMultiStore`](../../learn/advanced/04-store.md#commitmultistore) and, in turn calls the `PrepareCheckState` function of each module implementing the `HasPrepareCheckState` interface, in the order defined in `OrderPrepareCheckStaters`. It creates a child [context](../../learn/advanced/02-context.md) where the underlying `CacheMultiStore` is that of the next block's [`checkState`](../../learn/advanced/00-baseapp.md#state-updates). Writes to this state will be present in the [`checkState`](../../learn/advanced/00-baseapp.md#state-updates) of the next block, and therefore this method can be used to prepare the `checkState` for the next block. + +Here's an example of a concrete integration within an `simapp`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L510-L533 +``` + +This is the same example from `runtime` (the package that powers app di): + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/module.go#L63 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/runtime/module.go#L85 +``` diff --git a/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx b/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx new file mode 100644 index 00000000..243eca05 --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx @@ -0,0 +1,36 @@ +--- +title: "PreBlocker" + +--- + +--- + +--- + + +**Synopsis** +`PreBlocker` is optional method module developers can implement in their module. They will be triggered before [`BeginBlock`](../../learn/advanced/00-baseapp.md#beginblock). + + + +**Pre-requisite Readings** + +* [Module Manager](./01-module-manager.md) + + + +## PreBlocker + +There are two semantics around the new lifecycle method: + +- It runs before the `BeginBlocker` of all modules +- It can modify consensus parameters in storage, and signal the caller through the return value. + +When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameter in the deliver context: +``` +app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) +``` + +The new ctx must be passed to all the other lifecycle methods. + + diff --git a/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx new file mode 100644 index 00000000..abe50bac --- /dev/null +++ b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx @@ -0,0 +1,99 @@ +--- +title: "Recommended Folder Structure" + +--- + +--- + +--- + + +**Synopsis** +This document outlines the recommended structure of Cosmos SDK modules. These ideas are meant to be applied as suggestions. Application developers are encouraged to improve upon and contribute to module structure and development design. + + +## Structure + +A typical Cosmos SDK module can be structured as follows: + +```shell +proto +└── {project_name} +    └── {module_name} +    └── {proto_version} +       ├── {module_name}.proto +       ├── event.proto +       ├── genesis.proto +       ├── query.proto +       └── tx.proto +``` + +* `{module_name}.proto`: The module's common message type definitions. +* `event.proto`: The module's message type definitions related to events. +* `genesis.proto`: The module's message type definitions related to genesis state. +* `query.proto`: The module's Query service and related message type definitions. +* `tx.proto`: The module's Msg service and related message type definitions. + +```shell +x/{module_name} +├── client +│   ├── cli +│   │ ├── query.go +│   │   └── tx.go +│   └── testutil +│   ├── cli_test.go +│   └── suite.go +├── exported +│   └── exported.go +├── keeper +│   ├── genesis.go +│   ├── grpc_query.go +│   ├── hooks.go +│   ├── invariants.go +│   ├── keeper.go +│   ├── keys.go +│   ├── msg_server.go +│   └── querier.go +├── module +│   └── module.go +│   └── abci.go +│   └── autocli.go +├── simulation +│   ├── decoder.go +│   ├── genesis.go +│   ├── operations.go +│   └── params.go +├── {module_name}.pb.go +├── codec.go +├── errors.go +├── events.go +├── events.pb.go +├── expected_keepers.go +├── genesis.go +├── genesis.pb.go +├── keys.go +├── msgs.go +├── params.go +├── query.pb.go +├── tx.pb.go +└── README.md +``` + +* `client/`: The module's CLI client functionality implementation and the module's CLI testing suite. +* `exported/`: The module's exported types - typically interface types. If a module relies on keepers from another module, it is expected to receive the keepers as interface contracts through the `expected_keepers.go` file (see below) in order to avoid a direct dependency on the module implementing the keepers. However, these interface contracts can define methods that operate on and/or return types that are specific to the module that is implementing the keepers and this is where `exported/` comes into play. The interface types that are defined in `exported/` use canonical types, allowing for the module to receive the keepers as interface contracts through the `expected_keepers.go` file. This pattern allows for code to remain DRY and also alleviates import cycle chaos. +* `keeper/`: The module's `Keeper` and `MsgServer` implementation. +* `module/`: The module's `AppModule` and `AppModuleBasic` implementation. + * `abci.go`: The module's `BeginBlocker` and `EndBlocker` implementations (this file is only required if `BeginBlocker` and/or `EndBlocker` need to be defined). + * `autocli.go`: The module [autocli](/docs/sdk/v0.53/core/autocli) options. +* `simulation/`: The module's [simulation](/docs/sdk/v0.53/14-simulator.md) package defines functions used by the blockchain simulator application (`simapp`). +* `REAMDE.md`: The module's specification documents outlining important concepts, state storage structure, and message and event type definitions. Learn more how to write module specs in the [spec guidelines](../spec/SPEC_MODULE.md). +* The root directory includes type definitions for messages, events, and genesis state, including the type definitions generated by Protocol Buffers. + * `codec.go`: The module's registry methods for interface types. + * `errors.go`: The module's sentinel errors. + * `events.go`: The module's event types and constructors. + * `expected_keepers.go`: The module's [expected keeper](/docs/sdk/v0.53/06-keeper.md#type-definition) interfaces. + * `genesis.go`: The module's genesis state methods and helper functions. + * `keys.go`: The module's store keys and associated helper functions. + * `msgs.go`: The module's message type definitions and associated methods. + * `params.go`: The module's parameter type definitions and associated methods. + * `*.pb.go`: The module's type definitions generated by Protocol Buffers (as defined in the respective `*.proto` files above). diff --git a/docs/sdk/v0.53/module-reference/auth.mdx b/docs/sdk/v0.53/module-reference/auth.mdx new file mode 100644 index 00000000..48083832 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/auth.mdx @@ -0,0 +1,712 @@ +--- +title: "`x/auth`" + +--- + +--- + +--- + +## Abstract + +This document specifies the auth module of the Cosmos SDK. + +The auth module is responsible for specifying the base transaction and account types +for an application, since the SDK itself is agnostic to these particulars. It contains +the middlewares, where all basic transaction validity checks (signatures, nonces, auxiliary fields) +are performed, and exposes the account keeper, which allows other modules to read, write, and modify accounts. + +This module is used in the Cosmos Hub. + +## Contents + +* [Concepts](#concepts) + * [Gas & Fees](#gas--fees) +* [State](#state) + * [Accounts](#accounts) +* [AnteHandlers](#antehandlers) +* [Keepers](#keepers) + * [Account Keeper](#account-keeper) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) + +## Concepts + +**Note:** The auth module is different from the [authz module](../modules/authz/). + +The differences are: + +* `auth` - authentication of accounts and transactions for Cosmos SDK applications and is responsible for specifying the base transaction and account types. +* `authz` - authorization for accounts to perform actions on behalf of other accounts and enables a granter to grant authorizations to a grantee that allows the grantee to execute messages on behalf of the granter. + +### Gas & Fees + +Fees serve two purposes for an operator of the network. + +Fees limit the growth of the state stored by every full node and allow for +general purpose censorship of transactions of little economic value. Fees +are best suited as an anti-spam mechanism where validators are disinterested in +the use of the network and identities of users. + +Fees are determined by the gas limits and gas prices transactions provide, where +`fees = ceil(gasLimit * gasPrices)`. Txs incur gas costs for all state reads/writes, +signature verification, as well as costs proportional to the tx size. Operators +should set minimum gas prices when starting their nodes. They must set the unit +costs of gas in each token denomination they wish to support: + +`simd start ... --minimum-gas-prices=0.00001stake;0.05photinos` + +When adding transactions to mempool or gossipping transactions, validators check +if the transaction's gas prices, which are determined by the provided fees, meet +any of the validator's minimum gas prices. In other words, a transaction must +provide a fee of at least one denomination that matches a validator's minimum +gas price. + +CometBFT does not currently provide fee based mempool prioritization, and fee +based mempool filtering is local to node and not part of consensus. But with +minimum gas prices set, such a mechanism could be implemented by node operators. + +Because the market value for tokens will fluctuate, validators are expected to +dynamically adjust their minimum gas prices to a level that would encourage the +use of the network. + +## State + +### Accounts + +Accounts contain authentication information for a uniquely identified external user of an SDK blockchain, +including public key, address, and account number / sequence number for replay protection. For efficiency, +since account balances must also be fetched to pay fees, account structs also store the balance of a user +as `sdk.Coins`. + +Accounts are exposed externally as an interface, and stored internally as +either a base account or vesting account. Module clients wishing to add more +account types may do so. + +* `0x01 | Address -> ProtocolBuffer(account)` + +#### Account Interface + +The account interface exposes methods to read and write standard account information. +Note that all of these methods operate on an account struct conforming to the +interface - in order to write the account to the store, the account keeper will +need to be used. + +```go +// AccountI is an interface used to store coins at a given address within state. +// It presumes a notion of sequence numbers for replay protection, +// a notion of account numbers for replay protection for previously pruned accounts, +// and a pubkey for authentication purposes. +// +// Many complex conditions can be used in the concrete struct which implements AccountI. +type AccountI interface { + proto.Message + + GetAddress() sdk.AccAddress + SetAddress(sdk.AccAddress) error // errors if already set. + + GetPubKey() crypto.PubKey // can return nil. + SetPubKey(crypto.PubKey) error + + GetAccountNumber() uint64 + SetAccountNumber(uint64) error + + GetSequence() uint64 + SetSequence(uint64) error + + // Ensure that account implements stringer + String() string +} +``` + +##### Base Account + +A base account is the simplest and most common account type, which just stores all requisite +fields directly in a struct. + +```protobuf +// BaseAccount defines a base account type. It contains all the necessary fields +// for basic account functionality. Any custom account type should extend this +// type for additional functionality (e.g. vesting). +message BaseAccount { + string address = 1; + google.protobuf.Any pub_key = 2; + uint64 account_number = 3; + uint64 sequence = 4; +} +``` + +### Vesting Account + +See [Vesting](/docs/sdk/v0.53/modules/auth/vesting/). + +## AnteHandlers + +The `x/auth` module presently has no transaction handlers of its own, but does expose the special `AnteHandler`, used for performing basic validity checks on a transaction, such that it could be thrown out of the mempool. +The `AnteHandler` can be seen as a set of decorators that check transactions within the current context, per [ADR 010](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-010-modular-antehandler.md). + +Note that the `AnteHandler` is called on both `CheckTx` and `DeliverTx`, as CometBFT proposers presently have the ability to include in their proposed block transactions which fail `CheckTx`. + +### Decorators + +The auth module provides `AnteDecorator`s that are recursively chained together into a single `AnteHandler` in the following order: + +* `SetUpContextDecorator`: Sets the `GasMeter` in the `Context` and wraps the next `AnteHandler` with a defer clause to recover from any downstream `OutOfGas` panics in the `AnteHandler` chain to return an error with information on gas provided and gas used. + +* `RejectExtensionOptionsDecorator`: Rejects all extension options which can optionally be included in protobuf transactions. + +* `MempoolFeeDecorator`: Checks if the `tx` fee is above local mempool `minFee` parameter during `CheckTx`. + +* `ValidateBasicDecorator`: Calls `tx.ValidateBasic` and returns any non-nil error. + +* `TxTimeoutHeightDecorator`: Check for a `tx` height timeout. + +* `ValidateMemoDecorator`: Validates `tx` memo with application parameters and returns any non-nil error. + +* `ConsumeGasTxSizeDecorator`: Consumes gas proportional to the `tx` size based on application parameters. + +* `DeductFeeDecorator`: Deducts the `FeeAmount` from first signer of the `tx`. If the `x/feegrant` module is enabled and a fee granter is set, it deducts fees from the fee granter account. + +* `SetPubKeyDecorator`: Sets the pubkey from a `tx`'s signers that does not already have its corresponding pubkey saved in the state machine and in the current context. + +* `ValidateSigCountDecorator`: Validates the number of signatures in `tx` based on app-parameters. + +* `SigGasConsumeDecorator`: Consumes parameter-defined amount of gas for each signature. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. + +* `SigVerificationDecorator`: Verifies all signatures are valid. This requires pubkeys to be set in context for all signers as part of `SetPubKeyDecorator`. + +* `IncrementSequenceDecorator`: Increments the account sequence for each signer to prevent replay attacks. + +## Keepers + +The auth module only exposes one keeper, the account keeper, which can be used to read and write accounts. + +### Account Keeper + +Presently only one fully-permissioned account keeper is exposed, which has the ability to both read and write +all fields of all accounts, and to iterate over all stored accounts. + +```go +// AccountKeeperI is the interface contract that x/auth's keeper implements. +type AccountKeeperI interface { + // Return a new account with the next account number and the specified address. Does not save the new account to the store. + NewAccountWithAddress(sdk.Context, sdk.AccAddress) types.AccountI + + // Return a new account with the next account number. Does not save the new account to the store. + NewAccount(sdk.Context, types.AccountI) types.AccountI + + // Check if an account exists in the store. + HasAccount(sdk.Context, sdk.AccAddress) bool + + // Retrieve an account from the store. + GetAccount(sdk.Context, sdk.AccAddress) types.AccountI + + // Set an account in the store. + SetAccount(sdk.Context, types.AccountI) + + // Remove an account from the store. + RemoveAccount(sdk.Context, types.AccountI) + + // Iterate over all accounts, calling the provided function. Stop iteration when it returns true. + IterateAccounts(sdk.Context, func(types.AccountI) bool) + + // Fetch the public key of an account at a specified address + GetPubKey(sdk.Context, sdk.AccAddress) (crypto.PubKey, error) + + // Fetch the sequence of an account at a specified address. + GetSequence(sdk.Context, sdk.AccAddress) (uint64, error) + + // Fetch the next account number, and increment the internal counter. + NextAccountNumber(sdk.Context) uint64 +} +``` + +## Parameters + +The auth module contains the following parameters: + +| Key | Type | Example | +| ---------------------- | --------------- | ------- | +| MaxMemoCharacters | uint64 | 256 | +| TxSigLimit | uint64 | 7 | +| TxSizeCostPerByte | uint64 | 10 | +| SigVerifyCostED25519 | uint64 | 590 | +| SigVerifyCostSecp256k1 | uint64 | 1000 | + +## Client + +### CLI + +A user can query and interact with the `auth` module using the CLI. + +### Query + +The `query` commands allow users to query `auth` state. + +```bash +simd query auth --help +``` + +#### account + +The `account` command allow users to query for an account by it's address. + +```bash +simd query auth account [address] [flags] +``` + +Example: + +```bash +simd query auth account cosmos1... +``` + +Example Output: + +```bash +'@type': /cosmos.auth.v1beta1.BaseAccount +account_number: "0" +address: cosmos1zwg6tpl8aw4rawv8sgag9086lpw5hv33u5ctr2 +pub_key: + '@type': /cosmos.crypto.secp256k1.PubKey + key: ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD +sequence: "1" +``` + +#### accounts + +The `accounts` command allow users to query all the available accounts. + +```bash +simd query auth accounts [flags] +``` + +Example: + +```bash +simd query auth accounts +``` + +Example Output: + +```bash +accounts: +- '@type': /cosmos.auth.v1beta1.BaseAccount + account_number: "0" + address: cosmos1zwg6tpl8aw4rawv8sgag9086lpw5hv33u5ctr2 + pub_key: + '@type': /cosmos.crypto.secp256k1.PubKey + key: ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD + sequence: "1" +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "8" + address: cosmos1yl6hdjhmkf37639730gffanpzndzdpmhwlkfhr + pub_key: null + sequence: "0" + name: transfer + permissions: + - minter + - burner +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "4" + address: cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh + pub_key: null + sequence: "0" + name: bonded_tokens_pool + permissions: + - burner + - staking +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "5" + address: cosmos1tygms3xhhs3yv487phx3dw4a95jn7t7lpm470r + pub_key: null + sequence: "0" + name: not_bonded_tokens_pool + permissions: + - burner + - staking +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "6" + address: cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn + pub_key: null + sequence: "0" + name: gov + permissions: + - burner +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "3" + address: cosmos1jv65s3grqf6v6jl3dp4t6c9t9rk99cd88lyufl + pub_key: null + sequence: "0" + name: distribution + permissions: [] +- '@type': /cosmos.auth.v1beta1.BaseAccount + account_number: "1" + address: cosmos147k3r7v2tvwqhcmaxcfql7j8rmkrlsemxshd3j + pub_key: null + sequence: "0" +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "7" + address: cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q + pub_key: null + sequence: "0" + name: mint + permissions: + - minter +- '@type': /cosmos.auth.v1beta1.ModuleAccount + base_account: + account_number: "2" + address: cosmos17xpfvakm2amg962yls6f84z3kell8c5lserqta + pub_key: null + sequence: "0" + name: fee_collector + permissions: [] +pagination: + next_key: null + total: "0" +``` + +#### params + +The `params` command allow users to query the current auth parameters. + +```bash +simd query auth params [flags] +``` + +Example: + +```bash +simd query auth params +``` + +Example Output: + +```bash +max_memo_characters: "256" +sig_verify_cost_ed25519: "590" +sig_verify_cost_secp256k1: "1000" +tx_sig_limit: "7" +tx_size_cost_per_byte: "10" +``` + +### Transactions + +The `auth` module supports transactions commands to help you with signing and more. Compared to other modules you can access directly the `auth` module transactions commands using the only `tx` command. + +Use directly the `--help` flag to get more information about the `tx` command. + +```bash +simd tx --help +``` + +#### `sign` + +The `sign` command allows users to sign transactions that was generated offline. + +```bash +simd tx sign tx.json --from $ALICE > tx.signed.json +``` + +The result is a signed transaction that can be broadcasted to the network thanks to the broadcast command. + +More information about the `sign` command can be found running `simd tx sign --help`. + +#### `sign-batch` + +The `sign-batch` command allows users to sign multiples offline generated transactions. +The transactions can be in one file, with one tx per line, or in multiple files. + +```bash +simd tx sign txs.json --from $ALICE > tx.signed.json +``` + +or + +```bash +simd tx sign tx1.json tx2.json tx3.json --from $ALICE > tx.signed.json +``` + +The result is multiples signed transactions. For combining the signed transactions into one transactions, use the `--append` flag. + +More information about the `sign-batch` command can be found running `simd tx sign-batch --help`. + +#### `multi-sign` + +The `multi-sign` command allows users to sign transactions that was generated offline by a multisig account. + +```bash +simd tx multisign transaction.json k1k2k3 k1sig.json k2sig.json k3sig.json +``` + +Where `k1k2k3` is the multisig account address, `k1sig.json` is the signature of the first signer, `k2sig.json` is the signature of the second signer, and `k3sig.json` is the signature of the third signer. + +##### Nested multisig transactions + +To allow transactions to be signed by nested multisigs, meaning that a participant of a multisig account can be another multisig account, the `--skip-signature-verification` flag must be used. + +```bash +# First aggregate signatures of the multisig participant +simd tx multi-sign transaction.json ms1 ms1p1sig.json ms1p2sig.json --signature-only --skip-signature-verification > ms1sig.json + +# Then use the aggregated signatures and the other signatures to sign the final transaction +simd tx multi-sign transaction.json k1ms1 k1sig.json ms1sig.json --skip-signature-verification +``` + +Where `ms1` is the nested multisig account address, `ms1p1sig.json` is the signature of the first participant of the nested multisig account, `ms1p2sig.json` is the signature of the second participant of the nested multisig account, and `ms1sig.json` is the aggregated signature of the nested multisig account. + +`k1ms1` is a multisig account comprised of an individual signer and another nested multisig account (`ms1`). `k1sig.json` is the signature of the first signer of the individual member. + +More information about the `multi-sign` command can be found running `simd tx multi-sign --help`. + +#### `multisign-batch` + +The `multisign-batch` works the same way as `sign-batch`, but for multisig accounts. +With the difference that the `multisign-batch` command requires all transactions to be in one file, and the `--append` flag does not exist. + +More information about the `multisign-batch` command can be found running `simd tx multisign-batch --help`. + +#### `validate-signatures` + +The `validate-signatures` command allows users to validate the signatures of a signed transaction. + +```bash +$ simd tx validate-signatures tx.signed.json +Signers: + 0: cosmos1l6vsqhh7rnwsyr2kyz3jjg3qduaz8gwgyl8275 + +Signatures: + 0: cosmos1l6vsqhh7rnwsyr2kyz3jjg3qduaz8gwgyl8275 [OK] +``` + +More information about the `validate-signatures` command can be found running `simd tx validate-signatures --help`. + +#### `broadcast` + +The `broadcast` command allows users to broadcast a signed transaction to the network. + +```bash +simd tx broadcast tx.signed.json +``` + +More information about the `broadcast` command can be found running `simd tx broadcast --help`. + +### gRPC + +A user can query the `auth` module using gRPC endpoints. + +#### Account + +The `account` endpoint allow users to query for an account by it's address. + +```bash +cosmos.auth.v1beta1.Query/Account +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"address":"cosmos1.."}' \ + localhost:9090 \ + cosmos.auth.v1beta1.Query/Account +``` + +Example Output: + +```bash +{ + "account":{ + "@type":"/cosmos.auth.v1beta1.BaseAccount", + "address":"cosmos1zwg6tpl8aw4rawv8sgag9086lpw5hv33u5ctr2", + "pubKey":{ + "@type":"/cosmos.crypto.secp256k1.PubKey", + "key":"ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD" + }, + "sequence":"1" + } +} +``` + +#### Accounts + +The `accounts` endpoint allow users to query all the available accounts. + +```bash +cosmos.auth.v1beta1.Query/Accounts +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.auth.v1beta1.Query/Accounts +``` + +Example Output: + +```bash +{ + "accounts":[ + { + "@type":"/cosmos.auth.v1beta1.BaseAccount", + "address":"cosmos1zwg6tpl8aw4rawv8sgag9086lpw5hv33u5ctr2", + "pubKey":{ + "@type":"/cosmos.crypto.secp256k1.PubKey", + "key":"ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD" + }, + "sequence":"1" + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos1yl6hdjhmkf37639730gffanpzndzdpmhwlkfhr", + "accountNumber":"8" + }, + "name":"transfer", + "permissions":[ + "minter", + "burner" + ] + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", + "accountNumber":"4" + }, + "name":"bonded_tokens_pool", + "permissions":[ + "burner", + "staking" + ] + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos1tygms3xhhs3yv487phx3dw4a95jn7t7lpm470r", + "accountNumber":"5" + }, + "name":"not_bonded_tokens_pool", + "permissions":[ + "burner", + "staking" + ] + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", + "accountNumber":"6" + }, + "name":"gov", + "permissions":[ + "burner" + ] + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos1jv65s3grqf6v6jl3dp4t6c9t9rk99cd88lyufl", + "accountNumber":"3" + }, + "name":"distribution" + }, + { + "@type":"/cosmos.auth.v1beta1.BaseAccount", + "accountNumber":"1", + "address":"cosmos147k3r7v2tvwqhcmaxcfql7j8rmkrlsemxshd3j" + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q", + "accountNumber":"7" + }, + "name":"mint", + "permissions":[ + "minter" + ] + }, + { + "@type":"/cosmos.auth.v1beta1.ModuleAccount", + "baseAccount":{ + "address":"cosmos17xpfvakm2amg962yls6f84z3kell8c5lserqta", + "accountNumber":"2" + }, + "name":"fee_collector" + } + ], + "pagination":{ + "total":"9" + } +} +``` + +#### Params + +The `params` endpoint allow users to query the current auth parameters. + +```bash +cosmos.auth.v1beta1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.auth.v1beta1.Query/Params +``` + +Example Output: + +```bash +{ + "params": { + "maxMemoCharacters": "256", + "txSigLimit": "7", + "txSizeCostPerByte": "10", + "sigVerifyCostEd25519": "590", + "sigVerifyCostSecp256k1": "1000" + } +} +``` + +### REST + +A user can query the `auth` module using REST endpoints. + +#### Account + +The `account` endpoint allow users to query for an account by it's address. + +```bash +/cosmos/auth/v1beta1/account?address={address} +``` + +#### Accounts + +The `accounts` endpoint allow users to query all the available accounts. + +```bash +/cosmos/auth/v1beta1/accounts +``` + +#### Params + +The `params` endpoint allow users to query the current auth parameters. + +```bash +/cosmos/auth/v1beta1/params +``` diff --git a/docs/sdk/v0.53/module-reference/authz.mdx b/docs/sdk/v0.53/module-reference/authz.mdx new file mode 100644 index 00000000..4305ebec --- /dev/null +++ b/docs/sdk/v0.53/module-reference/authz.mdx @@ -0,0 +1,375 @@ +--- +title: "`x/authz`" + +--- + +--- + +--- + +## Abstract + +`x/authz` is an implementation of a Cosmos SDK module, per [ADR 30](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md), that allows +granting arbitrary privileges from one account (the granter) to another account (the grantee). Authorizations must be granted for a particular Msg service method one by one using an implementation of the `Authorization` interface. + +## Contents + +* [Concepts](#concepts) + * [Authorization and Grant](#authorization-and-grant) + * [Built-in Authorizations](#built-in-authorizations) + * [Gas](#gas) +* [State](#state) + * [Grant](#grant) + * [GrantQueue](#grantqueue) +* [Messages](#messages) + * [MsgGrant](#msggrant) + * [MsgRevoke](#msgrevoke) + * [MsgExec](#msgexec) +* [Events](#events) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) + +## Concepts + +### Authorization and Grant + +The `x/authz` module defines interfaces and messages grant authorizations to perform actions +on behalf of one account to other accounts. The design is defined in the [ADR 030](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md). + +A *grant* is an allowance to execute a Msg by the grantee on behalf of the granter. +Authorization is an interface that must be implemented by a concrete authorization logic to validate and execute grants. Authorizations are extensible and can be defined for any Msg service method even outside of the module where the Msg method is defined. See the `SendAuthorization` example in the next section for more details. + +**Note:** The authz module is different from the [auth (authentication)](../modules/auth/) module that is responsible for specifying the base transaction and account types. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/authorizations.go#L11-L25 +``` + +### Built-in Authorizations + +The Cosmos SDK `x/authz` module comes with following authorization types: + +#### GenericAuthorization + +`GenericAuthorization` implements the `Authorization` interface that gives unrestricted permission to execute the provided Msg on behalf of granter's account. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/authz.proto#L14-L22 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/generic_authorization.go#L16-L29 +``` + +* `msg` stores Msg type URL. + +#### SendAuthorization + +`SendAuthorization` implements the `Authorization` interface for the `cosmos.bank.v1beta1.MsgSend` Msg. + +* It takes a (positive) `SpendLimit` that specifies the maximum amount of tokens the grantee can spend. The `SpendLimit` is updated as the tokens are spent. +* It takes an (optional) `AllowList` that specifies to which addresses a grantee can send token. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/authz.proto#L11-L30 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/types/send_authorization.go#L29-L62 +``` + +* `spend_limit` keeps track of how many coins are left in the authorization. +* `allow_list` specifies an optional list of addresses to whom the grantee can send tokens on behalf of the granter. + +#### StakeAuthorization + +`StakeAuthorization` implements the `Authorization` interface for messages in the [staking module](/docs/sdk/v0.53/build/modules/staking). It takes an `AuthorizationType` to specify whether you want to authorise delegating, undelegating or redelegating (i.e. these have to be authorised separately). It also takes an optional `MaxTokens` that keeps track of a limit to the amount of tokens that can be delegated/undelegated/redelegated. If left empty, the amount is unlimited. Additionally, this Msg takes an `AllowList` or a `DenyList`, which allows you to select which validators you allow or deny grantees to stake with. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/authz.proto#L11-L35 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/staking/types/authz.go#L15-L35 +``` + +### Gas + +In order to prevent DoS attacks, granting `StakeAuthorization`s with `x/authz` incurs gas. `StakeAuthorization` allows you to authorize another account to delegate, undelegate, or redelegate to validators. The authorizer can define a list of validators they allow or deny delegations to. The Cosmos SDK iterates over these lists and charge 10 gas for each validator in both of the lists. + +Since the state maintaining a list for granter, grantee pair with same expiration, we are iterating over the list to remove the grant (incase of any revoke of paritcular `msgType`) from the list and we are charging 20 gas per iteration. + +## State + +### Grant + +Grants are identified by combining granter address (the address bytes of the granter), grantee address (the address bytes of the grantee) and Authorization type (its type URL). Hence we only allow one grant for the (granter, grantee, Authorization) triple. + +* Grant: `0x01 | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes | msgType_bytes -> ProtocolBuffer(AuthorizationGrant)` + +The grant object encapsulates an `Authorization` type and an expiration timestamp: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/authz.proto#L24-L32 +``` + +### GrantQueue + +We are maintaining a queue for authz pruning. Whenever a grant is created, an item will be added to `GrantQueue` with a key of expiration, granter, grantee. + +In `EndBlock` (which runs for every block) we continuously check and prune the expired grants by forming a prefix key with current blocktime that passed the stored expiration in `GrantQueue`, we iterate through all the matched records from `GrantQueue` and delete them from the `GrantQueue` & `Grant`s store. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/5f4ddc6f80f9707320eec42182184207fff3833a/x/authz/keeper/keeper.go#L378-L403 +``` + +* GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes -> ProtocalBuffer(GrantQueueItem)` + +The `expiration_bytes` are the expiration date in UTC with the format `"2006-01-02T15:04:05.000000000"`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/keeper/keys.go#L77-L93 +``` + +The `GrantQueueItem` object contains the list of type urls between granter and grantee that expire at the time indicated in the key. + +## Messages + +In this section we describe the processing of messages for the authz module. + +### MsgGrant + +An authorization grant is created using the `MsgGrant` message. +If there is already a grant for the `(granter, grantee, Authorization)` triple, then the new grant overwrites the previous one. To update or extend an existing grant, a new grant with the same `(granter, grantee, Authorization)` triple should be created. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L35-L45 +``` + +The message handling should fail if: + +* both granter and grantee have the same address. +* provided `Expiration` time is less than current unix timestamp (but a grant will be created if no `expiration` time is provided since `expiration` is optional). +* provided `Grant.Authorization` is not implemented. +* `Authorization.MsgTypeURL()` is not defined in the router (there is no defined handler in the app router to handle that Msg types). + +### MsgRevoke + +A grant can be removed with the `MsgRevoke` message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L69-L78 +``` + +The message handling should fail if: + +* both granter and grantee have the same address. +* provided `MsgTypeUrl` is empty. + +NOTE: The `MsgExec` message removes a grant if the grant has expired. + +### MsgExec + +When a grantee wants to execute a transaction on behalf of a granter, they must send `MsgExec`. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/authz/v1beta1/tx.proto#L52-L63 +``` + +The message handling should fail if: + +* provided `Authorization` is not implemented. +* grantee doesn't have permission to run the transaction. +* if granted authorization is expired. + +## Events + +The authz module emits proto events defined in [the Protobuf reference](https://buf.build/cosmos/cosmos-sdk/docs/main/cosmos.authz.v1beta1#cosmos.authz.v1beta1.EventGrant). + +## Client + +### CLI + +A user can query and interact with the `authz` module using the CLI. + +#### Query + +The `query` commands allow users to query `authz` state. + +```bash +simd query authz --help +``` + +##### grants + +The `grants` command allows users to query grants for a granter-grantee pair. If the message type URL is set, it selects grants only for that message type. + +```bash +simd query authz grants [granter-addr] [grantee-addr] [msg-type-url]? [flags] +``` + +Example: + +```bash +simd query authz grants cosmos1.. cosmos1.. /cosmos.bank.v1beta1.MsgSend +``` + +Example Output: + +```bash +grants: +- authorization: + '@type': /cosmos.bank.v1beta1.SendAuthorization + spend_limit: + - amount: "100" + denom: stake + expiration: "2022-01-01T00:00:00Z" +pagination: null +``` + +#### Transactions + +The `tx` commands allow users to interact with the `authz` module. + +```bash +simd tx authz --help +``` + +##### exec + +The `exec` command allows a grantee to execute a transaction on behalf of granter. + +```bash + simd tx authz exec [tx-json-file] --from [grantee] [flags] +``` + +Example: + +```bash +simd tx authz exec tx.json --from=cosmos1.. +``` + +##### grant + +The `grant` command allows a granter to grant an authorization to a grantee. + +```bash +simd tx authz grant --from [flags] +``` +- The `send` authorization_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](#SendAuthorization) + +Example: + +```bash + simd tx authz grant cosmos1.. send --spend-limit=100stake --allow-list=cosmos1...,cosmos2... --from=cosmos1.. +``` +- The `generic` authorization_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` ( required) documented [here](#GenericAuthorization). + +> Note: `msg-type` is any valid Cosmos SDK `Msg` type url. + +Example: +```bash + simd tx authz grant cosmos1.. generic --msg-type=/cosmos.bank.v1beta1.MsgSend --from=cosmos1.. +``` +- The `delegate`,`unbond`,`redelegate` authorization_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](#StakeAuthorization). +> Note: `allowed-validators` and `deny-validators` cannot both be empty. `spend-limit` represents the `MaxTokens` + +Example: + +```bash +simd tx authz grant cosmos1.. delegate --spend-limit=100stake --allowed-validators=cosmos...,cosmos... --deny-validators=cosmos... --from=cosmos1.. +``` + +##### revoke + +The `revoke` command allows a granter to revoke an authorization from a grantee. + +```bash +simd tx authz revoke [grantee] [msg-type-url] --from=[granter] [flags] +``` + +Example: + +```bash +simd tx authz revoke cosmos1.. /cosmos.bank.v1beta1.MsgSend --from=cosmos1.. +``` + +### gRPC + +A user can query the `authz` module using gRPC endpoints. + +#### Grants + +The `Grants` endpoint allows users to query grants for a granter-grantee pair. If the message type URL is set, it selects grants only for that message type. + +```bash +cosmos.authz.v1beta1.Query/Grants +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"granter":"cosmos1..","grantee":"cosmos1..","msg_type_url":"/cosmos.bank.v1beta1.MsgSend"}' \ + localhost:9090 \ + cosmos.authz.v1beta1.Query/Grants +``` + +Example Output: + +```bash +{ + "grants": [ + { + "authorization": { + "@type": "/cosmos.bank.v1beta1.SendAuthorization", + "spendLimit": [ + { + "denom":"stake", + "amount":"100" + } + ] + }, + "expiration": "2022-01-01T00:00:00Z" + } + ] +} +``` + +### REST + +A user can query the `authz` module using REST endpoints. + +```bash +/cosmos/authz/v1beta1/grants +``` + +Example: + +```bash +curl "localhost:1317/cosmos/authz/v1beta1/grants?granter=cosmos1..&grantee=cosmos1..&msg_type_url=/cosmos.bank.v1beta1.MsgSend" +``` + +Example Output: + +```bash +{ + "grants": [ + { + "authorization": { + "@type": "/cosmos.bank.v1beta1.SendAuthorization", + "spend_limit": [ + { + "denom": "stake", + "amount": "100" + } + ] + }, + "expiration": "2022-01-01T00:00:00Z" + } + ], + "pagination": null +} +``` diff --git a/docs/sdk/v0.53/module-reference/bank.mdx b/docs/sdk/v0.53/module-reference/bank.mdx new file mode 100644 index 00000000..95e40a71 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/bank.mdx @@ -0,0 +1,1041 @@ +--- +title: "`x/bank`" + +--- + +--- + +--- + +## Abstract + +This document specifies the bank module of the Cosmos SDK. + +The bank module is responsible for handling multi-asset coin transfers between +accounts and tracking special-case pseudo-transfers which must work differently +with particular kinds of accounts (notably delegating/undelegating for vesting +accounts). It exposes several interfaces with varying capabilities for secure +interaction with other modules which must alter user balances. + +In addition, the bank module tracks and provides query support for the total +supply of all assets used in the application. + +This module is used in the Cosmos Hub. + +## Contents + +* [Supply](#supply) + * [Total Supply](#total-supply) +* [Module Accounts](#module-accounts) + * [Permissions](#permissions) +* [State](#state) +* [Params](#params) +* [Keepers](#keepers) +* [Messages](#messages) +* [Events](#events) + * [Message Events](#message-events) + * [Keeper Events](#keeper-events) +* [Parameters](#parameters) + * [SendEnabled](#sendenabled) + * [DefaultSendEnabled](#defaultsendenabled) +* [Client](#client) + * [CLI](#cli) + * [Query](#query) + * [Transactions](#transactions) +* [gRPC](#grpc) + +## Supply + +The `supply` functionality: + +* passively tracks the total supply of coins within a chain, +* provides a pattern for modules to hold/interact with `Coins`, and +* introduces the invariant check to verify a chain's total supply. + +### Total Supply + +The total `Supply` of the network is equal to the sum of all coins from the +account. The total supply is updated every time a `Coin` is minted (eg: as part +of the inflation mechanism) or burned (eg: due to slashing or if a governance +proposal is vetoed). + +## Module Accounts + +The supply functionality introduces a new type of `auth.Account` which can be used by +modules to allocate tokens and in special cases mint or burn tokens. At a base +level these module accounts are capable of sending/receiving tokens to and from +`auth.Account`s and other module accounts. This design replaces previous +alternative designs where, to hold tokens, modules would burn the incoming +tokens from the sender account, and then track those tokens internally. Later, +in order to send tokens, the module would need to effectively mint tokens +within a destination account. The new design removes duplicate logic between +modules to perform this accounting. + +The `ModuleAccount` interface is defined as follows: + +```go +type ModuleAccount interface { + auth.Account // same methods as the Account interface + + GetName() string // name of the module; used to obtain the address + GetPermissions() []string // permissions of module account + HasPermission(string) bool +} +``` + +> **WARNING!** +> Any module or message handler that allows either direct or indirect sending of funds must explicitly guarantee those funds cannot be sent to module accounts (unless allowed). + +The supply `Keeper` also introduces new wrapper functions for the auth `Keeper` +and the bank `Keeper` that are related to `ModuleAccount`s in order to be able +to: + +* Get and set `ModuleAccount`s by providing the `Name`. +* Send coins from and to other `ModuleAccount`s or standard `Account`s + (`BaseAccount` or `VestingAccount`) by passing only the `Name`. +* `Mint` or `Burn` coins for a `ModuleAccount` (restricted to its permissions). + +### Permissions + +Each `ModuleAccount` has a different set of permissions that provide different +object capabilities to perform certain actions. Permissions need to be +registered upon the creation of the supply `Keeper` so that every time a +`ModuleAccount` calls the allowed functions, the `Keeper` can lookup the +permissions to that specific account and perform or not perform the action. + +The available permissions are: + +* `Minter`: allows for a module to mint a specific amount of coins. +* `Burner`: allows for a module to burn a specific amount of coins. +* `Staking`: allows for a module to delegate and undelegate a specific amount of coins. + +## State + +The `x/bank` module keeps state of the following primary objects: + +1. Account balances +2. Denomination metadata +3. The total supply of all balances +4. Information on which denominations are allowed to be sent. + +In addition, the `x/bank` module keeps the following indexes to manage the +aforementioned state: + +* Supply Index: `0x0 | byte(denom) -> byte(amount)` +* Denom Metadata Index: `0x1 | byte(denom) -> ProtocolBuffer(Metadata)` +* Balances Index: `0x2 | byte(address length) | []byte(address) | []byte(balance.Denom) -> ProtocolBuffer(balance)` +* Reverse Denomination to Address Index: `0x03 | byte(denom) | 0x00 | []byte(address) -> 0` + +## Params + +The bank module stores it's params in state with the prefix of `0x05`, +it can be updated with governance or the address with authority. + +* Params: `0x05 | ProtocolBuffer(Params)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/bank.proto#L12-L23 +``` + +## Keepers + +The bank module provides these exported keeper interfaces that can be +passed to other modules that read or update account balances. Modules +should use the least-permissive interface that provides the functionality they +require. + +Best practices dictate careful review of `bank` module code to ensure that +permissions are limited in the way that you expect. + +### Denied Addresses + +The `x/bank` module accepts a map of addresses that are considered blocklisted +from directly and explicitly receiving funds through means such as `MsgSend` and +`MsgMultiSend` and direct API calls like `SendCoinsFromModuleToAccount`. + +Typically, these addresses are module accounts. If these addresses receive funds +outside the expected rules of the state machine, invariants are likely to be +broken and could result in a halted network. + +By providing the `x/bank` module with a blocklisted set of addresses, an error occurs for the operation if a user or client attempts to directly or indirectly send funds to a blocklisted account, for example, by using [IBC](https://ibc.cosmos.network). + +### Common Types + +#### Input + +An input of a multiparty transfer + +```protobuf +// Input models transaction input. +message Input { + string address = 1; + repeated cosmos.base.v1beta1.Coin coins = 2; +} +``` + +#### Output + +An output of a multiparty transfer. + +```protobuf +// Output models transaction outputs. +message Output { + string address = 1; + repeated cosmos.base.v1beta1.Coin coins = 2; +} +``` + +### BaseKeeper + +The base keeper provides full-permission access: the ability to arbitrary modify any account's balance and mint or burn coins. + +Restricted permission to mint per module could be achieved by using baseKeeper with `WithMintCoinsRestriction` to give specific restrictions to mint (e.g. only minting certain denom). + +```go +// Keeper defines a module interface that facilitates the transfer of coins +// between accounts. +type Keeper interface { + SendKeeper + WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper + + InitGenesis(context.Context, *types.GenesisState) + ExportGenesis(context.Context) *types.GenesisState + + GetSupply(ctx context.Context, denom string) sdk.Coin + HasSupply(ctx context.Context, denom string) bool + GetPaginatedTotalSupply(ctx context.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) + IterateTotalSupply(ctx context.Context, cb func(sdk.Coin) bool) + GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, bool) + HasDenomMetaData(ctx context.Context, denom string) bool + SetDenomMetaData(ctx context.Context, denomMetaData types.Metadata) + IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) + + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + DelegateCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + UndelegateCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + + DelegateCoins(ctx context.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error + UndelegateCoins(ctx context.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error + + // GetAuthority gets the address capable of executing governance proposal messages. Usually the gov module account. + GetAuthority() string + + types.QueryServer +} +``` + +### SendKeeper + +The send keeper provides access to account balances and the ability to transfer coins between +accounts. The send keeper does not alter the total supply (mint or burn coins). + +```go +// SendKeeper defines a module interface that facilitates the transfer of coins +// between accounts without the possibility of creating coins. +type SendKeeper interface { + ViewKeeper + + AppendSendRestriction(restriction SendRestrictionFn) + PrependSendRestriction(restriction SendRestrictionFn) + ClearSendRestriction() + + InputOutputCoins(ctx context.Context, input types.Input, outputs []types.Output) error + SendCoins(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error + + GetParams(ctx context.Context) types.Params + SetParams(ctx context.Context, params types.Params) error + + IsSendEnabledDenom(ctx context.Context, denom string) bool + SetSendEnabled(ctx context.Context, denom string, value bool) + SetAllSendEnabled(ctx context.Context, sendEnableds []*types.SendEnabled) + DeleteSendEnabled(ctx context.Context, denom string) + IterateSendEnabledEntries(ctx context.Context, cb func(denom string, sendEnabled bool) (stop bool)) + GetAllSendEnabledEntries(ctx context.Context) []types.SendEnabled + + IsSendEnabledCoin(ctx context.Context, coin sdk.Coin) bool + IsSendEnabledCoins(ctx context.Context, coins ...sdk.Coin) error + + BlockedAddr(addr sdk.AccAddress) bool +} +``` + +#### Send Restrictions + +The `SendKeeper` applies a `SendRestrictionFn` before each transfer of funds. + +```golang +// A SendRestrictionFn can restrict sends and/or provide a new receiver address. +type SendRestrictionFn func(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) (newToAddr sdk.AccAddress, err error) +``` + +After the `SendKeeper` (or `BaseKeeper`) has been created, send restrictions can be added to it using the `AppendSendRestriction` or `PrependSendRestriction` functions. +Both functions compose the provided restriction with any previously provided restrictions. +`AppendSendRestriction` adds the provided restriction to be run after any previously provided send restrictions. +`PrependSendRestriction` adds the restriction to be run before any previously provided send restrictions. +The composition will short-circuit when an error is encountered. I.e. if the first one returns an error, the second is not run. + +During `SendCoins`, the send restriction is applied before coins are removed from the from address and adding them to the to address. +During `InputOutputCoins`, the send restriction is applied after the input coins are removed and once for each output before the funds are added. + +A send restriction function should make use of a custom value in the context to allow bypassing that specific restriction. + +Send Restrictions are not placed on `ModuleToAccount` or `ModuleToModule` transfers. This is done due to modules needing to move funds to user accounts and other module accounts. This is a design decision to allow for more flexibility in the state machine. The state machine should be able to move funds between module accounts and user accounts without restrictions. + +Secondly this limitation would limit the usage of the state machine even for itself. users would not be able to receive rewards, not be able to move funds between module accounts. In the case that a user sends funds from a user account to the community pool and then a governance proposal is used to get those tokens into the users account this would fall under the discretion of the app chain developer to what they would like to do here. We can not make strong assumptions here. +Thirdly, this issue could lead into a chain halt if a token is disabled and the token is moved in the begin/endblock. This is the last reason we see the current change and more damaging then beneficial for users. + +For example, in your module's keeper package, you'd define the send restriction function: + +```golang +var _ banktypes.SendRestrictionFn = Keeper{}.SendRestrictionFn + +func (k Keeper) SendRestrictionFn(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.AccAddress, error) { + // Bypass if the context says to. + if mymodule.HasBypass(ctx) { + return toAddr, nil + } + + // Your custom send restriction logic goes here. + return nil, errors.New("not implemented") +} +``` + +The bank keeper should be provided to your keeper's constructor so the send restriction can be added to it: + +```golang +func NewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, bankKeeper mymodule.BankKeeper) Keeper { + rv := Keeper{/*...*/} + bankKeeper.AppendSendRestriction(rv.SendRestrictionFn) + return rv +} +``` + +Then, in the `mymodule` package, define the context helpers: + +```golang +const bypassKey = "bypass-mymodule-restriction" + +// WithBypass returns a new context that will cause the mymodule bank send restriction to be skipped. +func WithBypass(ctx context.Context) context.Context { + return sdk.UnwrapSDKContext(ctx).WithValue(bypassKey, true) +} + +// WithoutBypass returns a new context that will cause the mymodule bank send restriction to not be skipped. +func WithoutBypass(ctx context.Context) context.Context { + return sdk.UnwrapSDKContext(ctx).WithValue(bypassKey, false) +} + +// HasBypass checks the context to see if the mymodule bank send restriction should be skipped. +func HasBypass(ctx context.Context) bool { + bypassValue := ctx.Value(bypassKey) + if bypassValue == nil { + return false + } + bypass, isBool := bypassValue.(bool) + return isBool && bypass +} +``` + +Now, anywhere where you want to use `SendCoins` or `InputOutputCoins`, but you don't want your send restriction applied: + +```golang +func (k Keeper) DoThing(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error { + return k.bankKeeper.SendCoins(mymodule.WithBypass(ctx), fromAddr, toAddr, amt) +} +``` + +### ViewKeeper + +The view keeper provides read-only access to account balances. The view keeper does not have balance alteration functionality. All balance lookups are `O(1)`. + +```go +// ViewKeeper defines a module interface that facilitates read only access to +// account balances. +type ViewKeeper interface { + ValidateBalance(ctx context.Context, addr sdk.AccAddress) error + HasBalance(ctx context.Context, addr sdk.AccAddress, amt sdk.Coin) bool + + GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins + GetAccountsBalances(ctx context.Context) []types.Balance + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + LockedCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoin(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + + IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(coin sdk.Coin) (stop bool)) + IterateAllBalances(ctx context.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) +} +``` + +## Messages + +### MsgSend + +Send coins from one address to another. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L38-L53 +``` + +The message will fail under the following conditions: + +* The coins do not have sending enabled +* The `to` address is restricted + +### MsgMultiSend + +Send coins from one sender and to a series of different address. If any of the receiving addresses do not correspond to an existing account, a new account is created. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L58-L69 +``` + +The message will fail under the following conditions: + +* Any of the coins do not have sending enabled +* Any of the `to` addresses are restricted +* Any of the coins are locked +* The inputs and outputs do not correctly correspond to one another + +### MsgUpdateParams + +The `bank` module params can be updated through `MsgUpdateParams`, which can be done using governance proposal. The signer will always be the `gov` module account address. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L74-L88 +``` + +The message handling can fail if: + +* signer is not the gov module account address. + +### MsgSetSendEnabled + +Used with the x/gov module to set create/edit SendEnabled entries. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L96-L117 +``` + +The message will fail under the following conditions: + +* The authority is not a bech32 address. +* The authority is not x/gov module's address. +* There are multiple SendEnabled entries with the same Denom. +* One or more SendEnabled entries has an invalid Denom. + +## Events + +The bank module emits the following events: + +### Message Events + +#### MsgSend + +| Type | Attribute Key | Attribute Value | +| -------- | ------------- | ------------------ | +| transfer | recipient | {recipientAddress} | +| transfer | amount | {amount} | +| message | module | bank | +| message | action | send | +| message | sender | {senderAddress} | + +#### MsgMultiSend + +| Type | Attribute Key | Attribute Value | +| -------- | ------------- | ------------------ | +| transfer | recipient | {recipientAddress} | +| transfer | amount | {amount} | +| message | module | bank | +| message | action | multisend | +| message | sender | {senderAddress} | + +### Keeper Events + +In addition to message events, the bank keeper will produce events when the following methods are called (or any method which ends up calling them) + +#### MintCoins + +```json +{ + "type": "coinbase", + "attributes": [ + { + "key": "minter", + "value": "{{sdk.AccAddress of the module minting coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being minted}}", + "index": true + } + ] +} +``` + +```json +{ + "type": "coin_received", + "attributes": [ + { + "key": "receiver", + "value": "{{sdk.AccAddress of the module minting coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being received}}", + "index": true + } + ] +} +``` + +#### BurnCoins + +```json +{ + "type": "burn", + "attributes": [ + { + "key": "burner", + "value": "{{sdk.AccAddress of the module burning coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being burned}}", + "index": true + } + ] +} +``` + +```json +{ + "type": "coin_spent", + "attributes": [ + { + "key": "spender", + "value": "{{sdk.AccAddress of the module burning coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being burned}}", + "index": true + } + ] +} +``` + +#### addCoins + +```json +{ + "type": "coin_received", + "attributes": [ + { + "key": "receiver", + "value": "{{sdk.AccAddress of the address beneficiary of the coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being received}}", + "index": true + } + ] +} +``` + +#### subUnlockedCoins/DelegateCoins + +```json +{ + "type": "coin_spent", + "attributes": [ + { + "key": "spender", + "value": "{{sdk.AccAddress of the address which is spending coins}}", + "index": true + }, + { + "key": "amount", + "value": "{{sdk.Coins being spent}}", + "index": true + } + ] +} +``` + +## Parameters + +The bank module contains the following parameters + +### SendEnabled + +The SendEnabled parameter is now deprecated and not to be use. It is replaced +with state store records. + +### DefaultSendEnabled + +The default send enabled value controls send transfer capability for all +coin denominations unless specifically included in the array of `SendEnabled` +parameters. + +## Client + +### CLI + +A user can query and interact with the `bank` module using the CLI. + +#### Query + +The `query` commands allow users to query `bank` state. + +```shell +simd query bank --help +``` + +##### balances + +The `balances` command allows users to query account balances by address. + +```shell +simd query bank balances [address] [flags] +``` + +Example: + +```shell +simd query bank balances cosmos1.. +``` + +Example Output: + +```yml +balances: +- amount: "1000000000" + denom: stake +pagination: + next_key: null + total: "0" +``` + +##### denom-metadata + +The `denom-metadata` command allows users to query metadata for coin denominations. A user can query metadata for a single denomination using the `--denom` flag or all denominations without it. + +```shell +simd query bank denom-metadata [flags] +``` + +Example: + +```shell +simd query bank denom-metadata --denom stake +``` + +Example Output: + +```yml +metadata: + base: stake + denom_units: + - aliases: + - STAKE + denom: stake + description: native staking token of simulation app + display: stake + name: SimApp Token + symbol: STK +``` + +##### total + +The `total` command allows users to query the total supply of coins. A user can query the total supply for a single coin using the `--denom` flag or all coins without it. + +```shell +simd query bank total [flags] +``` + +Example: + +```shell +simd query bank total --denom stake +``` + +Example Output: + +```yml +amount: "10000000000" +denom: stake +``` + +##### send-enabled + +The `send-enabled` command allows users to query for all or some SendEnabled entries. + +```shell +simd query bank send-enabled [denom1 ...] [flags] +``` + +Example: + +```shell +simd query bank send-enabled +``` + +Example output: + +```yml +send_enabled: +- denom: foocoin + enabled: true +- denom: barcoin +pagination: + next-key: null + total: 2 +``` + +#### Transactions + +The `tx` commands allow users to interact with the `bank` module. + +```shell +simd tx bank --help +``` + +##### send + +The `send` command allows users to send funds from one account to another. + +```shell +simd tx bank send [from_key_or_address] [to_address] [amount] [flags] +``` + +Example: + +```shell +simd tx bank send cosmos1.. cosmos1.. 100stake +``` + +## gRPC + +A user can query the `bank` module using gRPC endpoints. + +### Balance + +The `Balance` endpoint allows users to query account balance by address for a given denomination. + +```shell +cosmos.bank.v1beta1.Query/Balance +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"address":"cosmos1..","denom":"stake"}' \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/Balance +``` + +Example Output: + +```json +{ + "balance": { + "denom": "stake", + "amount": "1000000000" + } +} +``` + +### AllBalances + +The `AllBalances` endpoint allows users to query account balance by address for all denominations. + +```shell +cosmos.bank.v1beta1.Query/AllBalances +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"address":"cosmos1.."}' \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/AllBalances +``` + +Example Output: + +```json +{ + "balances": [ + { + "denom": "stake", + "amount": "1000000000" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### DenomMetadata + +The `DenomMetadata` endpoint allows users to query metadata for a single coin denomination. + +```shell +cosmos.bank.v1beta1.Query/DenomMetadata +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"denom":"stake"}' \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/DenomMetadata +``` + +Example Output: + +```json +{ + "metadata": { + "description": "native staking token of simulation app", + "denomUnits": [ + { + "denom": "stake", + "aliases": [ + "STAKE" + ] + } + ], + "base": "stake", + "display": "stake", + "name": "SimApp Token", + "symbol": "STK" + } +} +``` + +### DenomsMetadata + +The `DenomsMetadata` endpoint allows users to query metadata for all coin denominations. + +```shell +cosmos.bank.v1beta1.Query/DenomsMetadata +``` + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/DenomsMetadata +``` + +Example Output: + +```json +{ + "metadatas": [ + { + "description": "native staking token of simulation app", + "denomUnits": [ + { + "denom": "stake", + "aliases": [ + "STAKE" + ] + } + ], + "base": "stake", + "display": "stake", + "name": "SimApp Token", + "symbol": "STK" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### DenomOwners + +The `DenomOwners` endpoint allows users to query metadata for a single coin denomination. + +```shell +cosmos.bank.v1beta1.Query/DenomOwners +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"denom":"stake"}' \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/DenomOwners +``` + +Example Output: + +```json +{ + "denomOwners": [ + { + "address": "cosmos1..", + "balance": { + "denom": "stake", + "amount": "5000000000" + } + }, + { + "address": "cosmos1..", + "balance": { + "denom": "stake", + "amount": "5000000000" + } + }, + ], + "pagination": { + "total": "2" + } +} +``` + +### TotalSupply + +The `TotalSupply` endpoint allows users to query the total supply of all coins. + +```shell +cosmos.bank.v1beta1.Query/TotalSupply +``` + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/TotalSupply +``` + +Example Output: + +```json +{ + "supply": [ + { + "denom": "stake", + "amount": "10000000000" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### SupplyOf + +The `SupplyOf` endpoint allows users to query the total supply of a single coin. + +```shell +cosmos.bank.v1beta1.Query/SupplyOf +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"denom":"stake"}' \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/SupplyOf +``` + +Example Output: + +```json +{ + "amount": { + "denom": "stake", + "amount": "10000000000" + } +} +``` + +### Params + +The `Params` endpoint allows users to query the parameters of the `bank` module. + +```shell +cosmos.bank.v1beta1.Query/Params +``` + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/Params +``` + +Example Output: + +```json +{ + "params": { + "defaultSendEnabled": true + } +} +``` + +### SendEnabled + +The `SendEnabled` enpoints allows users to query the SendEnabled entries of the `bank` module. + +Any denominations NOT returned, use the `Params.DefaultSendEnabled` value. + +```shell +cosmos.bank.v1beta1.Query/SendEnabled +``` + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/SendEnabled +``` + +Example Output: + +```json +{ + "send_enabled": [ + { + "denom": "foocoin", + "enabled": true + }, + { + "denom": "barcoin" + } + ], + "pagination": { + "next-key": null, + "total": 2 + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/consensus.mdx b/docs/sdk/v0.53/module-reference/consensus.mdx new file mode 100644 index 00000000..6df6482f --- /dev/null +++ b/docs/sdk/v0.53/module-reference/consensus.mdx @@ -0,0 +1,10 @@ +--- +title: "`x/consensus`" + +--- + +--- + +--- + +Functionality to modify CometBFT's ABCI consensus params. diff --git a/docs/sdk/v0.53/module-reference/crisis.mdx b/docs/sdk/v0.53/module-reference/crisis.mdx new file mode 100644 index 00000000..b91647aa --- /dev/null +++ b/docs/sdk/v0.53/module-reference/crisis.mdx @@ -0,0 +1,115 @@ +--- +title: "`x/crisis`" + +--- + +--- + +--- + +NOTE: `x/crisis` is deprecated as of Cosmos SDK v0.53 and will be removed in the next release. + +## Overview + +The crisis module halts the blockchain under the circumstance that a blockchain +invariant is broken. Invariants can be registered with the application during the +application initialization process. + +## Contents + +* [State](#state) +* [Messages](#messages) +* [Events](#events) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + +## State + +### ConstantFee + +Due to the anticipated large gas cost requirement to verify an invariant (and +potential to exceed the maximum allowable block gas limit) a constant fee is +used instead of the standard gas consumption method. The constant fee is +intended to be larger than the anticipated gas cost of running the invariant +with the standard gas consumption method. + +The ConstantFee param is stored in the module params state with the prefix of `0x01`, +it can be updated with governance or the address with authority. + +* Params: `mint/params -> legacy_amino(sdk.Coin)` + +## Messages + +In this section we describe the processing of the crisis messages and the +corresponding updates to the state. + +### MsgVerifyInvariant + +Blockchain invariants can be checked using the `MsgVerifyInvariant` message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/crisis/v1beta1/tx.proto#L26-L42 +``` + +This message is expected to fail if: + +* the sender does not have enough coins for the constant fee +* the invariant route is not registered + +This message checks the invariant provided, and if the invariant is broken it +panics, halting the blockchain. If the invariant is broken, the constant fee is +never deducted as the transaction is never committed to a block (equivalent to +being refunded). However, if the invariant is not broken, the constant fee will +not be refunded. + +## Events + +The crisis module emits the following events: + +### Handlers + +#### MsgVerifyInvariance + +| Type | Attribute Key | Attribute Value | +|-----------|---------------|------------------| +| invariant | route | {invariantRoute} | +| message | module | crisis | +| message | action | verify_invariant | +| message | sender | {senderAddress} | + +## Parameters + +The crisis module contains the following parameters: + +| Key | Type | Example | +|-------------|---------------|-----------------------------------| +| ConstantFee | object (coin) | {"denom":"uatom","amount":"1000"} | + +## Client + +### CLI + +A user can query and interact with the `crisis` module using the CLI. + +#### Transactions + +The `tx` commands allow users to interact with the `crisis` module. + +```bash +simd tx crisis --help +``` + +##### invariant-broken + +The `invariant-broken` command submits proof when an invariant was broken to halt the chain + +```bash +simd tx crisis invariant-broken [module-name] [invariant-route] [flags] +``` + +Example: + +```bash +simd tx crisis invariant-broken bank total-supply --from=[keyname or address] +``` diff --git a/docs/sdk/v0.53/module-reference/distribution.mdx b/docs/sdk/v0.53/module-reference/distribution.mdx new file mode 100644 index 00000000..7f050638 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/distribution.mdx @@ -0,0 +1,1130 @@ +--- +title: "`x/distribution`" + +--- + +--- + +--- + +## Overview + +This _simple_ distribution mechanism describes a functional way to passively +distribute rewards between validators and delegators. Note that this mechanism does +not distribute funds in as precisely as active reward distribution mechanisms and +will therefore be upgraded in the future. + +The mechanism operates as follows. Collected rewards are pooled globally and +divided out passively to validators and delegators. Each validator has the +opportunity to charge commission to the delegators on the rewards collected on +behalf of the delegators. Fees are collected directly into a global reward pool +and validator proposer-reward pool. Due to the nature of passive accounting, +whenever changes to parameters which affect the rate of reward distribution +occurs, withdrawal of rewards must also occur. + +* Whenever withdrawing, one must withdraw the maximum amount they are entitled + to, leaving nothing in the pool. +* Whenever bonding, unbonding, or re-delegating tokens to an existing account, a + full withdrawal of the rewards must occur (as the rules for lazy accounting + change). +* Whenever a validator chooses to change the commission on rewards, all accumulated + commission rewards must be simultaneously withdrawn. + +The above scenarios are covered in `hooks.md`. + +The distribution mechanism outlined herein is used to lazily distribute the +following rewards between validators and associated delegators: + +* multi-token fees to be socially distributed +* inflated staked asset provisions +* validator commission on all rewards earned by their delegators stake + +Fees are pooled within a global pool. The mechanisms used allow for validators +and delegators to independently and lazily withdraw their rewards. + +## Shortcomings + +As a part of the lazy computations, each delegator holds an accumulation term +specific to each validator which is used to estimate what their approximate +fair portion of tokens held in the global fee pool is owed to them. + +```text +entitlement = delegator-accumulation / all-delegators-accumulation +``` + +Under the circumstance that there was constant and equal flow of incoming +reward tokens every block, this distribution mechanism would be equal to the +active distribution (distribute individually to all delegators each block). +However, this is unrealistic so deviations from the active distribution will +occur based on fluctuations of incoming reward tokens as well as timing of +reward withdrawal by other delegators. + +If you happen to know that incoming rewards are about to significantly increase, +you are incentivized to not withdraw until after this event, increasing the +worth of your existing _accum_. See [#2764](https://github.com/cosmos/cosmos-sdk/issues/2764) +for further details. + +## Effect on Staking + +Charging commission on Atom provisions while also allowing for Atom-provisions +to be auto-bonded (distributed directly to the validators bonded stake) is +problematic within BPoS. Fundamentally, these two mechanisms are mutually +exclusive. If both commission and auto-bonding mechanisms are simultaneously +applied to the staking-token then the distribution of staking-tokens between +any validator and its delegators will change with each block. This then +necessitates a calculation for each delegation records for each block - +which is considered computationally expensive. + +In conclusion, we can only have Atom commission and unbonded atoms +provisions or bonded atom provisions with no Atom commission, and we elect to +implement the former. Stakeholders wishing to rebond their provisions may elect +to set up a script to periodically withdraw and rebond rewards. + +## Contents + +* [Concepts](#concepts) +* [State](#state) + * [FeePool](#feepool) + * [Validator Distribution](#validator-distribution) + * [Delegation Distribution](#delegation-distribution) + * [Params](#params) +* [Begin Block](#begin-block) +* [Messages](#messages) +* [Hooks](#hooks) +* [Events](#events) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + +## Concepts + +In Proof of Stake (PoS) blockchains, rewards gained from transaction fees are paid to validators. The fee distribution module fairly distributes the rewards to the validators' constituent delegators. + +Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation. +The rewards for a single validator can then be calculated by taking the total rewards for the period before the delegation started, minus the current total rewards. +To learn more, see the [F1 Fee Distribution paper](https://github.com/cosmos/cosmos-sdk/tree/main/docs/spec/fee_distribution/f1_fee_distr.pdf). + +The commission to the validator is paid when the validator is removed or when the validator requests a withdrawal. +The commission is calculated and incremented at every `BeginBlock` operation to update accumulated fee amounts. + +The rewards to a delegator are distributed when the delegation is changed or removed, or a withdrawal is requested. +Before rewards are distributed, all slashes to the validator that occurred during the current delegation are applied. + +### Reference Counting in F1 Fee Distribution + +In F1 fee distribution, the rewards a delegator receives are calculated when their delegation is withdrawn. This calculation must read the terms of the summation of rewards divided by the share of tokens from the period which they ended when they delegated, and the final period that was created for the withdrawal. + +Additionally, as slashes change the amount of tokens a delegation will have (but we calculate this lazily, +only when a delegator un-delegates), we must calculate rewards in separate periods before / after any slashes +which occurred in between when a delegator delegated and when they withdrew their rewards. Thus slashes, like +delegations, reference the period which was ended by the slash event. + +All stored historical rewards records for periods which are no longer referenced by any delegations +or any slashes can thus be safely removed, as they will never be read (future delegations and future +slashes will always reference future periods). This is implemented by tracking a `ReferenceCount` +along with each historical reward storage entry. Each time a new object (delegation or slash) +is created which might need to reference the historical record, the reference count is incremented. +Each time one object which previously needed to reference the historical record is deleted, the reference +count is decremented. If the reference count hits zero, the historical record is deleted. + +### External Community Pool Keepers + +An external pool community keeper is defined as: + +```go +// ExternalCommunityPoolKeeper is the interface that an external community pool module keeper must fulfill +// for x/distribution to properly accept it as a community pool fund destination. +type ExternalCommunityPoolKeeper interface { + // GetCommunityPoolModule gets the module name that funds should be sent to for the community pool. + // This is the address that x/distribution will send funds to for external management. + GetCommunityPoolModule() string + // FundCommunityPool allows an account to directly fund the community fund pool. + FundCommunityPool(ctx sdk.Context, amount sdk.Coins, senderAddr sdk.AccAddress) error + // DistributeFromCommunityPool distributes funds from the community pool module account to + // a receiver address. + DistributeFromCommunityPool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error +} +``` + +By default, the distribution module will use a community pool implementation that is internal. An external community pool +can be provided to the module which will have funds be diverted to it instead of the internal implementation. The reference +external community pool maintained by the Cosmos SDK is [`x/protocolpool`](../protocolpool/README.md). + +## State + +### FeePool + +All globally tracked parameters for distribution are stored within +`FeePool`. Rewards are collected and added to the reward pool and +distributed to validators/delegators from here. + +Note that the reward pool holds decimal coins (`DecCoins`) to allow +for fractions of coins to be received from operations like inflation. +When coins are distributed from the pool they are truncated back to +`sdk.Coins` which are non-decimal. + +* FeePool: `0x00 -> ProtocolBuffer(FeePool)` + +```go +// coins with decimal +type DecCoins []DecCoin + +type DecCoin struct { + Amount math.LegacyDec + Denom string +} +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L116-L123 +``` + +### Validator Distribution + +Validator distribution information for the relevant validator is updated each time: + +1. delegation amount to a validator is updated, +2. any delegator withdraws from a validator, or +3. the validator withdraws its commission. + +* ValidatorDistInfo: `0x02 | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(validatorDistribution)` + +```go +type ValidatorDistInfo struct { + OperatorAddress sdk.AccAddress + SelfBondRewards sdkmath.DecCoins + ValidatorCommission types.ValidatorAccumulatedCommission +} +``` + +### Delegation Distribution + +Each delegation distribution only needs to record the height at which it last +withdrew fees. Because a delegation must withdraw fees each time it's +properties change (aka bonded tokens etc.) its properties will remain constant +and the delegator's _accumulation_ factor can be calculated passively knowing +only the height of the last withdrawal and its current properties. + +* DelegationDistInfo: `0x02 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValOperatorAddrLen (1 byte) | ValOperatorAddr -> ProtocolBuffer(delegatorDist)` + +```go +type DelegationDistInfo struct { + WithdrawalHeight int64 // last time this delegation withdrew rewards +} +``` + +### Params + +The distribution module stores it's params in state with the prefix of `0x09`, +it can be updated with governance or the address with authority. + +* Params: `0x09 | ProtocolBuffer(Params)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/distribution.proto#L12-L42 +``` + +## Begin Block + +At each `BeginBlock`, all fees received in the previous block are transferred to +the distribution `ModuleAccount` account. When a delegator or validator +withdraws their rewards, they are taken out of the `ModuleAccount`. During begin +block, the different claims on the fees collected are updated as follows: + +* The reserve community tax is charged. +* The remainder is distributed proportionally by voting power to all bonded validators + +### The Distribution Scheme + +See [params](#params) for description of parameters. + +Let `fees` be the total fees collected in the previous block, including +inflationary rewards to the stake. All fees are collected in a specific module +account during the block. During `BeginBlock`, they are sent to the +`"distribution"` `ModuleAccount`. No other sending of tokens occurs. Instead, the +rewards each account is entitled to are stored, and withdrawals can be triggered +through the messages `FundCommunityPool`, `WithdrawValidatorCommission` and +`WithdrawDelegatorReward`. + +#### Reward to the Community Pool + +The community pool gets `community_tax * fees`, plus any remaining dust after +validators get their rewards that are always rounded down to the nearest +integer value. + +#### Using an External Community Pool + +Starting with Cosmos SDK v0.53.0, an external community pool, such as `x/protocolpool`, can be used in place of the `x/distribution` managed community pool. + +Please view the warning in the next section before deciding to use an external community pool. + +```go +// ExternalCommunityPoolKeeper is the interface that an external community pool module keeper must fulfill +// for x/distribution to properly accept it as a community pool fund destination. +type ExternalCommunityPoolKeeper interface { + // GetCommunityPoolModule gets the module name that funds should be sent to for the community pool. + // This is the address that x/distribution will send funds to for external management. + GetCommunityPoolModule() string + // FundCommunityPool allows an account to directly fund the community fund pool. + FundCommunityPool(ctx sdk.Context, amount sdk.Coins, senderAddr sdk.AccAddress) error + // DistributeFromCommunityPool distributes funds from the community pool module account to + // a receiver address. + DistributeFromCommunityPool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error +} +``` + +```go +app.DistrKeeper = distrkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[distrtypes.StoreKey]), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + distrkeeper.WithExternalCommunityPool(app.ProtocolPoolKeeper), // New option. +) +``` + +#### External Community Pool Usage Warning + +When using an external community pool with `x/distribution`, the following handlers will return an error: + +**QueryService** + +- `CommunityPool` + +**MsgService** + +- `CommunityPoolSpend` +- `FundCommunityPool` + +If you have services that rely on this functionality from `x/distribution`, please update them to use the `x/protocolpool` equivalents. + +#### Reward To the Validators + +The proposer receives no extra rewards. All fees are distributed among all the +bonded validators, including the proposer, in proportion to their consensus power. + +```text +powFrac = validator power / total bonded validator power +voteMul = 1 - community_tax +``` + +All validators receive `fees * voteMul * powFrac`. + +#### Rewards to Delegators + +Each validator's rewards are distributed to its delegators. The validator also +has a self-delegation that is treated like a regular delegation in +distribution calculations. + +The validator sets a commission rate. The commission rate is flexible, but each +validator sets a maximum rate and a maximum daily increase. These maximums cannot be exceeded and protect delegators from sudden increases of validator commission rates to prevent validators from taking all of the rewards. + +The outstanding rewards that the operator is entitled to are stored in +`ValidatorAccumulatedCommission`, while the rewards the delegators are entitled +to are stored in `ValidatorCurrentRewards`. The [F1 fee distribution scheme](#concepts) is used to calculate the rewards per delegator as they +withdraw or update their delegation, and is thus not handled in `BeginBlock`. + +#### Example Distribution + +For this example distribution, the underlying consensus engine selects block proposers in +proportion to their power relative to the entire bonded power. + +All validators are equally performant at including pre-commits in their proposed +blocks. Then hold `(pre_commits included) / (total bonded validator power)` +constant so that the amortized block reward for the validator is `( validator power / total bonded power) * (1 - community tax rate)` of +the total rewards. Consequently, the reward for a single delegator is: + +```text +(delegator proportion of the validator power / validator power) * (validator power / total bonded power) + * (1 - community tax rate) * (1 - validator commission rate) += (delegator proportion of the validator power / total bonded power) * (1 - +community tax rate) * (1 - validator commission rate) +``` + +## Messages + +### MsgSetWithdrawAddress + +By default, the withdraw address is the delegator address. To change its withdraw address, a delegator must send a `MsgSetWithdrawAddress` message. +Changing the withdraw address is possible only if the parameter `WithdrawAddrEnabled` is set to `true`. + +The withdraw address cannot be any of the module accounts. These accounts are blocked from being withdraw addresses by being added to the distribution keeper's `blockedAddrs` array at initialization. + +Response: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L49-L60 +``` + +```go +func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error + if k.blockedAddrs[withdrawAddr.String()] { + fail with "`{withdrawAddr}` is not allowed to receive external funds" + } + + if !k.GetWithdrawAddrEnabled(ctx) { + fail with `ErrSetWithdrawAddrDisabled` + } + + k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) +``` + +### MsgWithdrawDelegatorReward + +A delegator can withdraw its rewards. +Internally in the distribution module, this transaction simultaneously removes the previous delegation with associated rewards, the same as if the delegator simply started a new delegation of the same value. +The rewards are sent immediately from the distribution `ModuleAccount` to the withdraw address. +Any remainder (truncated decimals) are sent to the community pool. +The starting height of the delegation is set to the current validator period, and the reference count for the previous period is decremented. +The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. + +In the F1 distribution, the total rewards are calculated per validator period, and a delegator receives a piece of those rewards in proportion to their stake in the validator. +In basic F1, the total rewards that all the delegators are entitled to between to periods is calculated the following way. +Let `R(X)` be the total accumulated rewards up to period `X` divided by the tokens staked at that time. The delegator allocation is `R(X) * delegator_stake`. +Then the rewards for all the delegators for staking between periods `A` and `B` are `(R(B) - R(A)) * total stake`. +However, these calculated rewards don't account for slashing. + +Taking the slashes into account requires iteration. +Let `F(X)` be the fraction a validator is to be slashed for a slashing event that happened at period `X`. +If the validator was slashed at periods `P1, ..., PN`, where `A < P1`, `PN < B`, the distribution module calculates the individual delegator's rewards, `T(A, B)`, as follows: + +```go +stake := initial stake +rewards := 0 +previous := A +for P in P1, ..., PN`: + rewards = (R(P) - previous) * stake + stake = stake * F(P) + previous = P +rewards = rewards + (R(B) - R(PN)) * stake +``` + +The historical rewards are calculated retroactively by playing back all the slashes and then attenuating the delegator's stake at each step. +The final calculated stake is equivalent to the actual staked coins in the delegation with a margin of error due to rounding errors. + +Response: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L66-L77 +``` + +### WithdrawValidatorCommission + +The validator can send the WithdrawValidatorCommission message to withdraw their accumulated commission. +The commission is calculated in every block during `BeginBlock`, so no iteration is required to withdraw. +The amount withdrawn is deducted from the `ValidatorOutstandingRewards` variable for the validator. +Only integer amounts can be sent. If the accumulated awards have decimals, the amount is truncated before the withdrawal is sent, and the remainder is left to be withdrawn later. + +### FundCommunityPool + + + +This handler will return an error if an `ExternalCommunityPool` is used. + + + +This message sends coins directly from the sender to the community pool. + +The transaction fails if the amount cannot be transferred from the sender to the distribution module account. + +```go +func (k Keeper) FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error { + if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { + return err + } + + feePool, err := k.FeePool.Get(ctx) + if err != nil { + return err + } + + feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) + + if err := k.FeePool.Set(ctx, feePool); err != nil { + return err + } + + return nil +} +``` + +### Common distribution operations + +These operations take place during many different messages. + +#### Initialize delegation + +Each time a delegation is changed, the rewards are withdrawn and the delegation is reinitialized. +Initializing a delegation increments the validator period and keeps track of the starting period of the delegation. + +```go +// initialize starting info for a new delegation +func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) { + // period has already been incremented - we want to store the period ended by this delegation action + previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1 + + // increment reference count for the period we're going to track + k.incrementReferenceCount(ctx, val, previousPeriod) + + validator := k.stakingKeeper.Validator(ctx, val) + delegation := k.stakingKeeper.Delegation(ctx, del, val) + + // calculate delegation stake in tokens + // we don't store directly, so multiply delegation shares * (tokens per share) + // note: necessary to truncate so we don't allow withdrawing more rewards than owed + stake := validator.TokensFromSharesTruncated(delegation.GetShares()) + k.SetDelegatorStartingInfo(ctx, val, del, types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(ctx.BlockHeight()))) +} +``` + +### MsgUpdateParams + +Distribution module params can be updated through `MsgUpdateParams`, which can be done using governance proposal and the signer will always be gov module account address. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/v1beta1/tx.proto#L133-L147 +``` + +The message handling can fail if: + +* signer is not the gov module account address. + +## Hooks + +Available hooks that can be called by and from this module. + +### Create or modify delegation distribution + +* triggered-by: `staking.MsgDelegate`, `staking.MsgBeginRedelegate`, `staking.MsgUndelegate` + +#### Before + +* The delegation rewards are withdrawn to the withdraw address of the delegator. + The rewards include the current period and exclude the starting period. +* The validator period is incremented. + The validator period is incremented because the validator's power and share distribution might have changed. +* The reference count for the delegator's starting period is decremented. + +#### After + +The starting height of the delegation is set to the previous period. +Because of the `Before`-hook, this period is the last period for which the delegator was rewarded. + +### Validator created + +* triggered-by: `staking.MsgCreateValidator` + +When a validator is created, the following validator variables are initialized: + +* Historical rewards +* Current accumulated rewards +* Accumulated commission +* Total outstanding rewards +* Period + +By default, all values are set to a `0`, except period, which is set to `1`. + +### Validator removed + +* triggered-by: `staking.RemoveValidator` + +Outstanding commission is sent to the validator's self-delegation withdrawal address. +Remaining delegator rewards get sent to the community fee pool. + +Note: The validator gets removed only when it has no remaining delegations. +At that time, all outstanding delegator rewards will have been withdrawn. +Any remaining rewards are dust amounts. + +### Validator is slashed + +* triggered-by: `staking.Slash` +* The current validator period reference count is incremented. + The reference count is incremented because the slash event has created a reference to it. +* The validator period is incremented. +* The slash event is stored for later use. + The slash event will be referenced when calculating delegator rewards. + +## Events + +The distribution module emits the following events: + +### BeginBlocker + +| Type | Attribute Key | Attribute Value | +|-----------------|---------------|--------------------| +| proposer_reward | validator | {validatorAddress} | +| proposer_reward | reward | {proposerReward} | +| commission | amount | {commissionAmount} | +| commission | validator | {validatorAddress} | +| rewards | amount | {rewardAmount} | +| rewards | validator | {validatorAddress} | + +### Handlers + +#### MsgSetWithdrawAddress + +| Type | Attribute Key | Attribute Value | +|----------------------|------------------|----------------------| +| set_withdraw_address | withdraw_address | {withdrawAddress} | +| message | module | distribution | +| message | action | set_withdraw_address | +| message | sender | {senderAddress} | + +#### MsgWithdrawDelegatorReward + +| Type | Attribute Key | Attribute Value | +|---------|---------------|---------------------------| +| withdraw_rewards | amount | {rewardAmount} | +| withdraw_rewards | validator | {validatorAddress} | +| message | module | distribution | +| message | action | withdraw_delegator_reward | +| message | sender | {senderAddress} | + +#### MsgWithdrawValidatorCommission + +| Type | Attribute Key | Attribute Value | +|------------|---------------|-------------------------------| +| withdraw_commission | amount | {commissionAmount} | +| message | module | distribution | +| message | action | withdraw_validator_commission | +| message | sender | {senderAddress} | + +## Parameters + +The distribution module contains the following parameters: + +| Key | Type | Example | +| ------------------- | ------------ | -------------------------- | +| communitytax | string (dec) | "0.020000000000000000" [0] | +| withdrawaddrenabled | bool | true | + +* [0] `communitytax` must be positive and cannot exceed 1.00. +* `baseproposerreward` and `bonusproposerreward` were parameters that are deprecated in v0.47 and are not used. + + +The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`. +Currently with the Cosmos SDK, tokens collected by the CommunityTax are accounted for but unspendable. + + +## Client + +## CLI + +A user can query and interact with the `distribution` module using the CLI. + +#### Query + +The `query` commands allow users to query `distribution` state. + +```shell +simd query distribution --help +``` + +##### commission + +The `commission` command allows users to query validator commission rewards by address. + +```shell +simd query distribution commission [address] [flags] +``` + +Example: + +```shell +simd query distribution commission cosmosvaloper1... +``` + +Example Output: + +```yml +commission: +- amount: "1000000.000000000000000000" + denom: stake +``` + +##### community-pool + +The `community-pool` command allows users to query all coin balances within the community pool. + +```shell +simd query distribution community-pool [flags] +``` + +Example: + +```shell +simd query distribution community-pool +``` + +Example Output: + +```yml +pool: +- amount: "1000000.000000000000000000" + denom: stake +``` + +##### params + +The `params` command allows users to query the parameters of the `distribution` module. + +```shell +simd query distribution params [flags] +``` + +Example: + +```shell +simd query distribution params +``` + +Example Output: + +```yml +base_proposer_reward: "0.000000000000000000" +bonus_proposer_reward: "0.000000000000000000" +community_tax: "0.020000000000000000" +withdraw_addr_enabled: true +``` + +##### rewards + +The `rewards` command allows users to query delegator rewards. Users can optionally include the validator address to query rewards earned from a specific validator. + +```shell +simd query distribution rewards [delegator-addr] [validator-addr] [flags] +``` + +Example: + +```shell +simd query distribution rewards cosmos1... +``` + +Example Output: + +```yml +rewards: +- reward: + - amount: "1000000.000000000000000000" + denom: stake + validator_address: cosmosvaloper1.. +total: +- amount: "1000000.000000000000000000" + denom: stake +``` + +##### slashes + +The `slashes` command allows users to query all slashes for a given block range. + +```shell +simd query distribution slashes [validator] [start-height] [end-height] [flags] +``` + +Example: + +```shell +simd query distribution slashes cosmosvaloper1... 1 1000 +``` + +Example Output: + +```yml +pagination: + next_key: null + total: "0" +slashes: +- validator_period: 20, + fraction: "0.009999999999999999" +``` + +##### validator-outstanding-rewards + +The `validator-outstanding-rewards` command allows users to query all outstanding (un-withdrawn) rewards for a validator and all their delegations. + +```shell +simd query distribution validator-outstanding-rewards [validator] [flags] +``` + +Example: + +```shell +simd query distribution validator-outstanding-rewards cosmosvaloper1... +``` + +Example Output: + +```yml +rewards: +- amount: "1000000.000000000000000000" + denom: stake +``` + +##### validator-distribution-info + +The `validator-distribution-info` command allows users to query validator commission and self-delegation rewards for validator. + +````shell +simd query distribution validator-distribution-info cosmosvaloper1... +``` + +Example Output: + +```yml +commission: +- amount: "100000.000000000000000000" + denom: stake +operator_address: cosmosvaloper1... +self_bond_rewards: +- amount: "100000.000000000000000000" + denom: stake +``` + +#### Transactions + +The `tx` commands allow users to interact with the `distribution` module. + +```shell +simd tx distribution --help +``` + +##### fund-community-pool + +The `fund-community-pool` command allows users to send funds to the community pool. + +```shell +simd tx distribution fund-community-pool [amount] [flags] +``` + +Example: + +```shell +simd tx distribution fund-community-pool 100stake --from cosmos1... +``` + +##### set-withdraw-addr + +The `set-withdraw-addr` command allows users to set the withdraw address for rewards associated with a delegator address. + +```shell +simd tx distribution set-withdraw-addr [withdraw-addr] [flags] +``` + +Example: + +```shell +simd tx distribution set-withdraw-addr cosmos1... --from cosmos1... +``` + +##### withdraw-all-rewards + +The `withdraw-all-rewards` command allows users to withdraw all rewards for a delegator. + +```shell +simd tx distribution withdraw-all-rewards [flags] +``` + +Example: + +```shell +simd tx distribution withdraw-all-rewards --from cosmos1... +``` + +##### withdraw-rewards + +The `withdraw-rewards` command allows users to withdraw all rewards from a given delegation address, +and optionally withdraw validator commission if the delegation address given is a validator operator and the user proves the `--commission` flag. + +```shell +simd tx distribution withdraw-rewards [validator-addr] [flags] +``` + +Example: + +```shell +simd tx distribution withdraw-rewards cosmosvaloper1... --from cosmos1... --commission +``` + +### gRPC + +A user can query the `distribution` module using gRPC endpoints. + +#### Params + +The `Params` endpoint allows users to query parameters of the `distribution` module. + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/Params +``` + +Example Output: + +```json +{ + "params": { + "communityTax": "20000000000000000", + "baseProposerReward": "00000000000000000", + "bonusProposerReward": "00000000000000000", + "withdrawAddrEnabled": true + } +} +``` + +#### ValidatorDistributionInfo + +The `ValidatorDistributionInfo` queries validator commission and self-delegation rewards for validator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"validator_address":"cosmosvalop1..."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/ValidatorDistributionInfo +``` + +Example Output: + +```json +{ + "commission": { + "commission": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] + }, + "self_bond_rewards": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ], + "validator_address": "cosmosvalop1..." +} +``` + +#### ValidatorOutstandingRewards + +The `ValidatorOutstandingRewards` endpoint allows users to query rewards of a validator address. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"validator_address":"cosmosvalop1.."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards +``` + +Example Output: + +```json +{ + "rewards": { + "rewards": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] + } +} +``` + +#### ValidatorCommission + +The `ValidatorCommission` endpoint allows users to query accumulated commission for a validator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"validator_address":"cosmosvalop1.."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/ValidatorCommission +``` + +Example Output: + +```json +{ + "commission": { + "commission": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] + } +} +``` + +#### ValidatorSlashes + +The `ValidatorSlashes` endpoint allows users to query slash events of a validator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"validator_address":"cosmosvalop1.."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/ValidatorSlashes +``` + +Example Output: + +```json +{ + "slashes": [ + { + "validator_period": "20", + "fraction": "0.009999999999999999" + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### DelegationRewards + +The `DelegationRewards` endpoint allows users to query the total rewards accrued by a delegation. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"delegator_address":"cosmos1...","validator_address":"cosmosvalop1..."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/DelegationRewards +``` + +Example Output: + +```json +{ + "rewards": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] +} +``` + +#### DelegationTotalRewards + +The `DelegationTotalRewards` endpoint allows users to query the total rewards accrued by each validator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"delegator_address":"cosmos1..."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/DelegationTotalRewards +``` + +Example Output: + +```json +{ + "rewards": [ + { + "validatorAddress": "cosmosvaloper1...", + "reward": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] + } + ], + "total": [ + { + "denom": "stake", + "amount": "1000000000000000" + } + ] +} +``` + +#### DelegatorValidators + +The `DelegatorValidators` endpoint allows users to query all validators for given delegator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"delegator_address":"cosmos1..."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/DelegatorValidators +``` + +Example Output: + +```json +{ + "validators": ["cosmosvaloper1..."] +} +``` + +#### DelegatorWithdrawAddress + +The `DelegatorWithdrawAddress` endpoint allows users to query the withdraw address of a delegator. + +Example: + +```shell +grpcurl -plaintext \ + -d '{"delegator_address":"cosmos1..."}' \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress +``` + +Example Output: + +```json +{ + "withdrawAddress": "cosmos1..." +} +``` + +#### CommunityPool + +The `CommunityPool` endpoint allows users to query the community pool coins. + +Example: + +```shell +grpcurl -plaintext \ + localhost:9090 \ + cosmos.distribution.v1beta1.Query/CommunityPool +``` + +Example Output: + +```json +{ + "pool": [ + { + "denom": "stake", + "amount": "1000000000000000000" + } + ] +} +``` diff --git a/docs/sdk/v0.53/module-reference/epochs.mdx b/docs/sdk/v0.53/module-reference/epochs.mdx new file mode 100644 index 00000000..5a77b02b --- /dev/null +++ b/docs/sdk/v0.53/module-reference/epochs.mdx @@ -0,0 +1,182 @@ +--- +title: "`x/epochs`" + +--- + +--- + +--- + +## Abstract + +Often in the SDK, we would like to run certain code every-so often. The +purpose of `epochs` module is to allow other modules to set that they +would like to be signaled once every period. So another module can +specify it wants to execute code once a week, starting at UTC-time = x. +`epochs` creates a generalized epoch interface to other modules so that +they can easily be signaled upon such events. + +## Contents + +1. **[Concept](#concepts)** +2. **[State](#state)** +3. **[Events](#events)** +4. **[Keeper](#keepers)** +5. **[Hooks](#hooks)** +6. **[Queries](#queries)** + +## Concepts + +The epochs module defines on-chain timers that execute at fixed time intervals. +Other SDK modules can then register logic to be executed at the timer ticks. +We refer to the period in between two timer ticks as an "epoch". + +Every timer has a unique identifier. +Every epoch will have a start time, and an end time, where `end time = start time + timer interval`. +On mainnet, we only utilize one identifier, with a time interval of `one day`. + +The timer will tick at the first block whose block time is greater than the timer end time, +and set the start as the prior timer end time. (Notably, it's not set to the block time!) +This means that if the chain has been down for a while, you will get one timer tick per block, +until the timer has caught up. + +## State + +The Epochs module keeps a single `EpochInfo` per identifier. +This contains the current state of the timer with the corresponding identifier. +Its fields are modified at every timer tick. +EpochInfos are initialized as part of genesis initialization or upgrade logic, +and are only modified on begin blockers. + +## Events + +The `epochs` module emits the following events: + +### BeginBlocker + +| Type | Attribute Key | Attribute Value | +| ----------- | ------------- | --------------- | +| epoch_start | epoch_number | {epoch_number} | +| epoch_start | start_time | {start_time} | + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +| --------- | ------------- | --------------- | +| epoch_end | epoch_number | {epoch_number} | + +## Keepers + +### Keeper functions + +Epochs keeper module provides utility functions to manage epochs. + +## Hooks + +```go + // the first block whose timestamp is after the duration is counted as the end of the epoch + AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) + // new epoch is next block of epoch end block + BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) +``` + +### How modules receive hooks + +On hook receiver function of other modules, they need to filter +`epochIdentifier` and only do executions for only specific +epochIdentifier. Filtering epochIdentifier could be in `Params` of other +modules so that they can be modified by governance. + +This is the standard dev UX of this: + +```golang +func (k MyModuleKeeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { + params := k.GetParams(ctx) + if epochIdentifier == params.DistrEpochIdentifier { + // my logic + } +} +``` + +### Panic isolation + +If a given epoch hook panics, its state update is reverted, but we keep +proceeding through the remaining hooks. This allows more advanced epoch +logic to be used, without concern over state machine halting, or halting +subsequent modules. + +This does mean that if there is behavior you expect from a prior epoch +hook, and that epoch hook reverted, your hook may also have an issue. So +do keep in mind "what if a prior hook didn't get executed" in the safety +checks you consider for a new epoch hook. + +## Queries + +The Epochs module provides the following queries to check the module's state. + +```protobuf +service Query { + // EpochInfos provide running epochInfos + rpc EpochInfos(QueryEpochsInfoRequest) returns (QueryEpochsInfoResponse) {} + // CurrentEpoch provide current epoch of specified identifier + rpc CurrentEpoch(QueryCurrentEpochRequest) returns (QueryCurrentEpochResponse) {} +} +``` + +### Epoch Infos + +Query the currently running epochInfos + +```sh + query epochs epoch-infos +``` + +```sh +``` + +**Example** + +An example output: + +epochs: +- current_epoch: "183" + current_epoch_start_height: "2438409" + current_epoch_start_time: "2021-12-18T17:16:09.898160996Z" + duration: 86400s + epoch_counting_started: true + identifier: day + start_time: "2021-06-18T17:00:00Z" +- current_epoch: "26" + current_epoch_start_height: "2424854" + current_epoch_start_time: "2021-12-17T17:02:07.229632445Z" + duration: 604800s + epoch_counting_started: true + identifier: week + start_time: "2021-06-18T17:00:00Z" + + + +### Current Epoch + +Query the current epoch by the specified identifier + +```sh + query epochs current-epoch [identifier] +``` + +```sh +``` +```sh +``` + +**Example** + +Query the current `day` epoch: + + query epochs current-epoch day + +Which in this example outputs: + +current_epoch: "183" + + diff --git a/docs/sdk/v0.53/module-reference/evidence.mdx b/docs/sdk/v0.53/module-reference/evidence.mdx new file mode 100644 index 00000000..cbf234fa --- /dev/null +++ b/docs/sdk/v0.53/module-reference/evidence.mdx @@ -0,0 +1,438 @@ +--- +title: "`x/evidence`" + +--- + +--- + +--- + +* [Concepts](#concepts) +* [State](#state) +* [Messages](#messages) +* [Events](#events) +* [Parameters](#parameters) +* [BeginBlock](#beginblock) +* [Client](#client) + * [CLI](#cli) + * [REST](#rest) + * [gRPC](#grpc) + +## Abstract + +`x/evidence` is an implementation of a Cosmos SDK module, per [ADR 009](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-009-evidence-module.md), +that allows for the submission and handling of arbitrary evidence of misbehavior such +as equivocation and counterfactual signing. + +The evidence module differs from standard evidence handling which typically expects the +underlying consensus engine, e.g. CometBFT, to automatically submit evidence when +it is discovered by allowing clients and foreign chains to submit more complex evidence +directly. + +All concrete evidence types must implement the `Evidence` interface contract. Submitted +`Evidence` is first routed through the evidence module's `Router` in which it attempts +to find a corresponding registered `Handler` for that specific `Evidence` type. +Each `Evidence` type must have a `Handler` registered with the evidence module's +keeper in order for it to be successfully routed and executed. + +Each corresponding handler must also fulfill the `Handler` interface contract. The +`Handler` for a given `Evidence` type can perform any arbitrary state transitions +such as slashing, jailing, and tombstoning. + +## Concepts + +### Evidence + +Any concrete type of evidence submitted to the `x/evidence` module must fulfill the +`Evidence` contract outlined below. Not all concrete types of evidence will fulfill +this contract in the same way and some data may be entirely irrelevant to certain +types of evidence. An additional `ValidatorEvidence`, which extends `Evidence`, +has also been created to define a contract for evidence against malicious validators. + +```go +// Evidence defines the contract which concrete evidence types of misbehavior +// must implement. +type Evidence interface { + proto.Message + + Route() string + String() string + Hash() []byte + ValidateBasic() error + + // Height at which the infraction occurred + GetHeight() int64 +} + +// ValidatorEvidence extends Evidence interface to define contract +// for evidence against malicious validators +type ValidatorEvidence interface { + Evidence + + // The consensus address of the malicious validator at time of infraction + GetConsensusAddress() sdk.ConsAddress + + // The total power of the malicious validator at time of infraction + GetValidatorPower() int64 + + // The total validator set power at time of infraction + GetTotalPower() int64 +} +``` + +### Registration & Handling + +The `x/evidence` module must first know about all types of evidence it is expected +to handle. This is accomplished by registering the `Route` method in the `Evidence` +contract with what is known as a `Router` (defined below). The `Router` accepts +`Evidence` and attempts to find the corresponding `Handler` for the `Evidence` +via the `Route` method. + +```go +type Router interface { + AddRoute(r string, h Handler) Router + HasRoute(r string) bool + GetRoute(path string) Handler + Seal() + Sealed() bool +} +``` + +The `Handler` (defined below) is responsible for executing the entirety of the +business logic for handling `Evidence`. This typically includes validating the +evidence, both stateless checks via `ValidateBasic` and stateful checks via any +keepers provided to the `Handler`. In addition, the `Handler` may also perform +capabilities such as slashing and jailing a validator. All `Evidence` handled +by the `Handler` should be persisted. + +```go +// Handler defines an agnostic Evidence handler. The handler is responsible +// for executing all corresponding business logic necessary for verifying the +// evidence as valid. In addition, the Handler may execute any necessary +// slashing and potential jailing. +type Handler func(context.Context, Evidence) error +``` + +## State + +Currently the `x/evidence` module only stores valid submitted `Evidence` in state. +The evidence state is also stored and exported in the `x/evidence` module's `GenesisState`. + +```protobuf +// GenesisState defines the evidence module's genesis state. +message GenesisState { + // evidence defines all the evidence at genesis. + repeated google.protobuf.Any evidence = 1; +} + +``` + +All `Evidence` is retrieved and stored via a prefix `KVStore` using prefix `0x00` (`KeyPrefixEvidence`). + +## Messages + +### MsgSubmitEvidence + +Evidence is submitted through a `MsgSubmitEvidence` message: + +```protobuf +// MsgSubmitEvidence represents a message that supports submitting arbitrary +// Evidence of misbehavior such as equivocation or counterfactual signing. +message MsgSubmitEvidence { + string submitter = 1; + google.protobuf.Any evidence = 2; +} +``` + +Note, the `Evidence` of a `MsgSubmitEvidence` message must have a corresponding +`Handler` registered with the `x/evidence` module's `Router` in order to be processed +and routed correctly. + +Given the `Evidence` is registered with a corresponding `Handler`, it is processed +as follows: + +```go +func SubmitEvidence(ctx Context, evidence Evidence) error { + if _, err := GetEvidence(ctx, evidence.Hash()); err == nil { + return errorsmod.Wrap(types.ErrEvidenceExists, strings.ToUpper(hex.EncodeToString(evidence.Hash()))) + } + if !router.HasRoute(evidence.Route()) { + return errorsmod.Wrap(types.ErrNoEvidenceHandlerExists, evidence.Route()) + } + + handler := router.GetRoute(evidence.Route()) + if err := handler(ctx, evidence); err != nil { + return errorsmod.Wrap(types.ErrInvalidEvidence, err.Error()) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSubmitEvidence, + sdk.NewAttribute(types.AttributeKeyEvidenceHash, strings.ToUpper(hex.EncodeToString(evidence.Hash()))), + ), + ) + + SetEvidence(ctx, evidence) + return nil +} +``` + +First, there must not already exist valid submitted `Evidence` of the exact same +type. Secondly, the `Evidence` is routed to the `Handler` and executed. Finally, +if there is no error in handling the `Evidence`, an event is emitted and it is persisted to state. + +## Events + +The `x/evidence` module emits the following events: + +### Handlers + +#### MsgSubmitEvidence + +| Type | Attribute Key | Attribute Value | +| --------------- | ------------- | --------------- | +| submit_evidence | evidence_hash | {evidenceHash} | +| message | module | evidence | +| message | sender | {senderAddress} | +| message | action | submit_evidence | + +## Parameters + +The evidence module does not contain any parameters. + +## BeginBlock + +### Evidence Handling + +CometBFT blocks can include +[Evidence](https://github.com/cometbft/cometbft/blob/main/spec/abci/abci%2B%2B_basic_concepts.md#evidence) that indicates if a validator committed malicious behavior. The relevant information is forwarded to the application as ABCI Evidence in `abci.RequestBeginBlock` so that the validator can be punished accordingly. + +#### Equivocation + +The Cosmos SDK handles two types of evidence inside the ABCI `BeginBlock`: + +* `DuplicateVoteEvidence`, +* `LightClientAttackEvidence`. + +The evidence module handles these two evidence types the same way. First, the Cosmos SDK converts the CometBFT concrete evidence type to an SDK `Evidence` interface using `Equivocation` as the concrete type. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/evidence/v1beta1/evidence.proto#L12-L32 +``` + +For some `Equivocation` submitted in `block` to be valid, it must satisfy: + +`Evidence.Timestamp >= block.Timestamp - MaxEvidenceAge` + +Where: + +* `Evidence.Timestamp` is the timestamp in the block at height `Evidence.Height` +* `block.Timestamp` is the current block timestamp. + +If valid `Equivocation` evidence is included in a block, the validator's stake is +reduced (slashed) by `SlashFractionDoubleSign` as defined by the `x/slashing` module +of what their stake was when the infraction occurred, rather than when the evidence was discovered. +We want to "follow the stake", i.e., the stake that contributed to the infraction +should be slashed, even if it has since been redelegated or started unbonding. + +In addition, the validator is permanently jailed and tombstoned to make it impossible for that +validator to ever re-enter the validator set. + +The `Equivocation` evidence is handled as follows: + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/x/evidence/keeper/infraction.go#L26-L140 +``` + +**Note:** The slashing, jailing, and tombstoning calls are delegated through the `x/slashing` module +that emits informative events and finally delegates calls to the `x/staking` module. See documentation +on slashing and jailing in [State Transitions](../staking/README.md#state-transitions). + +## Client + +### CLI + +A user can query and interact with the `evidence` module using the CLI. + +#### Query + +The `query` commands allows users to query `evidence` state. + +```bash +simd query evidence --help +``` + +#### evidence + +The `evidence` command allows users to list all evidence or evidence by hash. + +Usage: + +```bash +simd query evidence evidence [flags] +``` + +To query evidence by hash + +Example: + +```bash +simd query evidence evidence "DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660" +``` + +Example Output: + +```bash +evidence: + consensus_address: cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h + height: 11 + power: 100 + time: "2021-10-20T16:08:38.194017624Z" +``` + +To get all evidence + +Example: + +```bash +simd query evidence list +``` + +Example Output: + +```bash +evidence: + consensus_address: cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h + height: 11 + power: 100 + time: "2021-10-20T16:08:38.194017624Z" +pagination: + next_key: null + total: "1" +``` + +### REST + +A user can query the `evidence` module using REST endpoints. + +#### Evidence + +Get evidence by hash + +```bash +/cosmos/evidence/v1beta1/evidence/{hash} +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/evidence/v1beta1/evidence/DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660" +``` + +Example Output: + +```bash +{ + "evidence": { + "consensus_address": "cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h", + "height": "11", + "power": "100", + "time": "2021-10-20T16:08:38.194017624Z" + } +} +``` + +#### All evidence + +Get all evidence + +```bash +/cosmos/evidence/v1beta1/evidence +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/evidence/v1beta1/evidence" +``` + +Example Output: + +```bash +{ + "evidence": [ + { + "consensus_address": "cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h", + "height": "11", + "power": "100", + "time": "2021-10-20T16:08:38.194017624Z" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### gRPC + +A user can query the `evidence` module using gRPC endpoints. + +#### Evidence + +Get evidence by hash + +```bash +cosmos.evidence.v1beta1.Query/Evidence +``` + +Example: + +```bash +grpcurl -plaintext -d '{"evidence_hash":"DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660"}' localhost:9090 cosmos.evidence.v1beta1.Query/Evidence +``` + +Example Output: + +```bash +{ + "evidence": { + "consensus_address": "cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h", + "height": "11", + "power": "100", + "time": "2021-10-20T16:08:38.194017624Z" + } +} +``` + +#### All evidence + +Get all evidence + +```bash +cosmos.evidence.v1beta1.Query/AllEvidence +``` + +Example: + +```bash +grpcurl -plaintext localhost:9090 cosmos.evidence.v1beta1.Query/AllEvidence +``` + +Example Output: + +```bash +{ + "evidence": [ + { + "consensus_address": "cosmosvalcons1ntk8eualewuprz0gamh8hnvcem2nrcdsgz563h", + "height": "11", + "power": "100", + "time": "2021-10-20T16:08:38.194017624Z" + } + ], + "pagination": { + "total": "1" + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/feegrant.mdx b/docs/sdk/v0.53/module-reference/feegrant.mdx new file mode 100644 index 00000000..0aaaeba6 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/feegrant.mdx @@ -0,0 +1,398 @@ +--- +title: "`x/feegrant`" + +--- + +--- + +--- + +## Abstract + +This document specifies the fee grant module. For the full ADR, please see [Fee Grant ADR-029](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-029-fee-grant-module.md). + +This module allows accounts to grant fee allowances and to use fees from their accounts. Grantees can execute any transaction without the need to maintain sufficient fees. + +## Contents + +* [Concepts](#concepts) +* [State](#state) + * [FeeAllowance](#feeallowance) + * [FeeAllowanceQueue](#feeallowancequeue) +* [Messages](#messages) + * [Msg/GrantAllowance](#msggrantallowance) + * [Msg/RevokeAllowance](#msgrevokeallowance) +* [Events](#events) +* [Msg Server](#msg-server) + * [MsgGrantAllowance](#msggrantallowance-1) + * [MsgRevokeAllowance](#msgrevokeallowance-1) + * [Exec fee allowance](#exec-fee-allowance) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + +## Concepts + +### Grant + +`Grant` is stored in the KVStore to record a grant with full context. Every grant will contain `granter`, `grantee` and what kind of `allowance` is granted. `granter` is an account address who is giving permission to `grantee` (the beneficiary account address) to pay for some or all of `grantee`'s transaction fees. `allowance` defines what kind of fee allowance (`BasicAllowance` or `PeriodicAllowance`, see below) is granted to `grantee`. `allowance` accepts an interface which implements `FeeAllowanceI`, encoded as `Any` type. There can be only one existing fee grant allowed for a `grantee` and `granter`, self grants are not allowed. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/feegrant.proto#L83-L93 +``` + +`FeeAllowanceI` looks like: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/feegrant/fees.go#L9-L32 +``` + +### Fee Allowance types + +There are two types of fee allowances present at the moment: + +* `BasicAllowance` +* `PeriodicAllowance` +* `AllowedMsgAllowance` + +### BasicAllowance + +`BasicAllowance` is permission for `grantee` to use fee from a `granter`'s account. If any of the `spend_limit` or `expiration` reaches its limit, the grant will be removed from the state. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/feegrant.proto#L15-L28 +``` + +* `spend_limit` is the limit of coins that are allowed to be used from the `granter` account. If it is empty, it assumes there's no spend limit, `grantee` can use any number of available coins from `granter` account address before the expiration. + +* `expiration` specifies an optional time when this allowance expires. If the value is left empty, there is no expiry for the grant. + +* When a grant is created with empty values for `spend_limit` and `expiration`, it is still a valid grant. It won't restrict the `grantee` to use any number of coins from `granter` and it won't have any expiration. The only way to restrict the `grantee` is by revoking the grant. + +### PeriodicAllowance + +`PeriodicAllowance` is a repeating fee allowance for the mentioned period, we can mention when the grant can expire as well as when a period can reset. We can also define the maximum number of coins that can be used in a mentioned period of time. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/feegrant.proto#L34-L68 +``` + +* `basic` is the instance of `BasicAllowance` which is optional for periodic fee allowance. If empty, the grant will have no `expiration` and no `spend_limit`. + +* `period` is the specific period of time, after each period passes, `period_can_spend` will be reset. + +* `period_spend_limit` specifies the maximum number of coins that can be spent in the period. + +* `period_can_spend` is the number of coins left to be spent before the period_reset time. + +* `period_reset` keeps track of when a next period reset should happen. + +### AllowedMsgAllowance + +`AllowedMsgAllowance` is a fee allowance, it can be any of `BasicFeeAllowance`, `PeriodicAllowance` but restricted only to the allowed messages mentioned by the granter. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/feegrant.proto#L70-L81 +``` + +* `allowance` is either `BasicAllowance` or `PeriodicAllowance`. + +* `allowed_messages` is array of messages allowed to execute the given allowance. + +### FeeGranter flag + +`feegrant` module introduces a `FeeGranter` flag for CLI for the sake of executing transactions with fee granter. When this flag is set, `clientCtx` will append the granter account address for transactions generated through CLI. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/client/cmd.go#L249-L260 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/client/tx/tx.go#L109-L109 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/auth/tx/builder.go#L275-L284 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/tx/v1beta1/tx.proto#L203-L224 +``` + +Example cmd: + +```go +./simd tx gov submit-proposal --title="Test Proposal" --description="My awesome proposal" --type="Text" --from validator-key --fee-granter=cosmos1xh44hxt7spr67hqaa7nyx5gnutrz5fraw6grxn --chain-id=testnet --fees="10stake" +``` + +### Granted Fee Deductions + +Fees are deducted from grants in the `x/auth` ante handler. To learn more about how ante handlers work, read the [Auth Module AnteHandlers Guide](../auth/README.md#antehandlers). + +### Gas + +In order to prevent DoS attacks, using a filtered `x/feegrant` incurs gas. The SDK must assure that the `grantee`'s transactions all conform to the filter set by the `granter`. The SDK does this by iterating over the allowed messages in the filter and charging 10 gas per filtered message. The SDK will then iterate over the messages being sent by the `grantee` to ensure the messages adhere to the filter, also charging 10 gas per message. The SDK will stop iterating and fail the transaction if it finds a message that does not conform to the filter. + +**WARNING**: The gas is charged against the granted allowance. Ensure your messages conform to the filter, if any, before sending transactions using your allowance. + +### Pruning + +A queue in the state maintained with the prefix of expiration of the grants and checks them on EndBlock with the current block time for every block to prune. + +## State + +### FeeAllowance + +Fee Allowances are identified by combining `Grantee` (the account address of fee allowance grantee) with the `Granter` (the account address of fee allowance granter). + +Fee allowance grants are stored in the state as follows: + +* Grant: `0x00 | grantee_addr_len (1 byte) | grantee_addr_bytes | granter_addr_len (1 byte) | granter_addr_bytes -> ProtocolBuffer(Grant)` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/feegrant/feegrant.pb.go#L222-L230 +``` + +### FeeAllowanceQueue + +Fee Allowances queue items are identified by combining the `FeeAllowancePrefixQueue` (i.e., 0x01), `expiration`, `grantee` (the account address of fee allowance grantee), `granter` (the account address of fee allowance granter). Endblocker checks `FeeAllowanceQueue` state for the expired grants and prunes them from `FeeAllowance` if there are any found. + +Fee allowance queue keys are stored in the state as follows: + +* Grant: `0x01 | expiration_bytes | grantee_addr_len (1 byte) | grantee_addr_bytes | granter_addr_len (1 byte) | granter_addr_bytes -> EmptyBytes` + +## Messages + +### Msg/GrantAllowance + +A fee allowance grant will be created with the `MsgGrantAllowance` message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/tx.proto#L25-L39 +``` + +### Msg/RevokeAllowance + +An allowed grant fee allowance can be removed with the `MsgRevokeAllowance` message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/feegrant/v1beta1/tx.proto#L41-L54 +``` + +## Events + +The feegrant module emits the following events: + +## Msg Server + +### MsgGrantAllowance + +| Type | Attribute Key | Attribute Value | +| ------- | ------------- | ---------------- | +| message | action | set_feegrant | +| message | granter | {granterAddress} | +| message | grantee | {granteeAddress} | + +### MsgRevokeAllowance + +| Type | Attribute Key | Attribute Value | +| ------- | ------------- | ---------------- | +| message | action | revoke_feegrant | +| message | granter | {granterAddress} | +| message | grantee | {granteeAddress} | + +### Exec fee allowance + +| Type | Attribute Key | Attribute Value | +| ------- | ------------- | ---------------- | +| message | action | use_feegrant | +| message | granter | {granterAddress} | +| message | grantee | {granteeAddress} | + +### Prune fee allowances + +| Type | Attribute Key | Attribute Value | +| ------- | ------------- | ---------------- | +| message | action | prune_feegrant | +| message | pruner | {prunerAddress} | + +## Client + +### CLI + +A user can query and interact with the `feegrant` module using the CLI. + +#### Query + +The `query` commands allow users to query `feegrant` state. + +```shell +simd query feegrant --help +``` + +##### grant + +The `grant` command allows users to query a grant for a given granter-grantee pair. + +```shell +simd query feegrant grant [granter] [grantee] [flags] +``` + +Example: + +```shell +simd query feegrant grant cosmos1.. cosmos1.. +``` + +Example Output: + +```yml +allowance: + '@type': /cosmos.feegrant.v1beta1.BasicAllowance + expiration: null + spend_limit: + - amount: "100" + denom: stake +grantee: cosmos1.. +granter: cosmos1.. +``` + +##### grants + +The `grants` command allows users to query all grants for a given grantee. + +```shell +simd query feegrant grants [grantee] [flags] +``` + +Example: + +```shell +simd query feegrant grants cosmos1.. +``` + +Example Output: + +```yml +allowances: +- allowance: + '@type': /cosmos.feegrant.v1beta1.BasicAllowance + expiration: null + spend_limit: + - amount: "100" + denom: stake + grantee: cosmos1.. + granter: cosmos1.. +pagination: + next_key: null + total: "0" +``` + +#### Transactions + +The `tx` commands allow users to interact with the `feegrant` module. + +```shell +simd tx feegrant --help +``` + +##### grant + +The `grant` command allows users to grant fee allowances to another account. The fee allowance can have an expiration date, a total spend limit, and/or a periodic spend limit. + +```shell +simd tx feegrant grant [granter] [grantee] [flags] +``` + +Example (one-time spend limit): + +```shell +simd tx feegrant grant cosmos1.. cosmos1.. --spend-limit 100stake +``` + +Example (periodic spend limit): + +```shell +simd tx feegrant grant cosmos1.. cosmos1.. --period 3600 --period-limit 10stake +``` + +##### revoke + +The `revoke` command allows users to revoke a granted fee allowance. + +```shell +simd tx feegrant revoke [granter] [grantee] [flags] +``` + +Example: + +```shell +simd tx feegrant revoke cosmos1.. cosmos1.. +``` + +### gRPC + +A user can query the `feegrant` module using gRPC endpoints. + +#### Allowance + +The `Allowance` endpoint allows users to query a granted fee allowance. + +```shell +cosmos.feegrant.v1beta1.Query/Allowance +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"grantee":"cosmos1..","granter":"cosmos1.."}' \ + localhost:9090 \ + cosmos.feegrant.v1beta1.Query/Allowance +``` + +Example Output: + +```json +{ + "allowance": { + "granter": "cosmos1..", + "grantee": "cosmos1..", + "allowance": {"@type":"/cosmos.feegrant.v1beta1.BasicAllowance","spendLimit":[{"denom":"stake","amount":"100"}]} + } +} +``` + +#### Allowances + +The `Allowances` endpoint allows users to query all granted fee allowances for a given grantee. + +```shell +cosmos.feegrant.v1beta1.Query/Allowances +``` + +Example: + +```shell +grpcurl -plaintext \ + -d '{"address":"cosmos1.."}' \ + localhost:9090 \ + cosmos.feegrant.v1beta1.Query/Allowances +``` + +Example Output: + +```json +{ + "allowances": [ + { + "granter": "cosmos1..", + "grantee": "cosmos1..", + "allowance": {"@type":"/cosmos.feegrant.v1beta1.BasicAllowance","spendLimit":[{"denom":"stake","amount":"100"}]} + } + ], + "pagination": { + "total": "1" + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/gov.mdx b/docs/sdk/v0.53/module-reference/gov.mdx new file mode 100644 index 00000000..0f08547b --- /dev/null +++ b/docs/sdk/v0.53/module-reference/gov.mdx @@ -0,0 +1,2587 @@ +--- +title: "`x/gov`" + +--- + +--- + +--- + +## Abstract + +This paper specifies the Governance module of the Cosmos SDK, which was first +described in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) in +June 2016. + +The module enables Cosmos SDK based blockchain to support an on-chain governance +system. In this system, holders of the native staking token of the chain can vote +on proposals on a 1 token 1 vote basis. Next is a list of features the module +currently supports: + +* **Proposal submission:** Users can submit proposals with a deposit. Once the +minimum deposit is reached, the proposal enters voting period. The minimum deposit can be reached by collecting deposits from different users (including proposer) within deposit period. +* **Vote:** Participants can vote on proposals that reached MinDeposit and entered voting period. +* **Inheritance and penalties:** Delegators inherit their validator's vote if +they don't vote themselves. +* **Claiming deposit:** Users that deposited on proposals can recover their +deposits if the proposal was accepted or rejected. If the proposal was vetoed, or never entered voting period (minimum deposit not reached within deposit period), the deposit is burned. + +This module is in use on the Cosmos Hub (a.k.a [gaia](https://github.com/cosmos/gaia)). +Features that may be added in the future are described in [Future Improvements](#future-improvements). + +## Contents + +The following specification uses *ATOM* as the native staking token. The module +can be adapted to any Proof-Of-Stake blockchain by replacing *ATOM* with the native +staking token of the chain. + +* [Concepts](#concepts) + * [Proposal submission](#proposal-submission) + * [Deposit](#deposit) + * [Vote](#vote) + * [Software Upgrade](#software-upgrade) +* [State](#state) + * [Proposals](#proposals) + * [Parameters and base types](#parameters-and-base-types) + * [Deposit](#deposit-1) + * [ValidatorGovInfo](#validatorgovinfo) + * [Stores](#stores) + * [Proposal Processing Queue](#proposal-processing-queue) + * [Legacy Proposal](#legacy-proposal) +* [Messages](#messages) + * [Proposal Submission](#proposal-submission-1) + * [Deposit](#deposit-2) + * [Vote](#vote-1) +* [Events](#events) + * [EndBlocker](#endblocker) + * [Handlers](#handlers) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) +* [Metadata](#metadata) + * [Proposal](#proposal-3) + * [Vote](#vote-5) +* [Future Improvements](#future-improvements) + +## Concepts + +*Disclaimer: This is work in progress. Mechanisms are susceptible to change.* + +The governance process is divided in a few steps that are outlined below: + +* **Proposal submission:** Proposal is submitted to the blockchain with a + deposit. +* **Vote:** Once deposit reaches a certain value (`MinDeposit`), proposal is + confirmed and vote opens. Bonded Atom holders can then send `TxGovVote` + transactions to vote on the proposal. +* **Execution** After a period of time, the votes are tallied and depending + on the result, the messages in the proposal will be executed. + +### Proposal submission + +#### Right to submit a proposal + +Every account can submit proposals by sending a `MsgSubmitProposal` transaction. +Once a proposal is submitted, it is identified by its unique `proposalID`. + +#### Proposal Messages + +A proposal includes an array of `sdk.Msg`s which are executed automatically if the +proposal passes. The messages are executed by the governance `ModuleAccount` itself. Modules +such as `x/upgrade`, that want to allow certain messages to be executed by governance +only should add a whitelist within the respective msg server, granting the governance +module the right to execute the message once a quorum has been reached. The governance +module uses the `MsgServiceRouter` to check that these messages are correctly constructed +and have a respective path to execute on but do not perform a full validity check. + +### Deposit + +To prevent spam, proposals must be submitted with a deposit in the coins defined by +the `MinDeposit` param. + +When a proposal is submitted, it has to be accompanied with a deposit that must be +strictly positive, but can be inferior to `MinDeposit`. The submitter doesn't need +to pay for the entire deposit on their own. The newly created proposal is stored in +an *inactive proposal queue* and stays there until its deposit passes the `MinDeposit`. +Other token holders can increase the proposal's deposit by sending a `Deposit` +transaction. If a proposal doesn't pass the `MinDeposit` before the deposit end time +(the time when deposits are no longer accepted), the proposal will be destroyed: the +proposal will be removed from state and the deposit will be burned (see x/gov `EndBlocker`). +When a proposal deposit passes the `MinDeposit` threshold (even during the proposal +submission) before the deposit end time, the proposal will be moved into the +*active proposal queue* and the voting period will begin. + +The deposit is kept in escrow and held by the governance `ModuleAccount` until the +proposal is finalized (passed or rejected). + +#### Deposit refund and burn + +When a proposal is finalized, the coins from the deposit are either refunded or burned +according to the final tally of the proposal: + +* If the proposal is approved or rejected but *not* vetoed, each deposit will be + automatically refunded to its respective depositor (transferred from the governance + `ModuleAccount`). +* When the proposal is vetoed with greater than 1/3, deposits will be burned from the + governance `ModuleAccount` and the proposal information along with its deposit + information will be removed from state. +* All refunded or burned deposits are removed from the state. Events are issued when + burning or refunding a deposit. + +### Vote + +#### Participants + +*Participants* are users that have the right to vote on proposals. On the +Cosmos Hub, participants are bonded Atom holders. Unbonded Atom holders and +other users do not get the right to participate in governance. However, they +can submit and deposit on proposals. + +Note that when *participants* have bonded and unbonded Atoms, their voting power is calculated from their bonded Atom holdings only. + +#### Voting period + +Once a proposal reaches `MinDeposit`, it immediately enters `Voting period`. We +define `Voting period` as the interval between the moment the vote opens and +the moment the vote closes. The initial value of `Voting period` is 2 weeks. + +#### Option set + +The option set of a proposal refers to the set of choices a participant can +choose from when casting its vote. + +The initial option set includes the following options: + +* `Yes` +* `No` +* `NoWithVeto` +* `Abstain` + +`NoWithVeto` counts as `No` but also adds a `Veto` vote. `Abstain` option +allows voters to signal that they do not intend to vote in favor or against the +proposal but accept the result of the vote. + +*Note: from the UI, for urgent proposals we should maybe add a ‘Not Urgent’ option that casts a `NoWithVeto` vote.* + +#### Weighted Votes + +[ADR-037](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-037-gov-split-vote.md) introduces the weighted vote feature which allows a staker to split their votes into several voting options. For example, it could use 70% of its voting power to vote Yes and 30% of its voting power to vote No. + +Often times the entity owning that address might not be a single individual. For example, a company might have different stakeholders who want to vote differently, and so it makes sense to allow them to split their voting power. Currently, it is not possible for them to do "passthrough voting" and giving their users voting rights over their tokens. However, with this system, exchanges can poll their users for voting preferences, and then vote on-chain proportionally to the results of the poll. + +To represent weighted vote on chain, we use the following Protobuf message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1beta1/gov.proto#L34-L47 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1beta1/gov.proto#L181-L201 +``` + +For a weighted vote to be valid, the `options` field must not contain duplicate vote options, and the sum of weights of all options must be equal to 1. + +#### Custom Vote Calculation + +Cosmos SDK v0.53.0 introduced an option for developers to define a custom vote result and voting power calculation function. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/x/gov/keeper/tally.go#L15-L24 +``` + +This gives developers a more expressive way to handle governance on their appchains. +Developers can now build systems with: + +- Quadratic Voting +- Time-weighted Voting +- Reputation-Based voting + +##### Example + +```go +func myCustomVotingFunction( + ctx context.Context, + k Keeper, + proposal v1.Proposal, + validators map[string]v1.ValidatorGovInfo, +) (totalVoterPower math.LegacyDec, results map[v1.VoteOption]math.LegacyDec, err error) { + // ... tally logic +} + +govKeeper := govkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[govtypes.StoreKey]), + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.DistrKeeper, + app.MsgServiceRouter(), + govConfig, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govkeeper.WithCustomCalculateVoteResultsAndVotingPowerFn(myCustomVotingFunction), +) +``` + +### Quorum + +Quorum is defined as the minimum percentage of voting power that needs to be +cast on a proposal for the result to be valid. + +### Expedited Proposals + +A proposal can be expedited, making the proposal use shorter voting duration and a higher tally threshold by its default. If an expedited proposal fails to meet the threshold within the scope of shorter voting duration, the expedited proposal is then converted to a regular proposal and restarts voting under regular voting conditions. + +#### Threshold + +Threshold is defined as the minimum proportion of `Yes` votes (excluding +`Abstain` votes) for the proposal to be accepted. + +Initially, the threshold is set at 50% of `Yes` votes, excluding `Abstain` +votes. A possibility to veto exists if more than 1/3rd of all votes are +`NoWithVeto` votes. Note, both of these values are derived from the `TallyParams` +on-chain parameter, which is modifiable by governance. +This means that proposals are accepted iff: + +* There exist bonded tokens. +* Quorum has been achieved. +* The proportion of `Abstain` votes is inferior to 1/1. +* The proportion of `NoWithVeto` votes is inferior to 1/3, including + `Abstain` votes. +* The proportion of `Yes` votes, excluding `Abstain` votes, at the end of + the voting period is superior to 1/2. + +For expedited proposals, by default, the threshold is higher than with a *normal proposal*, namely, 66.7%. + +#### Inheritance + +If a delegator does not vote, it will inherit its validator vote. + +* If the delegator votes before its validator, it will not inherit from the + validator's vote. +* If the delegator votes after its validator, it will override its validator + vote with its own. If the proposal is urgent, it is possible + that the vote will close before delegators have a chance to react and + override their validator's vote. This is not a problem, as proposals require more than 2/3rd of the total voting power to pass, when tallied at the end of the voting period. Because as little as 1/3 + 1 validation power could collude to censor transactions, non-collusion is already assumed for ranges exceeding this threshold. + +#### Validator’s punishment for non-voting + +At present, validators are not punished for failing to vote. + +#### Governance address + +Later, we may add permissioned keys that could only sign txs from certain modules. For the MVP, the `Governance address` will be the main validator address generated at account creation. This address corresponds to a different PrivKey than the CometBFT PrivKey which is responsible for signing consensus messages. Validators thus do not have to sign governance transactions with the sensitive CometBFT PrivKey. + +#### Burnable Params + +There are three parameters that define if the deposit of a proposal should be burned or returned to the depositors. + +* `BurnVoteVeto` burns the proposal deposit if the proposal gets vetoed. +* `BurnVoteQuorum` burns the proposal deposit if the proposal deposit if the vote does not reach quorum. +* `BurnProposalDepositPrevote` burns the proposal deposit if it does not enter the voting phase. + +> Note: These parameters are modifiable via governance. + +## State + +### Constitution + +`Constitution` is found in the genesis state. It is a string field intended to be used to descibe the purpose of a particular blockchain, and its expected norms. A few examples of how the constitution field can be used: + +* define the purpose of the chain, laying a foundation for its future development +* set expectations for delegators +* set expectations for validators +* define the chain's relationship to "meatspace" entities, like a foundation or corporation + +Since this is more of a social feature than a technical feature, we'll now get into some items that may have been useful to have in a genesis constitution: + +* What limitations on governance exist, if any? + * is it okay for the community to slash the wallet of a whale that they no longer feel that they want around? (viz: Juno Proposal 4 and 16) + * can governance "socially slash" a validator who is using unapproved MEV? (viz: commonwealth.im/osmosis) + * In the event of an economic emergency, what should validators do? + * Terra crash of May, 2022, saw validators choose to run a new binary with code that had not been approved by governance, because the governance token had been inflated to nothing. +* What is the purpose of the chain, specifically? + * best example of this is the Cosmos hub, where different founding groups, have different interpertations of the purpose of the network. + +This genesis entry, "constitution" hasn't been designed for existing chains, who should likely just ratify a constitution using their governance system. Instead, this is for new chains. It will allow for validators to have a much clearer idea of purpose and the expecations placed on them while operating thier nodes. Likewise, for community members, the constitution will give them some idea of what to expect from both the "chain team" and the validators, respectively. + +This constitution is designed to be immutable, and placed only in genesis, though that could change over time by a pull request to the cosmos-sdk that allows for the constitution to be changed by governance. Communities whishing to make amendments to their original constitution should use the governance mechanism and a "signaling proposal" to do exactly that. + +**Ideal use scenario for a cosmos chain constitution** + +As a chain developer, you decide that you'd like to provide clarity to your key user groups: + +* validators +* token holders +* developers (yourself) + +You use the constitution to immutably store some Markdown in genesis, so that when difficult questions come up, the constutituon can provide guidance to the community. + +### Proposals + +`Proposal` objects are used to tally votes and generally track the proposal's state. +They contain an array of arbitrary `sdk.Msg`'s which the governance module will attempt +to resolve and then execute if the proposal passes. `Proposal`'s are identified by a +unique id and contains a series of timestamps: `submit_time`, `deposit_end_time`, +`voting_start_time`, `voting_end_time` which track the lifecycle of a proposal + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L51-L99 +``` + +A proposal will generally require more than just a set of messages to explain its +purpose but need some greater justification and allow a means for interested participants +to discuss and debate the proposal. +In most cases, **it is encouraged to have an off-chain system that supports the on-chain governance process**. +To accommodate for this, a proposal contains a special **`metadata`** field, a string, +which can be used to add context to the proposal. The `metadata` field allows custom use for networks, +however, it is expected that the field contains a URL or some form of CID using a system such as +[IPFS](https://docs.ipfs.io/concepts/content-addressing/). To support the case of +interoperability across networks, the SDK recommends that the `metadata` represents +the following `JSON` template: + +```json +{ + "title": "...", + "description": "...", + "forum": "...", // a link to the discussion platform (i.e. Discord) + "other": "..." // any extra data that doesn't correspond to the other fields +} +``` + +This makes it far easier for clients to support multiple networks. + +The metadata has a maximum length that is chosen by the app developer, and +passed into the gov keeper as a config. The default maximum length in the SDK is 255 characters. + +#### Writing a module that uses governance + +There are many aspects of a chain, or of the individual modules that you may want to +use governance to perform such as changing various parameters. This is very simple +to do. First, write out your message types and `MsgServer` implementation. Add an +`authority` field to the keeper which will be populated in the constructor with the +governance module account: `govKeeper.GetGovernanceAccount().GetAddress()`. Then for +the methods in the `msg_server.go`, perform a check on the message that the signer +matches `authority`. This will prevent any user from executing that message. + +### Parameters and base types + +`Parameters` define the rules according to which votes are run. There can only +be one active parameter set at any given time. If governance wants to change a +parameter set, either to modify a value or add/remove a parameter field, a new +parameter set has to be created and the previous one rendered inactive. + +#### DepositParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L152-L162 +``` + +#### VotingParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L164-L168 +``` + +#### TallyParams + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L170-L182 +``` + +Parameters are stored in a global `GlobalParams` KVStore. + +Additionally, we introduce some basic types: + +```go +type Vote byte + +const ( + VoteYes = 0x1 + VoteNo = 0x2 + VoteNoWithVeto = 0x3 + VoteAbstain = 0x4 +) + +type ProposalType string + +const ( + ProposalTypePlainText = "Text" + ProposalTypeSoftwareUpgrade = "SoftwareUpgrade" +) + +type ProposalStatus byte + +const ( + StatusNil ProposalStatus = 0x00 + StatusDepositPeriod ProposalStatus = 0x01 // Proposal is submitted. Participants can deposit on it but not vote + StatusVotingPeriod ProposalStatus = 0x02 // MinDeposit is reached, participants can vote + StatusPassed ProposalStatus = 0x03 // Proposal passed and successfully executed + StatusRejected ProposalStatus = 0x04 // Proposal has been rejected + StatusFailed ProposalStatus = 0x05 // Proposal passed but failed execution +) +``` + +### Deposit + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.proto#L38-L49 +``` + +### ValidatorGovInfo + +This type is used in a temp map when tallying + +```go + type ValidatorGovInfo struct { + Minus sdk.Dec + Vote Vote + } +``` + +## Stores + + +Stores are KVStores in the multi-store. The key to find the store is the first parameter in the list + + +We will use one KVStore `Governance` to store four mappings: + +* A mapping from `proposalID|'proposal'` to `Proposal`. +* A mapping from `proposalID|'addresses'|address` to `Vote`. This mapping allows + us to query all addresses that voted on the proposal along with their vote by + doing a range query on `proposalID:addresses`. +* A mapping from `ParamsKey|'Params'` to `Params`. This map allows to query all + x/gov params. +* A mapping from `VotingPeriodProposalKeyPrefix|proposalID` to a single byte. This allows + us to know if a proposal is in the voting period or not with very low gas cost. + +For pseudocode purposes, here are the two function we will use to read or write in stores: + +* `load(StoreKey, Key)`: Retrieve item stored at key `Key` in store found at key `StoreKey` in the multistore +* `store(StoreKey, Key, value)`: Write value `Value` at key `Key` in store found at key `StoreKey` in the multistore + +### Proposal Processing Queue + +**Store:** + +* `ProposalProcessingQueue`: A queue `queue[proposalID]` containing all the + `ProposalIDs` of proposals that reached `MinDeposit`. During each `EndBlock`, + all the proposals that have reached the end of their voting period are processed. + To process a finished proposal, the application tallies the votes, computes the + votes of each validator and checks if every validator in the validator set has + voted. If the proposal is accepted, deposits are refunded. Finally, the proposal + content `Handler` is executed. + +And the pseudocode for the `ProposalProcessingQueue`: + +```go + in EndBlock do + + for finishedProposalID in GetAllFinishedProposalIDs(block.Time) + proposal = load(Governance, ) // proposal is a const key + + validators = Keeper.getAllValidators() + tmpValMap := map(sdk.AccAddress)ValidatorGovInfo + + // Initiate mapping at 0. This is the amount of shares of the validator's vote that will be overridden by their delegator's votes + for each validator in validators + tmpValMap(validator.OperatorAddr).Minus = 0 + + // Tally + voterIterator = rangeQuery(Governance, ) //return all the addresses that voted on the proposal + for each (voterAddress, vote) in voterIterator + delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter + + for each delegation in delegations + // make sure delegation.Shares does NOT include shares being unbonded + tmpValMap(delegation.ValidatorAddr).Minus += delegation.Shares + proposal.updateTally(vote, delegation.Shares) + + _, isVal = stakingKeeper.getValidator(voterAddress) + if (isVal) + tmpValMap(voterAddress).Vote = vote + + tallyingParam = load(GlobalParams, 'TallyingParam') + + // Update tally if validator voted + for each validator in validators + if tmpValMap(validator).HasVoted + proposal.updateTally(tmpValMap(validator).Vote, (validator.TotalShares - tmpValMap(validator).Minus)) + + // Check if proposal is accepted or rejected + totalNonAbstain := proposal.YesVotes + proposal.NoVotes + proposal.NoWithVetoVotes + if (proposal.Votes.YesVotes/totalNonAbstain > tallyingParam.Threshold AND proposal.Votes.NoWithVetoVotes/totalNonAbstain < tallyingParam.Veto) + // proposal was accepted at the end of the voting period + // refund deposits (non-voters already punished) + for each (amount, depositor) in proposal.Deposits + depositor.AtomBalance += amount + + stateWriter, err := proposal.Handler() + if err != nil + // proposal passed but failed during state execution + proposal.CurrentStatus = ProposalStatusFailed + else + // proposal pass and state is persisted + proposal.CurrentStatus = ProposalStatusAccepted + stateWriter.save() + else + // proposal was rejected + proposal.CurrentStatus = ProposalStatusRejected + + store(Governance, , proposal) +``` + +### Legacy Proposal + + +Legacy proposals are deprecated. Use the new proposal flow by granting the governance module the right to execute the message. + + +A legacy proposal is the old implementation of governance proposal. +Contrary to proposal that can contain any messages, a legacy proposal allows to submit a set of pre-defined proposals. +These proposals are defined by their types and handled by handlers that are registered in the gov v1beta1 router. + +More information on how to submit proposals in the [client section](#client). + +## Messages + +### Proposal Submission + +Proposals can be submitted by any account via a `MsgSubmitProposal` transaction. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L42-L69 +``` + +All `sdk.Msgs` passed into the `messages` field of a `MsgSubmitProposal` message +must be registered in the app's `MsgServiceRouter`. Each of these messages must +have one signer, namely the gov module account. And finally, the metadata length +must not be larger than the `maxMetadataLen` config passed into the gov keeper. +The `initialDeposit` must be strictly positive and conform to the accepted denom of the `MinDeposit` param. + +**State modifications:** + +* Generate new `proposalID` +* Create new `Proposal` +* Initialise `Proposal`'s attributes +* Decrease balance of sender by `InitialDeposit` +* If `MinDeposit` is reached: + * Push `proposalID` in `ProposalProcessingQueue` +* Transfer `InitialDeposit` from the `Proposer` to the governance `ModuleAccount` + +### Deposit + +Once a proposal is submitted, if `Proposal.TotalDeposit < ActiveParam.MinDeposit`, Atom holders can send +`MsgDeposit` transactions to increase the proposal's deposit. + +A deposit is accepted iff: + +* The proposal exists +* The proposal is not in the voting period +* The deposited coins are conform to the accepted denom from the `MinDeposit` param + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L134-L147 +``` + +**State modifications:** + +* Decrease balance of sender by `deposit` +* Add `deposit` of sender in `proposal.Deposits` +* Increase `proposal.TotalDeposit` by sender's `deposit` +* If `MinDeposit` is reached: + * Push `proposalID` in `ProposalProcessingQueueEnd` +* Transfer `Deposit` from the `proposer` to the governance `ModuleAccount` + +### Vote + +Once `ActiveParam.MinDeposit` is reached, voting period starts. From there, +bonded Atom holders are able to send `MsgVote` transactions to cast their +vote on the proposal. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/tx.proto#L92-L108 +``` + +**State modifications:** + +* Record `Vote` of sender + + +Gas cost for this message has to take into account the future tallying of the vote in EndBlocker. + + +## Events + +The governance module emits the following events: + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +|-------------------|-----------------|------------------| +| inactive_proposal | proposal_id | {proposalID} | +| inactive_proposal | proposal_result | {proposalResult} | +| active_proposal | proposal_id | {proposalID} | +| active_proposal | proposal_result | {proposalResult} | + +### Handlers + +#### MsgSubmitProposal + +| Type | Attribute Key | Attribute Value | +|---------------------|---------------------|-----------------| +| submit_proposal | proposal_id | {proposalID} | +| submit_proposal [0] | voting_period_start | {proposalID} | +| proposal_deposit | amount | {depositAmount} | +| proposal_deposit | proposal_id | {proposalID} | +| message | module | governance | +| message | action | submit_proposal | +| message | sender | {senderAddress} | + +* [0] Event only emitted if the voting period starts during the submission. + +#### MsgVote + +| Type | Attribute Key | Attribute Value | +|---------------|---------------|-----------------| +| proposal_vote | option | {voteOption} | +| proposal_vote | proposal_id | {proposalID} | +| message | module | governance | +| message | action | vote | +| message | sender | {senderAddress} | + +#### MsgVoteWeighted + +| Type | Attribute Key | Attribute Value | +|---------------|---------------|-----------------------| +| proposal_vote | option | {weightedVoteOptions} | +| proposal_vote | proposal_id | {proposalID} | +| message | module | governance | +| message | action | vote | +| message | sender | {senderAddress} | + +#### MsgDeposit + +| Type | Attribute Key | Attribute Value | +|----------------------|---------------------|-----------------| +| proposal_deposit | amount | {depositAmount} | +| proposal_deposit | proposal_id | {proposalID} | +| proposal_deposit [0] | voting_period_start | {proposalID} | +| message | module | governance | +| message | action | deposit | +| message | sender | {senderAddress} | + +* [0] Event only emitted if the voting period starts during the submission. + +## Parameters + +The governance module contains the following parameters: + +| Key | Type | Example | +|-------------------------------|------------------|-----------------------------------------| +| min_deposit | array (coins) | [{"denom":"uatom","amount":"10000000"}] | +| max_deposit_period | string (time ns) | "172800000000000" (17280s) | +| voting_period | string (time ns) | "172800000000000" (17280s) | +| quorum | string (dec) | "0.334000000000000000" | +| threshold | string (dec) | "0.500000000000000000" | +| veto | string (dec) | "0.334000000000000000" | +| expedited_threshold | string (time ns) | "0.667000000000000000" | +| expedited_voting_period | string (time ns) | "86400000000000" (8600s) | +| expedited_min_deposit | array (coins) | [{"denom":"uatom","amount":"50000000"}] | +| burn_proposal_deposit_prevote | bool | false | +| burn_vote_quorum | bool | false | +| burn_vote_veto | bool | true | +| min_initial_deposit_ratio | string | "0.1" | + +**NOTE**: The governance module contains parameters that are objects unlike other +modules. If only a subset of parameters are desired to be changed, only they need +to be included and not the entire parameter object structure. + +## Client + +### CLI + +A user can query and interact with the `gov` module using the CLI. + +#### Query + +The `query` commands allow users to query `gov` state. + +```bash +simd query gov --help +``` + +##### deposit + +The `deposit` command allows users to query a deposit for a given proposal from a given depositor. + +```bash +simd query gov deposit [proposal-id] [depositer-addr] [flags] +``` + +Example: + +```bash +simd query gov deposit 1 cosmos1.. +``` + +Example Output: + +```bash +amount: +- amount: "100" + denom: stake +depositor: cosmos1.. +proposal_id: "1" +``` + +##### deposits + +The `deposits` command allows users to query all deposits for a given proposal. + +```bash +simd query gov deposits [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov deposits 1 +``` + +Example Output: + +```bash +deposits: +- amount: + - amount: "100" + denom: stake + depositor: cosmos1.. + proposal_id: "1" +pagination: + next_key: null + total: "0" +``` + +##### param + +The `param` command allows users to query a given parameter for the `gov` module. + +```bash +simd query gov param [param-type] [flags] +``` + +Example: + +```bash +simd query gov param voting +``` + +Example Output: + +```bash +voting_period: "172800000000000" +``` + +##### params + +The `params` command allows users to query all parameters for the `gov` module. + +```bash +simd query gov params [flags] +``` + +Example: + +```bash +simd query gov params +``` + +Example Output: + +```bash +deposit_params: + max_deposit_period: 172800s + min_deposit: + - amount: "10000000" + denom: stake +params: + expedited_min_deposit: + - amount: "50000000" + denom: stake + expedited_threshold: "0.670000000000000000" + expedited_voting_period: 86400s + max_deposit_period: 172800s + min_deposit: + - amount: "10000000" + denom: stake + min_initial_deposit_ratio: "0.000000000000000000" + proposal_cancel_burn_rate: "0.500000000000000000" + quorum: "0.334000000000000000" + threshold: "0.500000000000000000" + veto_threshold: "0.334000000000000000" + voting_period: 172800s +tally_params: + quorum: "0.334000000000000000" + threshold: "0.500000000000000000" + veto_threshold: "0.334000000000000000" +voting_params: + voting_period: 172800s +``` + +##### proposal + +The `proposal` command allows users to query a given proposal. + +```bash +simd query gov proposal [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov proposal 1 +``` + +Example Output: + +```bash +deposit_end_time: "2022-03-30T11:50:20.819676256Z" +final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" +id: "1" +messages: +- '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. +metadata: AQ== +status: PROPOSAL_STATUS_DEPOSIT_PERIOD +submit_time: "2022-03-28T11:50:20.819676256Z" +total_deposit: +- amount: "10" + denom: stake +voting_end_time: null +voting_start_time: null +``` + +##### proposals + +The `proposals` command allows users to query all proposals with optional filters. + +```bash +simd query gov proposals [flags] +``` + +Example: + +```bash +simd query gov proposals +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +proposals: +- deposit_end_time: "2022-03-30T11:50:20.819676256Z" + final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" + id: "1" + messages: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + metadata: AQ== + status: PROPOSAL_STATUS_DEPOSIT_PERIOD + submit_time: "2022-03-28T11:50:20.819676256Z" + total_deposit: + - amount: "10" + denom: stake + voting_end_time: null + voting_start_time: null +- deposit_end_time: "2022-03-30T14:02:41.165025015Z" + final_tally_result: + abstain_count: "0" + no_count: "0" + no_with_veto_count: "0" + yes_count: "0" + id: "2" + messages: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "10" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + metadata: AQ== + status: PROPOSAL_STATUS_DEPOSIT_PERIOD + submit_time: "2022-03-28T14:02:41.165025015Z" + total_deposit: + - amount: "10" + denom: stake + voting_end_time: null + voting_start_time: null +``` + +##### proposer + +The `proposer` command allows users to query the proposer for a given proposal. + +```bash +simd query gov proposer [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov proposer 1 +``` + +Example Output: + +```bash +proposal_id: "1" +proposer: cosmos1.. +``` + +##### tally + +The `tally` command allows users to query the tally of a given proposal vote. + +```bash +simd query gov tally [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov tally 1 +``` + +Example Output: + +```bash +abstain: "0" +"no": "0" +no_with_veto: "0" +"yes": "1" +``` + +##### vote + +The `vote` command allows users to query a vote for a given proposal. + +```bash +simd query gov vote [proposal-id] [voter-addr] [flags] +``` + +Example: + +```bash +simd query gov vote 1 cosmos1.. +``` + +Example Output: + +```bash +option: VOTE_OPTION_YES +options: +- option: VOTE_OPTION_YES + weight: "1.000000000000000000" +proposal_id: "1" +voter: cosmos1.. +``` + +##### votes + +The `votes` command allows users to query all votes for a given proposal. + +```bash +simd query gov votes [proposal-id] [flags] +``` + +Example: + +```bash +simd query gov votes 1 +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +votes: +- option: VOTE_OPTION_YES + options: + - option: VOTE_OPTION_YES + weight: "1.000000000000000000" + proposal_id: "1" + voter: cosmos1.. +``` + +#### Transactions + +The `tx` commands allow users to interact with the `gov` module. + +```bash +simd tx gov --help +``` + +##### deposit + +The `deposit` command allows users to deposit tokens for a given proposal. + +```bash +simd tx gov deposit [proposal-id] [deposit] [flags] +``` + +Example: + +```bash +simd tx gov deposit 1 10000000stake --from cosmos1.. +``` + +##### draft-proposal + +The `draft-proposal` command allows users to draft any type of proposal. +The command returns a `draft_proposal.json`, to be used by `submit-proposal` after being completed. +The `draft_metadata.json` is meant to be uploaded to [IPFS](#metadata). + +```bash +simd tx gov draft-proposal +``` + +##### submit-proposal + +The `submit-proposal` command allows users to submit a governance proposal along with some messages and metadata. +Messages, metadata and deposit are defined in a JSON file. + +```bash +simd tx gov submit-proposal [path-to-proposal-json] [flags] +``` + +Example: + +```bash +simd tx gov submit-proposal /path/to/proposal.json --from cosmos1.. +``` + +where `proposal.json` contains: + +```json +{ + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1...", // The gov module module address + "to_address": "cosmos1...", + "amount":[{"denom": "stake","amount": "10"}] + } + ], + "metadata": "AQ==", + "deposit": "10stake", + "title": "Proposal Title", + "summary": "Proposal Summary" +} +``` + + +By default the metadata, summary and title are both limited by 255 characters, this can be overridden by the application developer. + + + +When metadata is not specified, the title is limited to 255 characters and the summary 40x the title length. + + +##### submit-legacy-proposal + +The `submit-legacy-proposal` command allows users to submit a governance legacy proposal along with an initial deposit. + +```bash +simd tx gov submit-legacy-proposal [command] [flags] +``` + +Example: + +```bash +simd tx gov submit-legacy-proposal --title="Test Proposal" --description="testing" --type="Text" --deposit="100000000stake" --from cosmos1.. +``` + +Example (`param-change`): + +```bash +simd tx gov submit-legacy-proposal param-change proposal.json --from cosmos1.. +``` + +```json +{ + "title": "Test Proposal", + "description": "testing, testing, 1, 2, 3", + "changes": [ + { + "subspace": "staking", + "key": "MaxValidators", + "value": 100 + } + ], + "deposit": "10000000stake" +} +``` + +#### cancel-proposal + +Once proposal is canceled, from the deposits of proposal `deposits * proposal_cancel_ratio` will be burned or sent to `ProposalCancelDest` address , if `ProposalCancelDest` is empty then deposits will be burned. The `remaining deposits` will be sent to depositers. + +```bash +simd tx gov cancel-proposal [proposal-id] [flags] +``` + +Example: + +```bash +simd tx gov cancel-proposal 1 --from cosmos1... +``` + +##### vote + +The `vote` command allows users to submit a vote for a given governance proposal. + +```bash +simd tx gov vote [command] [flags] +``` + +Example: + +```bash +simd tx gov vote 1 yes --from cosmos1.. +``` + +##### weighted-vote + +The `weighted-vote` command allows users to submit a weighted vote for a given governance proposal. + +```bash +simd tx gov weighted-vote [proposal-id] [weighted-options] [flags] +``` + +Example: + +```bash +simd tx gov weighted-vote 1 yes=0.5,no=0.5 --from cosmos1.. +``` + +### gRPC + +A user can query the `gov` module using gRPC endpoints. + +#### Proposal + +The `Proposal` endpoint allows users to query a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Proposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Proposal +``` + +Example Output: + +```bash +{ + "proposal": { + "proposalId": "1", + "content": {"@type":"/cosmos.gov.v1beta1.TextProposal","description":"testing, testing, 1, 2, 3","title":"Test Proposal"}, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2021-09-16T19:40:08.712440474Z", + "depositEndTime": "2021-09-18T19:40:08.712440474Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "votingStartTime": "2021-09-16T19:40:08.712440474Z", + "votingEndTime": "2021-09-18T19:40:08.712440474Z", + "title": "Test Proposal", + "summary": "testing, testing, 1, 2, 3" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Proposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Proposal +``` + +Example Output: + +```bash +{ + "proposal": { + "id": "1", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Test Proposal", + "summary": "testing, testing, 1, 2, 3" + } +} +``` + +#### Proposals + +The `Proposals` endpoint allows users to query all proposals with optional filters. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Proposals +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "proposalId": "1", + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z" + }, + { + "proposalId": "2", + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "finalTallyResult": { + "yes": "0", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + }, + "submitTime": "2022-03-28T14:02:41.165025015Z", + "depositEndTime": "2022-03-30T14:02:41.165025015Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "votingStartTime": "0001-01-01T00:00:00Z", + "votingEndTime": "0001-01-01T00:00:00Z" + } + ], + "pagination": { + "total": "2" + } +} + +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Proposals +``` + +Example: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + cosmos.gov.v1.Query/Proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "id": "1", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T11:50:20.819676256Z", + "depositEndTime": "2022-03-30T11:50:20.819676256Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "votingStartTime": "2022-03-28T14:25:26.644857113Z", + "votingEndTime": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + }, + { + "id": "2", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "finalTallyResult": { + "yesCount": "0", + "abstainCount": "0", + "noCount": "0", + "noWithVetoCount": "0" + }, + "submitTime": "2022-03-28T14:02:41.165025015Z", + "depositEndTime": "2022-03-30T14:02:41.165025015Z", + "totalDeposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### Vote + +The `Vote` endpoint allows users to query a vote for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Vote +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Vote +``` + +Example Output: + +```bash +{ + "vote": { + "proposalId": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1000000000000000000" + } + ] + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Vote +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Vote +``` + +Example Output: + +```bash +{ + "vote": { + "proposalId": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } +} +``` + +#### Votes + +The `Votes` endpoint allows users to query all votes for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Votes +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1000000000000000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Votes +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### Params + +The `Params` endpoint allows users to query all parameters for the `gov` module. + + + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"params_type":"voting"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Params +``` + +Example Output: + +```bash +{ + "votingParams": { + "votingPeriod": "172800s" + }, + "depositParams": { + "maxDepositPeriod": "0s" + }, + "tallyParams": { + "quorum": "MA==", + "threshold": "MA==", + "vetoThreshold": "MA==" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"params_type":"voting"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Params +``` + +Example Output: + +```bash +{ + "votingParams": { + "votingPeriod": "172800s" + } +} +``` + +#### Deposit + +The `Deposit` endpoint allows users to query a deposit for a given proposal from a given depositor. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Deposit +``` + +Example: + +```bash +grpcurl -plaintext \ + '{"proposal_id":"1","depositor":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Deposit +``` + +Example Output: + +```bash +{ + "deposit": { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Deposit +``` + +Example: + +```bash +grpcurl -plaintext \ + '{"proposal_id":"1","depositor":"cosmos1.."}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Deposit +``` + +Example Output: + +```bash +{ + "deposit": { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +#### deposits + +The `Deposits` endpoint allows users to query all deposits for a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/Deposits +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/Deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/Deposits +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/Deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposalId": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### TallyResult + +The `TallyResult` endpoint allows users to query the tally of a given proposal. + +Using legacy v1beta1: + +```bash +cosmos.gov.v1beta1.Query/TallyResult +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1beta1.Query/TallyResult +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + } +} +``` + +Using v1: + +```bash +cosmos.gov.v1.Query/TallyResult +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' \ + localhost:9090 \ + cosmos.gov.v1.Query/TallyResult +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "noWithVeto": "0" + } +} +``` + +### REST + +A user can query the `gov` module using REST endpoints. + +#### proposal + +The `proposals` endpoint allows users to query a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1 +``` + +Example Output: + +```bash +{ + "proposal": { + "proposal_id": "1", + "content": null, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1 +``` + +Example Output: + +```bash +{ + "proposal": { + "id": "1", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } +} +``` + +#### proposals + +The `proposals` endpoint also allows users to query all proposals with optional filters. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "proposal_id": "1", + "content": null, + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z" + }, + { + "proposal_id": "2", + "content": null, + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "final_tally_result": { + "yes": "0", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + }, + "submit_time": "2022-03-28T14:02:41.165025015Z", + "deposit_end_time": "2022-03-30T14:02:41.165025015Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "voting_start_time": "0001-01-01T00:00:00Z", + "voting_end_time": "0001-01-01T00:00:00Z" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "id": "1", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_VOTING_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T11:50:20.819676256Z", + "deposit_end_time": "2022-03-30T11:50:20.819676256Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10000000010" + } + ], + "voting_start_time": "2022-03-28T14:25:26.644857113Z", + "voting_end_time": "2022-03-30T14:25:26.644857113Z", + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + }, + { + "id": "2", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10" + } + ] + } + ], + "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", + "final_tally_result": { + "yes_count": "0", + "abstain_count": "0", + "no_count": "0", + "no_with_veto_count": "0" + }, + "submit_time": "2022-03-28T14:02:41.165025015Z", + "deposit_end_time": "2022-03-30T14:02:41.165025015Z", + "total_deposit": [ + { + "denom": "stake", + "amount": "10" + } + ], + "voting_start_time": null, + "voting_end_time": null, + "metadata": "AQ==", + "title": "Proposal Title", + "summary": "Proposal Summary" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### voter vote + +The `votes` endpoint allows users to query a vote for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/votes/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/votes/cosmos1.. +``` + +Example Output: + +```bash +{ + "vote": { + "proposal_id": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/votes/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/votes/cosmos1.. +``` + +Example Output: + +```bash +{ + "vote": { + "proposal_id": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ], + "metadata": "" + } +} +``` + +#### votes + +The `votes` endpoint allows users to query all votes for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/votes +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "option": "VOTE_OPTION_YES", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/votes +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/votes +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "options": [ + { + "option": "VOTE_OPTION_YES", + "weight": "1.000000000000000000" + } + ], + "metadata": "" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### params + +The `params` endpoint allows users to query all parameters for the `gov` module. + + + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/params/{params_type} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/params/voting +``` + +Example Output: + +```bash +{ + "voting_params": { + "voting_period": "172800s" + }, + "deposit_params": { + "min_deposit": [ + ], + "max_deposit_period": "0s" + }, + "tally_params": { + "quorum": "0.000000000000000000", + "threshold": "0.000000000000000000", + "veto_threshold": "0.000000000000000000" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/params/{params_type} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/params/voting +``` + +Example Output: + +```bash +{ + "voting_params": { + "voting_period": "172800s" + }, + "deposit_params": { + "min_deposit": [ + ], + "max_deposit_period": "0s" + }, + "tally_params": { + "quorum": "0.000000000000000000", + "threshold": "0.000000000000000000", + "veto_threshold": "0.000000000000000000" + } +} +``` + +#### deposits + +The `deposits` endpoint allows users to query a deposit for a given proposal from a given depositor. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits/{depositor} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/deposits/cosmos1.. +``` + +Example Output: + +```bash +{ + "deposit": { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/deposits/{depositor} +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/deposits/cosmos1.. +``` + +Example Output: + +```bash +{ + "deposit": { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } +} +``` + +#### proposal deposits + +The `deposits` endpoint allows users to query all deposits for a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/deposits +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/deposits +``` + +Example Output: + +```bash +{ + "deposits": [ + { + "proposal_id": "1", + "depositor": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "10000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### tally + +The `tally` endpoint allows users to query the tally of a given proposal. + +Using legacy v1beta1: + +```bash +/cosmos/gov/v1beta1/proposals/{proposal_id}/tally +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1beta1/proposals/1/tally +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + } +} +``` + +Using v1: + +```bash +/cosmos/gov/v1/proposals/{proposal_id}/tally +``` + +Example: + +```bash +curl localhost:1317/cosmos/gov/v1/proposals/1/tally +``` + +Example Output: + +```bash +{ + "tally": { + "yes": "1000000", + "abstain": "0", + "no": "0", + "no_with_veto": "0" + } +} +``` + +## Metadata + +The gov module has two locations for metadata where users can provide further context about the on-chain actions they are taking. By default all metadata fields have a 255 character length field where metadata can be stored in json format, either on-chain or off-chain depending on the amount of data required. Here we provide a recommendation for the json structure and where the data should be stored. There are two important factors in making these recommendations. First, that the gov and group modules are consistent with one another, note the number of proposals made by all groups may be quite large. Second, that client applications such as block explorers and governance interfaces have confidence in the consistency of metadata structure accross chains. + +### Proposal + +Location: off-chain as json object stored on IPFS (mirrors [group proposal](../group/README.md#metadata)) + +```json +{ + "title": "", + "authors": [""], + "summary": "", + "details": "", + "proposal_forum_url": "", + "vote_option_context": "", +} +``` + + +The `authors` field is an array of strings, this is to allow for multiple authors to be listed in the metadata. +In v0.46, the `authors` field is a comma-separated string. Frontends are encouraged to support both formats for backwards compatibility. + + +### Vote + +Location: on-chain as json within 255 character limit (mirrors [group vote](../group/README.md#metadata)) + +```json +{ + "justification": "", +} +``` + +## Future Improvements + +The current documentation only describes the minimum viable product for the +governance module. Future improvements may include: + +* **`BountyProposals`:** If accepted, a `BountyProposal` creates an open + bounty. The `BountyProposal` specifies how many Atoms will be given upon + completion. These Atoms will be taken from the `reserve pool`. After a + `BountyProposal` is accepted by governance, anybody can submit a + `SoftwareUpgradeProposal` with the code to claim the bounty. Note that once a + `BountyProposal` is accepted, the corresponding funds in the `reserve pool` + are locked so that payment can always be honored. In order to link a + `SoftwareUpgradeProposal` to an open bounty, the submitter of the + `SoftwareUpgradeProposal` will use the `Proposal.LinkedProposal` attribute. + If a `SoftwareUpgradeProposal` linked to an open bounty is accepted by + governance, the funds that were reserved are automatically transferred to the + submitter. +* **Complex delegation:** Delegators could choose other representatives than + their validators. Ultimately, the chain of representatives would always end + up to a validator, but delegators could inherit the vote of their chosen + representative before they inherit the vote of their validator. In other + words, they would only inherit the vote of their validator if their other + appointed representative did not vote. +* **Better process for proposal review:** There would be two parts to + `proposal.Deposit`, one for anti-spam (same as in MVP) and an other one to + reward third party auditors. diff --git a/docs/sdk/v0.53/module-reference/group.mdx b/docs/sdk/v0.53/module-reference/group.mdx new file mode 100644 index 00000000..3a9a0237 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/group.mdx @@ -0,0 +1,2168 @@ +--- +title: "`x/group`" + +--- + +--- + +--- + +## Abstract + +The following documents specify the group module. + +This module allows the creation and management of on-chain multisig accounts and enables voting for message execution based on configurable decision policies. + +## Contents + +* [Concepts](#concepts) + * [Group](#group) + * [Group Policy](#group-policy) + * [Decision Policy](#decision-policy) + * [Proposal](#proposal) + * [Pruning](#pruning) +* [State](#state) + * [Group Table](#group-table) + * [Group Member Table](#group-member-table) + * [Group Policy Table](#group-policy-table) + * [Proposal Table](#proposal-table) + * [Vote Table](#vote-table) +* [Msg Service](#msg-service) + * [Msg/CreateGroup](#msgcreategroup) + * [Msg/UpdateGroupMembers](#msgupdategroupmembers) + * [Msg/UpdateGroupAdmin](#msgupdategroupadmin) + * [Msg/UpdateGroupMetadata](#msgupdategroupmetadata) + * [Msg/CreateGroupPolicy](#msgcreategrouppolicy) + * [Msg/CreateGroupWithPolicy](#msgcreategroupwithpolicy) + * [Msg/UpdateGroupPolicyAdmin](#msgupdategrouppolicyadmin) + * [Msg/UpdateGroupPolicyDecisionPolicy](#msgupdategrouppolicydecisionpolicy) + * [Msg/UpdateGroupPolicyMetadata](#msgupdategrouppolicymetadata) + * [Msg/SubmitProposal](#msgsubmitproposal) + * [Msg/WithdrawProposal](#msgwithdrawproposal) + * [Msg/Vote](#msgvote) + * [Msg/Exec](#msgexec) + * [Msg/LeaveGroup](#msgleavegroup) +* [Events](#events) + * [EventCreateGroup](#eventcreategroup) + * [EventUpdateGroup](#eventupdategroup) + * [EventCreateGroupPolicy](#eventcreategrouppolicy) + * [EventUpdateGroupPolicy](#eventupdategrouppolicy) + * [EventCreateProposal](#eventcreateproposal) + * [EventWithdrawProposal](#eventwithdrawproposal) + * [EventVote](#eventvote) + * [EventExec](#eventexec) + * [EventLeaveGroup](#eventleavegroup) + * [EventProposalPruned](#eventproposalpruned) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) +* [Metadata](#metadata) + +## Concepts + +### Group + +A group is simply an aggregation of accounts with associated weights. It is not +an account and doesn't have a balance. It doesn't in and of itself have any +sort of voting or decision weight. It does have an "administrator" which has +the ability to add, remove and update members in the group. Note that a +group policy account could be an administrator of a group, and that the +administrator doesn't necessarily have to be a member of the group. + +### Group Policy + +A group policy is an account associated with a group and a decision policy. +Group policies are abstracted from groups because a single group may have +multiple decision policies for different types of actions. Managing group +membership separately from decision policies results in the least overhead +and keeps membership consistent across different policies. The pattern that +is recommended is to have a single master group policy for a given group, +and then to create separate group policies with different decision policies +and delegate the desired permissions from the master account to +those "sub-accounts" using the `x/authz` module. + +### Decision Policy + +A decision policy is the mechanism by which members of a group can vote on +proposals, as well as the rules that dictate whether a proposal should pass +or not based on its tally outcome. + +All decision policies generally would have a mininum execution period and a +maximum voting window. The minimum execution period is the minimum amount of time +that must pass after submission in order for a proposal to potentially be executed, and it may +be set to 0. The maximum voting window is the maximum time after submission that a proposal may +be voted on before it is tallied. + +The chain developer also defines an app-wide maximum execution period, which is +the maximum amount of time after a proposal's voting period end where users are +allowed to execute a proposal. + +The current group module comes shipped with two decision policies: threshold +and percentage. Any chain developer can extend upon these two, by creating +custom decision policies, as long as they adhere to the `DecisionPolicy` +interface: + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/x/group/types.go#L27-L45 +``` + +#### Threshold decision policy + +A threshold decision policy defines a threshold of yes votes (based on a tally +of voter weights) that must be achieved in order for a proposal to pass. For +this decision policy, abstain and veto are simply treated as no's. + +This decision policy also has a VotingPeriod window and a MinExecutionPeriod +window. The former defines the duration after proposal submission where members +are allowed to vote, after which tallying is performed. The latter specifies +the minimum duration after proposal submission where the proposal can be +executed. If set to 0, then the proposal is allowed to be executed immediately +on submission (using the `TRY_EXEC` option). Obviously, MinExecutionPeriod +cannot be greater than VotingPeriod+MaxExecutionPeriod (where MaxExecution is +the app-defined duration that specifies the window after voting ended where a +proposal can be executed). + +#### Percentage decision policy + +A percentage decision policy is similar to a threshold decision policy, except +that the threshold is not defined as a constant weight, but as a percentage. +It's more suited for groups where the group members' weights can be updated, as +the percentage threshold stays the same, and doesn't depend on how those member +weights get updated. + +Same as the Threshold decision policy, the percentage decision policy has the +two VotingPeriod and MinExecutionPeriod parameters. + +### Proposal + +Any member(s) of a group can submit a proposal for a group policy account to decide upon. +A proposal consists of a set of messages that will be executed if the proposal +passes as well as any metadata associated with the proposal. + +#### Voting + +There are four choices to choose while voting - yes, no, abstain and veto. Not +all decision policies will take the four choices into account. Votes can contain some optional metadata. +In the current implementation, the voting window begins as soon as a proposal +is submitted, and the end is defined by the group policy's decision policy. + +#### Withdrawing Proposals + +Proposals can be withdrawn any time before the voting period end, either by the +admin of the group policy or by one of the proposers. Once withdrawn, it is +marked as `PROPOSAL_STATUS_WITHDRAWN`, and no more voting or execution is +allowed on it. + +#### Aborted Proposals + +If the group policy is updated during the voting period of the proposal, then +the proposal is marked as `PROPOSAL_STATUS_ABORTED`, and no more voting or +execution is allowed on it. This is because the group policy defines the rules +of proposal voting and execution, so if those rules change during the lifecycle +of a proposal, then the proposal should be marked as stale. + +#### Tallying + +Tallying is the counting of all votes on a proposal. It happens only once in +the lifecycle of a proposal, but can be triggered by two factors, whichever +happens first: + +* either someone tries to execute the proposal (see next section), which can + happen on a `Msg/Exec` transaction, or a `Msg/{SubmitProposal,Vote}` + transaction with the `Exec` field set. When a proposal execution is attempted, + a tally is done first to make sure the proposal passes. +* or on `EndBlock` when the proposal's voting period end just passed. + +If the tally result passes the decision policy's rules, then the proposal is +marked as `PROPOSAL_STATUS_ACCEPTED`, or else it is marked as +`PROPOSAL_STATUS_REJECTED`. In any case, no more voting is allowed anymore, and the tally +result is persisted to state in the proposal's `FinalTallyResult`. + +#### Executing Proposals + +Proposals are executed only when the tallying is done, and the group account's +decision policy allows the proposal to pass based on the tally outcome. They +are marked by the status `PROPOSAL_STATUS_ACCEPTED`. Execution must happen +before a duration of `MaxExecutionPeriod` (set by the chain developer) after +each proposal's voting period end. + +Proposals will not be automatically executed by the chain in this current design, +but rather a user must submit a `Msg/Exec` transaction to attempt to execute the +proposal based on the current votes and decision policy. Any user (not only the +group members) can execute proposals that have been accepted, and execution fees are +paid by the proposal executor. +It's also possible to try to execute a proposal immediately on creation or on +new votes using the `Exec` field of `Msg/SubmitProposal` and `Msg/Vote` requests. +In the former case, proposers signatures are considered as yes votes. +In these cases, if the proposal can't be executed (i.e. it didn't pass the +decision policy's rules), it will still be opened for new votes and +could be tallied and executed later on. + +A successful proposal execution will have its `ExecutorResult` marked as +`PROPOSAL_EXECUTOR_RESULT_SUCCESS`. The proposal will be automatically pruned +after execution. On the other hand, a failed proposal execution will be marked +as `PROPOSAL_EXECUTOR_RESULT_FAILURE`. Such a proposal can be re-executed +multiple times, until it expires after `MaxExecutionPeriod` after voting period +end. + +### Pruning + +Proposals and votes are automatically pruned to avoid state bloat. + +Votes are pruned: + +* either after a successful tally, i.e. a tally whose result passes the decision + policy's rules, which can be trigged by a `Msg/Exec` or a + `Msg/{SubmitProposal,Vote}` with the `Exec` field set, +* or on `EndBlock` right after the proposal's voting period end. This applies to proposals with status `aborted` or `withdrawn` too. + +whichever happens first. + +Proposals are pruned: + +* on `EndBlock` whose proposal status is `withdrawn` or `aborted` on proposal's voting period end before tallying, +* and either after a successful proposal execution, +* or on `EndBlock` right after the proposal's `voting_period_end` + + `max_execution_period` (defined as an app-wide configuration) is passed, + +whichever happens first. + +## State + +The `group` module uses the `orm` package which provides table storage with support for +primary keys and secondary indexes. `orm` also defines `Sequence` which is a persistent unique key generator based on a counter that can be used along with `Table`s. + +Here's the list of tables and associated sequences and indexes stored as part of the `group` module. + +### Group Table + +The `groupTable` stores `GroupInfo`: `0x0 | BigEndian(GroupId) -> ProtocolBuffer(GroupInfo)`. + +#### groupSeq + +The value of `groupSeq` is incremented when creating a new group and corresponds to the new `GroupId`: `0x1 | 0x1 -> BigEndian`. + +The second `0x1` corresponds to the ORM `sequenceStorageKey`. + +#### groupByAdminIndex + +`groupByAdminIndex` allows to retrieve groups by admin address: +`0x2 | len([]byte(group.Admin)) | []byte(group.Admin) | BigEndian(GroupId) -> []byte()`. + +### Group Member Table + +The `groupMemberTable` stores `GroupMember`s: `0x10 | BigEndian(GroupId) | []byte(member.Address) -> ProtocolBuffer(GroupMember)`. + +The `groupMemberTable` is a primary key table and its `PrimaryKey` is given by +`BigEndian(GroupId) | []byte(member.Address)` which is used by the following indexes. + +#### groupMemberByGroupIndex + +`groupMemberByGroupIndex` allows to retrieve group members by group id: +`0x11 | BigEndian(GroupId) | PrimaryKey -> []byte()`. + +#### groupMemberByMemberIndex + +`groupMemberByMemberIndex` allows to retrieve group members by member address: +`0x12 | len([]byte(member.Address)) | []byte(member.Address) | PrimaryKey -> []byte()`. + +### Group Policy Table + +The `groupPolicyTable` stores `GroupPolicyInfo`: `0x20 | len([]byte(Address)) | []byte(Address) -> ProtocolBuffer(GroupPolicyInfo)`. + +The `groupPolicyTable` is a primary key table and its `PrimaryKey` is given by +`len([]byte(Address)) | []byte(Address)` which is used by the following indexes. + +#### groupPolicySeq + +The value of `groupPolicySeq` is incremented when creating a new group policy and is used to generate the new group policy account `Address`: +`0x21 | 0x1 -> BigEndian`. + +The second `0x1` corresponds to the ORM `sequenceStorageKey`. + +#### groupPolicyByGroupIndex + +`groupPolicyByGroupIndex` allows to retrieve group policies by group id: +`0x22 | BigEndian(GroupId) | PrimaryKey -> []byte()`. + +#### groupPolicyByAdminIndex + +`groupPolicyByAdminIndex` allows to retrieve group policies by admin address: +`0x23 | len([]byte(Address)) | []byte(Address) | PrimaryKey -> []byte()`. + +### Proposal Table + +The `proposalTable` stores `Proposal`s: `0x30 | BigEndian(ProposalId) -> ProtocolBuffer(Proposal)`. + +#### proposalSeq + +The value of `proposalSeq` is incremented when creating a new proposal and corresponds to the new `ProposalId`: `0x31 | 0x1 -> BigEndian`. + +The second `0x1` corresponds to the ORM `sequenceStorageKey`. + +#### proposalByGroupPolicyIndex + +`proposalByGroupPolicyIndex` allows to retrieve proposals by group policy account address: +`0x32 | len([]byte(account.Address)) | []byte(account.Address) | BigEndian(ProposalId) -> []byte()`. + +#### ProposalsByVotingPeriodEndIndex + +`proposalsByVotingPeriodEndIndex` allows to retrieve proposals sorted by chronological `voting_period_end`: +`0x33 | sdk.FormatTimeBytes(proposal.VotingPeriodEnd) | BigEndian(ProposalId) -> []byte()`. + +This index is used when tallying the proposal votes at the end of the voting period, and for pruning proposals at `VotingPeriodEnd + MaxExecutionPeriod`. + +### Vote Table + +The `voteTable` stores `Vote`s: `0x40 | BigEndian(ProposalId) | []byte(voter.Address) -> ProtocolBuffer(Vote)`. + +The `voteTable` is a primary key table and its `PrimaryKey` is given by +`BigEndian(ProposalId) | []byte(voter.Address)` which is used by the following indexes. + +#### voteByProposalIndex + +`voteByProposalIndex` allows to retrieve votes by proposal id: +`0x41 | BigEndian(ProposalId) | PrimaryKey -> []byte()`. + +#### voteByVoterIndex + +`voteByVoterIndex` allows to retrieve votes by voter address: +`0x42 | len([]byte(voter.Address)) | []byte(voter.Address) | PrimaryKey -> []byte()`. + +## Msg Service + +### Msg/CreateGroup + +A new group can be created with the `MsgCreateGroup`, which has an admin address, a list of members and some optional metadata. + +The metadata has a maximum length that is chosen by the app developer, and +passed into the group keeper as a config. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L67-L80 +``` + +It's expected to fail if + +* metadata length is greater than `MaxMetadataLen` config +* members are not correctly set (e.g. wrong address format, duplicates, or with 0 weight). + +### Msg/UpdateGroupMembers + +Group members can be updated with the `UpdateGroupMembers`. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L88-L102 +``` + +In the list of `MemberUpdates`, an existing member can be removed by setting its weight to 0. + +It's expected to fail if: + +* the signer is not the admin of the group. +* for any one of the associated group policies, if its decision policy's `Validate()` method fails against the updated group. + +### Msg/UpdateGroupAdmin + +The `UpdateGroupAdmin` can be used to update a group admin. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L107-L120 +``` + +It's expected to fail if the signer is not the admin of the group. + +### Msg/UpdateGroupMetadata + +The `UpdateGroupMetadata` can be used to update a group metadata. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L125-L138 +``` + +It's expected to fail if: + +* new metadata length is greater than `MaxMetadataLen` config. +* the signer is not the admin of the group. + +### Msg/CreateGroupPolicy + +A new group policy can be created with the `MsgCreateGroupPolicy`, which has an admin address, a group id, a decision policy and some optional metadata. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L147-L165 +``` + +It's expected to fail if: + +* the signer is not the admin of the group. +* metadata length is greater than `MaxMetadataLen` config. +* the decision policy's `Validate()` method doesn't pass against the group. + +### Msg/CreateGroupWithPolicy + +A new group with policy can be created with the `MsgCreateGroupWithPolicy`, which has an admin address, a list of members, a decision policy, a `group_policy_as_admin` field to optionally set group and group policy admin with group policy address and some optional metadata for group and group policy. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L191-L215 +``` + +It's expected to fail for the same reasons as `Msg/CreateGroup` and `Msg/CreateGroupPolicy`. + +### Msg/UpdateGroupPolicyAdmin + +The `UpdateGroupPolicyAdmin` can be used to update a group policy admin. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L173-L186 +``` + +It's expected to fail if the signer is not the admin of the group policy. + +### Msg/UpdateGroupPolicyDecisionPolicy + +The `UpdateGroupPolicyDecisionPolicy` can be used to update a decision policy. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L226-L241 +``` + +It's expected to fail if: + +* the signer is not the admin of the group policy. +* the new decision policy's `Validate()` method doesn't pass against the group. + +### Msg/UpdateGroupPolicyMetadata + +The `UpdateGroupPolicyMetadata` can be used to update a group policy metadata. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L246-L259 +``` + +It's expected to fail if: + +* new metadata length is greater than `MaxMetadataLen` config. +* the signer is not the admin of the group. + +### Msg/SubmitProposal + +A new proposal can be created with the `MsgSubmitProposal`, which has a group policy account address, a list of proposers addresses, a list of messages to execute if the proposal is accepted and some optional metadata. +An optional `Exec` value can be provided to try to execute the proposal immediately after proposal creation. Proposers signatures are considered as yes votes in this case. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L281-L315 +``` + +It's expected to fail if: + +* metadata, title, or summary length is greater than `MaxMetadataLen` config. +* if any of the proposers is not a group member. + +### Msg/WithdrawProposal + +A proposal can be withdrawn using `MsgWithdrawProposal` which has an `address` (can be either a proposer or the group policy admin) and a `proposal_id` (which has to be withdrawn). + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L323-L333 +``` + +It's expected to fail if: + +* the signer is neither the group policy admin nor proposer of the proposal. +* the proposal is already closed or aborted. + +### Msg/Vote + +A new vote can be created with the `MsgVote`, given a proposal id, a voter address, a choice (yes, no, veto or abstain) and some optional metadata. +An optional `Exec` value can be provided to try to execute the proposal immediately after voting. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L338-L358 +``` + +It's expected to fail if: + +* metadata length is greater than `MaxMetadataLen` config. +* the proposal is not in voting period anymore. + +### Msg/Exec + +A proposal can be executed with the `MsgExec`. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L363-L373 +``` + +The messages that are part of this proposal won't be executed if: + +* the proposal has not been accepted by the group policy. +* the proposal has already been successfully executed. + +### Msg/LeaveGroup + +The `MsgLeaveGroup` allows group member to leave a group. + +```go reference +https://github.com/cosmos/cosmos-sdk/tree/release/v0.50.x/proto/cosmos/group/v1/tx.proto#L381-L391 +``` + +It's expected to fail if: + +* the group member is not part of the group. +* for any one of the associated group policies, if its decision policy's `Validate()` method fails against the updated group. + +## Events + +The group module emits the following events: + +### EventCreateGroup + +| Type | Attribute Key | Attribute Value | +| -------------------------------- | ------------- | -------------------------------- | +| message | action | /cosmos.group.v1.Msg/CreateGroup | +| cosmos.group.v1.EventCreateGroup | group_id | {groupId} | + +### EventUpdateGroup + +| Type | Attribute Key | Attribute Value | +| -------------------------------- | ------------- | ---------------------------------------------------------- | +| message | action | /cosmos.group.v1.Msg/UpdateGroup{Admin\|Metadata\|Members} | +| cosmos.group.v1.EventUpdateGroup | group_id | {groupId} | + +### EventCreateGroupPolicy + +| Type | Attribute Key | Attribute Value | +| -------------------------------------- | ------------- | -------------------------------------- | +| message | action | /cosmos.group.v1.Msg/CreateGroupPolicy | +| cosmos.group.v1.EventCreateGroupPolicy | address | {groupPolicyAddress} | + +### EventUpdateGroupPolicy + +| Type | Attribute Key | Attribute Value | +| -------------------------------------- | ------------- | ----------------------------------------------------------------------- | +| message | action | /cosmos.group.v1.Msg/UpdateGroupPolicy{Admin\|Metadata\|DecisionPolicy} | +| cosmos.group.v1.EventUpdateGroupPolicy | address | {groupPolicyAddress} | + +### EventCreateProposal + +| Type | Attribute Key | Attribute Value | +| ----------------------------------- | ------------- | ----------------------------------- | +| message | action | /cosmos.group.v1.Msg/CreateProposal | +| cosmos.group.v1.EventCreateProposal | proposal_id | {proposalId} | + +### EventWithdrawProposal + +| Type | Attribute Key | Attribute Value | +| ------------------------------------- | ------------- | ------------------------------------- | +| message | action | /cosmos.group.v1.Msg/WithdrawProposal | +| cosmos.group.v1.EventWithdrawProposal | proposal_id | {proposalId} | + +### EventVote + +| Type | Attribute Key | Attribute Value | +| ------------------------- | ------------- | ------------------------- | +| message | action | /cosmos.group.v1.Msg/Vote | +| cosmos.group.v1.EventVote | proposal_id | {proposalId} | + +## EventExec + +| Type | Attribute Key | Attribute Value | +| ------------------------- | ------------- | ------------------------- | +| message | action | /cosmos.group.v1.Msg/Exec | +| cosmos.group.v1.EventExec | proposal_id | {proposalId} | +| cosmos.group.v1.EventExec | logs | {logs_string} | + +### EventLeaveGroup + +| Type | Attribute Key | Attribute Value | +| ------------------------------- | ------------- | ------------------------------- | +| message | action | /cosmos.group.v1.Msg/LeaveGroup | +| cosmos.group.v1.EventLeaveGroup | proposal_id | {proposalId} | +| cosmos.group.v1.EventLeaveGroup | address | {address} | + +### EventProposalPruned + +| Type | Attribute Key | Attribute Value | +|-------------------------------------|---------------|---------------------------------| +| message | action | /cosmos.group.v1.Msg/LeaveGroup | +| cosmos.group.v1.EventProposalPruned | proposal_id | {proposalId} | +| cosmos.group.v1.EventProposalPruned | status | {ProposalStatus} | +| cosmos.group.v1.EventProposalPruned | tally_result | {TallyResult} | + +## Client + +### CLI + +A user can query and interact with the `group` module using the CLI. + +#### Query + +The `query` commands allow users to query `group` state. + +```bash +simd query group --help +``` + +##### group-info + +The `group-info` command allows users to query for group info by given group id. + +```bash +simd query group group-info [id] [flags] +``` + +Example: + +```bash +simd query group group-info 1 +``` + +Example Output: + +```bash +admin: cosmos1.. +group_id: "1" +metadata: AQ== +total_weight: "3" +version: "1" +``` + +##### group-policy-info + +The `group-policy-info` command allows users to query for group policy info by account address of group policy . + +```bash +simd query group group-policy-info [group-policy-account] [flags] +``` + +Example: + +```bash +simd query group group-policy-info cosmos1.. +``` + +Example Output: + +```bash +address: cosmos1.. +admin: cosmos1.. +decision_policy: + '@type': /cosmos.group.v1.ThresholdDecisionPolicy + threshold: "1" + windows: + min_execution_period: 0s + voting_period: 432000s +group_id: "1" +metadata: AQ== +version: "1" +``` + +##### group-members + +The `group-members` command allows users to query for group members by group id with pagination flags. + +```bash +simd query group group-members [id] [flags] +``` + +Example: + +```bash +simd query group group-members 1 +``` + +Example Output: + +```bash +members: +- group_id: "1" + member: + address: cosmos1.. + metadata: AQ== + weight: "2" +- group_id: "1" + member: + address: cosmos1.. + metadata: AQ== + weight: "1" +pagination: + next_key: null + total: "2" +``` + +##### groups-by-admin + +The `groups-by-admin` command allows users to query for groups by admin account address with pagination flags. + +```bash +simd query group groups-by-admin [admin] [flags] +``` + +Example: + +```bash +simd query group groups-by-admin cosmos1.. +``` + +Example Output: + +```bash +groups: +- admin: cosmos1.. + group_id: "1" + metadata: AQ== + total_weight: "3" + version: "1" +- admin: cosmos1.. + group_id: "2" + metadata: AQ== + total_weight: "3" + version: "1" +pagination: + next_key: null + total: "2" +``` + +##### group-policies-by-group + +The `group-policies-by-group` command allows users to query for group policies by group id with pagination flags. + +```bash +simd query group group-policies-by-group [group-id] [flags] +``` + +Example: + +```bash +simd query group group-policies-by-group 1 +``` + +Example Output: + +```bash +group_policies: +- address: cosmos1.. + admin: cosmos1.. + decision_policy: + '@type': /cosmos.group.v1.ThresholdDecisionPolicy + threshold: "1" + windows: + min_execution_period: 0s + voting_period: 432000s + group_id: "1" + metadata: AQ== + version: "1" +- address: cosmos1.. + admin: cosmos1.. + decision_policy: + '@type': /cosmos.group.v1.ThresholdDecisionPolicy + threshold: "1" + windows: + min_execution_period: 0s + voting_period: 432000s + group_id: "1" + metadata: AQ== + version: "1" +pagination: + next_key: null + total: "2" +``` + +##### group-policies-by-admin + +The `group-policies-by-admin` command allows users to query for group policies by admin account address with pagination flags. + +```bash +simd query group group-policies-by-admin [admin] [flags] +``` + +Example: + +```bash +simd query group group-policies-by-admin cosmos1.. +``` + +Example Output: + +```bash +group_policies: +- address: cosmos1.. + admin: cosmos1.. + decision_policy: + '@type': /cosmos.group.v1.ThresholdDecisionPolicy + threshold: "1" + windows: + min_execution_period: 0s + voting_period: 432000s + group_id: "1" + metadata: AQ== + version: "1" +- address: cosmos1.. + admin: cosmos1.. + decision_policy: + '@type': /cosmos.group.v1.ThresholdDecisionPolicy + threshold: "1" + windows: + min_execution_period: 0s + voting_period: 432000s + group_id: "1" + metadata: AQ== + version: "1" +pagination: + next_key: null + total: "2" +``` + +##### proposal + +The `proposal` command allows users to query for proposal by id. + +```bash +simd query group proposal [id] [flags] +``` + +Example: + +```bash +simd query group proposal 1 +``` + +Example Output: + +```bash +proposal: + address: cosmos1.. + executor_result: EXECUTOR_RESULT_NOT_RUN + group_policy_version: "1" + group_version: "1" + metadata: AQ== + msgs: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "100000000" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + proposal_id: "1" + proposers: + - cosmos1.. + result: RESULT_UNFINALIZED + status: STATUS_SUBMITTED + submitted_at: "2021-12-17T07:06:26.310638964Z" + windows: + min_execution_period: 0s + voting_period: 432000s + vote_state: + abstain_count: "0" + no_count: "0" + veto_count: "0" + yes_count: "0" + summary: "Summary" + title: "Title" +``` + +##### proposals-by-group-policy + +The `proposals-by-group-policy` command allows users to query for proposals by account address of group policy with pagination flags. + +```bash +simd query group proposals-by-group-policy [group-policy-account] [flags] +``` + +Example: + +```bash +simd query group proposals-by-group-policy cosmos1.. +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "1" +proposals: +- address: cosmos1.. + executor_result: EXECUTOR_RESULT_NOT_RUN + group_policy_version: "1" + group_version: "1" + metadata: AQ== + msgs: + - '@type': /cosmos.bank.v1beta1.MsgSend + amount: + - amount: "100000000" + denom: stake + from_address: cosmos1.. + to_address: cosmos1.. + proposal_id: "1" + proposers: + - cosmos1.. + result: RESULT_UNFINALIZED + status: STATUS_SUBMITTED + submitted_at: "2021-12-17T07:06:26.310638964Z" + windows: + min_execution_period: 0s + voting_period: 432000s + vote_state: + abstain_count: "0" + no_count: "0" + veto_count: "0" + yes_count: "0" + summary: "Summary" + title: "Title" +``` + +##### vote + +The `vote` command allows users to query for vote by proposal id and voter account address. + +```bash +simd query group vote [proposal-id] [voter] [flags] +``` + +Example: + +```bash +simd query group vote 1 cosmos1.. +``` + +Example Output: + +```bash +vote: + choice: CHOICE_YES + metadata: AQ== + proposal_id: "1" + submitted_at: "2021-12-17T08:05:02.490164009Z" + voter: cosmos1.. +``` + +##### votes-by-proposal + +The `votes-by-proposal` command allows users to query for votes by proposal id with pagination flags. + +```bash +simd query group votes-by-proposal [proposal-id] [flags] +``` + +Example: + +```bash +simd query group votes-by-proposal 1 +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "1" +votes: +- choice: CHOICE_YES + metadata: AQ== + proposal_id: "1" + submitted_at: "2021-12-17T08:05:02.490164009Z" + voter: cosmos1.. +``` + +##### votes-by-voter + +The `votes-by-voter` command allows users to query for votes by voter account address with pagination flags. + +```bash +simd query group votes-by-voter [voter] [flags] +``` + +Example: + +```bash +simd query group votes-by-voter cosmos1.. +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "1" +votes: +- choice: CHOICE_YES + metadata: AQ== + proposal_id: "1" + submitted_at: "2021-12-17T08:05:02.490164009Z" + voter: cosmos1.. +``` + +### Transactions + +The `tx` commands allow users to interact with the `group` module. + +```bash +simd tx group --help +``` + +#### create-group + +The `create-group` command allows users to create a group which is an aggregation of member accounts with associated weights and +an administrator account. + +```bash +simd tx group create-group [admin] [metadata] [members-json-file] +``` + +Example: + +```bash +simd tx group create-group cosmos1.. "AQ==" members.json +``` + +#### update-group-admin + +The `update-group-admin` command allows users to update a group's admin. + +```bash +simd tx group update-group-admin [admin] [group-id] [new-admin] [flags] +``` + +Example: + +```bash +simd tx group update-group-admin cosmos1.. 1 cosmos1.. +``` + +#### update-group-members + +The `update-group-members` command allows users to update a group's members. + +```bash +simd tx group update-group-members [admin] [group-id] [members-json-file] [flags] +``` + +Example: + +```bash +simd tx group update-group-members cosmos1.. 1 members.json +``` + +#### update-group-metadata + +The `update-group-metadata` command allows users to update a group's metadata. + +```bash +simd tx group update-group-metadata [admin] [group-id] [metadata] [flags] +``` + +Example: + +```bash +simd tx group update-group-metadata cosmos1.. 1 "AQ==" +``` + +#### create-group-policy + +The `create-group-policy` command allows users to create a group policy which is an account associated with a group and a decision policy. + +```bash +simd tx group create-group-policy [admin] [group-id] [metadata] [decision-policy] [flags] +``` + +Example: + +```bash +simd tx group create-group-policy cosmos1.. 1 "AQ==" '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +``` + +#### create-group-with-policy + +The `create-group-with-policy` command allows users to create a group which is an aggregation of member accounts with associated weights and an administrator account with decision policy. If the `--group-policy-as-admin` flag is set to `true`, the group policy address becomes the group and group policy admin. + +```bash +simd tx group create-group-with-policy [admin] [group-metadata] [group-policy-metadata] [members-json-file] [decision-policy] [flags] +``` + +Example: + +```bash +simd tx group create-group-with-policy cosmos1.. "AQ==" "AQ==" members.json '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +``` + +#### update-group-policy-admin + +The `update-group-policy-admin` command allows users to update a group policy admin. + +```bash +simd tx group update-group-policy-admin [admin] [group-policy-account] [new-admin] [flags] +``` + +Example: + +```bash +simd tx group update-group-policy-admin cosmos1.. cosmos1.. cosmos1.. +``` + +#### update-group-policy-metadata + +The `update-group-policy-metadata` command allows users to update a group policy metadata. + +```bash +simd tx group update-group-policy-metadata [admin] [group-policy-account] [new-metadata] [flags] +``` + +Example: + +```bash +simd tx group update-group-policy-metadata cosmos1.. cosmos1.. "AQ==" +``` + +#### update-group-policy-decision-policy + +The `update-group-policy-decision-policy` command allows users to update a group policy's decision policy. + +```bash +simd tx group update-group-policy-decision-policy [admin] [group-policy-account] [decision-policy] [flags] +``` + +Example: + +```bash +simd tx group update-group-policy-decision-policy cosmos1.. cosmos1.. '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"2", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +``` + +#### submit-proposal + +The `submit-proposal` command allows users to submit a new proposal. + +```bash +simd tx group submit-proposal [group-policy-account] [proposer[,proposer]*] [msg_tx_json_file] [metadata] [flags] +``` + +Example: + +```bash +simd tx group submit-proposal cosmos1.. cosmos1.. msg_tx.json "AQ==" +``` + +#### withdraw-proposal + +The `withdraw-proposal` command allows users to withdraw a proposal. + +```bash +simd tx group withdraw-proposal [proposal-id] [group-policy-admin-or-proposer] +``` + +Example: + +```bash +simd tx group withdraw-proposal 1 cosmos1.. +``` + +#### vote + +The `vote` command allows users to vote on a proposal. + +```bash +simd tx group vote proposal-id] [voter] [choice] [metadata] [flags] +``` + +Example: + +```bash +simd tx group vote 1 cosmos1.. CHOICE_YES "AQ==" +``` + +#### exec + +The `exec` command allows users to execute a proposal. + +```bash +simd tx group exec [proposal-id] [flags] +``` + +Example: + +```bash +simd tx group exec 1 +``` + +#### leave-group + +The `leave-group` command allows group member to leave the group. + +```bash +simd tx group leave-group [member-address] [group-id] +``` + +Example: + +```bash +simd tx group leave-group cosmos1... 1 +``` + +### gRPC + +A user can query the `group` module using gRPC endpoints. + +#### GroupInfo + +The `GroupInfo` endpoint allows users to query for group info by given group id. + +```bash +cosmos.group.v1.Query/GroupInfo +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"group_id":1}' localhost:9090 cosmos.group.v1.Query/GroupInfo +``` + +Example Output: + +```bash +{ + "info": { + "groupId": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "totalWeight": "3" + } +} +``` + +#### GroupPolicyInfo + +The `GroupPolicyInfo` endpoint allows users to query for group policy info by account address of group policy. + +```bash +cosmos.group.v1.Query/GroupPolicyInfo +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"address":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupPolicyInfo +``` + +Example Output: + +```bash +{ + "info": { + "address": "cosmos1..", + "groupId": "1", + "admin": "cosmos1..", + "version": "1", + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows": {"voting_period": "120h", "min_execution_period": "0s"}}, + } +} +``` + +#### GroupMembers + +The `GroupMembers` endpoint allows users to query for group members by group id with pagination flags. + +```bash +cosmos.group.v1.Query/GroupMembers +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"group_id":"1"}' localhost:9090 cosmos.group.v1.Query/GroupMembers +``` + +Example Output: + +```bash +{ + "members": [ + { + "groupId": "1", + "member": { + "address": "cosmos1..", + "weight": "1" + } + }, + { + "groupId": "1", + "member": { + "address": "cosmos1..", + "weight": "2" + } + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### GroupsByAdmin + +The `GroupsByAdmin` endpoint allows users to query for groups by admin account address with pagination flags. + +```bash +cosmos.group.v1.Query/GroupsByAdmin +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"admin":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupsByAdmin +``` + +Example Output: + +```bash +{ + "groups": [ + { + "groupId": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "totalWeight": "3" + }, + { + "groupId": "2", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "totalWeight": "3" + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### GroupPoliciesByGroup + +The `GroupPoliciesByGroup` endpoint allows users to query for group policies by group id with pagination flags. + +```bash +cosmos.group.v1.Query/GroupPoliciesByGroup +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"group_id":"1"}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByGroup +``` + +Example Output: + +```bash +{ + "GroupPolicies": [ + { + "address": "cosmos1..", + "groupId": "1", + "admin": "cosmos1..", + "version": "1", + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, + }, + { + "address": "cosmos1..", + "groupId": "1", + "admin": "cosmos1..", + "version": "1", + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### GroupPoliciesByAdmin + +The `GroupPoliciesByAdmin` endpoint allows users to query for group policies by admin account address with pagination flags. + +```bash +cosmos.group.v1.Query/GroupPoliciesByAdmin +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"admin":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByAdmin +``` + +Example Output: + +```bash +{ + "GroupPolicies": [ + { + "address": "cosmos1..", + "groupId": "1", + "admin": "cosmos1..", + "version": "1", + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, + }, + { + "address": "cosmos1..", + "groupId": "1", + "admin": "cosmos1..", + "version": "1", + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, + } + ], + "pagination": { + "total": "2" + } +} +``` + +#### Proposal + +The `Proposal` endpoint allows users to query for proposal by id. + +```bash +cosmos.group.v1.Query/Proposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' localhost:9090 cosmos.group.v1.Query/Proposal +``` + +Example Output: + +```bash +{ + "proposal": { + "proposalId": "1", + "address": "cosmos1..", + "proposers": [ + "cosmos1.." + ], + "submittedAt": "2021-12-17T07:06:26.310638964Z", + "groupVersion": "1", + "GroupPolicyVersion": "1", + "status": "STATUS_SUBMITTED", + "result": "RESULT_UNFINALIZED", + "voteState": { + "yesCount": "0", + "noCount": "0", + "abstainCount": "0", + "vetoCount": "0" + }, + "windows": { + "min_execution_period": "0s", + "voting_period": "432000s" + }, + "executorResult": "EXECUTOR_RESULT_NOT_RUN", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "title": "Title", + "summary": "Summary", + } +} +``` + +#### ProposalsByGroupPolicy + +The `ProposalsByGroupPolicy` endpoint allows users to query for proposals by account address of group policy with pagination flags. + +```bash +cosmos.group.v1.Query/ProposalsByGroupPolicy +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"address":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/ProposalsByGroupPolicy +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "proposalId": "1", + "address": "cosmos1..", + "proposers": [ + "cosmos1.." + ], + "submittedAt": "2021-12-17T08:03:27.099649352Z", + "groupVersion": "1", + "GroupPolicyVersion": "1", + "status": "STATUS_CLOSED", + "result": "RESULT_ACCEPTED", + "voteState": { + "yesCount": "1", + "noCount": "0", + "abstainCount": "0", + "vetoCount": "0" + }, + "windows": { + "min_execution_period": "0s", + "voting_period": "432000s" + }, + "executorResult": "EXECUTOR_RESULT_NOT_RUN", + "messages": [ + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + ], + "title": "Title", + "summary": "Summary", + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### VoteByProposalVoter + +The `VoteByProposalVoter` endpoint allows users to query for vote by proposal id and voter account address. + +```bash +cosmos.group.v1.Query/VoteByProposalVoter +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1","voter":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/VoteByProposalVoter +``` + +Example Output: + +```bash +{ + "vote": { + "proposalId": "1", + "voter": "cosmos1..", + "choice": "CHOICE_YES", + "submittedAt": "2021-12-17T08:05:02.490164009Z" + } +} +``` + +#### VotesByProposal + +The `VotesByProposal` endpoint allows users to query for votes by proposal id with pagination flags. + +```bash +cosmos.group.v1.Query/VotesByProposal +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"proposal_id":"1"}' localhost:9090 cosmos.group.v1.Query/VotesByProposal +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "choice": "CHOICE_YES", + "submittedAt": "2021-12-17T08:05:02.490164009Z" + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### VotesByVoter + +The `VotesByVoter` endpoint allows users to query for votes by voter account address with pagination flags. + +```bash +cosmos.group.v1.Query/VotesByVoter +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"voter":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/VotesByVoter +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposalId": "1", + "voter": "cosmos1..", + "choice": "CHOICE_YES", + "submittedAt": "2021-12-17T08:05:02.490164009Z" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### REST + +A user can query the `group` module using REST endpoints. + +#### GroupInfo + +The `GroupInfo` endpoint allows users to query for group info by given group id. + +```bash +/cosmos/group/v1/group_info/{group_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/group_info/1 +``` + +Example Output: + +```bash +{ + "info": { + "id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "total_weight": "3" + } +} +``` + +#### GroupPolicyInfo + +The `GroupPolicyInfo` endpoint allows users to query for group policy info by account address of group policy. + +```bash +/cosmos/group/v1/group_policy_info/{address} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/group_policy_info/cosmos1.. +``` + +Example Output: + +```bash +{ + "info": { + "address": "cosmos1..", + "group_id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "decision_policy": { + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "1", + "windows": { + "voting_period": "120h", + "min_execution_period": "0s" + } + }, + } +} +``` + +#### GroupMembers + +The `GroupMembers` endpoint allows users to query for group members by group id with pagination flags. + +```bash +/cosmos/group/v1/group_members/{group_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/group_members/1 +``` + +Example Output: + +```bash +{ + "members": [ + { + "group_id": "1", + "member": { + "address": "cosmos1..", + "weight": "1", + "metadata": "AQ==" + } + }, + { + "group_id": "1", + "member": { + "address": "cosmos1..", + "weight": "2", + "metadata": "AQ==" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### GroupsByAdmin + +The `GroupsByAdmin` endpoint allows users to query for groups by admin account address with pagination flags. + +```bash +/cosmos/group/v1/groups_by_admin/{admin} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/groups_by_admin/cosmos1.. +``` + +Example Output: + +```bash +{ + "groups": [ + { + "id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "total_weight": "3" + }, + { + "id": "2", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "total_weight": "3" + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### GroupPoliciesByGroup + +The `GroupPoliciesByGroup` endpoint allows users to query for group policies by group id with pagination flags. + +```bash +/cosmos/group/v1/group_policies_by_group/{group_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/group_policies_by_group/1 +``` + +Example Output: + +```bash +{ + "group_policies": [ + { + "address": "cosmos1..", + "group_id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "decision_policy": { + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "1", + "windows": { + "voting_period": "120h", + "min_execution_period": "0s" + } + }, + }, + { + "address": "cosmos1..", + "group_id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "decision_policy": { + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "1", + "windows": { + "voting_period": "120h", + "min_execution_period": "0s" + } + }, + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### GroupPoliciesByAdmin + +The `GroupPoliciesByAdmin` endpoint allows users to query for group policies by admin account address with pagination flags. + +```bash +/cosmos/group/v1/group_policies_by_admin/{admin} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/group_policies_by_admin/cosmos1.. +``` + +Example Output: + +```bash +{ + "group_policies": [ + { + "address": "cosmos1..", + "group_id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "decision_policy": { + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "1", + "windows": { + "voting_period": "120h", + "min_execution_period": "0s" + } + }, + }, + { + "address": "cosmos1..", + "group_id": "1", + "admin": "cosmos1..", + "metadata": "AQ==", + "version": "1", + "decision_policy": { + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "1", + "windows": { + "voting_period": "120h", + "min_execution_period": "0s" + } + }, + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +``` + +#### Proposal + +The `Proposal` endpoint allows users to query for proposal by id. + +```bash +/cosmos/group/v1/proposal/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/proposal/1 +``` + +Example Output: + +```bash +{ + "proposal": { + "proposal_id": "1", + "address": "cosmos1..", + "metadata": "AQ==", + "proposers": [ + "cosmos1.." + ], + "submitted_at": "2021-12-17T07:06:26.310638964Z", + "group_version": "1", + "group_policy_version": "1", + "status": "STATUS_SUBMITTED", + "result": "RESULT_UNFINALIZED", + "vote_state": { + "yes_count": "0", + "no_count": "0", + "abstain_count": "0", + "veto_count": "0" + }, + "windows": { + "min_execution_period": "0s", + "voting_period": "432000s" + }, + "executor_result": "EXECUTOR_RESULT_NOT_RUN", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "100000000" + } + ] + } + ], + "title": "Title", + "summary": "Summary", + } +} +``` + +#### ProposalsByGroupPolicy + +The `ProposalsByGroupPolicy` endpoint allows users to query for proposals by account address of group policy with pagination flags. + +```bash +/cosmos/group/v1/proposals_by_group_policy/{address} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/proposals_by_group_policy/cosmos1.. +``` + +Example Output: + +```bash +{ + "proposals": [ + { + "id": "1", + "group_policy_address": "cosmos1..", + "metadata": "AQ==", + "proposers": [ + "cosmos1.." + ], + "submit_time": "2021-12-17T08:03:27.099649352Z", + "group_version": "1", + "group_policy_version": "1", + "status": "STATUS_CLOSED", + "result": "RESULT_ACCEPTED", + "vote_state": { + "yes_count": "1", + "no_count": "0", + "abstain_count": "0", + "veto_count": "0" + }, + "windows": { + "min_execution_period": "0s", + "voting_period": "432000s" + }, + "executor_result": "EXECUTOR_RESULT_NOT_RUN", + "messages": [ + { + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1..", + "to_address": "cosmos1..", + "amount": [ + { + "denom": "stake", + "amount": "100000000" + } + ] + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### VoteByProposalVoter + +The `VoteByProposalVoter` endpoint allows users to query for vote by proposal id and voter account address. + +```bash +/cosmos/group/v1/vote_by_proposal_voter/{proposal_id}/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1beta1/vote_by_proposal_voter/1/cosmos1.. +``` + +Example Output: + +```bash +{ + "vote": { + "proposal_id": "1", + "voter": "cosmos1..", + "choice": "CHOICE_YES", + "metadata": "AQ==", + "submitted_at": "2021-12-17T08:05:02.490164009Z" + } +} +``` + +#### VotesByProposal + +The `VotesByProposal` endpoint allows users to query for votes by proposal id with pagination flags. + +```bash +/cosmos/group/v1/votes_by_proposal/{proposal_id} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/votes_by_proposal/1 +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "option": "CHOICE_YES", + "metadata": "AQ==", + "submit_time": "2021-12-17T08:05:02.490164009Z" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### VotesByVoter + +The `VotesByVoter` endpoint allows users to query for votes by voter account address with pagination flags. + +```bash +/cosmos/group/v1/votes_by_voter/{voter} +``` + +Example: + +```bash +curl localhost:1317/cosmos/group/v1/votes_by_voter/cosmos1.. +``` + +Example Output: + +```bash +{ + "votes": [ + { + "proposal_id": "1", + "voter": "cosmos1..", + "choice": "CHOICE_YES", + "metadata": "AQ==", + "submitted_at": "2021-12-17T08:05:02.490164009Z" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +## Metadata + +The group module has four locations for metadata where users can provide further context about the on-chain actions they are taking. By default all metadata fields have a 255 character length field where metadata can be stored in json format, either on-chain or off-chain depending on the amount of data required. Here we provide a recommendation for the json structure and where the data should be stored. There are two important factors in making these recommendations. First, that the group and gov modules are consistent with one another, note the number of proposals made by all groups may be quite large. Second, that client applications such as block explorers and governance interfaces have confidence in the consistency of metadata structure across chains. + +### Proposal + +Location: off-chain as json object stored on IPFS (mirrors [gov proposal](../gov/README.md#metadata)) + +```json +{ + "title": "", + "authors": [""], + "summary": "", + "details": "", + "proposal_forum_url": "", + "vote_option_context": "", +} +``` + + +The `authors` field is an array of strings, this is to allow for multiple authors to be listed in the metadata. +In v0.46, the `authors` field is a comma-separated string. Frontends are encouraged to support both formats for backwards compatibility. + + +### Vote + +Location: on-chain as json within 255 character limit (mirrors [gov vote](../gov/README.md#metadata)) + +```json +{ + "justification": "", +} +``` + +### Group + +Location: off-chain as json object stored on IPFS + +```json +{ + "name": "", + "description": "", + "group_website_url": "", + "group_forum_url": "", +} +``` + +### Decision policy + +Location: on-chain as json within 255 character limit + +```json +{ + "name": "", + "description": "", +} +``` diff --git a/docs/sdk/v0.53/module-reference/mint.mdx b/docs/sdk/v0.53/module-reference/mint.mdx new file mode 100644 index 00000000..c2d9f541 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/mint.mdx @@ -0,0 +1,460 @@ +--- +title: "`x/mint`" + +--- + +--- + +--- + +The `x/mint` module handles the regular minting of new tokens in a configurable manner. + +## Contents + +* [State](#state) + * [Minter](#minter) + * [Params](#params) +* [Begin-Block](#begin-block) + * [NextInflationRate](#nextinflationrate) + * [NextAnnualProvisions](#nextannualprovisions) + * [BlockProvision](#blockprovision) +* [Parameters](#parameters) +* [Events](#events) + * [BeginBlocker](#beginblocker) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) + +## Concepts + +### The Minting Mechanism + +The default minting mechanism was designed to: + +* allow for a flexible inflation rate determined by market demand targeting a particular bonded-stake ratio +* effect a balance between market liquidity and staked supply + +In order to best determine the appropriate market rate for inflation rewards, a +moving change rate is used. The moving change rate mechanism ensures that if +the % bonded is either over or under the goal %-bonded, the inflation rate will +adjust to further incentivize or disincentivize being bonded, respectively. Setting the goal +%-bonded at less than 100% encourages the network to maintain some non-staked tokens +which should help provide some liquidity. + +It can be broken down in the following way: + +* If the actual percentage of bonded tokens is below the goal %-bonded the inflation rate will + increase until a maximum value is reached +* If the goal % bonded (67% in Cosmos-Hub) is maintained, then the inflation + rate will stay constant +* If the actual percentage of bonded tokens is above the goal %-bonded the inflation rate will + decrease until a minimum value is reached + +### Custom Minters + +As of Cosmos SDK v0.53.0, developers can set a custom `MintFn` for the module for specialized token minting logic. + +The function signature that a `MintFn` must implement is as follows: + +```go +// MintFn defines the function that needs to be implemented in order to customize the minting process. +type MintFn func(ctx sdk.Context, k *Keeper) error +``` + +This can be passed to the `Keeper` upon creation with an additional `Option`: + +```go +app.MintKeeper = mintkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[minttypes.StoreKey]), + app.StakingKeeper, + app.AccountKeeper, + app.BankKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + // mintkeeper.WithMintFn(CUSTOM_MINT_FN), // custom mintFn can be added here + ) +``` + +#### Custom Minter DI Example + +Below is a simple approach to creating a custom mint function with extra dependencies in DI configurations. +For this basic example, we will make the minter simply double the supply of `foo` coin. + +First, we will define a function that takes our required dependencies, and returns a `MintFn`. + +```go +// MyCustomMintFunction is a custom mint function that doubles the supply of `foo` coin. +func MyCustomMintFunction(bank bankkeeper.BaseKeeper) mintkeeper.MintFn { + return func(ctx sdk.Context, k *mintkeeper.Keeper) error { + supply := bank.GetSupply(ctx, "foo") + err := k.MintCoins(ctx, sdk.NewCoins(supply.Add(supply))) + if err != nil { + return err + } + return nil + } +} +``` + +Then, pass the function defined above into the `depinject.Supply` function with the required dependencies. + +```go +// NewSimApp returns a reference to an initialized SimApp. +func NewSimApp( + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + loadLatest bool, + appOpts servertypes.AppOptions, + baseAppOptions ...func(*baseapp.BaseApp), +) *SimApp { + var ( + app = &SimApp{} + appBuilder *runtime.AppBuilder + appConfig = depinject.Configs( + AppConfig, + depinject.Supply( + appOpts, + logger, + // our custom mint function with the necessary dependency passed in. + MyCustomMintFunction(app.BankKeeper), + ), + ) + ) + // ... +} +``` + +## State + +### Minter + +The minter is a space for holding current inflation information. + +* Minter: `0x00 -> ProtocolBuffer(minter)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/mint/v1beta1/mint.proto#L10-L24 +``` + +### Params + +The mint module stores its params in state with the prefix of `0x01`, +it can be updated with governance or the address with authority. + +* Params: `mint/params -> legacy_amino(params)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/mint/v1beta1/mint.proto#L26-L59 +``` + +## Begin-Block + +Minting parameters are recalculated and inflation paid at the beginning of each block. + +### Inflation rate calculation + +Inflation rate is calculated using an "inflation calculation function" that's +passed to the `NewAppModule` function. If no function is passed, then the SDK's +default inflation function will be used (`NextInflationRate`). In case a custom +inflation calculation logic is needed, this can be achieved by defining and +passing a function that matches `InflationCalculationFn`'s signature. + +```go +type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) math.LegacyDec +``` + +#### NextInflationRate + +The target annual inflation rate is recalculated each block. +The inflation is also subject to a rate change (positive or negative) +depending on the distance from the desired ratio (67%). The maximum rate change +possible is defined to be 13% per year, however, the annual inflation is capped +as between 7% and 20%. + +```go +NextInflationRate(params Params, bondedRatio math.LegacyDec) (inflation math.LegacyDec) { + inflationRateChangePerYear = (1 - bondedRatio/params.GoalBonded) * params.InflationRateChange + inflationRateChange = inflationRateChangePerYear/blocksPerYr + + // increase the new annual inflation for this next block + inflation += inflationRateChange + if inflation > params.InflationMax { + inflation = params.InflationMax + } + if inflation < params.InflationMin { + inflation = params.InflationMin + } + + return inflation +} +``` + +### NextAnnualProvisions + +Calculate the annual provisions based on current total supply and inflation +rate. This parameter is calculated once per block. + +```go +NextAnnualProvisions(params Params, totalSupply math.LegacyDec) (provisions math.LegacyDec) { + return Inflation * totalSupply +``` + +### BlockProvision + +Calculate the provisions generated for each block based on current annual provisions. The provisions are then minted by the `mint` module's `ModuleMinterAccount` and then transferred to the `auth`'s `FeeCollector` `ModuleAccount`. + +```go +BlockProvision(params Params) sdk.Coin { + provisionAmt = AnnualProvisions/ params.BlocksPerYear + return sdk.NewCoin(params.MintDenom, provisionAmt.Truncate()) +``` + +## Parameters + +The minting module contains the following parameters: + +| Key | Type | Example | +|---------------------|-----------------|------------------------| +| MintDenom | string | "uatom" | +| InflationRateChange | string (dec) | "0.130000000000000000" | +| InflationMax | string (dec) | "0.200000000000000000" | +| InflationMin | string (dec) | "0.070000000000000000" | +| GoalBonded | string (dec) | "0.670000000000000000" | +| BlocksPerYear | string (uint64) | "6311520" | + +## Events + +The minting module emits the following events: + +### BeginBlocker + +| Type | Attribute Key | Attribute Value | +|------|-------------------|--------------------| +| mint | bonded_ratio | {bondedRatio} | +| mint | inflation | {inflation} | +| mint | annual_provisions | {annualProvisions} | +| mint | amount | {amount} | + +## Client + +### CLI + +A user can query and interact with the `mint` module using the CLI. + +#### Query + +The `query` commands allows users to query `mint` state. + +```shell +simd query mint --help +``` + +##### annual-provisions + +The `annual-provisions` command allows users to query the current minting annual provisions value + +```shell +simd query mint annual-provisions [flags] +``` + +Example: + +```shell +simd query mint annual-provisions +``` + +Example Output: + +```shell +22268504368893.612100895088410693 +``` + +##### inflation + +The `inflation` command allows users to query the current minting inflation value + +```shell +simd query mint inflation [flags] +``` + +Example: + +```shell +simd query mint inflation +``` + +Example Output: + +```shell +0.199200302563256955 +``` + +##### params + +The `params` command allows users to query the current minting parameters + +```shell +simd query mint params [flags] +``` + +Example: + +```yml +blocks_per_year: "4360000" +goal_bonded: "0.670000000000000000" +inflation_max: "0.200000000000000000" +inflation_min: "0.070000000000000000" +inflation_rate_change: "0.130000000000000000" +mint_denom: stake +``` + +### gRPC + +A user can query the `mint` module using gRPC endpoints. + +#### AnnualProvisions + +The `AnnualProvisions` endpoint allows users to query the current minting annual provisions value + +```shell +/cosmos.mint.v1beta1.Query/AnnualProvisions +``` + +Example: + +```shell +grpcurl -plaintext localhost:9090 cosmos.mint.v1beta1.Query/AnnualProvisions +``` + +Example Output: + +```json +{ + "annualProvisions": "1432452520532626265712995618" +} +``` + +#### Inflation + +The `Inflation` endpoint allows users to query the current minting inflation value + +```shell +/cosmos.mint.v1beta1.Query/Inflation +``` + +Example: + +```shell +grpcurl -plaintext localhost:9090 cosmos.mint.v1beta1.Query/Inflation +``` + +Example Output: + +```json +{ + "inflation": "130197115720711261" +} +``` + +#### Params + +The `Params` endpoint allows users to query the current minting parameters + +```shell +/cosmos.mint.v1beta1.Query/Params +``` + +Example: + +```shell +grpcurl -plaintext localhost:9090 cosmos.mint.v1beta1.Query/Params +``` + +Example Output: + +```json +{ + "params": { + "mintDenom": "stake", + "inflationRateChange": "130000000000000000", + "inflationMax": "200000000000000000", + "inflationMin": "70000000000000000", + "goalBonded": "670000000000000000", + "blocksPerYear": "6311520" + } +} +``` + +### REST + +A user can query the `mint` module using REST endpoints. + +#### annual-provisions + +```shell +/cosmos/mint/v1beta1/annual_provisions +``` + +Example: + +```shell +curl "localhost:1317/cosmos/mint/v1beta1/annual_provisions" +``` + +Example Output: + +```json +{ + "annualProvisions": "1432452520532626265712995618" +} +``` + +#### inflation + +```shell +/cosmos/mint/v1beta1/inflation +``` + +Example: + +```shell +curl "localhost:1317/cosmos/mint/v1beta1/inflation" +``` + +Example Output: + +```json +{ + "inflation": "130197115720711261" +} +``` + +#### params + +```shell +/cosmos/mint/v1beta1/params +``` + +Example: + +```shell +curl "localhost:1317/cosmos/mint/v1beta1/params" +``` + +Example Output: + +```json +{ + "params": { + "mintDenom": "stake", + "inflationRateChange": "130000000000000000", + "inflationMax": "200000000000000000", + "inflationMin": "70000000000000000", + "goalBonded": "670000000000000000", + "blocksPerYear": "6311520" + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/nft.mdx b/docs/sdk/v0.53/module-reference/nft.mdx new file mode 100644 index 00000000..ddab94ca --- /dev/null +++ b/docs/sdk/v0.53/module-reference/nft.mdx @@ -0,0 +1,92 @@ +--- +title: "`x/nft`" + +--- + +--- + +--- + +## Contents + +## Abstract + +`x/nft` is an implementation of a Cosmos SDK module, per [ADR 43](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-043-nft-module.md), that allows you to create nft classification, create nft, transfer nft, update nft, and support various queries by integrating the module. It is fully compatible with the ERC721 specification. + +* [Concepts](#concepts) + * [Class](#class) + * [NFT](#nft) +* [State](#state) + * [Class](#class-1) + * [NFT](#nft-1) + * [NFTOfClassByOwner](#nftofclassbyowner) + * [Owner](#owner) + * [TotalSupply](#totalsupply) +* [Messages](#messages) + * [MsgSend](#msgsend) +* [Events](#events) + +## Concepts + +### Class + +`x/nft` module defines a struct `Class` to describe the common characteristics of a class of nft, under this class, you can create a variety of nft, which is equivalent to an erc721 contract for Ethereum. The design is defined in the [ADR 043](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-043-nft-module.md). + +### NFT + +The full name of NFT is Non-Fungible Tokens. Because of the irreplaceable nature of NFT, it means that it can be used to represent unique things. The nft implemented by this module is fully compatible with Ethereum ERC721 standard. + +## State + +### Class + +Class is mainly composed of `id`, `name`, `symbol`, `description`, `uri`, `uri_hash`,`data` where `id` is the unique identifier of the class, similar to the Ethereum ERC721 contract address, the others are optional. + +* Class: `0x01 | classID | -> ProtocolBuffer(Class)` + +### NFT + +NFT is mainly composed of `class_id`, `id`, `uri`, `uri_hash` and `data`. Among them, `class_id` and `id` are two-tuples that identify the uniqueness of nft, `uri` and `uri_hash` is optional, which identifies the off-chain storage location of the nft, and `data` is an Any type. Use Any chain of `x/nft` modules can be customized by extending this field + +* NFT: `0x02 | classID | 0x00 | nftID |-> ProtocolBuffer(NFT)` + +### NFTOfClassByOwner + +NFTOfClassByOwner is mainly to realize the function of querying all nfts using classID and owner, without other redundant functions. + +* NFTOfClassByOwner: `0x03 | owner | 0x00 | classID | 0x00 | nftID |-> 0x01` + +### Owner + +Since there is no extra field in NFT to indicate the owner of nft, an additional key-value pair is used to save the ownership of nft. With the transfer of nft, the key-value pair is updated synchronously. + +* OwnerKey: `0x04 | classID | 0x00 | nftID |-> owner` + +### TotalSupply + +TotalSupply is responsible for tracking the number of all nfts under a certain class. Mint operation is performed under the changed class, supply increases by one, burn operation, and supply decreases by one. + +* OwnerKey: `0x05 | classID |-> totalSupply` + +## Messages + +In this section we describe the processing of messages for the NFT module. + + +The validation of `ClassID` and `NftID` is left to the app developer. +The SDK does not provide any validation for these fields. + + +### MsgSend + +You can use the `MsgSend` message to transfer the ownership of nft. This is a function provided by the `x/nft` module. Of course, you can use the `Transfer` method to implement your own transfer logic, but you need to pay extra attention to the transfer permissions. + +The message handling should fail if: + +* provided `ClassID` does not exist. +* provided `Id` does not exist. +* provided `Sender` does not the owner of nft. + +## Events + +The nft module emits proto events defined in [the Protobuf reference](https://buf.build/cosmos/cosmos-sdk/docs/main:cosmos.nft.v1beta1). diff --git a/docs/sdk/v0.53/module-reference/params.mdx b/docs/sdk/v0.53/module-reference/params.mdx new file mode 100644 index 00000000..421ffe37 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/params.mdx @@ -0,0 +1,82 @@ +--- +title: "`x/params`" + +--- + +--- + +--- + +NOTE: `x/params` is deprecated as of Cosmos SDK v0.53 and will be removed in the next release. + +## Abstract + +Package params provides a globally available parameter store. + +There are two main types, Keeper and Subspace. Subspace is an isolated namespace for a +paramstore, where keys are prefixed by preconfigured spacename. Keeper has a +permission to access all existing spaces. + +Subspace can be used by the individual keepers, which need a private parameter store +that the other keepers cannot modify. The params Keeper can be used to add a route to `x/gov` router in order to modify any parameter in case a proposal passes. + +The following contents explains how to use params module for master and user modules. + +## Contents + +* [Keeper](#keeper) +* [Subspace](#subspace) + * [Key](#key) + * [KeyTable](#keytable) + * [ParamSet](#paramset) + +## Keeper + +In the app initialization stage, [subspaces](#subspace) can be allocated for other modules' keeper using `Keeper.Subspace` and are stored in `Keeper.spaces`. Then, those modules can have a reference to their specific parameter store through `Keeper.GetSubspace`. + +Example: + +```go +type ExampleKeeper struct { + paramSpace paramtypes.Subspace +} + +func (k ExampleKeeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) +} +``` + +## Subspace + +`Subspace` is a prefixed subspace of the parameter store. Each module which uses the +parameter store will take a `Subspace` to isolate permission to access. + +### Key + +Parameter keys are human readable alphanumeric strings. A parameter for the key +`"ExampleParameter"` is stored under `[]byte("SubspaceName" + "/" + "ExampleParameter")`, + where `"SubspaceName"` is the name of the subspace. + +Subkeys are secondary parameter keys those are used along with a primary parameter key. +Subkeys can be used for grouping or dynamic parameter key generation during runtime. + +### KeyTable + +All of the parameter keys that will be used should be registered at the compile +time. `KeyTable` is essentially a `map[string]attribute`, where the `string` is a parameter key. + +Currently, `attribute` consists of a `reflect.Type`, which indicates the parameter +type to check that provided key and value are compatible and registered, as well as a function `ValueValidatorFn` to validate values. + +Only primary keys have to be registered on the `KeyTable`. Subkeys inherit the +attribute of the primary key. + +### ParamSet + +Modules often define parameters as a proto message. The generated struct can implement +`ParamSet` interface to be used with the following methods: + +* `KeyTable.RegisterParamSet()`: registers all parameters in the struct +* `Subspace.{Get, Set}ParamSet()`: Get to & Set from the struct + +The implementor should be a pointer in order to use `GetParamSet()`. diff --git a/docs/sdk/v0.53/module-reference/protocolpool.mdx b/docs/sdk/v0.53/module-reference/protocolpool.mdx new file mode 100644 index 00000000..e95f0631 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/protocolpool.mdx @@ -0,0 +1,165 @@ +--- +title: "`x/protocolpool`" + +--- + +--- + +--- + +## Concepts + +`x/protocolpool` is a supplemental Cosmos SDK module that handles functionality for community pool funds. The module provides a separate module account for the community pool making it easier to track the pool assets. Starting with v0.53 of the Cosmos SDK, community funds can be tracked using this module instead of the `x/distribution` module. Funds are migrated from the `x/distribution` module's community pool to `x/protocolpool`'s module account automatically. + +This module is `supplemental`; it is not required to run a Cosmos SDK chain. `x/protocolpool` enhances the community pool functionality provided by `x/distribution` and enables custom modules to further extend the community pool. + +Note: _as long as an external commmunity pool keeper (here, `x/protocolpool`) is wired in DI configs, `x/distribution` will automatically use it for its external pool._ + +## Usage Limitations + +The following `x/distribution` handlers will now return an error when the `protocolpool` module is used with `x/distribution`: + +**QueryService** + +- `CommunityPool` + +**MsgService** + +- `CommunityPoolSpend` +- `FundCommunityPool` + +If you have services that rely on this functionality from `x/distribution`, please update them to use the `x/protocolpool` equivalents. + +## State Transitions + +### FundCommunityPool + +FundCommunityPool can be called by any valid account to send funds to the `x/protocolpool` module account. + +```protobuf + // FundCommunityPool defines a method to allow an account to directly + // fund the community pool. + rpc FundCommunityPool(MsgFundCommunityPool) returns (MsgFundCommunityPoolResponse); +``` + +### CommunityPoolSpend + +CommunityPoolSpend can be called by the module authority (default governance module account) or any account with authorization to spend funds from the `x/protocolpool` module account to a receiver address. + +```protobuf + // CommunityPoolSpend defines a governance operation for sending tokens from + // the community pool in the x/protocolpool module to another account, which + // could be the governance module itself. The authority is defined in the + // keeper. + rpc CommunityPoolSpend(MsgCommunityPoolSpend) returns (MsgCommunityPoolSpendResponse); +``` + +### CreateContinuousFund + +CreateContinuousFund is a message used to initiate a continuous fund for a specific recipient. The proposed percentage of funds will be distributed only on withdraw request for the recipient. The fund distribution continues until expiry time is reached or continuous fund request is canceled. +NOTE: This feature is designed to work with the SDK's default bond denom. + +```protobuf + // CreateContinuousFund defines a method to distribute a percentage of funds to an address continuously. + // This ContinuousFund can be indefinite or run until a given expiry time. + // Funds come from validator block rewards from x/distribution, but may also come from + // any user who funds the ProtocolPoolEscrow module account directly through x/bank. + rpc CreateContinuousFund(MsgCreateContinuousFund) returns (MsgCreateContinuousFundResponse); +``` + +### CancelContinuousFund + +CancelContinuousFund is a message used to cancel an existing continuous fund proposal for a specific recipient. Cancelling a continuous fund stops further distribution of funds, and the state object is removed from storage. + +```protobuf + // CancelContinuousFund defines a method for cancelling continuous fund. + rpc CancelContinuousFund(MsgCancelContinuousFund) returns (MsgCancelContinuousFundResponse); +``` + +## Messages + +### MsgFundCommunityPool + +This message sends coins directly from the sender to the community pool. + + +If you know the `x/protocolpool` module account address, you can directly use bank `send` transaction instead. + + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/proto/cosmos/protocolpool/v1/tx.proto#L43-L53 +``` + +* The msg will fail if the amount cannot be transferred from the sender to the `x/protocolpool` module account. + +```go +func (k Keeper) FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error { + return k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount) +} +``` + +### MsgCommunityPoolSpend + +This message distributes funds from the `x/protocolpool` module account to the recipient using `DistributeFromCommunityPool` keeper method. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/proto/cosmos/protocolpool/v1/tx.proto#L58-L69 +``` + +The message will fail under the following conditions: + +* The amount cannot be transferred to the recipient from the `x/protocolpool` module account. +* The `recipient` address is restricted + +```go +func (k Keeper) DistributeFromCommunityPool(ctx context.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error { + return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, receiveAddr, amount) +} +``` + +### MsgCreateContinuousFund + +This message is used to create a continuous fund for a specific recipient. The proposed percentage of funds will be distributed only on withdraw request for the recipient. This fund distribution continues until expiry time is reached or continuous fund request is canceled. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/proto/cosmos/protocolpool/v1/tx.proto#L114-L130 +``` + +The message will fail under the following conditions: + +- The recipient address is empty or restricted. +- The percentage is zero/negative/greater than one. +- The Expiry time is less than the current block time. + + +If two continuous fund proposals to the same address are created, the previous ContinuousFund will be updated with the new ContinuousFund. + + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/keeper/msg_server.go#L103-L166 +``` + +### MsgCancelContinuousFund + +This message is used to cancel an existing continuous fund proposal for a specific recipient. Once canceled, the continuous fund will no longer distribute funds at each begin block, and the state object will be removed. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/proto/cosmos/protocolpool/v1/tx.proto#L136-L161 +``` + +The message will fail under the following conditions: + +- The recipient address is empty or restricted. +- The ContinuousFund for the recipient does not exist. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/keeper/msg_server.go#L188-L226 +``` + +## Client + +It takes the advantage of `AutoCLI` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/autocli.go +``` diff --git a/docs/sdk/v0.53/module-reference/slashing.mdx b/docs/sdk/v0.53/module-reference/slashing.mdx new file mode 100644 index 00000000..acce875a --- /dev/null +++ b/docs/sdk/v0.53/module-reference/slashing.mdx @@ -0,0 +1,816 @@ +--- +title: "`x/slashing`" + +--- + +--- + +--- + +## Abstract + +This section specifies the slashing module of the Cosmos SDK, which implements functionality +first outlined in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) in June 2016. + +The slashing module enables Cosmos SDK-based blockchains to disincentivize any attributable action +by a protocol-recognized actor with value at stake by penalizing them ("slashing"). + +Penalties may include, but are not limited to: + +* Burning some amount of their stake +* Removing their ability to vote on future blocks for a period of time. + +This module will be used by the Cosmos Hub, the first hub in the Cosmos ecosystem. + +## Contents + +* [Concepts](#concepts) + * [States](#states) + * [Tombstone Caps](#tombstone-caps) + * [Infraction Timelines](#infraction-timelines) +* [State](#state) + * [Signing Info (Liveness)](#signing-info-liveness) + * [Params](#params) +* [Messages](#messages) + * [Unjail](#unjail) +* [BeginBlock](#beginblock) + * [Liveness Tracking](#liveness-tracking) +* [Hooks](#hooks) +* [Events](#events) +* [Staking Tombstone](#staking-tombstone) +* [Parameters](#parameters) +* [CLI](#cli) + * [Query](#query) + * [Transactions](#transactions) + * [gRPC](#grpc) + * [REST](#rest) + +## Concepts + +### States + +At any given time, there are any number of validators registered in the state +machine. Each block, the top `MaxValidators` (defined by `x/staking`) validators +who are not jailed become _bonded_, meaning that they may propose and vote on +blocks. Validators who are _bonded_ are _at stake_, meaning that part or all of +their stake and their delegators' stake is at risk if they commit a protocol fault. + +For each of these validators we keep a `ValidatorSigningInfo` record that contains +information partaining to validator's liveness and other infraction related +attributes. + +### Tombstone Caps + +In order to mitigate the impact of initially likely categories of non-malicious +protocol faults, the Cosmos Hub implements for each validator +a _tombstone_ cap, which only allows a validator to be slashed once for a double +sign fault. For example, if you misconfigure your HSM and double-sign a bunch of +old blocks, you'll only be punished for the first double-sign (and then immediately tombstombed). This will still be quite expensive and desirable to avoid, but tombstone caps +somewhat blunt the economic impact of unintentional misconfiguration. + +Liveness faults do not have caps, as they can't stack upon each other. Liveness bugs are "detected" as soon as the infraction occurs, and the validators are immediately put in jail, so it is not possible for them to commit multiple liveness faults without unjailing in between. + +### Infraction Timelines + +To illustrate how the `x/slashing` module handles submitted evidence through +CometBFT consensus, consider the following examples: + +**Definitions**: + +_[_ : timeline start +_]_ : timeline end +_Cn_ : infraction `n` committed +_Dn_ : infraction `n` discovered +_Vb_ : validator bonded +_Vu_ : validator unbonded + +#### Single Double Sign Infraction + +\[----------C1----D1,Vu-----\] + +A single infraction is committed then later discovered, at which point the +validator is unbonded and slashed at the full amount for the infraction. + +#### Multiple Double Sign Infractions + +\[----------C1--C2---C3---D1,D2,D3Vu-----\] + +Multiple infractions are committed and then later discovered, at which point the +validator is jailed and slashed for only one infraction. Because the validator +is also tombstoned, they can not rejoin the validator set. + +## State + +### Signing Info (Liveness) + +Every block includes a set of precommits by the validators for the previous block, +known as the `LastCommitInfo` provided by CometBFT. A `LastCommitInfo` is valid so +long as it contains precommits from +2/3 of total voting power. + +Proposers are incentivized to include precommits from all validators in the CometBFT `LastCommitInfo` +by receiving additional fees proportional to the difference between the voting +power included in the `LastCommitInfo` and +2/3 (see [fee distribution](../distribution/README.md#begin-block)). + +```go +type LastCommitInfo struct { + Round int32 + Votes []VoteInfo +} +``` + +Validators are penalized for failing to be included in the `LastCommitInfo` for some +number of blocks by being automatically jailed, potentially slashed, and unbonded. + +Information about validator's liveness activity is tracked through `ValidatorSigningInfo`. +It is indexed in the store as follows: + +* ValidatorSigningInfo: `0x01 | ConsAddrLen (1 byte) | ConsAddress -> ProtocolBuffer(ValSigningInfo)` +* MissedBlocksBitArray: `0x02 | ConsAddrLen (1 byte) | ConsAddress | LittleEndianUint64(signArrayIndex) -> VarInt(didMiss)` (varint is a number encoding format) + +The first mapping allows us to easily lookup the recent signing info for a +validator based on the validator's consensus address. + +The second mapping (`MissedBlocksBitArray`) acts +as a bit-array of size `SignedBlocksWindow` that tells us if the validator missed +the block for a given index in the bit-array. The index in the bit-array is given +as little endian uint64. +The result is a `varint` that takes on `0` or `1`, where `0` indicates the +validator did not miss (did sign) the corresponding block, and `1` indicates +they missed the block (did not sign). + +Note that the `MissedBlocksBitArray` is not explicitly initialized up-front. Keys +are added as we progress through the first `SignedBlocksWindow` blocks for a newly +bonded validator. The `SignedBlocksWindow` parameter defines the size +(number of blocks) of the sliding window used to track validator liveness. + +The information stored for tracking validator liveness is as follows: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/slashing/v1beta1/slashing.proto#L13-L35 +``` + +### Params + +The slashing module stores it's params in state with the prefix of `0x00`, +it can be updated with governance or the address with authority. + +* Params: `0x00 | ProtocolBuffer(Params)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/slashing/v1beta1/slashing.proto#L37-L59 +``` + +## Messages + +In this section we describe the processing of messages for the `slashing` module. + +### Unjail + +If a validator was automatically unbonded due to downtime and wishes to come back online & +possibly rejoin the bonded set, it must send `MsgUnjail`: + +```protobuf +// MsgUnjail is an sdk.Msg used for unjailing a jailed validator, thus returning +// them into the bonded validator set, so they can begin receiving provisions +// and rewards again. +message MsgUnjail { + string validator_addr = 1; +} +``` + +Below is a pseudocode of the `MsgSrv/Unjail` RPC: + +```go +unjail(tx MsgUnjail) + validator = getValidator(tx.ValidatorAddr) + if validator == nil + fail with "No validator found" + + if getSelfDelegation(validator) == 0 + fail with "validator must self delegate before unjailing" + + if !validator.Jailed + fail with "Validator not jailed, cannot unjail" + + info = GetValidatorSigningInfo(operator) + if info.Tombstoned + fail with "Tombstoned validator cannot be unjailed" + if block time < info.JailedUntil + fail with "Validator still jailed, cannot unjail until period has expired" + + validator.Jailed = false + setValidator(validator) + + return +``` + +If the validator has enough stake to be in the top `n = MaximumBondedValidators`, it will be automatically rebonded, +and all delegators still delegated to the validator will be rebonded and begin to again collect +provisions and rewards. + +## BeginBlock + +### Liveness Tracking + +At the beginning of each block, we update the `ValidatorSigningInfo` for each +validator and check if they've crossed below the liveness threshold over a +sliding window. This sliding window is defined by `SignedBlocksWindow` and the +index in this window is determined by `IndexOffset` found in the validator's +`ValidatorSigningInfo`. For each block processed, the `IndexOffset` is incremented +regardless if the validator signed or not. Once the index is determined, the +`MissedBlocksBitArray` and `MissedBlocksCounter` are updated accordingly. + +Finally, in order to determine if a validator crosses below the liveness threshold, +we fetch the maximum number of blocks missed, `maxMissed`, which is +`SignedBlocksWindow - (MinSignedPerWindow * SignedBlocksWindow)` and the minimum +height at which we can determine liveness, `minHeight`. If the current block is +greater than `minHeight` and the validator's `MissedBlocksCounter` is greater than +`maxMissed`, they will be slashed by `SlashFractionDowntime`, will be jailed +for `DowntimeJailDuration`, and have the following values reset: +`MissedBlocksBitArray`, `MissedBlocksCounter`, and `IndexOffset`. + +**Note**: Liveness slashes do **NOT** lead to a tombstombing. + +```go +height := block.Height + +for vote in block.LastCommitInfo.Votes { + signInfo := GetValidatorSigningInfo(vote.Validator.Address) + + // This is a relative index, so we counts blocks the validator SHOULD have + // signed. We use the 0-value default signing info if not present, except for + // start height. + index := signInfo.IndexOffset % SignedBlocksWindow() + signInfo.IndexOffset++ + + // Update MissedBlocksBitArray and MissedBlocksCounter. The MissedBlocksCounter + // just tracks the sum of MissedBlocksBitArray. That way we avoid needing to + // read/write the whole array each time. + missedPrevious := GetValidatorMissedBlockBitArray(vote.Validator.Address, index) + missed := !signed + + switch { + case !missedPrevious && missed: + // array index has changed from not missed to missed, increment counter + SetValidatorMissedBlockBitArray(vote.Validator.Address, index, true) + signInfo.MissedBlocksCounter++ + + case missedPrevious && !missed: + // array index has changed from missed to not missed, decrement counter + SetValidatorMissedBlockBitArray(vote.Validator.Address, index, false) + signInfo.MissedBlocksCounter-- + + default: + // array index at this index has not changed; no need to update counter + } + + if missed { + // emit events... + } + + minHeight := signInfo.StartHeight + SignedBlocksWindow() + maxMissed := SignedBlocksWindow() - MinSignedPerWindow() + + // If we are past the minimum height and the validator has missed too many + // jail and slash them. + if height > minHeight && signInfo.MissedBlocksCounter > maxMissed { + validator := ValidatorByConsAddr(vote.Validator.Address) + + // emit events... + + // We need to retrieve the stake distribution which signed the block, so we + // subtract ValidatorUpdateDelay from the block height, and subtract an + // additional 1 since this is the LastCommit. + // + // Note, that this CAN result in a negative "distributionHeight" up to + // -ValidatorUpdateDelay-1, i.e. at the end of the pre-genesis block (none) = at the beginning of the genesis block. + // That's fine since this is just used to filter unbonding delegations & redelegations. + distributionHeight := height - sdk.ValidatorUpdateDelay - 1 + + SlashWithInfractionReason(vote.Validator.Address, distributionHeight, vote.Validator.Power, SlashFractionDowntime(), stakingtypes.Downtime) + Jail(vote.Validator.Address) + + signInfo.JailedUntil = block.Time.Add(DowntimeJailDuration()) + + // We need to reset the counter & array so that the validator won't be + // immediately slashed for downtime upon rebonding. + signInfo.MissedBlocksCounter = 0 + signInfo.IndexOffset = 0 + ClearValidatorMissedBlockBitArray(vote.Validator.Address) + } + + SetValidatorSigningInfo(vote.Validator.Address, signInfo) +} +``` + +## Hooks + +This section contains a description of the module's `hooks`. Hooks are operations that are executed automatically when events are raised. + +### Staking hooks + +The slashing module implements the `StakingHooks` defined in `x/staking` and are used as record-keeping of validators information. During the app initialization, these hooks should be registered in the staking module struct. + +The following hooks impact the slashing state: + +* `AfterValidatorBonded` creates a `ValidatorSigningInfo` instance as described in the following section. +* `AfterValidatorCreated` stores a validator's consensus key. +* `AfterValidatorRemoved` removes a validator's consensus key. + +### Validator Bonded + +Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the +now-bonded validator, which `StartHeight` of the current block. + +If the validator was out of the validator set and gets bonded again, its new bonded height is set. + +```go +onValidatorBonded(address sdk.ValAddress) + + signingInfo, found = GetValidatorSigningInfo(address) + if !found { + signingInfo = ValidatorSigningInfo { + StartHeight : CurrentHeight, + IndexOffset : 0, + JailedUntil : time.Unix(0, 0), + Tombstone : false, + MissedBloskCounter : 0 + } else { + signingInfo.StartHeight = CurrentHeight + } + + setValidatorSigningInfo(signingInfo) + } + + return +``` + +## Events + +The slashing module emits the following events: + +### MsgServer + +#### MsgUnjail + +| Type | Attribute Key | Attribute Value | +| ------- | ------------- | ------------------ | +| message | module | slashing | +| message | sender | {validatorAddress} | + +### Keeper + +### BeginBlocker: HandleValidatorSignature + +| Type | Attribute Key | Attribute Value | +| ----- | ------------- | --------------------------- | +| slash | address | {validatorConsensusAddress} | +| slash | power | {validatorPower} | +| slash | reason | {slashReason} | +| slash | jailed [0] | {validatorConsensusAddress} | +| slash | burned coins | {math.Int} | + +* [0] Only included if the validator is jailed. + +| Type | Attribute Key | Attribute Value | +| -------- | ------------- | --------------------------- | +| liveness | address | {validatorConsensusAddress} | +| liveness | missed_blocks | {missedBlocksCounter} | +| liveness | height | {blockHeight} | + +#### Slash + +* same as `"slash"` event from `HandleValidatorSignature`, but without the `jailed` attribute. + +#### Jail + +| Type | Attribute Key | Attribute Value | +| ----- | ------------- | ------------------ | +| slash | jailed | {validatorAddress} | + +## Staking Tombstone + +### Abstract + +In the current implementation of the `slashing` module, when the consensus engine +informs the state machine of a validator's consensus fault, the validator is +partially slashed, and put into a "jail period", a period of time in which they +are not allowed to rejoin the validator set. However, because of the nature of +consensus faults and ABCI, there can be a delay between an infraction occurring, +and evidence of the infraction reaching the state machine (this is one of the +primary reasons for the existence of the unbonding period). + +> Note: The tombstone concept, only applies to faults that have a delay between +> the infraction occurring and evidence reaching the state machine. For example, +> evidence of a validator double signing may take a while to reach the state machine +> due to unpredictable evidence gossip layer delays and the ability of validators to +> selectively reveal double-signatures (e.g. to infrequently-online light clients). +> Liveness slashing, on the other hand, is detected immediately as soon as the +> infraction occurs, and therefore no slashing period is needed. A validator is +> immediately put into jail period, and they cannot commit another liveness fault +> until they unjail. In the future, there may be other types of byzantine faults +> that have delays (for example, submitting evidence of an invalid proposal as a transaction). +> When implemented, it will have to be decided whether these future types of +> byzantine faults will result in a tombstoning (and if not, the slash amounts +> will not be capped by a slashing period). + +In the current system design, once a validator is put in the jail for a consensus +fault, after the `JailPeriod` they are allowed to send a transaction to `unjail` +themselves, and thus rejoin the validator set. + +One of the "design desires" of the `slashing` module is that if multiple +infractions occur before evidence is executed (and a validator is put in jail), +they should only be punished for single worst infraction, but not cumulatively. +For example, if the sequence of events is: + +1. Validator A commits Infraction 1 (worth 30% slash) +2. Validator A commits Infraction 2 (worth 40% slash) +3. Validator A commits Infraction 3 (worth 35% slash) +4. Evidence for Infraction 1 reaches state machine (and validator is put in jail) +5. Evidence for Infraction 2 reaches state machine +6. Evidence for Infraction 3 reaches state machine + +Only Infraction 2 should have its slash take effect, as it is the highest. This +is done, so that in the case of the compromise of a validator's consensus key, +they will only be punished once, even if the hacker double-signs many blocks. +Because, the unjailing has to be done with the validator's operator key, they +have a chance to re-secure their consensus key, and then signal that they are +ready using their operator key. We call this period during which we track only +the max infraction, the "slashing period". + +Once, a validator rejoins by unjailing themselves, we begin a new slashing period; +if they commit a new infraction after unjailing, it gets slashed cumulatively on +top of the worst infraction from the previous slashing period. + +However, while infractions are grouped based off of the slashing periods, because +evidence can be submitted up to an `unbondingPeriod` after the infraction, we +still have to allow for evidence to be submitted for previous slashing periods. +For example, if the sequence of events is: + +1. Validator A commits Infraction 1 (worth 30% slash) +2. Validator A commits Infraction 2 (worth 40% slash) +3. Evidence for Infraction 1 reaches state machine (and Validator A is put in jail) +4. Validator A unjails + +We are now in a new slashing period, however we still have to keep the door open +for the previous infraction, as the evidence for Infraction 2 may still come in. +As the number of slashing periods increase, it creates more complexity as we have +to keep track of the highest infraction amount for every single slashing period. + +> Note: Currently, according to the `slashing` module spec, a new slashing period +> is created every time a validator is unbonded then rebonded. This should probably +> be changed to jailed/unjailed. See issue [#3205](https://github.com/cosmos/cosmos-sdk/issues/3205) +> for further details. For the remainder of this, I will assume that we only start +> a new slashing period when a validator gets unjailed. + +The maximum number of slashing periods is the `len(UnbondingPeriod) / len(JailPeriod)`. +The current defaults in Gaia for the `UnbondingPeriod` and `JailPeriod` are 3 weeks +and 2 days, respectively. This means there could potentially be up to 11 slashing +periods concurrently being tracked per validator. If we set the `JailPeriod >= UnbondingPeriod`, +we only have to track 1 slashing period (i.e not have to track slashing periods). + +Currently, in the jail period implementation, once a validator unjails, all of +their delegators who are delegated to them (haven't unbonded / redelegated away), +stay with them. Given that consensus safety faults are so egregious +(way more so than liveness faults), it is probably prudent to have delegators not +"auto-rebond" to the validator. + +#### Proposal: infinite jail + +We propose setting the "jail time" for a +validator who commits a consensus safety fault, to `infinite` (i.e. a tombstone state). +This essentially kicks the validator out of the validator set and does not allow +them to re-enter the validator set. All of their delegators (including the operator themselves) +have to either unbond or redelegate away. The validator operator can create a new +validator if they would like, with a new operator key and consensus key, but they +have to "re-earn" their delegations back. + +Implementing the tombstone system and getting rid of the slashing period tracking +will make the `slashing` module way simpler, especially because we can remove all +of the hooks defined in the `slashing` module consumed by the `staking` module +(the `slashing` module still consumes hooks defined in `staking`). + +#### Single slashing amount + +Another optimization that can be made is that if we assume that all ABCI faults +for CometBFT consensus are slashed at the same level, we don't have to keep +track of "max slash". Once an ABCI fault happens, we don't have to worry about +comparing potential future ones to find the max. + +Currently the only CometBFT ABCI fault is: + +* Unjustified precommits (double signs) + +It is currently planned to include the following fault in the near future: + +* Signing a precommit when you're in unbonding phase (needed to make light client bisection safe) + +Given that these faults are both attributable byzantine faults, we will likely +want to slash them equally, and thus we can enact the above change. + +> Note: This change may make sense for current CometBFT consensus, but maybe +> not for a different consensus algorithm or future versions of CometBFT that +> may want to punish at different levels (for example, partial slashing). + +## Parameters + +The slashing module contains the following parameters: + +| Key | Type | Example | +| ----------------------- | -------------- | ---------------------- | +| SignedBlocksWindow | string (int64) | "100" | +| MinSignedPerWindow | string (dec) | "0.500000000000000000" | +| DowntimeJailDuration | string (ns) | "600000000000" | +| SlashFractionDoubleSign | string (dec) | "0.050000000000000000" | +| SlashFractionDowntime | string (dec) | "0.010000000000000000" | + +## CLI + +A user can query and interact with the `slashing` module using the CLI. + +### Query + +The `query` commands allow users to query `slashing` state. + +```shell +simd query slashing --help +``` + +#### params + +The `params` command allows users to query genesis parameters for the slashing module. + +```shell +simd query slashing params [flags] +``` + +Example: + +```shell +simd query slashing params +``` + +Example Output: + +```yml +downtime_jail_duration: 600s +min_signed_per_window: "0.500000000000000000" +signed_blocks_window: "100" +slash_fraction_double_sign: "0.050000000000000000" +slash_fraction_downtime: "0.010000000000000000" +``` + +#### signing-info + +The `signing-info` command allows users to query signing-info of the validator using consensus public key. + +```shell +simd query slashing signing-infos [flags] +``` + +Example: + +```shell +simd query slashing signing-info '{"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys6jD5B6tPgC8="}' + +``` + +Example Output: + +```yml +address: cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c +index_offset: "2068" +jailed_until: "1970-01-01T00:00:00Z" +missed_blocks_counter: "0" +start_height: "0" +tombstoned: false +``` + +#### signing-infos + +The `signing-infos` command allows users to query signing infos of all validators. + +```shell +simd query slashing signing-infos [flags] +``` + +Example: + +```shell +simd query slashing signing-infos +``` + +Example Output: + +```yml +info: +- address: cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c + index_offset: "2075" + jailed_until: "1970-01-01T00:00:00Z" + missed_blocks_counter: "0" + start_height: "0" + tombstoned: false +pagination: + next_key: null + total: "0" +``` + +### Transactions + +The `tx` commands allow users to interact with the `slashing` module. + +```bash +simd tx slashing --help +``` + +#### unjail + +The `unjail` command allows users to unjail a validator previously jailed for downtime. + +```bash +simd tx slashing unjail --from mykey [flags] +``` + +Example: + +```bash +simd tx slashing unjail --from mykey +``` + +### gRPC + +A user can query the `slashing` module using gRPC endpoints. + +#### Params + +The `Params` endpoint allows users to query the parameters of slashing module. + +```shell +cosmos.slashing.v1beta1.Query/Params +``` + +Example: + +```shell +grpcurl -plaintext localhost:9090 cosmos.slashing.v1beta1.Query/Params +``` + +Example Output: + +```json +{ + "params": { + "signedBlocksWindow": "100", + "minSignedPerWindow": "NTAwMDAwMDAwMDAwMDAwMDAw", + "downtimeJailDuration": "600s", + "slashFractionDoubleSign": "NTAwMDAwMDAwMDAwMDAwMDA=", + "slashFractionDowntime": "MTAwMDAwMDAwMDAwMDAwMDA=" + } +} +``` + +#### SigningInfo + +The SigningInfo queries the signing info of given cons address. + +```shell +cosmos.slashing.v1beta1.Query/SigningInfo +``` + +Example: + +```shell +grpcurl -plaintext -d '{"cons_address":"cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c"}' localhost:9090 cosmos.slashing.v1beta1.Query/SigningInfo +``` + +Example Output: + +```json +{ + "valSigningInfo": { + "address": "cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c", + "indexOffset": "3493", + "jailedUntil": "1970-01-01T00:00:00Z" + } +} +``` + +#### SigningInfos + +The SigningInfos queries signing info of all validators. + +```shell +cosmos.slashing.v1beta1.Query/SigningInfos +``` + +Example: + +```shell +grpcurl -plaintext localhost:9090 cosmos.slashing.v1beta1.Query/SigningInfos +``` + +Example Output: + +```json +{ + "info": [ + { + "address": "cosmosvalcons1nrqslkwd3pz096lh6t082frdqc84uwxn0t958c", + "indexOffset": "2467", + "jailedUntil": "1970-01-01T00:00:00Z" + } + ], + "pagination": { + "total": "1" + } +} +``` + +### REST + +A user can query the `slashing` module using REST endpoints. + +#### Params + +```shell +/cosmos/slashing/v1beta1/params +``` + +Example: + +```shell +curl "localhost:1317/cosmos/slashing/v1beta1/params" +``` + +Example Output: + +```json +{ + "params": { + "signed_blocks_window": "100", + "min_signed_per_window": "0.500000000000000000", + "downtime_jail_duration": "600s", + "slash_fraction_double_sign": "0.050000000000000000", + "slash_fraction_downtime": "0.010000000000000000" +} +``` + +#### signing_info + +```shell +/cosmos/slashing/v1beta1/signing_infos/%s +``` + +Example: + +```shell +curl "localhost:1317/cosmos/slashing/v1beta1/signing_infos/cosmosvalcons1nrqslkwd3pz096lh6t082frdqc84uwxn0t958c" +``` + +Example Output: + +```json +{ + "val_signing_info": { + "address": "cosmosvalcons1nrqslkwd3pz096lh6t082frdqc84uwxn0t958c", + "start_height": "0", + "index_offset": "4184", + "jailed_until": "1970-01-01T00:00:00Z", + "tombstoned": false, + "missed_blocks_counter": "0" + } +} +``` + +#### signing_infos + +```shell +/cosmos/slashing/v1beta1/signing_infos +``` + +Example: + +```shell +curl "localhost:1317/cosmos/slashing/v1beta1/signing_infos +``` + +Example Output: + +```json +{ + "info": [ + { + "address": "cosmosvalcons1nrqslkwd3pz096lh6t082frdqc84uwxn0t958c", + "start_height": "0", + "index_offset": "4169", + "jailed_until": "1970-01-01T00:00:00Z", + "tombstoned": false, + "missed_blocks_counter": "0" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/staking.mdx b/docs/sdk/v0.53/module-reference/staking.mdx new file mode 100644 index 00000000..8af903f1 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/staking.mdx @@ -0,0 +1,3057 @@ +--- +title: "`x/staking`" + +--- + +--- + +--- + +## Abstract + +This paper specifies the Staking module of the Cosmos SDK that was first +described in the [Cosmos Whitepaper](https://cosmos.network/about/whitepaper) +in June 2016. + +The module enables Cosmos SDK-based blockchain to support an advanced +Proof-of-Stake (PoS) system. In this system, holders of the native staking token of +the chain can become validators and can delegate tokens to validators, +ultimately determining the effective validator set for the system. + +This module is used in the Cosmos Hub, the first Hub in the Cosmos +network. + +## Contents + +* [State](#state) + * [Pool](#pool) + * [LastTotalPower](#lasttotalpower) + * [ValidatorUpdates](#validatorupdates) + * [UnbondingID](#unbondingid) + * [Params](#params) + * [Validator](#validator) + * [Delegation](#delegation) + * [UnbondingDelegation](#unbondingdelegation) + * [Redelegation](#redelegation) + * [Queues](#queues) + * [HistoricalInfo](#historicalinfo) +* [State Transitions](#state-transitions) + * [Validators](#validators) + * [Delegations](#delegations) + * [Slashing](#slashing) + * [How Shares are calculated](#how-shares-are-calculated) +* [Messages](#messages) + * [MsgCreateValidator](#msgcreatevalidator) + * [MsgEditValidator](#msgeditvalidator) + * [MsgDelegate](#msgdelegate) + * [MsgUndelegate](#msgundelegate) + * [MsgCancelUnbondingDelegation](#msgcancelunbondingdelegation) + * [MsgBeginRedelegate](#msgbeginredelegate) + * [MsgUpdateParams](#msgupdateparams) +* [Begin-Block](#begin-block) + * [Historical Info Tracking](#historical-info-tracking) +* [End-Block](#end-block) + * [Validator Set Changes](#validator-set-changes) + * [Queues](#queues-1) +* [Hooks](#hooks) +* [Events](#events) + * [EndBlocker](#endblocker) + * [Msg's](#msgs) +* [Parameters](#parameters) +* [Client](#client) + * [CLI](#cli) + * [gRPC](#grpc) + * [REST](#rest) + +## State + +### Pool + +Pool is used for tracking bonded and not-bonded token supply of the bond denomination. + +### LastTotalPower + +LastTotalPower tracks the total amounts of bonded tokens recorded during the previous end block. +Store entries prefixed with "Last" must remain unchanged until EndBlock. + +* LastTotalPower: `0x12 -> ProtocolBuffer(math.Int)` + +### ValidatorUpdates + +ValidatorUpdates contains the validator updates returned to ABCI at the end of every block. +The values are overwritten in every block. + +* ValidatorUpdates `0x61 -> []abci.ValidatorUpdate` + +### UnbondingID + +UnbondingID stores the ID of the latest unbonding operation. It enables creating unique IDs for unbonding operations, i.e., UnbondingID is incremented every time a new unbonding operation (validator unbonding, unbonding delegation, redelegation) is initiated. + +* UnbondingID: `0x37 -> uint64` + +### Params + +The staking module stores its params in state with the prefix of `0x51`, +it can be updated with governance or the address with authority. + +* Params: `0x51 | ProtocolBuffer(Params)` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L310-L333 +``` + +### Validator + +Validators can have one of three statuses + +* `Unbonded`: The validator is not in the active set. They cannot sign blocks and do not earn + rewards. They can receive delegations. +* `Bonded`: Once the validator receives sufficient bonded tokens they automatically join the + active set during [`EndBlock`](#validator-set-changes) and their status is updated to `Bonded`. + They are signing blocks and receiving rewards. They can receive further delegations. + They can be slashed for misbehavior. Delegators to this validator who unbond their delegation + must wait the duration of the UnbondingTime, a chain-specific param, during which time + they are still slashable for offences of the source validator if those offences were committed + during the period of time that the tokens were bonded. +* `Unbonding`: When a validator leaves the active set, either by choice or due to slashing, jailing or + tombstoning, an unbonding of all their delegations begins. All delegations must then wait the UnbondingTime + before their tokens are moved to their accounts from the `BondedPool`. + + +Tombstoning is permanent, once tombstoned a validator's consensus key can not be reused within the chain where the tombstoning happened. + + +Validators objects should be primarily stored and accessed by the +`OperatorAddr`, an SDK validator address for the operator of the validator. Two +additional indices are maintained per validator object in order to fulfill +required lookups for slashing and validator-set updates. A third special index +(`LastValidatorPower`) is also maintained which however remains constant +throughout each block, unlike the first two indices which mirror the validator +records within a block. + +* Validators: `0x21 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(validator)` +* ValidatorsByConsAddr: `0x22 | ConsAddrLen (1 byte) | ConsAddr -> OperatorAddr` +* ValidatorsByPower: `0x23 | BigEndian(ConsensusPower) | OperatorAddrLen (1 byte) | OperatorAddr -> OperatorAddr` +* LastValidatorsPower: `0x11 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(ConsensusPower)` +* ValidatorsByUnbondingID: `0x38 | UnbondingID -> 0x21 | OperatorAddrLen (1 byte) | OperatorAddr` + +`Validators` is the primary index - it ensures that each operator can have only one +associated validator, where the public key of that validator can change in the +future. Delegators can refer to the immutable operator of the validator, without +concern for the changing public key. + +`ValidatorsByUnbondingID` is an additional index that enables lookups for + validators by the unbonding IDs corresponding to their current unbonding. + +`ValidatorByConsAddr` is an additional index that enables lookups for slashing. +When CometBFT reports evidence, it provides the validator address, so this +map is needed to find the operator. Note that the `ConsAddr` corresponds to the +address which can be derived from the validator's `ConsPubKey`. + +`ValidatorsByPower` is an additional index that provides a sorted list of +potential validators to quickly determine the current active set. Here +ConsensusPower is validator.Tokens/10^6 by default. Note that all validators +where `Jailed` is true are not stored within this index. + +`LastValidatorsPower` is a special index that provides a historical list of the +last-block's bonded validators. This index remains constant during a block but +is updated during the validator set update process which takes place in [`EndBlock`](#end-block). + +Each validator's state is stored in a `Validator` struct: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L82-L138 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L26-L80 +``` + +### Delegation + +Delegations are identified by combining `DelegatorAddr` (the address of the delegator) +with the `ValidatorAddr` Delegators are indexed in the store as follows: + +* Delegation: `0x31 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(delegation)` + +Stake holders may delegate coins to validators; under this circumstance their +funds are held in a `Delegation` data structure. It is owned by one +delegator, and is associated with the shares for one validator. The sender of +the transaction is the owner of the bond. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L198-L216 +``` + +#### Delegator Shares + +When one delegates tokens to a Validator, they are issued a number of delegator shares based on a +dynamic exchange rate, calculated as follows from the total number of tokens delegated to the +validator and the number of shares issued so far: + +`Shares per Token = validator.TotalShares() / validator.Tokens()` + +Only the number of shares received is stored on the DelegationEntry. When a delegator then +Undelegates, the token amount they receive is calculated from the number of shares they currently +hold and the inverse exchange rate: + +`Tokens per Share = validator.Tokens() / validatorShares()` + +These `Shares` are simply an accounting mechanism. They are not a fungible asset. The reason for +this mechanism is to simplify the accounting around slashing. Rather than iteratively slashing the +tokens of every delegation entry, instead the Validator's total bonded tokens can be slashed, +effectively reducing the value of each issued delegator share. + +### UnbondingDelegation + +Shares in a `Delegation` can be unbonded, but they must for some time exist as +an `UnbondingDelegation`, where shares can be reduced if Byzantine behavior is +detected. + +`UnbondingDelegation` are indexed in the store as: + +* UnbondingDelegation: `0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(unbondingDelegation)` +* UnbondingDelegationsFromValidator: `0x33 | ValidatorAddrLen (1 byte) | ValidatorAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil` +* UnbondingDelegationByUnbondingId: `0x38 | UnbondingId -> 0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr` + `UnbondingDelegation` is used in queries, to lookup all unbonding delegations for + a given delegator. + +`UnbondingDelegationsFromValidator` is used in slashing, to lookup all + unbonding delegations associated with a given validator that need to be + slashed. + + `UnbondingDelegationByUnbondingId` is an additional index that enables + lookups for unbonding delegations by the unbonding IDs of the containing + unbonding delegation entries. + +A UnbondingDelegation object is created every time an unbonding is initiated. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L218-L261 +``` + +### Redelegation + +The bonded tokens worth of a `Delegation` may be instantly redelegated from a +source validator to a different validator (destination validator). However when +this occurs they must be tracked in a `Redelegation` object, whereby their +shares can be slashed if their tokens have contributed to a Byzantine fault +committed by the source validator. + +`Redelegation` are indexed in the store as: + +* Redelegations: `0x34 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddr -> ProtocolBuffer(redelegation)` +* RedelegationsBySrc: `0x35 | ValidatorSrcAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddrLen (1 byte) | ValidatorDstAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil` +* RedelegationsByDst: `0x36 | ValidatorDstAddrLen (1 byte) | ValidatorDstAddr | ValidatorSrcAddrLen (1 byte) | ValidatorSrcAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil` +* RedelegationByUnbondingId: `0x38 | UnbondingId -> 0x34 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddr` + + `Redelegations` is used for queries, to lookup all redelegations for a given + delegator. + + `RedelegationsBySrc` is used for slashing based on the `ValidatorSrcAddr`. + + `RedelegationsByDst` is used for slashing based on the `ValidatorDstAddr` + +The first map here is used for queries, to lookup all redelegations for a given +delegator. The second map is used for slashing based on the `ValidatorSrcAddr`, +while the third map is for slashing based on the `ValidatorDstAddr`. + +`RedelegationByUnbondingId` is an additional index that enables + lookups for redelegations by the unbonding IDs of the containing + redelegation entries. + +A redelegation object is created every time a redelegation occurs. To prevent +"redelegation hopping" redelegations may not occur under the situation that: + +* the (re)delegator already has another immature redelegation in progress + with a destination to a validator (let's call it `Validator X`) +* and, the (re)delegator is attempting to create a _new_ redelegation + where the source validator for this new redelegation is `Validator X`. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L263-L308 +``` + +### Queues + +All queue objects are sorted by timestamp. The time used within any queue is +firstly converted to UTC, rounded to the nearest nanosecond then sorted. The sortable time format +used is a slight modification of the RFC3339Nano and uses the format string +`"2006-01-02T15:04:05.000000000"`. Notably this format: + +* right pads all zeros +* drops the time zone info (we already use UTC) + +In all cases, the stored timestamp represents the maturation time of the queue +element. + +#### UnbondingDelegationQueue + +For the purpose of tracking progress of unbonding delegations the unbonding +delegations queue is kept. + +* UnbondingDelegation: `0x41 | format(time) -> []DVPair` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L162-L172 +``` + +#### RedelegationQueue + +For the purpose of tracking progress of redelegations the redelegation queue is +kept. + +* RedelegationQueue: `0x42 | format(time) -> []DVVTriplet` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L179-L191 +``` + +#### ValidatorQueue + +For the purpose of tracking progress of unbonding validators the validator +queue is kept. + +* ValidatorQueueTime: `0x43 | format(time) -> []sdk.ValAddress` + +The stored object by each key is an array of validator operator addresses from +which the validator object can be accessed. Typically it is expected that only +a single validator record will be associated with a given timestamp however it is possible +that multiple validators exist in the queue at the same location. + +### HistoricalInfo + +HistoricalInfo objects are stored and pruned at each block such that the staking keeper persists +the `n` most recent historical info defined by staking module parameter: `HistoricalEntries`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/staking.proto#L17-L24 +``` + +At each BeginBlock, the staking keeper will persist the current Header and the Validators that committed +the current block in a `HistoricalInfo` object. The Validators are sorted on their address to ensure that +they are in a deterministic order. +The oldest HistoricalEntries will be pruned to ensure that there only exist the parameter-defined number of +historical entries. + +## State Transitions + +### Validators + +State transitions in validators are performed on every [`EndBlock`](#validator-set-changes) +in order to check for changes in the active `ValidatorSet`. + +A validator can be `Unbonded`, `Unbonding` or `Bonded`. `Unbonded` +and `Unbonding` are collectively called `Not Bonded`. A validator can move +directly between all the states, except for from `Bonded` to `Unbonded`. + +#### Not bonded to Bonded + +The following transition occurs when a validator's ranking in the `ValidatorPowerIndex` surpasses +that of the `LastValidator`. + +* set `validator.Status` to `Bonded` +* send the `validator.Tokens` from the `NotBondedTokens` to the `BondedPool` `ModuleAccount` +* delete the existing record from `ValidatorByPowerIndex` +* add a new updated record to the `ValidatorByPowerIndex` +* update the `Validator` object for this validator +* if it exists, delete any `ValidatorQueue` record for this validator + +#### Bonded to Unbonding + +When a validator begins the unbonding process the following operations occur: + +* send the `validator.Tokens` from the `BondedPool` to the `NotBondedTokens` `ModuleAccount` +* set `validator.Status` to `Unbonding` +* delete the existing record from `ValidatorByPowerIndex` +* add a new updated record to the `ValidatorByPowerIndex` +* update the `Validator` object for this validator +* insert a new record into the `ValidatorQueue` for this validator + +#### Unbonding to Unbonded + +A validator moves from unbonding to unbonded when the `ValidatorQueue` object +moves from bonded to unbonded + +* update the `Validator` object for this validator +* set `validator.Status` to `Unbonded` + +#### Jail/Unjail + +when a validator is jailed it is effectively removed from the CometBFT set. +this process may be also be reversed. the following operations occur: + +* set `Validator.Jailed` and update object +* if jailed delete record from `ValidatorByPowerIndex` +* if unjailed add record to `ValidatorByPowerIndex` + +Jailed validators are not present in any of the following stores: + +* the power store (from consensus power to address) + +### Delegations + +#### Delegate + +When a delegation occurs both the validator and the delegation objects are affected + +* determine the delegators shares based on tokens delegated and the validator's exchange rate +* remove tokens from the sending account +* add shares the delegation object or add them to a created validator object +* add new delegator shares and update the `Validator` object +* transfer the `delegation.Amount` from the delegator's account to the `BondedPool` or the `NotBondedPool` `ModuleAccount` depending if the `validator.Status` is `Bonded` or not +* delete the existing record from `ValidatorByPowerIndex` +* add an new updated record to the `ValidatorByPowerIndex` + +#### Begin Unbonding + +As a part of the Undelegate and Complete Unbonding state transitions Unbond +Delegation may be called. + +* subtract the unbonded shares from delegator +* add the unbonded tokens to an `UnbondingDelegationEntry` +* update the delegation or remove the delegation if there are no more shares +* if the delegation is the operator of the validator and no more shares exist then trigger a jail validator +* update the validator with removed the delegator shares and associated coins +* if the validator state is `Bonded`, transfer the `Coins` worth of the unbonded + shares from the `BondedPool` to the `NotBondedPool` `ModuleAccount` +* remove the validator if it is unbonded and there are no more delegation shares. +* remove the validator if it is unbonded and there are no more delegation shares +* get a unique `unbondingId` and map it to the `UnbondingDelegationEntry` in `UnbondingDelegationByUnbondingId` +* call the `AfterUnbondingInitiated(unbondingId)` hook +* add the unbonding delegation to `UnbondingDelegationQueue` with the completion time set to `UnbondingTime` + +#### Cancel an `UnbondingDelegation` Entry + +When a `cancel unbond delegation` occurs both the `validator`, the `delegation` and an `UnbondingDelegationQueue` state will be updated. + +* if cancel unbonding delegation amount equals to the `UnbondingDelegation` entry `balance`, then the `UnbondingDelegation` entry deleted from `UnbondingDelegationQueue`. +* if the `cancel unbonding delegation amount is less than the `UnbondingDelegation` entry balance, then the `UnbondingDelegation` entry will be updated with new balance in the `UnbondingDelegationQueue`. +* cancel `amount` is [Delegated](#delegations) back to the original `validator`. + +#### Complete Unbonding + +For undelegations which do not complete immediately, the following operations +occur when the unbonding delegation queue element matures: + +* remove the entry from the `UnbondingDelegation` object +* transfer the tokens from the `NotBondedPool` `ModuleAccount` to the delegator `Account` + +#### Begin Redelegation + +Redelegations affect the delegation, source and destination validators. + +* perform an `unbond` delegation from the source validator to retrieve the tokens worth of the unbonded shares +* using the unbonded tokens, `Delegate` them to the destination validator +* if the `sourceValidator.Status` is `Bonded`, and the `destinationValidator` is not, + transfer the newly delegated tokens from the `BondedPool` to the `NotBondedPool` `ModuleAccount` +* otherwise, if the `sourceValidator.Status` is not `Bonded`, and the `destinationValidator` + is `Bonded`, transfer the newly delegated tokens from the `NotBondedPool` to the `BondedPool` `ModuleAccount` +* record the token amount in an new entry in the relevant `Redelegation` + +From when a redelegation begins until it completes, the delegator is in a state of "pseudo-unbonding", and can still be +slashed for infractions that occurred before the redelegation began. + +#### Complete Redelegation + +When a redelegations complete the following occurs: + +* remove the entry from the `Redelegation` object + +### Slashing + +#### Slash Validator + +When a Validator is slashed, the following occurs: + +* The total `slashAmount` is calculated as the `slashFactor` (a chain parameter) \* `TokensFromConsensusPower`, + the total number of tokens bonded to the validator at the time of the infraction. +* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occurred before the unbonding or + redelegation began from the validator are slashed by the `slashFactor` percentage of the initialBalance. +* Each amount slashed from redelegations and unbonding delegations is subtracted from the + total slash amount. +* The `remaingSlashAmount` is then slashed from the validator's tokens in the `BondedPool` or + `NonBondedPool` depending on the validator's status. This reduces the total supply of tokens. + +In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash +occurs at the block where the evidence is included, not at the block where the infraction occurred. +Put otherwise, validators are not slashed retroactively, only when they are caught. + +#### Slash Unbonding Delegation + +When a validator is slashed, so are those unbonding delegations from the validator that began unbonding +after the time of the infraction. Every entry in every unbonding delegation from the validator +is slashed by `slashFactor`. The amount slashed is calculated from the `InitialBalance` of the +delegation and is capped to prevent a resulting negative balance. Completed (or mature) unbondings are not slashed. + +#### Slash Redelegation + +When a validator is slashed, so are all redelegations from the validator that began after the +infraction. Redelegations are slashed by `slashFactor`. +Redelegations that began before the infraction are not slashed. +The amount slashed is calculated from the `InitialBalance` of the delegation and is capped to +prevent a resulting negative balance. +Mature redelegations (that have completed pseudo-unbonding) are not slashed. + +### How Shares are calculated + +At any given point in time, each validator has a number of tokens, `T`, and has a number of shares issued, `S`. +Each delegator, `i`, holds a number of shares, `S_i`. +The number of tokens is the sum of all tokens delegated to the validator, plus the rewards, minus the slashes. + +The delegator is entitled to a portion of the underlying tokens proportional to their proportion of shares. +So delegator `i` is entitled to `T * S_i / S` of the validator's tokens. + +When a delegator delegates new tokens to the validator, they receive a number of shares proportional to their contribution. +So when delegator `j` delegates `T_j` tokens, they receive `S_j = S * T_j / T` shares. +The total number of tokens is now `T + T_j`, and the total number of shares is `S + S_j`. +`j`s proportion of the shares is the same as their proportion of the total tokens contributed: `(S + S_j) / S = (T + T_j) / T`. + +A special case is the initial delegation, when `T = 0` and `S = 0`, so `T_j / T` is undefined. +For the initial delegation, delegator `j` who delegates `T_j` tokens receive `S_j = T_j` shares. +So a validator that hasn't received any rewards and has not been slashed will have `T = S`. + +## Messages + +In this section we describe the processing of the staking messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](#state) section. + +### MsgCreateValidator + +A validator is created using the `MsgCreateValidator` message. +The validator must be created with an initial delegation from the operator. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L20-L21 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L50-L73 +``` + +This message is expected to fail if: + +* another validator with this operator address is already registered +* another validator with this pubkey is already registered +* the initial self-delegation tokens are of a denom not specified as the bonding denom +* the commission parameters are faulty, namely: + * `MaxRate` is either > 1 or < 0 + * the initial `Rate` is either negative or > `MaxRate` + * the initial `MaxChangeRate` is either negative or > `MaxRate` +* the description fields are too large + +This message creates and stores the `Validator` object at appropriate indexes. +Additionally a self-delegation is made with the initial tokens delegation +tokens `Delegation`. The validator always starts as unbonded but may be bonded +in the first end-block. + +### MsgEditValidator + +The `Description`, `CommissionRate` of a validator can be updated using the +`MsgEditValidator` message. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L23-L24 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L78-L97 +``` + +This message is expected to fail if: + +* the initial `CommissionRate` is either negative or > `MaxRate` +* the `CommissionRate` has already been updated within the previous 24 hours +* the `CommissionRate` is > `MaxChangeRate` +* the description fields are too large + +This message stores the updated `Validator` object. + +### MsgDelegate + +Within this message the delegator provides coins, and in return receives +some amount of their validator's (newly created) delegator-shares that are +assigned to `Delegation.Shares`. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L26-L28 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L102-L114 +``` + +This message is expected to fail if: + +* the validator does not exist +* the `Amount` `Coin` has a denomination different than one defined by `params.BondDenom` +* the exchange rate is invalid, meaning the validator has no tokens (due to slashing) but there are outstanding shares +* the amount delegated is less than the minimum allowed delegation + +If an existing `Delegation` object for provided addresses does not already +exist then it is created as part of this message otherwise the existing +`Delegation` is updated to include the newly received shares. + +The delegator receives newly minted shares at the current exchange rate. +The exchange rate is the number of existing shares in the validator divided by +the number of currently delegated tokens. + +The validator is updated in the `ValidatorByPower` index, and the delegation is +tracked in validator object in the `Validators` index. + +It is possible to delegate to a jailed validator, the only difference being it +will not be added to the power index until it is unjailed. + +![Delegation sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/delegation_sequence.svg) + +### MsgUndelegate + +The `MsgUndelegate` message allows delegators to undelegate their tokens from +validator. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L34-L36 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L140-L152 +``` + +This message returns a response containing the completion time of the undelegation: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L154-L158 +``` + +This message is expected to fail if: + +* the delegation doesn't exist +* the validator doesn't exist +* the delegation has less shares than the ones worth of `Amount` +* existing `UnbondingDelegation` has maximum entries as defined by `params.MaxEntries` +* the `Amount` has a denomination different than one defined by `params.BondDenom` + +When this message is processed the following actions occur: + +* validator's `DelegatorShares` and the delegation's `Shares` are both reduced by the message `SharesAmount` +* calculate the token worth of the shares remove that amount tokens held within the validator +* with those removed tokens, if the validator is: + * `Bonded` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares. + * `Unbonding` - add them to an entry in `UnbondingDelegation` (create `UnbondingDelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). + * `Unbonded` - then send the coins the message `DelegatorAddr` +* if there are no more `Shares` in the delegation, then the delegation object is removed from the store + * under this situation if the delegation is the validator's self-delegation then also jail the validator. + +![Unbond sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/unbond_sequence.svg) + +### MsgCancelUnbondingDelegation + +The `MsgCancelUnbondingDelegation` message allows delegators to cancel the `unbondingDelegation` entry and delegate back to a previous validator. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L38-L42 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L160-L175 +``` + +This message is expected to fail if: + +* the `unbondingDelegation` entry is already processed. +* the `cancel unbonding delegation` amount is greater than the `unbondingDelegation` entry balance. +* the `cancel unbonding delegation` height doesn't exist in the `unbondingDelegationQueue` of the delegator. + +When this message is processed the following actions occur: + +* if the `unbondingDelegation` Entry balance is zero + * in this condition `unbondingDelegation` entry will be removed from `unbondingDelegationQueue`. + * otherwise `unbondingDelegationQueue` will be updated with new `unbondingDelegation` entry balance and initial balance +* the validator's `DelegatorShares` and the delegation's `Shares` are both increased by the message `Amount`. + +### MsgBeginRedelegate + +The redelegation command allows delegators to instantly switch validators. Once +the unbonding period has passed, the redelegation is automatically completed in +the EndBlocker. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L30-L32 +``` + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L119-L132 +``` + +This message returns a response containing the completion time of the redelegation: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L133-L138 +``` + +This message is expected to fail if: + +* the delegation doesn't exist +* the source or destination validators don't exist +* the delegation has less shares than the ones worth of `Amount` +* the source validator has a receiving redelegation which is not matured (aka. the redelegation may be transitive) +* existing `Redelegation` has maximum entries as defined by `params.MaxEntries` +* the `Amount` `Coin` has a denomination different than one defined by `params.BondDenom` + +When this message is processed the following actions occur: + +* the source validator's `DelegatorShares` and the delegations `Shares` are both reduced by the message `SharesAmount` +* calculate the token worth of the shares remove that amount tokens held within the source validator. +* if the source validator is: + * `Bonded` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares (this may be effectively reversed in the next step however). + * `Unbonding` - add an entry to the `Redelegation` (create `Redelegation` if it doesn't exist) with the same completion time as the validator (`UnbondingMinTime`). + * `Unbonded` - no action required in this step +* Delegate the token worth to the destination validator, possibly moving tokens back to the bonded state. +* if there are no more `Shares` in the source delegation, then the source delegation object is removed from the store + * under this situation if the delegation is the validator's self-delegation then also jail the validator. + +![Begin redelegation sequence](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/begin_redelegation_sequence.svg) + +### MsgUpdateParams + +The `MsgUpdateParams` update the staking module parameters. +The params are updated through a governance proposal where the signer is the gov module account address. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/staking/v1beta1/tx.proto#L182-L195 +``` + +The message handling can fail if: + +* signer is not the authority defined in the staking keeper (usually the gov module account). + +## Begin-Block + +Each abci begin block call, the historical info will get stored and pruned +according to the `HistoricalEntries` parameter. + +### Historical Info Tracking + +If the `HistoricalEntries` parameter is 0, then the `BeginBlock` performs a no-op. + +Otherwise, the latest historical info is stored under the key `historicalInfoKey|height`, while any entries older than `height - HistoricalEntries` is deleted. +In most cases, this results in a single entry being pruned per block. +However, if the parameter `HistoricalEntries` has changed to a lower value there will be multiple entries in the store that must be pruned. + +## End-Block + +Each abci end block call, the operations to update queues and validator set +changes are specified to execute. + +### Validator Set Changes + +The staking validator set is updated during this process by state transitions +that run at the end of every block. As a part of this process any updated +validators are also returned back to CometBFT for inclusion in the CometBFT +validator set which is responsible for validating CometBFT messages at the +consensus layer. Operations are as following: + +* the new validator set is taken as the top `params.MaxValidators` number of + validators retrieved from the `ValidatorsByPower` index +* the previous validator set is compared with the new validator set: + * missing validators begin unbonding and their `Tokens` are transferred from the + `BondedPool` to the `NotBondedPool` `ModuleAccount` + * new validators are instantly bonded and their `Tokens` are transferred from the + `NotBondedPool` to the `BondedPool` `ModuleAccount` + +In all cases, any validators leaving or entering the bonded validator set or +changing balances and staying within the bonded validator set incur an update +message reporting their new consensus power which is passed back to CometBFT. + +The `LastTotalPower` and `LastValidatorsPower` hold the state of the total power +and validator power from the end of the last block, and are used to check for +changes that have occurred in `ValidatorsByPower` and the total new power, which +is calculated during `EndBlock`. + +### Queues + +Within staking, certain state-transitions are not instantaneous but take place +over a duration of time (typically the unbonding period). When these +transitions are mature certain operations must take place in order to complete +the state operation. This is achieved through the use of queues which are +checked/processed at the end of each block. + +#### Unbonding Validators + +When a validator is kicked out of the bonded validator set (either through +being jailed, or not having sufficient bonded tokens) it begins the unbonding +process along with all its delegations begin unbonding (while still being +delegated to this validator). At this point the validator is said to be an +"unbonding validator", whereby it will mature to become an "unbonded validator" +after the unbonding period has passed. + +Each block the validator queue is to be checked for mature unbonding validators +(namely with a completion time <= current time and completion height <= current +block height). At this point any mature validators which do not have any +delegations remaining are deleted from state. For all other mature unbonding +validators that still have remaining delegations, the `validator.Status` is +switched from `types.Unbonding` to +`types.Unbonded`. + +Unbonding operations can be put on hold by external modules via the `PutUnbondingOnHold(unbondingId)` method. + As a result, an unbonding operation (e.g., an unbonding delegation) that is on hold, cannot complete + even if it reaches maturity. For an unbonding operation with `unbondingId` to eventually complete + (after it reaches maturity), every call to `PutUnbondingOnHold(unbondingId)` must be matched + by a call to `UnbondingCanComplete(unbondingId)`. + +#### Unbonding Delegations + +Complete the unbonding of all mature `UnbondingDelegations.Entries` within the +`UnbondingDelegations` queue with the following procedure: + +* transfer the balance coins to the delegator's wallet address +* remove the mature entry from `UnbondingDelegation.Entries` +* remove the `UnbondingDelegation` object from the store if there are no + remaining entries. + +#### Redelegations + +Complete the unbonding of all mature `Redelegation.Entries` within the +`Redelegations` queue with the following procedure: + +* remove the mature entry from `Redelegation.Entries` +* remove the `Redelegation` object from the store if there are no + remaining entries. + +## Hooks + +Other modules may register operations to execute when a certain event has +occurred within staking. These events can be registered to execute either +right `Before` or `After` the staking event (as per the hook name). The +following hooks can registered with staking: + +* `AfterValidatorCreated(Context, ValAddress) error` + * called when a validator is created +* `BeforeValidatorModified(Context, ValAddress) error` + * called when a validator's state is changed +* `AfterValidatorRemoved(Context, ConsAddress, ValAddress) error` + * called when a validator is deleted +* `AfterValidatorBonded(Context, ConsAddress, ValAddress) error` + * called when a validator is bonded +* `AfterValidatorBeginUnbonding(Context, ConsAddress, ValAddress) error` + * called when a validator begins unbonding +* `BeforeDelegationCreated(Context, AccAddress, ValAddress) error` + * called when a delegation is created +* `BeforeDelegationSharesModified(Context, AccAddress, ValAddress) error` + * called when a delegation's shares are modified +* `AfterDelegationModified(Context, AccAddress, ValAddress) error` + * called when a delegation is created or modified +* `BeforeDelegationRemoved(Context, AccAddress, ValAddress) error` + * called when a delegation is removed +* `AfterUnbondingInitiated(Context, UnbondingID)` + * called when an unbonding operation (validator unbonding, unbonding delegation, redelegation) was initiated + +## Events + +The staking module emits the following events: + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +| --------------------- | --------------------- | ------------------------- | +| complete_unbonding | amount | {totalUnbondingAmount} | +| complete_unbonding | validator | {validatorAddress} | +| complete_unbonding | delegator | {delegatorAddress} | +| complete_redelegation | amount | {totalRedelegationAmount} | +| complete_redelegation | source_validator | {srcValidatorAddress} | +| complete_redelegation | destination_validator | {dstValidatorAddress} | +| complete_redelegation | delegator | {delegatorAddress} | + +## Msg's + +### MsgCreateValidator + +| Type | Attribute Key | Attribute Value | +| ---------------- | ------------- | ------------------ | +| create_validator | validator | {validatorAddress} | +| create_validator | amount | {delegationAmount} | +| message | module | staking | +| message | action | create_validator | +| message | sender | {senderAddress} | + +### MsgEditValidator + +| Type | Attribute Key | Attribute Value | +| -------------- | ------------------- | ------------------- | +| edit_validator | commission_rate | {commissionRate} | +| edit_validator | min_self_delegation | {minSelfDelegation} | +| message | module | staking | +| message | action | edit_validator | +| message | sender | {senderAddress} | + +### MsgDelegate + +| Type | Attribute Key | Attribute Value | +| -------- | ------------- | ------------------ | +| delegate | validator | {validatorAddress} | +| delegate | amount | {delegationAmount} | +| message | module | staking | +| message | action | delegate | +| message | sender | {senderAddress} | + +### MsgUndelegate + +| Type | Attribute Key | Attribute Value | +| ------- | ------------------- | ------------------ | +| unbond | validator | {validatorAddress} | +| unbond | amount | {unbondAmount} | +| unbond | completion_time [0] | {completionTime} | +| message | module | staking | +| message | action | begin_unbonding | +| message | sender | {senderAddress} | + +* [0] Time is formatted in the RFC3339 standard + +### MsgCancelUnbondingDelegation + +| Type | Attribute Key | Attribute Value | +| ----------------------------- | ------------------ | ------------------------------------| +| cancel_unbonding_delegation | validator | {validatorAddress} | +| cancel_unbonding_delegation | delegator | {delegatorAddress} | +| cancel_unbonding_delegation | amount | {cancelUnbondingDelegationAmount} | +| cancel_unbonding_delegation | creation_height | {unbondingCreationHeight} | +| message | module | staking | +| message | action | cancel_unbond | +| message | sender | {senderAddress} | + +### MsgBeginRedelegate + +| Type | Attribute Key | Attribute Value | +| ---------- | --------------------- | --------------------- | +| redelegate | source_validator | {srcValidatorAddress} | +| redelegate | destination_validator | {dstValidatorAddress} | +| redelegate | amount | {unbondAmount} | +| redelegate | completion_time [0] | {completionTime} | +| message | module | staking | +| message | action | begin_redelegate | +| message | sender | {senderAddress} | + +* [0] Time is formatted in the RFC3339 standard + +## Parameters + +The staking module contains the following parameters: + +| Key | Type | Example | +|-------------------|------------------|------------------------| +| UnbondingTime | string (time ns) | "259200000000000" | +| MaxValidators | uint16 | 100 | +| KeyMaxEntries | uint16 | 7 | +| HistoricalEntries | uint16 | 3 | +| BondDenom | string | "stake" | +| MinCommissionRate | string | "0.000000000000000000" | + +## Client + +### CLI + +A user can query and interact with the `staking` module using the CLI. + +#### Query + +The `query` commands allows users to query `staking` state. + +```bash +simd query staking --help +``` + +##### delegation + +The `delegation` command allows users to query delegations for an individual delegator on an individual validator. + +Usage: + +```bash +simd query staking delegation [delegator-addr] [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +balance: + amount: "10000000000" + denom: stake +delegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + shares: "10000000000.000000000000000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +##### delegations + +The `delegations` command allows users to query delegations for an individual delegator on all validators. + +Usage: + +```bash +simd query staking delegations [delegator-addr] [flags] +``` + +Example: + +```bash +simd query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +``` + +Example Output: + +```bash +delegation_responses: +- balance: + amount: "10000000000" + denom: stake + delegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + shares: "10000000000.000000000000000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +- balance: + amount: "10000000000" + denom: stake + delegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + shares: "10000000000.000000000000000000" + validator_address: cosmosvaloper1x20lytyf6zkcrv5edpkfkn8sz578qg5sqfyqnp +pagination: + next_key: null + total: "0" +``` + +##### delegations-to + +The `delegations-to` command allows users to query delegations on an individual validator. + +Usage: + +```bash +simd query staking delegations-to [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +- balance: + amount: "504000000" + denom: stake + delegation: + delegator_address: cosmos1q2qwwynhv8kh3lu5fkeex4awau9x8fwt45f5cp + shares: "504000000.000000000000000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +- balance: + amount: "78125000000" + denom: uixo + delegation: + delegator_address: cosmos1qvppl3479hw4clahe0kwdlfvf8uvjtcd99m2ca + shares: "78125000000.000000000000000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +pagination: + next_key: null + total: "0" +``` + +##### historical-info + +The `historical-info` command allows users to query historical information at given height. + +Usage: + +```bash +simd query staking historical-info [height] [flags] +``` + +Example: + +```bash +simd query staking historical-info 10 +``` + +Example Output: + +```bash +header: + app_hash: Lbx8cXpI868wz8sgp4qPYVrlaKjevR5WP/IjUxwp3oo= + chain_id: testnet + consensus_hash: BICRvH3cKD93v7+R1zxE2ljD34qcvIZ0Bdi389qtoi8= + data_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= + evidence_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= + height: "10" + last_block_id: + hash: RFbkpu6pWfSThXxKKl6EZVDnBSm16+U0l0xVjTX08Fk= + part_set_header: + hash: vpIvXD4rxD5GM4MXGz0Sad9I7//iVYLzZsEU4BVgWIU= + total: 1 + last_commit_hash: Ne4uXyx4QtNp4Zx89kf9UK7oG9QVbdB6e7ZwZkhy8K0= + last_results_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= + next_validators_hash: nGBgKeWBjoxeKFti00CxHsnULORgKY4LiuQwBuUrhCs= + proposer_address: mMEP2c2IRPLr99LedSRtBg9eONM= + time: "2021-10-01T06:00:49.785790894Z" + validators_hash: nGBgKeWBjoxeKFti00CxHsnULORgKY4LiuQwBuUrhCs= + version: + app: "0" + block: "11" +valset: +- commission: + commission_rates: + max_change_rate: "0.010000000000000000" + max_rate: "0.200000000000000000" + rate: "0.100000000000000000" + update_time: "2021-10-01T05:52:50.380144238Z" + consensus_pubkey: + '@type': /cosmos.crypto.ed25519.PubKey + key: Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8= + delegator_shares: "10000000.000000000000000000" + description: + details: "" + identity: "" + moniker: myvalidator + security_contact: "" + website: "" + jailed: false + min_self_delegation: "1" + operator_address: cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc + status: BOND_STATUS_BONDED + tokens: "10000000" + unbonding_height: "0" + unbonding_time: "1970-01-01T00:00:00Z" +``` + +##### params + +The `params` command allows users to query values set as staking parameters. + +Usage: + +```bash +simd query staking params [flags] +``` + +Example: + +```bash +simd query staking params +``` + +Example Output: + +```bash +bond_denom: stake +historical_entries: 10000 +max_entries: 7 +max_validators: 50 +unbonding_time: 1814400s +``` + +##### pool + +The `pool` command allows users to query values for amounts stored in the staking pool. + +Usage: + +```bash +simd q staking pool [flags] +``` + +Example: + +```bash +simd q staking pool +``` + +Example Output: + +```bash +bonded_tokens: "10000000" +not_bonded_tokens: "0" +``` + +##### redelegation + +The `redelegation` command allows users to query a redelegation record based on delegator and a source and destination validator address. + +Usage: + +```bash +simd query staking redelegation [delegator-addr] [src-validator-addr] [dst-validator-addr] [flags] +``` + +Example: + +```bash +simd query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +pagination: null +redelegation_responses: +- entries: + - balance: "50000000" + redelegation_entry: + completion_time: "2021-10-24T20:33:21.960084845Z" + creation_height: 2.382847e+06 + initial_balance: "50000000" + shares_dst: "50000000.000000000000000000" + - balance: "5000000000" + redelegation_entry: + completion_time: "2021-10-25T21:33:54.446846862Z" + creation_height: 2.397271e+06 + initial_balance: "5000000000" + shares_dst: "5000000000.000000000000000000" + redelegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + entries: null + validator_dst_address: cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm + validator_src_address: cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm +``` + +##### redelegations + +The `redelegations` command allows users to query all redelegation records for an individual delegator. + +Usage: + +```bash +simd query staking redelegations [delegator-addr] [flags] +``` + +Example: + +```bash +simd query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +redelegation_responses: +- entries: + - balance: "50000000" + redelegation_entry: + completion_time: "2021-10-24T20:33:21.960084845Z" + creation_height: 2.382847e+06 + initial_balance: "50000000" + shares_dst: "50000000.000000000000000000" + - balance: "5000000000" + redelegation_entry: + completion_time: "2021-10-25T21:33:54.446846862Z" + creation_height: 2.397271e+06 + initial_balance: "5000000000" + shares_dst: "5000000000.000000000000000000" + redelegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + entries: null + validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm + validator_src_address: cosmosvaloper1zppjyal5emta5cquje8ndkpz0rs046m7zqxrpp +- entries: + - balance: "562770000000" + redelegation_entry: + completion_time: "2021-10-25T21:42:07.336911677Z" + creation_height: 2.39735e+06 + initial_balance: "562770000000" + shares_dst: "562770000000.000000000000000000" + redelegation: + delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + entries: null + validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm + validator_src_address: cosmosvaloper1zppjyal5emta5cquje8ndkpz0rs046m7zqxrpp +``` + +##### redelegations-from + +The `redelegations-from` command allows users to query delegations that are redelegating _from_ a validator. + +Usage: + +```bash +simd query staking redelegations-from [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking redelegations-from cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +redelegation_responses: +- entries: + - balance: "50000000" + redelegation_entry: + completion_time: "2021-10-24T20:33:21.960084845Z" + creation_height: 2.382847e+06 + initial_balance: "50000000" + shares_dst: "50000000.000000000000000000" + - balance: "5000000000" + redelegation_entry: + completion_time: "2021-10-25T21:33:54.446846862Z" + creation_height: 2.397271e+06 + initial_balance: "5000000000" + shares_dst: "5000000000.000000000000000000" + redelegation: + delegator_address: cosmos1pm6e78p4pgn0da365plzl4t56pxy8hwtqp2mph + entries: null + validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm + validator_src_address: cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy +- entries: + - balance: "221000000" + redelegation_entry: + completion_time: "2021-10-05T21:05:45.669420544Z" + creation_height: 2.120693e+06 + initial_balance: "221000000" + shares_dst: "221000000.000000000000000000" + redelegation: + delegator_address: cosmos1zqv8qxy2zgn4c58fz8jt8jmhs3d0attcussrf6 + entries: null + validator_dst_address: cosmosvaloper10mseqwnwtjaqfrwwp2nyrruwmjp6u5jhah4c3y + validator_src_address: cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy +``` + +##### unbonding-delegation + +The `unbonding-delegation` command allows users to query unbonding delegations for an individual delegator on an individual validator. + +Usage: + +```bash +simd query staking unbonding-delegation [delegator-addr] [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +entries: +- balance: "52000000" + completion_time: "2021-11-02T11:35:55.391594709Z" + creation_height: "55078" + initial_balance: "52000000" +validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +##### unbonding-delegations + +The `unbonding-delegations` command allows users to query all unbonding-delegations records for one delegator. + +Usage: + +```bash +simd query staking unbonding-delegations [delegator-addr] [flags] +``` + +Example: + +```bash +simd query staking unbonding-delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +unbonding_responses: +- delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p + entries: + - balance: "52000000" + completion_time: "2021-11-02T11:35:55.391594709Z" + creation_height: "55078" + initial_balance: "52000000" + validator_address: cosmosvaloper1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzmvtaaa + +``` + +##### unbonding-delegations-from + +The `unbonding-delegations-from` command allows users to query delegations that are unbonding _from_ a validator. + +Usage: + +```bash +simd query staking unbonding-delegations-from [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +pagination: + next_key: null + total: "0" +unbonding_responses: +- delegator_address: cosmos1qqq9txnw4c77sdvzx0tkedsafl5s3vk7hn53fn + entries: + - balance: "150000000" + completion_time: "2021-11-01T21:41:13.098141574Z" + creation_height: "46823" + initial_balance: "150000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +- delegator_address: cosmos1peteje73eklqau66mr7h7rmewmt2vt99y24f5z + entries: + - balance: "24000000" + completion_time: "2021-10-31T02:57:18.192280361Z" + creation_height: "21516" + initial_balance: "24000000" + validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +##### validator + +The `validator` command allows users to query details about an individual validator. + +Usage: + +```bash +simd query staking validator [validator-addr] [flags] +``` + +Example: + +```bash +simd query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +``` + +Example Output: + +```bash +commission: + commission_rates: + max_change_rate: "0.020000000000000000" + max_rate: "0.200000000000000000" + rate: "0.050000000000000000" + update_time: "2021-10-01T19:24:52.663191049Z" +consensus_pubkey: + '@type': /cosmos.crypto.ed25519.PubKey + key: sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc= +delegator_shares: "32948270000.000000000000000000" +description: + details: Witval is the validator arm from Vitwit. Vitwit is into software consulting + and services business since 2015. We are working closely with Cosmos ecosystem + since 2018. We are also building tools for the ecosystem, Aneka is our explorer + for the cosmos ecosystem. + identity: 51468B615127273A + moniker: Witval + security_contact: "" + website: "" +jailed: false +min_self_delegation: "1" +operator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj +status: BOND_STATUS_BONDED +tokens: "32948270000" +unbonding_height: "0" +unbonding_time: "1970-01-01T00:00:00Z" +``` + +##### validators + +The `validators` command allows users to query details about all validators on a network. + +Usage: + +```bash +simd query staking validators [flags] +``` + +Example: + +```bash +simd query staking validators +``` + +Example Output: + +```bash +pagination: + next_key: FPTi7TKAjN63QqZh+BaXn6gBmD5/ + total: "0" +validators: +commission: + commission_rates: + max_change_rate: "0.020000000000000000" + max_rate: "0.200000000000000000" + rate: "0.050000000000000000" + update_time: "2021-10-01T19:24:52.663191049Z" +consensus_pubkey: + '@type': /cosmos.crypto.ed25519.PubKey + key: sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc= +delegator_shares: "32948270000.000000000000000000" +description: + details: Witval is the validator arm from Vitwit. Vitwit is into software consulting + and services business since 2015. We are working closely with Cosmos ecosystem + since 2018. We are also building tools for the ecosystem, Aneka is our explorer + for the cosmos ecosystem. + identity: 51468B615127273A + moniker: Witval + security_contact: "" + website: "" + jailed: false + min_self_delegation: "1" + operator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj + status: BOND_STATUS_BONDED + tokens: "32948270000" + unbonding_height: "0" + unbonding_time: "1970-01-01T00:00:00Z" +- commission: + commission_rates: + max_change_rate: "0.100000000000000000" + max_rate: "0.200000000000000000" + rate: "0.050000000000000000" + update_time: "2021-10-04T18:02:21.446645619Z" + consensus_pubkey: + '@type': /cosmos.crypto.ed25519.PubKey + key: GDNpuKDmCg9GnhnsiU4fCWktuGUemjNfvpCZiqoRIYA= + delegator_shares: "559343421.000000000000000000" + description: + details: Noderunners is a professional validator in POS networks. We have a huge + node running experience, reliable soft and hardware. Our commissions are always + low, our support to delegators is always full. Stake with us and start receiving + your Cosmos rewards now! + identity: 812E82D12FEA3493 + moniker: Noderunners + security_contact: info@noderunners.biz + website: http://noderunners.biz + jailed: false + min_self_delegation: "1" + operator_address: cosmosvaloper1q5ku90atkhktze83j9xjaks2p7uruag5zp6wt7 + status: BOND_STATUS_BONDED + tokens: "559343421" + unbonding_height: "0" + unbonding_time: "1970-01-01T00:00:00Z" +``` + +#### Transactions + +The `tx` commands allows users to interact with the `staking` module. + +```bash +simd tx staking --help +``` + +##### create-validator + +The command `create-validator` allows users to create new validator initialized with a self-delegation to it. + +Usage: + +```bash +simd tx staking create-validator [path/to/validator.json] [flags] +``` + +Example: + +```bash +simd tx staking create-validator /path/to/validator.json \ + --chain-id="name_of_chain_id" \ + --gas="auto" \ + --gas-adjustment="1.2" \ + --gas-prices="0.025stake" \ + --from=mykey +``` + +where `validator.json` contains: + +```json +{ + "pubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"BnbwFpeONLqvWqJb3qaUbL5aoIcW3fSuAp9nT3z5f20="}, + "amount": "1000000stake", + "moniker": "my-moniker", + "website": "https://myweb.site", + "security": "security-contact@gmail.com", + "details": "description of your validator", + "commission-rate": "0.10", + "commission-max-rate": "0.20", + "commission-max-change-rate": "0.01", + "min-self-delegation": "1" +} +``` + +and pubkey can be obtained by using `simd tendermint show-validator` command. + +##### delegate + +The command `delegate` allows users to delegate liquid tokens to a validator. + +Usage: + +```bash +simd tx staking delegate [validator-addr] [amount] [flags] +``` + +Example: + +```bash +simd tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey +``` + +##### edit-validator + +The command `edit-validator` allows users to edit an existing validator account. + +Usage: + +```bash +simd tx staking edit-validator [flags] +``` + +Example: + +```bash +simd tx staking edit-validator --moniker "new_moniker_name" --website "new_webiste_url" --from mykey +``` + +##### redelegate + +The command `redelegate` allows users to redelegate illiquid tokens from one validator to another. + +Usage: + +```bash +simd tx staking redelegate [src-validator-addr] [dst-validator-addr] [amount] [flags] +``` + +Example: + +```bash +simd tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 100stake --from mykey +``` + +##### unbond + +The command `unbond` allows users to unbond shares from a validator. + +Usage: + +```bash +simd tx staking unbond [validator-addr] [amount] [flags] +``` + +Example: + +```bash +simd tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake --from mykey +``` + +##### cancel unbond + +The command `cancel-unbond` allow users to cancel the unbonding delegation entry and delegate back to the original validator. + +Usage: + +```bash +simd tx staking cancel-unbond [validator-addr] [amount] [creation-height] +``` + +Example: + +```bash +simd tx staking cancel-unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100stake 123123 --from mykey +``` + +### gRPC + +A user can query the `staking` module using gRPC endpoints. + +#### Validators + +The `Validators` endpoint queries all validators that match the given status. + +```bash +cosmos.staking.v1beta1.Query/Validators +``` + +Example: + +```bash +grpcurl -plaintext localhost:9090 cosmos.staking.v1beta1.Query/Validators +``` + +Example Output: + +```bash +{ + "validators": [ + { + "operatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8="}, + "status": "BOND_STATUS_BONDED", + "tokens": "10000000", + "delegatorShares": "10000000000000000000000000", + "description": { + "moniker": "myvalidator" + }, + "unbondingTime": "1970-01-01T00:00:00Z", + "commission": { + "commissionRates": { + "rate": "100000000000000000", + "maxRate": "200000000000000000", + "maxChangeRate": "10000000000000000" + }, + "updateTime": "2021-10-01T05:52:50.380144238Z" + }, + "minSelfDelegation": "1" + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### Validator + +The `Validator` endpoint queries validator information for given validator address. + +```bash +cosmos.staking.v1beta1.Query/Validator +``` + +Example: + +```bash +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/Validator +``` + +Example Output: + +```bash +{ + "validator": { + "operatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8="}, + "status": "BOND_STATUS_BONDED", + "tokens": "10000000", + "delegatorShares": "10000000000000000000000000", + "description": { + "moniker": "myvalidator" + }, + "unbondingTime": "1970-01-01T00:00:00Z", + "commission": { + "commissionRates": { + "rate": "100000000000000000", + "maxRate": "200000000000000000", + "maxChangeRate": "10000000000000000" + }, + "updateTime": "2021-10-01T05:52:50.380144238Z" + }, + "minSelfDelegation": "1" + } +} +``` + +#### ValidatorDelegations + +The `ValidatorDelegations` endpoint queries delegate information for given validator. + +```bash +cosmos.staking.v1beta1.Query/ValidatorDelegations +``` + +Example: + +```bash +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/ValidatorDelegations +``` + +Example Output: + +```bash +{ + "delegationResponses": [ + { + "delegation": { + "delegatorAddress": "cosmos1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgy3ua5t", + "validatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "shares": "10000000000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "10000000" + } + } + ], + "pagination": { + "total": "1" + } +} +``` + +#### ValidatorUnbondingDelegations + +The `ValidatorUnbondingDelegations` endpoint queries delegate information for given validator. + +```bash +cosmos.staking.v1beta1.Query/ValidatorUnbondingDelegations +``` + +Example: + +```bash +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/ValidatorUnbondingDelegations +``` + +Example Output: + +```bash +{ + "unbonding_responses": [ + { + "delegator_address": "cosmos1z3pzzw84d6xn00pw9dy3yapqypfde7vg6965fy", + "validator_address": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "entries": [ + { + "creation_height": "25325", + "completion_time": "2021-10-31T09:24:36.797320636Z", + "initial_balance": "20000000", + "balance": "20000000" + } + ] + }, + { + "delegator_address": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", + "validator_address": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "entries": [ + { + "creation_height": "13100", + "completion_time": "2021-10-30T12:53:02.272266791Z", + "initial_balance": "1000000", + "balance": "1000000" + } + ] + }, + ], + "pagination": { + "next_key": null, + "total": "8" + } +} +``` + +#### Delegation + +The `Delegation` endpoint queries delegate information for given validator delegator pair. + +```bash +cosmos.staking.v1beta1.Query/Delegation +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/Delegation +``` + +Example Output: + +```bash +{ + "delegation_response": + { + "delegation": + { + "delegator_address":"cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", + "validator_address":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "shares":"25083119936.000000000000000000" + }, + "balance": + { + "denom":"stake", + "amount":"25083119936" + } + } +} +``` + +#### UnbondingDelegation + +The `UnbondingDelegation` endpoint queries unbonding information for given validator delegator. + +```bash +cosmos.staking.v1beta1.Query/UnbondingDelegation +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/UnbondingDelegation +``` + +Example Output: + +```bash +{ + "unbond": { + "delegator_address": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", + "validator_address": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", + "entries": [ + { + "creation_height": "136984", + "completion_time": "2021-11-08T05:38:47.505593891Z", + "initial_balance": "400000000", + "balance": "400000000" + }, + { + "creation_height": "137005", + "completion_time": "2021-11-08T05:40:53.526196312Z", + "initial_balance": "385000000", + "balance": "385000000" + } + ] + } +} +``` + +#### DelegatorDelegations + +The `DelegatorDelegations` endpoint queries all delegations of a given delegator address. + +```bash +cosmos.staking.v1beta1.Query/DelegatorDelegations +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/DelegatorDelegations +``` + +Example Output: + +```bash +{ + "delegation_responses": [ + {"delegation":{"delegator_address":"cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77","validator_address":"cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8","shares":"25083339023.000000000000000000"},"balance":{"denom":"stake","amount":"25083339023"}} + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### DelegatorUnbondingDelegations + +The `DelegatorUnbondingDelegations` endpoint queries all unbonding delegations of a given delegator address. + +```bash +cosmos.staking.v1beta1.Query/DelegatorUnbondingDelegations +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/DelegatorUnbondingDelegations +``` + +Example Output: + +```bash +{ + "unbonding_responses": [ + { + "delegator_address": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", + "validator_address": "cosmosvaloper1sjllsnramtg3ewxqwwrwjxfgc4n4ef9uxyejze", + "entries": [ + { + "creation_height": "136984", + "completion_time": "2021-11-08T05:38:47.505593891Z", + "initial_balance": "400000000", + "balance": "400000000" + }, + { + "creation_height": "137005", + "completion_time": "2021-11-08T05:40:53.526196312Z", + "initial_balance": "385000000", + "balance": "385000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### Redelegations + +The `Redelegations` endpoint queries redelegations of given address. + +```bash +cosmos.staking.v1beta1.Query/Redelegations +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf", "src_validator_addr" : "cosmosvaloper1j7euyj85fv2jugejrktj540emh9353ltgppc3g", "dst_validator_addr" : "cosmosvaloper1yy3tnegzmkdcm7czzcy3flw5z0zyr9vkkxrfse"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/Redelegations +``` + +Example Output: + +```bash +{ + "redelegation_responses": [ + { + "redelegation": { + "delegator_address": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf", + "validator_src_address": "cosmosvaloper1j7euyj85fv2jugejrktj540emh9353ltgppc3g", + "validator_dst_address": "cosmosvaloper1yy3tnegzmkdcm7czzcy3flw5z0zyr9vkkxrfse", + "entries": null + }, + "entries": [ + { + "redelegation_entry": { + "creation_height": 135932, + "completion_time": "2021-11-08T03:52:55.299147901Z", + "initial_balance": "2900000", + "shares_dst": "2900000.000000000000000000" + }, + "balance": "2900000" + } + ] + } + ], + "pagination": null +} +``` + +#### DelegatorValidators + +The `DelegatorValidators` endpoint queries all validators information for given delegator. + +```bash +cosmos.staking.v1beta1.Query/DelegatorValidators +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/DelegatorValidators +``` + +Example Output: + +```bash +{ + "validators": [ + { + "operator_address": "cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "UPwHWxH1zHJWGOa/m6JB3f5YjHMvPQPkVbDqqi+U7Uw=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "347260647559", + "delegator_shares": "347260647559.000000000000000000", + "description": { + "moniker": "BouBouNode", + "identity": "", + "website": "https://boubounode.com", + "security_contact": "", + "details": "AI-based Validator. #1 AI Validator on Game of Stakes. Fairly priced. Don't trust (humans), verify. Made with BouBou love." + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.061000000000000000", + "max_rate": "0.300000000000000000", + "max_change_rate": "0.150000000000000000" + }, + "update_time": "2021-10-01T15:00:00Z" + }, + "min_self_delegation": "1" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### DelegatorValidator + +The `DelegatorValidator` endpoint queries validator information for given delegator validator + +```bash +cosmos.staking.v1beta1.Query/DelegatorValidator +``` + +Example: + +```bash +grpcurl -plaintext \ +-d '{"delegator_addr": "cosmos1eh5mwu044gd5ntkkc2xgfg8247mgc56f3n8rr7", "validator_addr": "cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8"}' \ +localhost:9090 cosmos.staking.v1beta1.Query/DelegatorValidator +``` + +Example Output: + +```bash +{ + "validator": { + "operator_address": "cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "UPwHWxH1zHJWGOa/m6JB3f5YjHMvPQPkVbDqqi+U7Uw=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "347262754841", + "delegator_shares": "347262754841.000000000000000000", + "description": { + "moniker": "BouBouNode", + "identity": "", + "website": "https://boubounode.com", + "security_contact": "", + "details": "AI-based Validator. #1 AI Validator on Game of Stakes. Fairly priced. Don't trust (humans), verify. Made with BouBou love." + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.061000000000000000", + "max_rate": "0.300000000000000000", + "max_change_rate": "0.150000000000000000" + }, + "update_time": "2021-10-01T15:00:00Z" + }, + "min_self_delegation": "1" + } +} +``` + +#### HistoricalInfo + +```bash +cosmos.staking.v1beta1.Query/HistoricalInfo +``` + +Example: + +```bash +grpcurl -plaintext -d '{"height" : 1}' localhost:9090 cosmos.staking.v1beta1.Query/HistoricalInfo +``` + +Example Output: + +```bash +{ + "hist": { + "header": { + "version": { + "block": "11", + "app": "0" + }, + "chain_id": "simd-1", + "height": "140142", + "time": "2021-10-11T10:56:29.720079569Z", + "last_block_id": { + "hash": "9gri/4LLJUBFqioQ3NzZIP9/7YHR9QqaM6B2aJNQA7o=", + "part_set_header": { + "total": 1, + "hash": "Hk1+C864uQkl9+I6Zn7IurBZBKUevqlVtU7VqaZl1tc=" + } + }, + "last_commit_hash": "VxrcS27GtvGruS3I9+AlpT7udxIT1F0OrRklrVFSSKc=", + "data_hash": "80BjOrqNYUOkTnmgWyz9AQ8n7SoEmPVi4QmAe8RbQBY=", + "validators_hash": "95W49n2hw8RWpr1GPTAO5MSPi6w6Wjr3JjjS7AjpBho=", + "next_validators_hash": "95W49n2hw8RWpr1GPTAO5MSPi6w6Wjr3JjjS7AjpBho=", + "consensus_hash": "BICRvH3cKD93v7+R1zxE2ljD34qcvIZ0Bdi389qtoi8=", + "app_hash": "ZZaxnSY3E6Ex5Bvkm+RigYCK82g8SSUL53NymPITeOE=", + "last_results_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", + "evidence_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", + "proposer_address": "aH6dO428B+ItuoqPq70efFHrSMY=" + }, + "valset": [ + { + "operator_address": "cosmosvaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "1426045203613", + "delegator_shares": "1426045203613.000000000000000000", + "description": { + "moniker": "SG-1", + "identity": "48608633F99D1B60", + "website": "https://sg-1.online", + "security_contact": "", + "details": "SG-1 - your favorite validator on Witval. We offer 100% Soft Slash protection." + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.037500000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.030000000000000000" + }, + "update_time": "2021-10-01T15:00:00Z" + }, + "min_self_delegation": "1" + } + ] + } +} + +``` + +#### Pool + +The `Pool` endpoint queries the pool information. + +```bash +cosmos.staking.v1beta1.Query/Pool +``` + +Example: + +```bash +grpcurl -plaintext -d localhost:9090 cosmos.staking.v1beta1.Query/Pool +``` + +Example Output: + +```bash +{ + "pool": { + "not_bonded_tokens": "369054400189", + "bonded_tokens": "15657192425623" + } +} +``` + +#### Params + +The `Params` endpoint queries the pool information. + +```bash +cosmos.staking.v1beta1.Query/Params +``` + +Example: + +```bash +grpcurl -plaintext localhost:9090 cosmos.staking.v1beta1.Query/Params +``` + +Example Output: + +```bash +{ + "params": { + "unbondingTime": "1814400s", + "maxValidators": 100, + "maxEntries": 7, + "historicalEntries": 10000, + "bondDenom": "stake" + } +} +``` + +### REST + +A user can query the `staking` module using REST endpoints. + +#### DelegatorDelegations + +The `DelegtaorDelegations` REST endpoint queries all delegations of a given delegator address. + +```bash +/cosmos/staking/v1beta1/delegations/{delegatorAddr} +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/delegations/cosmos1vcs68xf2tnqes5tg0khr0vyevm40ff6zdxatp5" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "delegation_responses": [ + { + "delegation": { + "delegator_address": "cosmos1vcs68xf2tnqes5tg0khr0vyevm40ff6zdxatp5", + "validator_address": "cosmosvaloper1quqxfrxkycr0uzt4yk0d57tcq3zk7srm7sm6r8", + "shares": "256250000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "256250000" + } + }, + { + "delegation": { + "delegator_address": "cosmos1vcs68xf2tnqes5tg0khr0vyevm40ff6zdxatp5", + "validator_address": "cosmosvaloper194v8uwee2fvs2s8fa5k7j03ktwc87h5ym39jfv", + "shares": "255150000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "255150000" + } + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` + +#### Redelegations + +The `Redelegations` REST endpoint queries redelegations of given address. + +```bash +/cosmos/staking/v1beta1/delegators/{delegatorAddr}/redelegations +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/delegators/cosmos1thfntksw0d35n2tkr0k8v54fr8wxtxwxl2c56e/redelegations?srcValidatorAddr=cosmosvaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qx4cuznf&dstValidatorAddr=cosmosvaloper1vq8tw77kp8lvxq9u3c8eeln9zymn68rng8pgt4" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "redelegation_responses": [ + { + "redelegation": { + "delegator_address": "cosmos1thfntksw0d35n2tkr0k8v54fr8wxtxwxl2c56e", + "validator_src_address": "cosmosvaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qx4cuznf", + "validator_dst_address": "cosmosvaloper1vq8tw77kp8lvxq9u3c8eeln9zymn68rng8pgt4", + "entries": null + }, + "entries": [ + { + "redelegation_entry": { + "creation_height": 151523, + "completion_time": "2021-11-09T06:03:25.640682116Z", + "initial_balance": "200000000", + "shares_dst": "200000000.000000000000000000" + }, + "balance": "200000000" + } + ] + } + ], + "pagination": null +} +``` + +#### DelegatorUnbondingDelegations + +The `DelegatorUnbondingDelegations` REST endpoint queries all unbonding delegations of a given delegator address. + +```bash +/cosmos/staking/v1beta1/delegators/{delegatorAddr}/unbonding_delegations +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/delegators/cosmos1nxv42u3lv642q0fuzu2qmrku27zgut3n3z7lll/unbonding_delegations" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "unbonding_responses": [ + { + "delegator_address": "cosmos1nxv42u3lv642q0fuzu2qmrku27zgut3n3z7lll", + "validator_address": "cosmosvaloper1e7mvqlz50ch6gw4yjfemsc069wfre4qwmw53kq", + "entries": [ + { + "creation_height": "2442278", + "completion_time": "2021-10-12T10:59:03.797335857Z", + "initial_balance": "50000000000", + "balance": "50000000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### DelegatorValidators + +The `DelegatorValidators` REST endpoint queries all validators information for given delegator address. + +```bash +/cosmos/staking/v1beta1/delegators/{delegatorAddr}/validators +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/delegators/cosmos1xwazl8ftks4gn00y5x3c47auquc62ssune9ppv/validators" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "validators": [ + { + "operator_address": "cosmosvaloper1xwazl8ftks4gn00y5x3c47auquc62ssuvynw64", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "5v4n3px3PkfNnKflSgepDnsMQR1hiNXnqOC11Y72/PQ=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "21592843799", + "delegator_shares": "21592843799.000000000000000000", + "description": { + "moniker": "jabbey", + "identity": "", + "website": "https://twitter.com/JoeAbbey", + "security_contact": "", + "details": "just another dad in the cosmos" + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.100000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.100000000000000000" + }, + "update_time": "2021-10-09T19:03:54.984821705Z" + }, + "min_self_delegation": "1" + } + ], + "pagination": { + "next_key": null, + "total": "1" + } +} +``` + +#### DelegatorValidator + +The `DelegatorValidator` REST endpoint queries validator information for given delegator validator pair. + +```bash +/cosmos/staking/v1beta1/delegators/{delegatorAddr}/validators/{validatorAddr} +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/delegators/cosmos1xwazl8ftks4gn00y5x3c47auquc62ssune9ppv/validators/cosmosvaloper1xwazl8ftks4gn00y5x3c47auquc62ssuvynw64" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "validator": { + "operator_address": "cosmosvaloper1xwazl8ftks4gn00y5x3c47auquc62ssuvynw64", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "5v4n3px3PkfNnKflSgepDnsMQR1hiNXnqOC11Y72/PQ=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "21592843799", + "delegator_shares": "21592843799.000000000000000000", + "description": { + "moniker": "jabbey", + "identity": "", + "website": "https://twitter.com/JoeAbbey", + "security_contact": "", + "details": "just another dad in the cosmos" + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.100000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.100000000000000000" + }, + "update_time": "2021-10-09T19:03:54.984821705Z" + }, + "min_self_delegation": "1" + } +} +``` + +#### HistoricalInfo + +The `HistoricalInfo` REST endpoint queries the historical information for given height. + +```bash +/cosmos/staking/v1beta1/historical_info/{height} +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/historical_info/153332" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "hist": { + "header": { + "version": { + "block": "11", + "app": "0" + }, + "chain_id": "cosmos-1", + "height": "153332", + "time": "2021-10-12T09:05:35.062230221Z", + "last_block_id": { + "hash": "NX8HevR5khb7H6NGKva+jVz7cyf0skF1CrcY9A0s+d8=", + "part_set_header": { + "total": 1, + "hash": "zLQ2FiKM5tooL3BInt+VVfgzjlBXfq0Hc8Iux/xrhdg=" + } + }, + "last_commit_hash": "P6IJrK8vSqU3dGEyRHnAFocoDGja0bn9euLuy09s350=", + "data_hash": "eUd+6acHWrNXYju8Js449RJ99lOYOs16KpqQl4SMrEM=", + "validators_hash": "mB4pravvMsJKgi+g8aYdSeNlt0kPjnRFyvtAQtaxcfw=", + "next_validators_hash": "mB4pravvMsJKgi+g8aYdSeNlt0kPjnRFyvtAQtaxcfw=", + "consensus_hash": "BICRvH3cKD93v7+R1zxE2ljD34qcvIZ0Bdi389qtoi8=", + "app_hash": "fuELArKRK+CptnZ8tu54h6xEleSWenHNmqC84W866fU=", + "last_results_hash": "p/BPexV4LxAzlVcPRvW+lomgXb6Yze8YLIQUo/4Kdgc=", + "evidence_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", + "proposer_address": "G0MeY8xQx7ooOsni8KE/3R/Ib3Q=" + }, + "valset": [ + { + "operator_address": "cosmosvaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "1416521659632", + "delegator_shares": "1416521659632.000000000000000000", + "description": { + "moniker": "SG-1", + "identity": "48608633F99D1B60", + "website": "https://sg-1.online", + "security_contact": "", + "details": "SG-1 - your favorite validator on cosmos. We offer 100% Soft Slash protection." + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.037500000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.030000000000000000" + }, + "update_time": "2021-10-01T15:00:00Z" + }, + "min_self_delegation": "1" + }, + { + "operator_address": "cosmosvaloper1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzmvtaaa", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "uExZyjNLtr2+FFIhNDAMcQ8+yTrqE7ygYTsI7khkA5Y=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "1348298958808", + "delegator_shares": "1348298958808.000000000000000000", + "description": { + "moniker": "Cosmostation", + "identity": "AE4C403A6E7AA1AC", + "website": "https://www.cosmostation.io", + "security_contact": "admin@stamper.network", + "details": "Cosmostation validator node. Delegate your tokens and Start Earning Staking Rewards" + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.050000000000000000", + "max_rate": "1.000000000000000000", + "max_change_rate": "0.200000000000000000" + }, + "update_time": "2021-10-01T15:06:38.821314287Z" + }, + "min_self_delegation": "1" + } + ] + } +} +``` + +#### Parameters + +The `Parameters` REST endpoint queries the staking parameters. + +```bash +/cosmos/staking/v1beta1/params +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/params" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "params": { + "unbonding_time": "2419200s", + "max_validators": 100, + "max_entries": 7, + "historical_entries": 10000, + "bond_denom": "stake" + } +} +``` + +#### Pool + +The `Pool` REST endpoint queries the pool information. + +```bash +/cosmos/staking/v1beta1/pool +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/pool" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "pool": { + "not_bonded_tokens": "432805737458", + "bonded_tokens": "15783637712645" + } +} +``` + +#### Validators + +The `Validators` REST endpoint queries all validators that match the given status. + +```bash +/cosmos/staking/v1beta1/validators +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/validators" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "validators": [ + { + "operator_address": "cosmosvaloper1q3jsx9dpfhtyqqgetwpe5tmk8f0ms5qywje8tw", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "N7BPyek2aKuNZ0N/8YsrqSDhGZmgVaYUBuddY8pwKaE=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "383301887799", + "delegator_shares": "383301887799.000000000000000000", + "description": { + "moniker": "SmartNodes", + "identity": "D372724899D1EDC8", + "website": "https://smartnodes.co", + "security_contact": "", + "details": "Earn Rewards with Crypto Staking & Node Deployment" + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.050000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.100000000000000000" + }, + "update_time": "2021-10-01T15:51:31.596618510Z" + }, + "min_self_delegation": "1" + }, + { + "operator_address": "cosmosvaloper1q5ku90atkhktze83j9xjaks2p7uruag5zp6wt7", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "GDNpuKDmCg9GnhnsiU4fCWktuGUemjNfvpCZiqoRIYA=" + }, + "jailed": false, + "status": "BOND_STATUS_UNBONDING", + "tokens": "1017819654", + "delegator_shares": "1017819654.000000000000000000", + "description": { + "moniker": "Noderunners", + "identity": "812E82D12FEA3493", + "website": "http://noderunners.biz", + "security_contact": "info@noderunners.biz", + "details": "Noderunners is a professional validator in POS networks. We have a huge node running experience, reliable soft and hardware. Our commissions are always low, our support to delegators is always full. Stake with us and start receiving your cosmos rewards now!" + }, + "unbonding_height": "147302", + "unbonding_time": "2021-11-08T22:58:53.718662452Z", + "commission": { + "commission_rates": { + "rate": "0.050000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.100000000000000000" + }, + "update_time": "2021-10-04T18:02:21.446645619Z" + }, + "min_self_delegation": "1" + } + ], + "pagination": { + "next_key": "FONDBFkE4tEEf7yxWWKOD49jC2NK", + "total": "2" + } +} +``` + +#### Validator + +The `Validator` REST endpoint queries validator information for given validator address. + +```bash +/cosmos/staking/v1beta1/validators/{validatorAddr} +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "validator": { + "operator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "consensus_pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc=" + }, + "jailed": false, + "status": "BOND_STATUS_BONDED", + "tokens": "33027900000", + "delegator_shares": "33027900000.000000000000000000", + "description": { + "moniker": "Witval", + "identity": "51468B615127273A", + "website": "", + "security_contact": "", + "details": "Witval is the validator arm from Vitwit. Vitwit is into software consulting and services business since 2015. We are working closely with Cosmos ecosystem since 2018. We are also building tools for the ecosystem, Aneka is our explorer for the cosmos ecosystem." + }, + "unbonding_height": "0", + "unbonding_time": "1970-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0.050000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.020000000000000000" + }, + "update_time": "2021-10-01T19:24:52.663191049Z" + }, + "min_self_delegation": "1" + } +} +``` + +#### ValidatorDelegations + +The `ValidatorDelegations` REST endpoint queries delegate information for given validator. + +```bash +/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q/delegations" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "delegation_responses": [ + { + "delegation": { + "delegator_address": "cosmos190g5j8aszqhvtg7cprmev8xcxs6csra7xnk3n3", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "31000000000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "31000000000" + } + }, + { + "delegation": { + "delegator_address": "cosmos1ddle9tczl87gsvmeva3c48nenyng4n56qwq4ee", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "628470000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "628470000" + } + }, + { + "delegation": { + "delegator_address": "cosmos10fdvkczl76m040smd33lh9xn9j0cf26kk4s2nw", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "838120000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "838120000" + } + }, + { + "delegation": { + "delegator_address": "cosmos1n8f5fknsv2yt7a8u6nrx30zqy7lu9jfm0t5lq8", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "500000000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "500000000" + } + }, + { + "delegation": { + "delegator_address": "cosmos16msryt3fqlxtvsy8u5ay7wv2p8mglfg9hrek2e", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "61310000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "61310000" + } + } + ], + "pagination": { + "next_key": null, + "total": "5" + } +} +``` + +#### Delegation + +The `Delegation` REST endpoint queries delegate information for given validator delegator pair. + +```bash +/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations/{delegatorAddr} +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q/delegations/cosmos1n8f5fknsv2yt7a8u6nrx30zqy7lu9jfm0t5lq8" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "delegation_response": { + "delegation": { + "delegator_address": "cosmos1n8f5fknsv2yt7a8u6nrx30zqy7lu9jfm0t5lq8", + "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", + "shares": "500000000.000000000000000000" + }, + "balance": { + "denom": "stake", + "amount": "500000000" + } + } +} +``` + +#### UnbondingDelegation + +The `UnbondingDelegation` REST endpoint queries unbonding information for given validator delegator pair. + +```bash +/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations/{delegatorAddr}/unbonding_delegation +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu/delegations/cosmos1ze2ye5u5k3qdlexvt2e0nn0508p04094ya0qpm/unbonding_delegation" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "unbond": { + "delegator_address": "cosmos1ze2ye5u5k3qdlexvt2e0nn0508p04094ya0qpm", + "validator_address": "cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu", + "entries": [ + { + "creation_height": "153687", + "completion_time": "2021-11-09T09:41:18.352401903Z", + "initial_balance": "525111", + "balance": "525111" + } + ] + } +} +``` + +#### ValidatorUnbondingDelegations + +The `ValidatorUnbondingDelegations` REST endpoint queries unbonding delegations of a validator. + +```bash +/cosmos/staking/v1beta1/validators/{validatorAddr}/unbonding_delegations +``` + +Example: + +```bash +curl -X GET \ +"http://localhost:1317/cosmos/staking/v1beta1/validators/cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu/unbonding_delegations" \ +-H "accept: application/json" +``` + +Example Output: + +```bash +{ + "unbonding_responses": [ + { + "delegator_address": "cosmos1q9snn84jfrd9ge8t46kdcggpe58dua82vnj7uy", + "validator_address": "cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu", + "entries": [ + { + "creation_height": "90998", + "completion_time": "2021-11-05T00:14:37.005841058Z", + "initial_balance": "24000000", + "balance": "24000000" + } + ] + }, + { + "delegator_address": "cosmos1qf36e6wmq9h4twhdvs6pyq9qcaeu7ye0s3dqq2", + "validator_address": "cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu", + "entries": [ + { + "creation_height": "47478", + "completion_time": "2021-11-01T22:47:26.714116854Z", + "initial_balance": "8000000", + "balance": "8000000" + } + ] + } + ], + "pagination": { + "next_key": null, + "total": "2" + } +} +``` diff --git a/docs/sdk/v0.53/module-reference/upgrade.mdx b/docs/sdk/v0.53/module-reference/upgrade.mdx new file mode 100644 index 00000000..2d8e8ae5 --- /dev/null +++ b/docs/sdk/v0.53/module-reference/upgrade.mdx @@ -0,0 +1,612 @@ +--- +title: "`x/upgrade`" + +--- + +--- + +--- + +## Abstract + +`x/upgrade` is an implementation of a Cosmos SDK module that facilitates smoothly +upgrading a live Cosmos chain to a new (breaking) software version. It accomplishes this by +providing a `PreBlocker` hook that prevents the blockchain state machine from +proceeding once a pre-defined upgrade block height has been reached. + +The module does not prescribe anything regarding how governance decides to do an +upgrade, but just the mechanism for coordinating the upgrade safely. Without software +support for upgrades, upgrading a live chain is risky because all of the validators +need to pause their state machines at exactly the same point in the process. If +this is not done correctly, there can be state inconsistencies which are hard to +recover from. + +* [Concepts](#concepts) +* [State](#state) +* [Events](#events) +* [Client](#client) + * [CLI](#cli) + * [REST](#rest) + * [gRPC](#grpc) +* [Resources](#resources) + +## Concepts + +### Plan + +The `x/upgrade` module defines a `Plan` type in which a live upgrade is scheduled +to occur. A `Plan` can be scheduled at a specific block height. +A `Plan` is created once a (frozen) release candidate along with an appropriate upgrade +`Handler` (see below) is agreed upon, where the `Name` of a `Plan` corresponds to a +specific `Handler`. Typically, a `Plan` is created through a governance proposal +process, where if voted upon and passed, will be scheduled. The `Info` of a `Plan` +may contain various metadata about the upgrade, typically application specific +upgrade info to be included on-chain such as a git commit that validators could +automatically upgrade to. + +```go +type Plan struct { + Name string + Height int64 + Info string +} +``` + +#### Sidecar Process + +If an operator running the application binary also runs a sidecar process to assist +in the automatic download and upgrade of a binary, the `Info` allows this process to +be seamless. This tool is [Cosmovisor](https://github.com/cosmos/cosmos-sdk/tree/main/tools/cosmovisor#readme). + +### Handler + +The `x/upgrade` module facilitates upgrading from major version X to major version Y. To +accomplish this, node operators must first upgrade their current binary to a new +binary that has a corresponding `Handler` for the new version Y. It is assumed that +this version has fully been tested and approved by the community at large. This +`Handler` defines what state migrations need to occur before the new binary Y +can successfully run the chain. Naturally, this `Handler` is application specific +and not defined on a per-module basis. Registering a `Handler` is done via +`Keeper#SetUpgradeHandler` in the application. + +```go +type UpgradeHandler func(Context, Plan, VersionMap) (VersionMap, error) +``` + +During each `EndBlock` execution, the `x/upgrade` module checks if there exists a +`Plan` that should execute (is scheduled at that height). If so, the corresponding +`Handler` is executed. If the `Plan` is expected to execute but no `Handler` is registered +or if the binary was upgraded too early, the node will gracefully panic and exit. + +### StoreLoader + +The `x/upgrade` module also facilitates store migrations as part of the upgrade. The +`StoreLoader` sets the migrations that need to occur before the new binary can +successfully run the chain. This `StoreLoader` is also application specific and +not defined on a per-module basis. Registering this `StoreLoader` is done via +`app#SetStoreLoader` in the application. + +```go +func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades) baseapp.StoreLoader +``` + +If there's a planned upgrade and the upgrade height is reached, the old binary writes `Plan` to the disk before panicking. + +This information is critical to ensure the `StoreUpgrades` happens smoothly at correct height and +expected upgrade. It eliminiates the chances for the new binary to execute `StoreUpgrades` multiple +times everytime on restart. Also if there are multiple upgrades planned on same height, the `Name` +will ensure these `StoreUpgrades` takes place only in planned upgrade handler. + +### Proposal + +Typically, a `Plan` is proposed and submitted through governance via a proposal +containing a `MsgSoftwareUpgrade` message. +This proposal prescribes to the standard governance process. If the proposal passes, +the `Plan`, which targets a specific `Handler`, is persisted and scheduled. The +upgrade can be delayed or hastened by updating the `Plan.Height` in a new proposal. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/upgrade/v1beta1/tx.proto#L29-L41 +``` + +#### Cancelling Upgrade Proposals + +Upgrade proposals can be cancelled. There exists a gov-enabled `MsgCancelUpgrade` +message type, which can be embedded in a proposal, voted on and, if passed, will +remove the scheduled upgrade `Plan`. +Of course this requires that the upgrade was known to be a bad idea well before the +upgrade itself, to allow time for a vote. + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/upgrade/v1beta1/tx.proto#L48-L57 +``` + +If such a possibility is desired, the upgrade height is to be +`2 * (VotingPeriod + DepositPeriod) + (SafetyDelta)` from the beginning of the +upgrade proposal. The `SafetyDelta` is the time available from the success of an +upgrade proposal and the realization it was a bad idea (due to external social consensus). + +A `MsgCancelUpgrade` proposal can also be made while the original +`MsgSoftwareUpgrade` proposal is still being voted upon, as long as the `VotingPeriod` +ends after the `MsgSoftwareUpgrade` proposal. + +## State + +The internal state of the `x/upgrade` module is relatively minimal and simple. The +state contains the currently active upgrade `Plan` (if one exists) by key +`0x0` and if a `Plan` is marked as "done" by key `0x1`. The state +contains the consensus versions of all app modules in the application. The versions +are stored as big endian `uint64`, and can be accessed with prefix `0x2` appended +by the corresponding module name of type `string`. The state maintains a +`Protocol Version` which can be accessed by key `0x3`. + +* Plan: `0x0 -> Plan` +* Done: `0x1 | byte(plan name) -> BigEndian(Block Height)` +* ConsensusVersion: `0x2 | byte(module name) -> BigEndian(Module Consensus Version)` +* ProtocolVersion: `0x3 -> BigEndian(Protocol Version)` + +The `x/upgrade` module contains no genesis state. + +## Events + +The `x/upgrade` does not emit any events by itself. Any and all proposal related +events are emitted through the `x/gov` module. + +## Client + +### CLI + +A user can query and interact with the `upgrade` module using the CLI. + +#### Query + +The `query` commands allow users to query `upgrade` state. + +```bash +simd query upgrade --help +``` + +##### applied + +The `applied` command allows users to query the block header for height at which a completed upgrade was applied. + +```bash +simd query upgrade applied [upgrade-name] [flags] +``` + +If upgrade-name was previously executed on the chain, this returns the header for the block at which it was applied. +This helps a client determine which binary was valid over a given range of blocks, as well as more context to understand past migrations. + +Example: + +```bash +simd query upgrade applied "test-upgrade" +``` + +Example Output: + +```bash +"block_id": { + "hash": "A769136351786B9034A5F196DC53F7E50FCEB53B48FA0786E1BFC45A0BB646B5", + "parts": { + "total": 1, + "hash": "B13CBD23011C7480E6F11BE4594EE316548648E6A666B3575409F8F16EC6939E" + } + }, + "block_size": "7213", + "header": { + "version": { + "block": "11" + }, + "chain_id": "testnet-2", + "height": "455200", + "time": "2021-04-10T04:37:57.085493838Z", + "last_block_id": { + "hash": "0E8AD9309C2DC411DF98217AF59E044A0E1CCEAE7C0338417A70338DF50F4783", + "parts": { + "total": 1, + "hash": "8FE572A48CD10BC2CBB02653CA04CA247A0F6830FF19DC972F64D339A355E77D" + } + }, + "last_commit_hash": "DE890239416A19E6164C2076B837CC1D7F7822FC214F305616725F11D2533140", + "data_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", + "validators_hash": "A31047ADE54AE9072EE2A12FF260A8990BA4C39F903EAF5636B50D58DBA72582", + "next_validators_hash": "A31047ADE54AE9072EE2A12FF260A8990BA4C39F903EAF5636B50D58DBA72582", + "consensus_hash": "048091BC7DDC283F77BFBF91D73C44DA58C3DF8A9CBC867405D8B7F3DAADA22F", + "app_hash": "28ECC486AFC332BA6CC976706DBDE87E7D32441375E3F10FD084CD4BAF0DA021", + "last_results_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", + "evidence_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", + "proposer_address": "2ABC4854B1A1C5AA8403C4EA853A81ACA901CC76" + }, + "num_txs": "0" +} +``` + +##### module versions + +The `module_versions` command gets a list of module names and their respective consensus versions. + +Following the command with a specific module name will return only +that module's information. + +```bash +simd query upgrade module_versions [optional module_name] [flags] +``` + +Example: + +```bash +simd query upgrade module_versions +``` + +Example Output: + +```bash +module_versions: +- name: auth + version: "2" +- name: authz + version: "1" +- name: bank + version: "2" +- name: distribution + version: "2" +- name: evidence + version: "1" +- name: feegrant + version: "1" +- name: genutil + version: "1" +- name: gov + version: "2" +- name: ibc + version: "2" +- name: mint + version: "1" +- name: params + version: "1" +- name: slashing + version: "2" +- name: staking + version: "2" +- name: transfer + version: "1" +- name: upgrade + version: "1" +- name: vesting + version: "1" +``` + +Example: + +```bash +regen query upgrade module_versions ibc +``` + +Example Output: + +```bash +module_versions: +- name: ibc + version: "2" +``` + +##### plan + +The `plan` command gets the currently scheduled upgrade plan, if one exists. + +```bash +regen query upgrade plan [flags] +``` + +Example: + +```bash +simd query upgrade plan +``` + +Example Output: + +```bash +height: "130" +info: "" +name: test-upgrade +time: "0001-01-01T00:00:00Z" +upgraded_client_state: null +``` + +#### Transactions + +The upgrade module supports the following transactions: + +* `software-proposal` - submits an upgrade proposal: + +```bash +simd tx upgrade software-upgrade v2 --title="Test Proposal" --summary="testing" --deposit="100000000stake" --upgrade-height 1000000 \ +--upgrade-info '{ "binaries": { "linux/amd64":"https://example.com/simd.zip?checksum=sha256:aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f" } }' --from cosmos1.. +``` + +* `cancel-software-upgrade` - cancels a previously submitted upgrade proposal: + +```bash +simd tx upgrade cancel-software-upgrade --title="Test Proposal" --summary="testing" --deposit="100000000stake" --from cosmos1.. +``` + +### REST + +A user can query the `upgrade` module using REST endpoints. + +#### Applied Plan + +`AppliedPlan` queries a previously applied upgrade plan by its name. + +```bash +/cosmos/upgrade/v1beta1/applied_plan/{name} +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/upgrade/v1beta1/applied_plan/v2.0-upgrade" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "height": "30" +} +``` + +#### Current Plan + +`CurrentPlan` queries the current upgrade plan. + +```bash +/cosmos/upgrade/v1beta1/current_plan +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/upgrade/v1beta1/current_plan" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "plan": "v2.1-upgrade" +} +``` + +#### Module versions + +`ModuleVersions` queries the list of module versions from state. + +```bash +/cosmos/upgrade/v1beta1/module_versions +``` + +Example: + +```bash +curl -X GET "http://localhost:1317/cosmos/upgrade/v1beta1/module_versions" -H "accept: application/json" +``` + +Example Output: + +```bash +{ + "module_versions": [ + { + "name": "auth", + "version": "2" + }, + { + "name": "authz", + "version": "1" + }, + { + "name": "bank", + "version": "2" + }, + { + "name": "distribution", + "version": "2" + }, + { + "name": "evidence", + "version": "1" + }, + { + "name": "feegrant", + "version": "1" + }, + { + "name": "genutil", + "version": "1" + }, + { + "name": "gov", + "version": "2" + }, + { + "name": "ibc", + "version": "2" + }, + { + "name": "mint", + "version": "1" + }, + { + "name": "params", + "version": "1" + }, + { + "name": "slashing", + "version": "2" + }, + { + "name": "staking", + "version": "2" + }, + { + "name": "transfer", + "version": "1" + }, + { + "name": "upgrade", + "version": "1" + }, + { + "name": "vesting", + "version": "1" + } + ] +} +``` + +### gRPC + +A user can query the `upgrade` module using gRPC endpoints. + +#### Applied Plan + +`AppliedPlan` queries a previously applied upgrade plan by its name. + +```bash +cosmos.upgrade.v1beta1.Query/AppliedPlan +``` + +Example: + +```bash +grpcurl -plaintext \ + -d '{"name":"v2.0-upgrade"}' \ + localhost:9090 \ + cosmos.upgrade.v1beta1.Query/AppliedPlan +``` + +Example Output: + +```bash +{ + "height": "30" +} +``` + +#### Current Plan + +`CurrentPlan` queries the current upgrade plan. + +```bash +cosmos.upgrade.v1beta1.Query/CurrentPlan +``` + +Example: + +```bash +grpcurl -plaintext localhost:9090 cosmos.slashing.v1beta1.Query/CurrentPlan +``` + +Example Output: + +```bash +{ + "plan": "v2.1-upgrade" +} +``` + +#### Module versions + +`ModuleVersions` queries the list of module versions from state. + +```bash +cosmos.upgrade.v1beta1.Query/ModuleVersions +``` + +Example: + +```bash +grpcurl -plaintext localhost:9090 cosmos.slashing.v1beta1.Query/ModuleVersions +``` + +Example Output: + +```bash +{ + "module_versions": [ + { + "name": "auth", + "version": "2" + }, + { + "name": "authz", + "version": "1" + }, + { + "name": "bank", + "version": "2" + }, + { + "name": "distribution", + "version": "2" + }, + { + "name": "evidence", + "version": "1" + }, + { + "name": "feegrant", + "version": "1" + }, + { + "name": "genutil", + "version": "1" + }, + { + "name": "gov", + "version": "2" + }, + { + "name": "ibc", + "version": "2" + }, + { + "name": "mint", + "version": "1" + }, + { + "name": "params", + "version": "1" + }, + { + "name": "slashing", + "version": "2" + }, + { + "name": "staking", + "version": "2" + }, + { + "name": "transfer", + "version": "1" + }, + { + "name": "upgrade", + "version": "1" + }, + { + "name": "vesting", + "version": "1" + } + ] +} +``` + +## Resources + +A list of (external) resources to learn more about the `x/upgrade` module. + +* [Cosmos Dev Series: Cosmos Blockchain Upgrade](https://medium.com/web3-surfers/cosmos-dev-series-cosmos-sdk-based-blockchain-upgrade-b5e99181554c) - The blog post that explains how software upgrades work in detail. diff --git a/docs/sdk/v0.53/user/run-node/interact-node.mdx b/docs/sdk/v0.53/node-operations/interact-node.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/interact-node.mdx rename to docs/sdk/v0.53/node-operations/interact-node.mdx diff --git a/docs/sdk/v0.53/user/run-node/keyring.mdx b/docs/sdk/v0.53/node-operations/keyring.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/keyring.mdx rename to docs/sdk/v0.53/node-operations/keyring.mdx diff --git a/docs/sdk/v0.53/user/run-node/run-node.mdx b/docs/sdk/v0.53/node-operations/run-node.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/run-node.mdx rename to docs/sdk/v0.53/node-operations/run-node.mdx diff --git a/docs/sdk/v0.53/user/run-node/run-production.mdx b/docs/sdk/v0.53/node-operations/run-production.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/run-production.mdx rename to docs/sdk/v0.53/node-operations/run-production.mdx diff --git a/docs/sdk/v0.53/user/run-node/run-testnet.mdx b/docs/sdk/v0.53/node-operations/run-testnet.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/run-testnet.mdx rename to docs/sdk/v0.53/node-operations/run-testnet.mdx diff --git a/docs/sdk/v0.53/user/run-node/txs.mdx b/docs/sdk/v0.53/node-operations/txs.mdx similarity index 100% rename from docs/sdk/v0.53/user/run-node/txs.mdx rename to docs/sdk/v0.53/node-operations/txs.mdx diff --git a/docs/sdk/v0.53/user.mdx b/docs/sdk/v0.53/node-operations/user.mdx similarity index 100% rename from docs/sdk/v0.53/user.mdx rename to docs/sdk/v0.53/node-operations/user.mdx diff --git a/docs/sdk/v0.53/overview.mdx b/docs/sdk/v0.53/overview.mdx new file mode 100644 index 00000000..578ff391 --- /dev/null +++ b/docs/sdk/v0.53/overview.mdx @@ -0,0 +1,98 @@ +--- +title: "Overview" +description: "The Cosmos SDK is an open-source framework for building multi-asset public Proof-of-Stake (PoS) blockchains and permissioned Proof-of-Authority (PoA) blockchains. Build application-specific blockchains with modular architecture and native interoperability." +mode: "wide" +--- + +import { Card, CardGroup } from '@mintlify/components' + + + + Learn the fundamentals of the Cosmos SDK architecture and application-specific blockchains + + + Start building your blockchain application with step-by-step guides + + + Explore pre-built modules for staking, governance, token issuance, and more + + + Enable cross-chain communication with the Inter-Blockchain Communication protocol + + + +## What is the Cosmos SDK + +The [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is a framework that facilitates the development of secure state machines on top of CometBFT. At its core, the SDK is a boilerplate implementation of the ABCI in Go. It comes with a `multistore` to persist data and a `router` to handle transactions. + +The SDK design is based on the following principles: + +- **Composability**: Build custom blockchains by composing different modules +- **Capabilities**: Object-capability model for secure inter-module interactions +- **Flexibility**: Choose consensus engines, customize modules, and configure parameters +- **Sovereignty**: Full control over your blockchain's governance and economics + +## Key Features + + + + Plug-and-play modules for common blockchain functionality + + + Support for CometBFT, Rollkit, and other consensus engines + + + Built-in IBC support for cross-chain communication + + + Deterministic state transitions with ABCI integration + + + CLI scaffolding, testing frameworks, and simulation tools + + + Battle-tested in production by Cosmos Hub, Osmosis, and many others + + + +## Quick Start + +Get started with the Cosmos SDK by exploring these essential resources: + + + + Set up your development environment and build your first app + + + Learn through hands-on examples and guided tutorials + + + Create custom modules for your blockchain + + + Explore the complete API documentation + + + +## Architecture Overview + +The Cosmos SDK follows a modular architecture where functionality is organized into discrete modules: + +- **Core Modules**: Essential modules like `auth`, `bank`, `staking`, and `gov` +- **IBC Modules**: Enable cross-chain communication and asset transfers +- **Custom Modules**: Build your own modules for application-specific logic +- **Keeper Pattern**: Encapsulate module state and expose controlled interfaces + +Learn more about the [SDK architecture](/docs/sdk/v0.53/core-concepts/baseapp) and [module system](/docs/sdk/v0.53/building-modules/intro). + +## Version Information + +This documentation covers Cosmos SDK v0.53, which includes: + +- Enhanced ABCI++ integration for vote extensions and optimistic execution +- Improved module interfaces and dependency injection +- AutoCLI for automatic CLI generation +- Circuit breaker for runtime safety +- Optimized state management and performance improvements + +For migration guides and breaking changes, see the [Release Notes](/docs/sdk/v0.53/changelog/release-notes). \ No newline at end of file diff --git a/docs/sdk/v0.53/release-notes.mdx b/docs/sdk/v0.53/release-notes.mdx new file mode 100644 index 00000000..c6aa88c4 --- /dev/null +++ b/docs/sdk/v0.53/release-notes.mdx @@ -0,0 +1,39 @@ +--- +title: "Release Notes" +description: "Cosmos SDK v0.53 release notes and changelog" +--- + +## Overview + +This page provides release notes and changelog information for Cosmos SDK v0.53. + + +For the most up-to-date and detailed changelog, please refer to the official Cosmos SDK repository. + + +## Resources + +- [Full Changelog on GitHub](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md) +- [Release Notes](https://github.com/cosmos/cosmos-sdk/releases?q=v0.53&expanded=true) +- [Migration Guide](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/UPGRADING.md) + +## Major Changes in v0.53 + +### Key Features +- Enhanced ABCI 2.0 support with vote extensions +- Improved module system with better dependency injection +- Optimized state management and store improvements +- Enhanced testing framework with better simulation tools + +### Breaking Changes +- Module interfaces have been updated +- Changes to keeper patterns +- Updated transaction handling + +### Module Updates +- **x/auth**: Enhanced account management +- **x/bank**: Improved token handling +- **x/staking**: Optimized delegation logic +- **x/gov**: Enhanced governance features + +For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md). \ No newline at end of file diff --git a/docs/sdk/v0.53/runtime-abci/checktx.mdx b/docs/sdk/v0.53/runtime-abci/checktx.mdx new file mode 100644 index 00000000..9cfed380 --- /dev/null +++ b/docs/sdk/v0.53/runtime-abci/checktx.mdx @@ -0,0 +1,53 @@ +--- +title: "CheckTx" +description: "CheckTx is called by the `BaseApp` when comet receives a transaction from a client, over the p2p network or RPC. The CheckTx method is responsible for..." +--- + +CheckTx is called by the `BaseApp` when comet receives a transaction from a client, over the p2p network or RPC. The CheckTx method is responsible for validating the transaction and returning an error if the transaction is invalid. + +```mermaid +graph TD + subgraph SDK[Cosmos SDK] + B[Baseapp] + A[AnteHandlers] + B <-->|Validate TX| A + end + C[CometBFT] <-->|CheckTx|SDK + U((User)) -->|Submit TX| C + N[P2P] -->|Receive TX| C +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/31c604762a434c7b676b6a89897ecbd7c4653a23/baseapp/abci.go#L350-L390 +``` + +## CheckTx Handler + +`CheckTxHandler` allows users to extend the logic of `CheckTx`. `CheckTxHandler` is called by passing context and the transaction bytes received through ABCI. It is required that the handler returns deterministic results given the same transaction bytes. + + +we return the raw decoded transaction here to avoid decoding it twice. + + +```go +type CheckTxHandler func(ctx sdk.Context, tx []byte) (Tx, error) +``` + +Setting a custom `CheckTxHandler` is optional. It can be done from your app.go file: + +```go +func NewSimApp( + logger log.Logger, + db corestore.KVStoreWithBatch, + traceStore io.Writer, + loadLatest bool, + appOpts servertypes.AppOptions, + baseAppOptions ...func(*baseapp.BaseApp), +) *SimApp { + ... + // Create ChecktxHandler + checktxHandler := abci.NewCustomCheckTxHandler(...) + app.SetCheckTxHandler(checktxHandler) + ... +} +``` diff --git a/docs/sdk/v0.53/runtime-abci/introduction.mdx b/docs/sdk/v0.53/runtime-abci/introduction.mdx new file mode 100644 index 00000000..66c3d712 --- /dev/null +++ b/docs/sdk/v0.53/runtime-abci/introduction.mdx @@ -0,0 +1,52 @@ +--- +title: "Introduction" +description: "ABCI, Application Blockchain Interface is the interface between CometBFT and the application. More information about ABCI can be found [here](https://..." +--- + +## What is ABCI? + +ABCI, Application Blockchain Interface is the interface between CometBFT and the application. More information about ABCI can be found [here](https://docs.cometbft.com/v0.38/spec/abci/). CometBFT version 0.38 included a new version of ABCI (called ABCI 2.0) which added several new methods. + +The 5 methods introduced in ABCI 2.0 are: + +* `PrepareProposal` +* `ProcessProposal` +* `ExtendVote` +* `VerifyVoteExtension` +* `FinalizeBlock` + +## The Flow + +## PrepareProposal + +Based on validator voting power, CometBFT chooses a block proposer and calls `PrepareProposal` on the block proposer's application (Cosmos SDK). The selected block proposer is responsible for collecting outstanding transactions from the mempool, adhering to the application's specifications. The application can enforce custom transaction ordering and incorporate additional transactions, potentially generated from vote extensions in the previous block. + +To perform this manipulation on the application side, a custom handler must be implemented. By default, the Cosmos SDK provides `PrepareProposalHandler`, used in conjunction with an application specific mempool. A custom handler can be written by application developer, if a noop handler provided, all transactions are considered valid. + +Please note that vote extensions will only be available on the following height in which vote extensions are enabled. More information about vote extensions can be found [here](/docs/sdk/v0.53/build/abci/vote-extensions). + +After creating the proposal, the proposer returns it to CometBFT. + +PrepareProposal CAN be non-deterministic. + +## ProcessProposal + +This method allows validators to perform application-specific checks on the block proposal and is called on all validators. This is an important step in the consensus process, as it ensures that the block is valid and meets the requirements of the application. For example, validators could check that the block contains all the required transactions or that the block does not create any invalid state transitions. + +The implementation of `ProcessProposal` MUST be deterministic. + +## ExtendVote and VerifyVoteExtensions + +These methods allow applications to extend the voting process by requiring validators to perform additional actions beyond simply validating blocks. + +If vote extensions are enabled, `ExtendVote` will be called on every validator and each one will return its vote extension which is in practice a bunch of bytes. As mentioned above this data (vote extension) can only be retrieved in the next block height during `PrepareProposal`. Additionally, this data can be arbitrary, but in the provided tutorials, it serves as an oracle or proof of transactions in the mempool. Essentially, vote extensions are processed and injected as transactions. Examples of use-cases for vote extensions include prices for a price oracle or encryption shares for an encrypted transaction mempool. `ExtendVote` CAN be non-deterministic. + +`VerifyVoteExtensions` is performed on every validator multiple times in order to verify other validators' vote extensions. This check is submitted to validate the integrity and validity of the vote extensions preventing malicious or invalid vote extensions. + +Additionally, applications must keep the vote extension data concise as it can degrade the performance of their chain, see testing results [here](https://docs.cometbft.com/v0.38/qa/cometbft-qa-38#vote-extensions-testbed). + +`VerifyVoteExtensions` MUST be deterministic. + +## FinalizeBlock + +`FinalizeBlock` is then called and is responsible for updating the state of the blockchain and making the block available to users. diff --git a/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx b/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx new file mode 100644 index 00000000..794d6f3e --- /dev/null +++ b/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx @@ -0,0 +1,48 @@ +--- +title: "Prepare Proposal" +description: "`PrepareProposal` handles construction of the block, meaning that when a proposer" +--- + +`PrepareProposal` handles construction of the block, meaning that when a proposer +is preparing to propose a block, it requests the application to evaluate a +`RequestPrepareProposal`, which contains a series of transactions from CometBFT's +mempool. At this point, the application has complete control over the proposal. +It can modify, delete, and inject transactions from its own app-side mempool into +the proposal or even ignore all the transactions altogether. What the application +does with the transactions provided to it by `RequestPrepareProposal` has no +effect on CometBFT's mempool. + +Note, that the application defines the semantics of the `PrepareProposal` and it +MAY be non-deterministic and is only executed by the current block proposer. + +Now, reading mempool twice in the previous sentence is confusing, lets break it down. +CometBFT has a mempool that handles gossiping transactions to other nodes +in the network. The order of these transactions is determined by CometBFT's mempool, +using FIFO as the sole ordering mechanism. It's worth noting that the priority mempool +in Comet was removed or deprecated. +However, since the application is able to fully inspect +all transactions, it can provide greater control over transaction ordering. +Allowing the application to handle ordering enables the application to define how +it would like the block constructed. + +The Cosmos SDK defines the `DefaultProposalHandler` type, which provides applications with +`PrepareProposal` and `ProcessProposal` handlers. If you decide to implement your +own `PrepareProposal` handler, you must ensure that the transactions +selected DO NOT exceed the maximum block gas (if set) and the maximum bytes provided +by `req.MaxBytes`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci_utils.go +``` + +This default implementation can be overridden by the application developer in +favor of a custom implementation in [`app_di.go`](../building-apps/01-app-go-di.md): + +```go +prepareOpt := func(app *baseapp.BaseApp) { + abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) + app.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) +} + +baseAppOptions = append(baseAppOptions, prepareOpt) +``` diff --git a/docs/sdk/v0.53/runtime-abci/process-proposal.mdx b/docs/sdk/v0.53/runtime-abci/process-proposal.mdx new file mode 100644 index 00000000..a6297a30 --- /dev/null +++ b/docs/sdk/v0.53/runtime-abci/process-proposal.mdx @@ -0,0 +1,35 @@ +--- +title: "Process Proposal" +description: "`ProcessProposal` handles the validation of a proposal from `PrepareProposal`," +--- + +`ProcessProposal` handles the validation of a proposal from `PrepareProposal`, +which also includes a block header. After a block has been proposed, +the other validators have the right to accept or reject that block. The validator in the +default implementation of `PrepareProposal` runs basic validity checks on each +transaction. + +Note, `ProcessProposal` MUST be deterministic. Non-deterministic behaviors will cause apphash mismatches. +This means if `ProcessProposal` panics or fails and we reject, all honest validator +processes should reject (i.e., prevote nil). If so, CometBFT will start a new round with a new block proposal and the same cycle will happen with `PrepareProposal` +and `ProcessProposal` for the new proposal. + +Here is the implementation of the default implementation: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci_utils.go#L219-L226 +``` + +Like `PrepareProposal`, this implementation is the default and can be modified by +the application developer in [`app_di.go`](../building-apps/01-app-go-di.md). If you decide to implement +your own `ProcessProposal` handler, you must ensure that the transactions +provided in the proposal DO NOT exceed the maximum block gas and `maxtxbytes` (if set). + +```go +processOpt := func(app *baseapp.BaseApp) { + abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) + app.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) +} + +baseAppOptions = append(baseAppOptions, processOpt) +``` diff --git a/docs/sdk/v0.53/learn/advanced/store.mdx b/docs/sdk/v0.53/state-store/store.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/store.mdx rename to docs/sdk/v0.53/state-store/store.mdx diff --git a/docs/sdk/v0.53/learn/advanced/simulation.mdx b/docs/sdk/v0.53/testing-simulation/simulation.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/simulation.mdx rename to docs/sdk/v0.53/testing-simulation/simulation.mdx diff --git a/docs/sdk/v0.53/testing-simulation/simulator.mdx b/docs/sdk/v0.53/testing-simulation/simulator.mdx new file mode 100644 index 00000000..abc39e75 --- /dev/null +++ b/docs/sdk/v0.53/testing-simulation/simulator.mdx @@ -0,0 +1,178 @@ +--- +title: "Module Simulation" + +--- + +--- + +--- + + +**Pre-requisite Readings** + +* [Cosmos Blockchain Simulator](../../learn/advanced/12-simulation.md) + + + +## Synopsis + +This document guides developers on integrating their custom modules with the Cosmos SDK `Simulations`. +Simulations are useful for testing edge cases in module implementations. + +* [Simulation Package](#simulation-package) +* [Simulation App Module](#simulation-app-module) +* [SimsX](#simsx) + * [Example Implementations](#example-implementations) +* [Store decoders](#store-decoders) +* [Randomized genesis](#randomized-genesis) +* [Random weighted operations](#random-weighted-operations) + * [Using Simsx](#using-simsx) +* [App Simulator manager](#app-simulator-manager) +* [Running Simulations](#running-simulations) + +## Simulation Package + +The Cosmos SDK suggests organizing your simulation related code in a `x//simulation` package. + +## Simulation App Module + +To integrate with the Cosmos SDK `SimulationManager`, app modules must implement the `AppModuleSimulation` interface. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/3c6deab626648e47de752c33dac5d06af83e3ee3/types/module/simulation.go#L16-L27 +``` + +See an example implementation of these methods from `x/distribution` [here](https://github.com/cosmos/cosmos-sdk/blob/b55b9e14fb792cc8075effb373be9d26327fddea/x/distribution/module.go#L170-L194). + +## SimsX + +Cosmos SDK v0.53.0 introduced a new package, `simsx`, providing improved DevX for writing simulation code. + +It exposes the following extension interfaces that modules may implement to integrate with the new `simsx` runner. +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/testutil/simsx/runner.go#L223-L234 +``` + +These methods allow constructing randomized messages and/or proposal messages. + + +Note that modules should **not** implement both `HasWeightedOperationsX` and `HasWeightedOperationsXWithProposals`. +See the runner code [here](https://github.com/cosmos/cosmos-sdk/blob/main/testutil/simsx/runner.go#L330-L339) for details + +If the module does **not** have message handlers or governance proposal handlers, these interface methods do **not** need to be implemented. + + +### Example Implementations + +- `HasWeightedOperationsXWithProposals`: [x/gov](https://github.com/cosmos/cosmos-sdk/blob/main/x/gov/module.go#L242-L261) +- `HasWeightedOperationsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L199-L203) +- `HasProposalMsgsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L194-L197) + +## Store decoders + +Registering the store decoders is required for the `AppImportExport` simulation. This allows +for the key-value pairs from the stores to be decoded to their corresponding types. +In particular, it matches the key to a concrete type and then unmarshalls the value from the `KVPair` to the type provided. + +Modules using [collections](https://github.com/cosmos/cosmos-sdk/blob/main/collections/README.md) can use the `NewStoreDecoderFuncFromCollectionsSchema` function that builds the decoder for you: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L181-L184 +``` + +Modules not using collections must manually build the store decoder. +See the implementation [here](https://github.com/cosmos/cosmos-sdk/blob/main/x/distribution/simulation/decoder.go) from the distribution module for an example. + +## Randomized genesis + +The simulator tests different scenarios and values for genesis parameters. +App modules must implement a `GenerateGenesisState` method to generate the initial random `GenesisState` from a given seed. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/types/module/simulation.go#L20 +``` + +See an example from `x/auth` [here](https://github.com/cosmos/cosmos-sdk/blob/main/x/auth/module.go#L169-L172). + +Once the module's genesis parameters are generated randomly (or with the key and +values defined in a `params` file), they are marshaled to JSON format and added +to the app genesis JSON for the simulation. + +## Random weighted operations + +Operations are one of the crucial parts of the Cosmos SDK simulation. They are the transactions +(`Msg`) that are simulated with random field values. The sender of the operation +is also assigned randomly. + +Operations on the simulation are simulated using the full [transaction cycle](../../learn/advanced/01-transactions.md) of a +`ABCI` application that exposes the `BaseApp`. + +### Using Simsx + +Simsx introduces the ability to define a `MsgFactory` for each of a module's messages. + +These factories are registered in `WeightedOperationsX` and/or `ProposalMsgsX`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/x/distribution/module.go#L196-L206 +``` + +Note that the name passed in to `weights.Get` must match the name of the operation set in the `WeightedOperations`. + +For example, if the module contains an operation `op_weight_msg_set_withdraw_address`, the name passed to `weights.Get` should be `msg_set_withdraw_address`. + +See the `x/distribution` for an example of implementing message factories [here](https://github.com/cosmos/cosmos-sdk/blob/main/x/distribution/simulation/msg_factory.go) + +## App Simulator manager + +The following step is setting up the `SimulatorManager` at the app level. This +is required for the simulation test files in the next step. + +```go +type CoolApp struct { +... +sm *module.SimulationManager +} +``` + +Within the constructor of the application, construct the simulation manager using the modules from `ModuleManager` and call the `RegisterStoreDecoders` method. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/simapp/app.go#L650-L660 +``` + +Note that you may override some modules. +This is useful if the existing module configuration in the `ModuleManager` should be different in the `SimulationManager`. + +Finally, the application should expose the `SimulationManager` via the following method defined in the `Runtime` interface: + +```go +// SimulationManager implements the SimulationApp interface +func (app *SimApp) SimulationManager() *module.SimulationManager { +return app.sm +} +``` + +## Running Simulations + +To run the simulation, use the `simsx` runner. + +Call the following function from the `simsx` package to begin simulating with a default seed: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/testutil/simsx/runner.go#L69-L88 +``` + +If a custom seed is desired, tests should use `RunWithSeed`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/b55b9e14fb792cc8075effb373be9d26327fddea/testutil/simsx/runner.go#L151-L168 +``` + +These functions should be called in tests (i.e., app_test.go, app_sim_test.go, etc.) + +Example: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/main/simapp/sim_test.go#L53-L65 +``` \ No newline at end of file diff --git a/docs/sdk/v0.53/testing-simulation/testing.mdx b/docs/sdk/v0.53/testing-simulation/testing.mdx new file mode 100644 index 00000000..b1e795ab --- /dev/null +++ b/docs/sdk/v0.53/testing-simulation/testing.mdx @@ -0,0 +1,128 @@ +--- +title: "Testing" + +--- + +--- + +--- + +The Cosmos SDK contains different types of [tests](https://martinfowler.com/articles/practical-test-pyramid.html). +These tests have different goals and are used at different stages of the development cycle. +We advice, as a general rule, to use tests at all stages of the development cycle. +It is adviced, as a chain developer, to test your application and modules in a similar way than the SDK. + +The rationale behind testing can be found in [ADR-59](/docs/sdk/v0.53/build/architecture/adr-059-test-scopes). + +## Unit Tests + +Unit tests are the lowest test category of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). +All packages and modules should have unit test coverage. Modules should have their dependencies mocked: this means mocking keepers. + +The SDK uses `mockgen` to generate mocks for keepers: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/scripts/mockgen.sh#L3-L6 +``` + +You can read more about mockgen [here](https://go.uber.org/mock). + +### Example + +As an example, we will walkthrough the [keeper tests](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper_test.go) of the `x/gov` module. + +The `x/gov` module has a `Keeper` type, which requires a few external dependencies (ie. imports outside `x/gov` to work properly). + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper.go#L22-L24 +``` + +In order to only test `x/gov`, we mock the [expected keepers](/docs/sdk/v0.53/building-modules/keeper.html#type-definition) and instantiate the `Keeper` with the mocked dependencies. Note that we may need to configure the mocked dependencies to return the expected values: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/common_test.go#L68-L82 +``` + +This allows us to test the `x/gov` module without having to import other modules. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper_test.go#L3-L42 +``` + +We can test then create unit tests using the newly created `Keeper` instance. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper_test.go#L83-L107 +``` + +## Integration Tests + +Integration tests are at the second level of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). +In the SDK, we locate our integration tests under [`/tests/integrations`](https://github.com/cosmos/cosmos-sdk/tree/main/tests/integration). + +The goal of these integration tests is to test how a component interacts with other dependencies. Compared to unit tests, integration tests do not mock dependencies. Instead, they use the direct dependencies of the component. This differs as well from end-to-end tests, which test the component with a full application. + +Integration tests interact with the tested module via the defined `Msg` and `Query` services. The result of the test can be verified by checking the state of the application, by checking the emitted events or the response. It is adviced to combine two of these methods to verify the result of the test. + +The SDK provides small helpers for quickly setting up an integration tests. These helpers can be found at . + +### Example + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/a2f73a7dd37bea0ab303792c55fa1e4e1db3b898/testutil/integration/example_test.go#L30-L116 +``` + +## Deterministic and Regression tests + +Tests are written for queries in the Cosmos SDK which have `module_query_safe` Protobuf annotation. + +Each query is tested using 2 methods: + +* Use property-based testing with the [`rapid`](https://pkg.go.dev/pgregory.net/rapid@v0.5.3) library. The property that is tested is that the query response and gas consumption are the same upon 1000 query calls. +* Regression tests are written with hardcoded responses and gas, and verify they don't change upon 1000 calls and between SDK patch versions. + +Here's an example of regression tests: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/tests/integration/bank/keeper/deterministic_test.go#L143-L160 +``` + +## Simulations + +Simulations uses as well a minimal application, built with [`depinject`](../packages/01-depinject.md): + + +You can as well use the `AppConfig` `configurator` for creating an `AppConfig` [inline](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/slashing/app_test.go#L54-L62). There is no difference between those two ways, use whichever you prefer. + + +Following is an example for `x/gov/` simulations: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/simulation/operations_test.go#L415-L441 +``` + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/simulation/operations_test.go#L94-L136 +``` + +## End-to-end Tests + +End-to-end tests are at the top of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). +They must test the whole application flow, from the user perspective (for instance, CLI tests). They are located under [`/tests/e2e`](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e). + + +For that, the SDK is using `simapp` but you should use your own application (`appd`). +Here are some examples: + +* SDK E2E tests: . +* Cosmos Hub E2E tests: . +* Osmosis E2E tests: . + + +**warning** +The SDK is in the process of creating its E2E tests, as defined in [ADR-59](https://docs.cosmos.network/main/architecture/adr-059-test-scopes.html). This page will eventually be updated with better examples. + + +## Learn More + +Learn more about testing scope in [ADR-59](/docs/sdk/v0.53/architecture/adr-059-test-scopes.html). diff --git a/docs/sdk/v0.53/learn/beginner/gas-fees.mdx b/docs/sdk/v0.53/transactions-fees/gas-fees.mdx similarity index 100% rename from docs/sdk/v0.53/learn/beginner/gas-fees.mdx rename to docs/sdk/v0.53/transactions-fees/gas-fees.mdx diff --git a/docs/sdk/v0.53/learn/advanced/transactions.mdx b/docs/sdk/v0.53/transactions-fees/transactions.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/transactions.mdx rename to docs/sdk/v0.53/transactions-fees/transactions.mdx diff --git a/docs/sdk/v0.53/learn/beginner/tx-lifecycle.mdx b/docs/sdk/v0.53/transactions-fees/tx-lifecycle.mdx similarity index 100% rename from docs/sdk/v0.53/learn/beginner/tx-lifecycle.mdx rename to docs/sdk/v0.53/transactions-fees/tx-lifecycle.mdx diff --git a/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx new file mode 100644 index 00000000..d11f5db3 --- /dev/null +++ b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx @@ -0,0 +1,68 @@ +--- +title: "Upgrading Modules" + +--- + +--- + +--- + + +**Synopsis** +[In-Place Store Migrations](../../learn/advanced/15-upgrade.md) allow your modules to upgrade to new versions that include breaking changes. This document outlines how to build modules to take advantage of this functionality. + + + +**Pre-requisite Readings** + +* [In-Place Store Migration](../../learn/advanced/15-upgrade.md) + + + +## Consensus Version + +Successful upgrades of existing modules require each `AppModule` to implement the function `ConsensusVersion() uint64`. + +* The versions must be hard-coded by the module developer. +* The initial version **must** be set to 1. + +Consensus versions serve as state-breaking versions of app modules and must be incremented when the module introduces breaking changes. + +## Registering Migrations + +To register the functionality that takes place during a module upgrade, you must register which migrations you want to take place. + +Migration registration takes place in the `Configurator` using the `RegisterMigration` method. The `AppModule` reference to the configurator is in the `RegisterServices` method. + +You can register one or more migrations. If you register more than one migration script, list the migrations in increasing order and ensure there are enough migrations that lead to the desired consensus version. For example, to migrate to version 3 of a module, register separate migrations for version 1 and version 2 as shown in the following example: + +```go +func (am AppModule) RegisterServices(cfg module.Configurator) { + // --snip-- + cfg.RegisterMigration(types.ModuleName, 1, func(ctx sdk.Context) error { + // Perform in-place store migrations from ConsensusVersion 1 to 2. + }) + cfg.RegisterMigration(types.ModuleName, 2, func(ctx sdk.Context) error { + // Perform in-place store migrations from ConsensusVersion 2 to 3. + }) +} +``` + +Since these migrations are functions that need access to a Keeper's store, use a wrapper around the keepers called `Migrator` as shown in this example: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/migrations.go +``` + +## Writing Migration Scripts + +To define the functionality that takes place during an upgrade, write a migration script and place the functions in a `migrations/` directory. For example, to write migration scripts for the bank module, place the functions in `x/bank/migrations/`. Use the recommended naming convention for these functions. For example, `v2bank` is the script that migrates the package `x/bank/migrations/v2`: + +```go +// Migrating bank module from version 1 to 2 +func (m Migrator) Migrate1to2(ctx sdk.Context) error { + return v2bank.MigrateStore(ctx, m.keeper.storeKey) // v2bank is package `x/bank/migrations/v2`. +} +``` + +To see example code of changes that were implemented in a migration of balance keys, check out [migrateBalanceKeys](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/migrations/v2/store.go#L55-L76). For context, this code introduced migrations of the bank store that updated addresses to be prefixed by their length in bytes as outlined in [ADR-028](../architecture/adr-028-public-key-addresses.md). diff --git a/docs/sdk/v0.53/learn/advanced/upgrade.mdx b/docs/sdk/v0.53/upgrades-migrations/upgrade.mdx similarity index 100% rename from docs/sdk/v0.53/learn/advanced/upgrade.mdx rename to docs/sdk/v0.53/upgrades-migrations/upgrade.mdx diff --git a/scripts/versioning/README.md b/scripts/versioning/README.md index 31db04c7..a88e9c0d 100644 --- a/scripts/versioning/README.md +++ b/scripts/versioning/README.md @@ -171,25 +171,47 @@ npm run sheets #### `release-notes.js` -Standalone changelog and release notes management. +Changelog and release notes management. **Usage:** ```bash -npm run release-notes [version|latest] [evm|sdk|ibc] +# Fetch latest release for default product (EVM) +npm run release-notes + +# Fetch latest for specific product +npm run release-notes latest sdk + +# Fetch all configured versions for a product +npm run release-notes all sdk + +# Fetch specific version for a product +npm run release-notes v0.53 sdk + +# Fetch specific version with custom source +npm run release-notes release/v0.53.x sdk v0.53 ``` **What it does:** -- Fetches changelog from the product's GitHub repository (auto-detects `CHANGELOG.md`/variants) -- Parses and converts to Mintlify format -- Updates release notes file in `docs//next/` +- Fetches changelog from the product's GitHub repository +- Supports multiple versions per product +- Handles version-specific release branches +- Converts to Mintlify format +- Updates release notes in `docs///changelog/release-notes.mdx` + +**Product Configurations:** + +- **evm** → `cosmos/evm` (versions: `next`) +- **sdk** → `cosmos/cosmos-sdk` (versions: `v0.53`, `v0.50`, `v0.47`) +- **ibc** → `cosmos/ibc-go` (versions: `v8`, `v7`, `v6`) +- **cometbft** → `cometbft/cometbft` (versions: `v0.38`, `v0.37`) -**Sources:** +**Version Resolution:** -- evm → `cosmos/evm` -- sdk → `cosmos/cosmos-sdk` -- ibc → `cosmos/ibc-go` +- EVM: Uses `next` as the primary version +- SDK/IBC: Checks release branches first (`release/vX.Y.x`), then tags, then main +- Searches for `CHANGELOG.md`, `RELEASE_NOTES.md`, and other common locations ### Supporting Scripts diff --git a/scripts/versioning/release-notes.js b/scripts/versioning/release-notes.js index ff50b004..a74a4b3a 100644 --- a/scripts/versioning/release-notes.js +++ b/scripts/versioning/release-notes.js @@ -3,6 +3,7 @@ /** * Release Notes Management * Combines changelog fetching and parsing functionality + * Supports multiple products and versions */ import fs from 'fs'; @@ -11,15 +12,33 @@ import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); -// Get source from command line argument, default to latest release +// Parse command line arguments +// Usage: node release-notes.js [source/version] [product] [specific-version] +// Examples: +// node release-notes.js latest evm # Fetch latest for EVM (default behavior) +// node release-notes.js all sdk # Fetch all versions for SDK +// node release-notes.js v0.53 sdk # Fetch specific version for SDK +// node release-notes.js latest ibc v1.0 # Fetch for IBC v1.0 const SOURCE = process.argv[2] || 'latest'; const SUBDIR = process.argv[3] || process.env.DOCS_SUBDIR || process.env.SUBDIR || 'evm'; +const SPECIFIC_VERSION = process.argv[4]; // Optional: specific version to target -// Repo mapping per product +// Repo mapping per product - expandable for future products const PRODUCT_REPOS = { evm: 'cosmos/evm', sdk: 'cosmos/cosmos-sdk', - ibc: 'cosmos/ibc-go' + ibc: 'cosmos/ibc-go', + cometbft: 'cometbft/cometbft', + // Add more products as needed +}; + +// Version configurations per product +const PRODUCT_VERSIONS = { + evm: ['next'], // EVM uses 'next' as primary + sdk: ['v0.53', 'v0.50', 'v0.47'], // SDK has multiple versions + ibc: ['v8', 'v7', 'v6'], // Example IBC versions + cometbft: ['v0.38', 'v0.37'], // Example CometBFT versions + // Add version configs as needed }; const REPO = PRODUCT_REPOS[SUBDIR] || PRODUCT_REPOS.evm; @@ -45,26 +64,50 @@ async function getLatestRelease() { } } -async function fetchChangelog(source) { - console.log(` Fetching changelog from ${REPO}: ${source}...`); +async function fetchChangelog(source, version = null) { + // Determine the actual source to fetch from + let fetchSource = source; + + // For SDK/IBC, try release branches first + if (version && SUBDIR !== 'evm') { + // Try release/vX.Y.x branch format + fetchSource = `release/${version}.x`; + } else if (source === 'latest' && version) { + // For specific version requests + fetchSource = version; + } + + console.log(` Fetching changelog from ${REPO}: ${fetchSource}...`); const errors = []; - for (const p of CHANGELOG_PATHS) { - const url = `https://raw.githubusercontent.com/${REPO}/${source}/${p}`; - try { - const response = await fetch(url); - if (!response.ok) { - errors.push(`${p}: ${response.status}`); - continue; - } - const changelog = await response.text(); - if (changelog && changelog.trim().length > 0) { - console.log(`✓ Fetched ${p} (${changelog.split('\n').length} lines)`); - return changelog; + const sources = [fetchSource]; + + // Add fallback sources + if (fetchSource !== source) { + sources.push(source); + } + if (version && !sources.includes(version)) { + sources.push(version); + } + + for (const src of sources) { + for (const p of CHANGELOG_PATHS) { + const url = `https://raw.githubusercontent.com/${REPO}/${src}/${p}`; + try { + const response = await fetch(url); + if (!response.ok) { + errors.push(`${src}/${p}: ${response.status}`); + continue; + } + const changelog = await response.text(); + if (changelog && changelog.trim().length > 0) { + console.log(`✓ Fetched ${p} from ${src} (${changelog.split('\n').length} lines)`); + return changelog; + } + errors.push(`${src}/${p}: empty`); + } catch (err) { + errors.push(`${src}/${p}: ${err.message}`); } - errors.push(`${p}: empty`); - } catch (err) { - errors.push(`${p}: ${err.message}`); } } @@ -151,9 +194,18 @@ ${update.changes.map(change => ` ${change}`).join('\n')} return mintlifyContent; } -async function updateReleaseNotes(content) { - // Create directory if it doesn't exist - const outputPath = path.join(__dirname, '..', '..', 'docs', SUBDIR, 'next', 'changelog', 'release-notes.mdx'); +async function updateReleaseNotes(content, version = 'next') { + // Determine output path based on product and version + const outputPath = path.join( + __dirname, + '..', + '..', + 'docs', + SUBDIR, + version, + 'changelog', + 'release-notes.mdx' + ); const dir = path.dirname(outputPath); if (!fs.existsSync(dir)) { @@ -170,26 +222,86 @@ async function updateReleaseNotes(content) { return { outputPath, versionCount }; } +async function processVersion(version, source) { + try { + // Fetch and process changelog for this version + const changelog = await fetchChangelog(source, version); + const mintlifyContent = parseChangelogToMintlify(changelog); + const result = await updateReleaseNotes(mintlifyContent, version); + + return { + version, + success: true, + ...result + }; + } catch (error) { + console.error(` Failed for ${version}: ${error.message}`); + return { + version, + success: false, + error: error.message + }; + } +} + async function main() { try { - // Determine source - let source = SOURCE; - if (source === 'latest') { - source = await getLatestRelease(); - console.log(` Using latest release: ${source}`); + console.log(`\n=== Release Notes Update ===`); + console.log(` Product: ${PRODUCT_LABEL}`); + console.log(` Repository: ${REPO}`); + + let results = []; + + // Handle different modes + if (SOURCE === 'all') { + // Process all configured versions for this product + const versions = PRODUCT_VERSIONS[SUBDIR] || ['next']; + console.log(` Processing versions: ${versions.join(', ')}\n`); + + for (const version of versions) { + const result = await processVersion(version, 'latest'); + results.push(result); + } + } else if (SPECIFIC_VERSION) { + // Process specific version only + console.log(` Processing specific version: ${SPECIFIC_VERSION}\n`); + const result = await processVersion(SPECIFIC_VERSION, SOURCE); + results.push(result); + } else { + // Default behavior - process for 'next' or default version + let source = SOURCE; + if (source === 'latest') { + source = await getLatestRelease(); + console.log(` Using latest release: ${source}`); + } + + const targetVersion = PRODUCT_VERSIONS[SUBDIR]?.[0] || 'next'; + const result = await processVersion(targetVersion, source); + results.push(result); } - // Fetch and process changelog - const changelog = await fetchChangelog(source); - const mintlifyContent = parseChangelogToMintlify(changelog); - const result = await updateReleaseNotes(mintlifyContent); + // Summary + console.log('\n=== Summary ==='); + const successful = results.filter(r => r.success); + const failed = results.filter(r => !r.success); - console.log('\n Release notes update completed'); - console.log(` Summary:`); - console.log(` Repo: ${REPO}`); - console.log(` Source: ${source}`); - console.log(` Versions: ${result.versionCount}`); - console.log(` Output: ${result.outputPath}`); + if (successful.length > 0) { + console.log('✓ Successful updates:'); + successful.forEach(r => { + console.log(` ${r.version}: ${r.versionCount} versions -> ${r.outputPath}`); + }); + } + + if (failed.length > 0) { + console.log('✗ Failed updates:'); + failed.forEach(r => { + console.log(` ${r.version}: ${r.error}`); + }); + } + + if (failed.length > 0) { + process.exit(1); + } } catch (error) { console.error(' Failed to update release notes:', error.message); @@ -197,4 +309,9 @@ async function main() { } } -main(); +// Support both direct execution and module import +if (import.meta.url === `file://${process.argv[1]}`) { + main(); +} + +export { fetchChangelog, parseChangelogToMintlify, updateReleaseNotes }; From 89faf02299723c6cd50e1f182e598e8808fb6947 Mon Sep 17 00:00:00 2001 From: Cordt Date: Sun, 14 Sep 2025 08:13:07 -0600 Subject: [PATCH 2/5] restucturing contd. --- .github/workflows/auto-freeze-version.yml | 8 +- .github/workflows/sync-evm-changelog.yml | 2 +- .gitignore | 8 +- README.md | 2 +- .../testing-and-fuzzing.mdx | 2 +- .../smart-contracts/precompiles/overview.mdx | 4 +- docs/sdk/v0.47/changelog/release-notes.mdx | 2 +- docs/sdk/v0.50/changelog/release-notes.mdx | 2 +- docs/sdk/v0.50/release-notes.mdx | 2 +- .../v0.53/app-wiring-runtime/app-go-di.mdx | 3 - docs/sdk/v0.53/app-wiring-runtime/app-go.mdx | 3 - .../v0.53/app-wiring-runtime/app-mempool.mdx | 3 - .../v0.53/app-wiring-runtime/app-testnet.mdx | 3 - .../v0.53/app-wiring-runtime/app-upgrade.mdx | 3 - docs/sdk/v0.53/app-wiring-runtime/runtime.mdx | 3 - .../app-wiring-runtime/vote-extensions.mdx | 3 - docs/sdk/v0.53/changelog/release-notes.mdx | 2 +- .../protobuf-annotations.mdx | 3 - .../messages-and-queries.mdx | 3 - .../v0.53/messaging-queries/msg-services.mdx | 3 - .../messaging-queries/query-services.mdx | 3 - .../v0.53/module-anatomy-keepers/errors.mdx | 3 - .../v0.53/module-anatomy-keepers/genesis.mdx | 3 - .../module-anatomy-keepers/invariants.mdx | 3 - .../v0.53/module-anatomy-keepers/keeper.mdx | 3 - .../module-interfaces.mdx | 3 - .../module-anatomy-keepers/module-manager.mdx | 3 - .../v0.53/module-anatomy-keepers/preblock.mdx | 3 - .../module-anatomy-keepers/structure.mdx | 3 - docs/sdk/v0.53/module-reference/auth.mdx | 3 - docs/sdk/v0.53/module-reference/authz.mdx | 3 - docs/sdk/v0.53/module-reference/bank.mdx | 3 - docs/sdk/v0.53/module-reference/consensus.mdx | 3 - docs/sdk/v0.53/module-reference/crisis.mdx | 3 - .../v0.53/module-reference/distribution.mdx | 3 - docs/sdk/v0.53/module-reference/epochs.mdx | 3 - docs/sdk/v0.53/module-reference/evidence.mdx | 3 - docs/sdk/v0.53/module-reference/feegrant.mdx | 3 - docs/sdk/v0.53/module-reference/gov.mdx | 3 - docs/sdk/v0.53/module-reference/group.mdx | 3 - docs/sdk/v0.53/module-reference/mint.mdx | 3 - docs/sdk/v0.53/module-reference/nft.mdx | 3 - docs/sdk/v0.53/module-reference/params.mdx | 3 - .../v0.53/module-reference/protocolpool.mdx | 3 - docs/sdk/v0.53/module-reference/slashing.mdx | 3 - docs/sdk/v0.53/module-reference/staking.mdx | 3 - docs/sdk/v0.53/module-reference/upgrade.mdx | 3 - docs/sdk/v0.53/overview.mdx | 2 +- docs/sdk/v0.53/release-notes.mdx | 2 +- .../v0.53/testing-simulation/simulator.mdx | 5 +- docs/sdk/v0.53/testing-simulation/testing.mdx | 3 - .../upgrades-migrations/module-upgrade.mdx | 3 - scripts/{versioning => }/GSHEET-SETUP.md | 4 +- .../README.md => VERSIONING-README.md} | 24 +- scripts/convert-docusaurus-to-mintlify.js | 405 ++++++++++++++++++ scripts/docusaurus-to-mintlify.js | 405 ++++++++++++++++++ scripts/{versioning => }/package-lock.json | 10 +- scripts/package.json | 24 ++ scripts/{versioning => }/release-notes.js | 0 scripts/{versioning => }/sheets-manager.js | 2 +- scripts/{versioning => }/version-manager.js | 20 +- scripts/versioning/package.json | 19 - scripts/versioning/restructure-navigation.js | 83 ---- scripts/versioning/test-versioning.js | 90 ---- 64 files changed, 884 insertions(+), 362 deletions(-) rename scripts/{versioning => }/GSHEET-SETUP.md (96%) rename scripts/{versioning/README.md => VERSIONING-README.md} (95%) create mode 100755 scripts/convert-docusaurus-to-mintlify.js create mode 100644 scripts/docusaurus-to-mintlify.js rename scripts/{versioning => }/package-lock.json (98%) create mode 100644 scripts/package.json rename scripts/{versioning => }/release-notes.js (100%) rename scripts/{versioning => }/sheets-manager.js (98%) rename scripts/{versioning => }/version-manager.js (94%) delete mode 100644 scripts/versioning/package.json delete mode 100755 scripts/versioning/restructure-navigation.js delete mode 100644 scripts/versioning/test-versioning.js diff --git a/.github/workflows/auto-freeze-version.yml b/.github/workflows/auto-freeze-version.yml index 499503be..0f23e116 100644 --- a/.github/workflows/auto-freeze-version.yml +++ b/.github/workflows/auto-freeze-version.yml @@ -50,12 +50,12 @@ jobs: - name: Install versioning dependencies run: | - cd scripts/versioning + cd scripts npm install - name: Setup Google Sheets API credentials run: | - echo '${{ secrets.GOOGLE_SERVICE_ACCOUNT_KEY }}' > scripts/versioning/service-account-key.json + echo '${{ secrets.GOOGLE_SERVICE_ACCOUNT_KEY }}' > scripts/service-account-key.json echo "✓ Google Sheets API credentials configured" - name: Run version freeze process @@ -68,7 +68,7 @@ jobs: export BATCH_MODE=true # Run the automated version freeze - NEW_VERSION="$NEW_VERSION" node scripts/versioning/version-manager.js + NEW_VERSION="$NEW_VERSION" node scripts/version-manager.js - name: Commit and create PR run: | @@ -128,4 +128,4 @@ jobs: - name: Cleanup credentials if: always() run: | - rm -f scripts/versioning/service-account-key.json \ No newline at end of file + rm -f scripts/service-account-key.json \ No newline at end of file diff --git a/.github/workflows/sync-evm-changelog.yml b/.github/workflows/sync-evm-changelog.yml index a7b2d2b3..e58f157c 100644 --- a/.github/workflows/sync-evm-changelog.yml +++ b/.github/workflows/sync-evm-changelog.yml @@ -50,7 +50,7 @@ jobs: - name: Parse and convert changelog id: convert - run: node scripts/versioning/release-notes.js ${{ steps.fetch-changelog.outputs.release_tag }} + run: node scripts/release-notes.js ${{ steps.fetch-changelog.outputs.release_tag }} - name: Update changelog file run: | diff --git a/.gitignore b/.gitignore index d97c981c..f555acb5 100644 --- a/.gitignore +++ b/.gitignore @@ -67,9 +67,9 @@ build/ .yarn/ # Keep most scripts ignored, but include versioning tools scripts/* -!scripts/versioning/ -!scripts/versioning/** -tests/* +!scripts/ +!scripts/** +scripts/test/* .ingress/ CLAUDE.md @@ -79,7 +79,7 @@ CLAUDE.md # Google Sheets API credentials **/service-account-key.json -scripts/versioning/node_modules/ +scripts/node_modules/ # Projects directory .projects/ diff --git a/README.md b/README.md index f1976d63..e6e58db8 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Documentation for all parts of the Cosmos Stack. - `docs//next/` - Active development documentation - `docs//` - Versioned documentation, by major release. -- `scripts/versioning/` - Versioning automation - see [README](scripts/versioning/README.md). +- `scripts/` - Versioning automation - see [README](scripts/README.md). - `snippets/` - Custom components - Due to platform limitations, components cannot be versioned. However, it is possible to feed specific / versioned data to a component through a prop in the import (see `docs/evm/v0.4.x/documentation/evm-compatibility/eip-reference.mdx` for a working example). ## Contributing diff --git a/docs/evm/next/documentation/getting-started/tooling-and-resources/testing-and-fuzzing.mdx b/docs/evm/next/documentation/getting-started/tooling-and-resources/testing-and-fuzzing.mdx index 5749a95c..6f5854fa 100644 --- a/docs/evm/next/documentation/getting-started/tooling-and-resources/testing-and-fuzzing.mdx +++ b/docs/evm/next/documentation/getting-started/tooling-and-resources/testing-and-fuzzing.mdx @@ -97,7 +97,7 @@ tests/evm-tools-compatibility/ **Setup:** ```bash # Start comparison testing environment -cd tests/jsonrpc +cd scripts/test/jsonrpc # Build required Docker images make localnet-build-env diff --git a/docs/evm/next/documentation/smart-contracts/precompiles/overview.mdx b/docs/evm/next/documentation/smart-contracts/precompiles/overview.mdx index b96027ea..1e52cad0 100644 --- a/docs/evm/next/documentation/smart-contracts/precompiles/overview.mdx +++ b/docs/evm/next/documentation/smart-contracts/precompiles/overview.mdx @@ -222,8 +222,8 @@ All precompiles include comprehensive Solidity test suites for validation: ```bash # Run precompile tests -cd tests && npm test +cd scripts/test && npm test # Test specific precompile -npx hardhat test test/Bank.test.js +npx hardhat test scripts/test/Bank.test.js ``` diff --git a/docs/sdk/v0.47/changelog/release-notes.mdx b/docs/sdk/v0.47/changelog/release-notes.mdx index b34f815e..2f92c210 100644 --- a/docs/sdk/v0.47/changelog/release-notes.mdx +++ b/docs/sdk/v0.47/changelog/release-notes.mdx @@ -404,4 +404,4 @@ mode: "custom" - A SendEnabled query has been added to both GRPC and CLI. - ## Previous Versions - [CHANGELOG of previous versions](https://github.com/cosmos/cosmos-sdk/blob/main/CHANGELOG.md#v0460---2022-07-26). - \ No newline at end of file + diff --git a/docs/sdk/v0.50/changelog/release-notes.mdx b/docs/sdk/v0.50/changelog/release-notes.mdx index 741fb657..6cf2ff60 100644 --- a/docs/sdk/v0.50/changelog/release-notes.mdx +++ b/docs/sdk/v0.50/changelog/release-notes.mdx @@ -505,4 +505,4 @@ mode: "custom" - * (x/gov) [#16231](https://github.com/cosmos/cosmos-sdk/pull/16231) Fix Rawlog JSON formatting of proposal_vote option field.* (cli) [#16138](https://github.com/cosmos/cosmos-sdk/pull/16138) Fix snapshot commands panic if snapshot don't exists. - * (x/staking) [#16043](https://github.com/cosmos/cosmos-sdk/pull/16043) Call `AfterUnbondingInitiated` hook for new unbonding entries only and fix `UnbondingDelegation` entries handling. This is a behavior change compared to Cosmos SDK v0.47.x, now the hook is called only for new unbonding entries. - * (types) [#16010](https://github.com/cosmos/cosmos-sdk/pull/16010) Let `module.CoreAppModuleBasicAdaptor` fallback to legacy genesis handling. - \ No newline at end of file + diff --git a/docs/sdk/v0.50/release-notes.mdx b/docs/sdk/v0.50/release-notes.mdx index 46a6d471..9383ade0 100644 --- a/docs/sdk/v0.50/release-notes.mdx +++ b/docs/sdk/v0.50/release-notes.mdx @@ -35,4 +35,4 @@ For the most up-to-date and detailed changelog, please refer to the official Cos - Enhanced security and performance - Better developer experience -For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.50.x/CHANGELOG.md). \ No newline at end of file +For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.50.x/CHANGELOG.md). diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx index a296bb5e..7906406c 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx @@ -3,9 +3,6 @@ title: "Overview of `app_di.go`" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx index 89c90504..0d4638fa 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-go.mdx @@ -3,9 +3,6 @@ title: "Overview of `app.go`" --- ---- - ---- This section is intended to provide an overview of the `SimApp` `app.go` file and is still a work in progress. For now please instead read the [tutorials](https://tutorials.cosmos.network) for a deep dive on how to build a chain. diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx index 9fffbb29..af678dc7 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx @@ -3,9 +3,6 @@ title: "Application Mempool" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx index afe051c7..06766c78 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx @@ -3,9 +3,6 @@ title: "Application Testnets" --- ---- - ---- Building an application is complicated and requires a lot of testing. The Cosmos SDK provides a way to test your application in a real-world environment: a testnet. diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx index 66e77b3e..f4e3560a 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx @@ -3,9 +3,6 @@ title: "Application Upgrade" --- ---- - ---- This document describes how to upgrade your application. If you are looking specifically for the changes to perform between SDK versions, see the [SDK migrations documentation](https://docs.cosmos.network/main/migrations/intro). diff --git a/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx index 841c7e52..9b531b00 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx @@ -3,9 +3,6 @@ title: "What is `runtime`?" --- ---- - ---- The `runtime` package in the Cosmos SDK provides a flexible framework for configuring and managing blockchain applications. It serves as the foundation for creating modular blockchain applications using a declarative configuration approach. diff --git a/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx index 27920d03..8328d64f 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx @@ -3,9 +3,6 @@ title: "Vote Extensions" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/changelog/release-notes.mdx b/docs/sdk/v0.53/changelog/release-notes.mdx index 36a1e130..e723019e 100644 --- a/docs/sdk/v0.53/changelog/release-notes.mdx +++ b/docs/sdk/v0.53/changelog/release-notes.mdx @@ -505,4 +505,4 @@ mode: "custom" - * (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct. - * (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`. - * (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`. - \ No newline at end of file + diff --git a/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx b/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx index 9b2b0b2d..e94da803 100644 --- a/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx +++ b/docs/sdk/v0.53/encoding-protobuf/protobuf-annotations.mdx @@ -3,9 +3,6 @@ title: "ProtocolBuffer Annotations" --- ---- - ---- This document explains the various protobuf scalars that have been added to make working with protobuf easier for Cosmos SDK application developers diff --git a/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx index 86e53729..e52b94b6 100644 --- a/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx +++ b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx @@ -3,9 +3,6 @@ title: "Messages and Queries" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/messaging-queries/msg-services.mdx b/docs/sdk/v0.53/messaging-queries/msg-services.mdx index b885d58b..c41a0e09 100644 --- a/docs/sdk/v0.53/messaging-queries/msg-services.mdx +++ b/docs/sdk/v0.53/messaging-queries/msg-services.mdx @@ -3,9 +3,6 @@ title: "`Msg` Services" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/messaging-queries/query-services.mdx b/docs/sdk/v0.53/messaging-queries/query-services.mdx index 15f45e2e..64c3c2b0 100644 --- a/docs/sdk/v0.53/messaging-queries/query-services.mdx +++ b/docs/sdk/v0.53/messaging-queries/query-services.mdx @@ -3,9 +3,6 @@ title: "Query Services" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx index a42546c3..99d31a16 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx @@ -3,9 +3,6 @@ title: "Errors" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx b/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx index 5ca509a6..030b307f 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/genesis.mdx @@ -3,9 +3,6 @@ title: "Module Genesis" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx index 21ab3d11..150d4679 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx @@ -3,9 +3,6 @@ title: "Invariants" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx index a3c903a2..9fd43f7b 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx @@ -3,9 +3,6 @@ title: "Keepers" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx index 777311bd..5b411e8a 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx @@ -3,9 +3,6 @@ title: "Module Interfaces" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx b/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx index 9527587c..0722e4c4 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/module-manager.mdx @@ -3,9 +3,6 @@ title: "Module Manager" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx b/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx index 243eca05..6c367c1f 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/preblock.mdx @@ -3,9 +3,6 @@ title: "PreBlocker" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx index abe50bac..afc2b382 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx @@ -3,9 +3,6 @@ title: "Recommended Folder Structure" --- ---- - ---- **Synopsis** diff --git a/docs/sdk/v0.53/module-reference/auth.mdx b/docs/sdk/v0.53/module-reference/auth.mdx index 48083832..61479757 100644 --- a/docs/sdk/v0.53/module-reference/auth.mdx +++ b/docs/sdk/v0.53/module-reference/auth.mdx @@ -3,9 +3,6 @@ title: "`x/auth`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/authz.mdx b/docs/sdk/v0.53/module-reference/authz.mdx index 4305ebec..ac6227bb 100644 --- a/docs/sdk/v0.53/module-reference/authz.mdx +++ b/docs/sdk/v0.53/module-reference/authz.mdx @@ -3,9 +3,6 @@ title: "`x/authz`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/bank.mdx b/docs/sdk/v0.53/module-reference/bank.mdx index 95e40a71..3cbe919f 100644 --- a/docs/sdk/v0.53/module-reference/bank.mdx +++ b/docs/sdk/v0.53/module-reference/bank.mdx @@ -3,9 +3,6 @@ title: "`x/bank`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/consensus.mdx b/docs/sdk/v0.53/module-reference/consensus.mdx index 6df6482f..44776b96 100644 --- a/docs/sdk/v0.53/module-reference/consensus.mdx +++ b/docs/sdk/v0.53/module-reference/consensus.mdx @@ -3,8 +3,5 @@ title: "`x/consensus`" --- ---- - ---- Functionality to modify CometBFT's ABCI consensus params. diff --git a/docs/sdk/v0.53/module-reference/crisis.mdx b/docs/sdk/v0.53/module-reference/crisis.mdx index b91647aa..1c792d8f 100644 --- a/docs/sdk/v0.53/module-reference/crisis.mdx +++ b/docs/sdk/v0.53/module-reference/crisis.mdx @@ -3,9 +3,6 @@ title: "`x/crisis`" --- ---- - ---- NOTE: `x/crisis` is deprecated as of Cosmos SDK v0.53 and will be removed in the next release. diff --git a/docs/sdk/v0.53/module-reference/distribution.mdx b/docs/sdk/v0.53/module-reference/distribution.mdx index 7f050638..ddb61dc1 100644 --- a/docs/sdk/v0.53/module-reference/distribution.mdx +++ b/docs/sdk/v0.53/module-reference/distribution.mdx @@ -3,9 +3,6 @@ title: "`x/distribution`" --- ---- - ---- ## Overview diff --git a/docs/sdk/v0.53/module-reference/epochs.mdx b/docs/sdk/v0.53/module-reference/epochs.mdx index 5a77b02b..9144fb30 100644 --- a/docs/sdk/v0.53/module-reference/epochs.mdx +++ b/docs/sdk/v0.53/module-reference/epochs.mdx @@ -3,9 +3,6 @@ title: "`x/epochs`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/evidence.mdx b/docs/sdk/v0.53/module-reference/evidence.mdx index cbf234fa..620d197e 100644 --- a/docs/sdk/v0.53/module-reference/evidence.mdx +++ b/docs/sdk/v0.53/module-reference/evidence.mdx @@ -3,9 +3,6 @@ title: "`x/evidence`" --- ---- - ---- * [Concepts](#concepts) * [State](#state) diff --git a/docs/sdk/v0.53/module-reference/feegrant.mdx b/docs/sdk/v0.53/module-reference/feegrant.mdx index 0aaaeba6..d00f27a8 100644 --- a/docs/sdk/v0.53/module-reference/feegrant.mdx +++ b/docs/sdk/v0.53/module-reference/feegrant.mdx @@ -3,9 +3,6 @@ title: "`x/feegrant`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/gov.mdx b/docs/sdk/v0.53/module-reference/gov.mdx index 0f08547b..f4de2d19 100644 --- a/docs/sdk/v0.53/module-reference/gov.mdx +++ b/docs/sdk/v0.53/module-reference/gov.mdx @@ -3,9 +3,6 @@ title: "`x/gov`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/group.mdx b/docs/sdk/v0.53/module-reference/group.mdx index 3a9a0237..7e0f970e 100644 --- a/docs/sdk/v0.53/module-reference/group.mdx +++ b/docs/sdk/v0.53/module-reference/group.mdx @@ -3,9 +3,6 @@ title: "`x/group`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/mint.mdx b/docs/sdk/v0.53/module-reference/mint.mdx index c2d9f541..45c3f03d 100644 --- a/docs/sdk/v0.53/module-reference/mint.mdx +++ b/docs/sdk/v0.53/module-reference/mint.mdx @@ -3,9 +3,6 @@ title: "`x/mint`" --- ---- - ---- The `x/mint` module handles the regular minting of new tokens in a configurable manner. diff --git a/docs/sdk/v0.53/module-reference/nft.mdx b/docs/sdk/v0.53/module-reference/nft.mdx index ddab94ca..03ac0966 100644 --- a/docs/sdk/v0.53/module-reference/nft.mdx +++ b/docs/sdk/v0.53/module-reference/nft.mdx @@ -3,9 +3,6 @@ title: "`x/nft`" --- ---- - ---- ## Contents diff --git a/docs/sdk/v0.53/module-reference/params.mdx b/docs/sdk/v0.53/module-reference/params.mdx index 421ffe37..03eb0928 100644 --- a/docs/sdk/v0.53/module-reference/params.mdx +++ b/docs/sdk/v0.53/module-reference/params.mdx @@ -3,9 +3,6 @@ title: "`x/params`" --- ---- - ---- NOTE: `x/params` is deprecated as of Cosmos SDK v0.53 and will be removed in the next release. diff --git a/docs/sdk/v0.53/module-reference/protocolpool.mdx b/docs/sdk/v0.53/module-reference/protocolpool.mdx index e95f0631..9895df98 100644 --- a/docs/sdk/v0.53/module-reference/protocolpool.mdx +++ b/docs/sdk/v0.53/module-reference/protocolpool.mdx @@ -3,9 +3,6 @@ title: "`x/protocolpool`" --- ---- - ---- ## Concepts diff --git a/docs/sdk/v0.53/module-reference/slashing.mdx b/docs/sdk/v0.53/module-reference/slashing.mdx index acce875a..6785048e 100644 --- a/docs/sdk/v0.53/module-reference/slashing.mdx +++ b/docs/sdk/v0.53/module-reference/slashing.mdx @@ -3,9 +3,6 @@ title: "`x/slashing`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/staking.mdx b/docs/sdk/v0.53/module-reference/staking.mdx index 8af903f1..531745e2 100644 --- a/docs/sdk/v0.53/module-reference/staking.mdx +++ b/docs/sdk/v0.53/module-reference/staking.mdx @@ -3,9 +3,6 @@ title: "`x/staking`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/module-reference/upgrade.mdx b/docs/sdk/v0.53/module-reference/upgrade.mdx index 2d8e8ae5..144743e8 100644 --- a/docs/sdk/v0.53/module-reference/upgrade.mdx +++ b/docs/sdk/v0.53/module-reference/upgrade.mdx @@ -3,9 +3,6 @@ title: "`x/upgrade`" --- ---- - ---- ## Abstract diff --git a/docs/sdk/v0.53/overview.mdx b/docs/sdk/v0.53/overview.mdx index 578ff391..f4d46f81 100644 --- a/docs/sdk/v0.53/overview.mdx +++ b/docs/sdk/v0.53/overview.mdx @@ -95,4 +95,4 @@ This documentation covers Cosmos SDK v0.53, which includes: - Circuit breaker for runtime safety - Optimized state management and performance improvements -For migration guides and breaking changes, see the [Release Notes](/docs/sdk/v0.53/changelog/release-notes). \ No newline at end of file +For migration guides and breaking changes, see the [Release Notes](/docs/sdk/v0.53/changelog/release-notes). diff --git a/docs/sdk/v0.53/release-notes.mdx b/docs/sdk/v0.53/release-notes.mdx index c6aa88c4..03cedac2 100644 --- a/docs/sdk/v0.53/release-notes.mdx +++ b/docs/sdk/v0.53/release-notes.mdx @@ -36,4 +36,4 @@ For the most up-to-date and detailed changelog, please refer to the official Cos - **x/staking**: Optimized delegation logic - **x/gov**: Enhanced governance features -For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md). \ No newline at end of file +For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md). diff --git a/docs/sdk/v0.53/testing-simulation/simulator.mdx b/docs/sdk/v0.53/testing-simulation/simulator.mdx index abc39e75..bd11551f 100644 --- a/docs/sdk/v0.53/testing-simulation/simulator.mdx +++ b/docs/sdk/v0.53/testing-simulation/simulator.mdx @@ -3,9 +3,6 @@ title: "Module Simulation" --- ---- - ---- **Pre-requisite Readings** @@ -175,4 +172,4 @@ Example: ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/simapp/sim_test.go#L53-L65 -``` \ No newline at end of file +``` diff --git a/docs/sdk/v0.53/testing-simulation/testing.mdx b/docs/sdk/v0.53/testing-simulation/testing.mdx index b1e795ab..77c721d3 100644 --- a/docs/sdk/v0.53/testing-simulation/testing.mdx +++ b/docs/sdk/v0.53/testing-simulation/testing.mdx @@ -3,9 +3,6 @@ title: "Testing" --- ---- - ---- The Cosmos SDK contains different types of [tests](https://martinfowler.com/articles/practical-test-pyramid.html). These tests have different goals and are used at different stages of the development cycle. diff --git a/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx index d11f5db3..670ef637 100644 --- a/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx +++ b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx @@ -3,9 +3,6 @@ title: "Upgrading Modules" --- ---- - ---- **Synopsis** diff --git a/scripts/versioning/GSHEET-SETUP.md b/scripts/GSHEET-SETUP.md similarity index 96% rename from scripts/versioning/GSHEET-SETUP.md rename to scripts/GSHEET-SETUP.md index b1df6dc6..a1826254 100644 --- a/scripts/versioning/GSHEET-SETUP.md +++ b/scripts/GSHEET-SETUP.md @@ -68,7 +68,7 @@ Uses version-specific tab `v0.5.0` with snapshot data. 3. Click "Add Key" → "Create New Key" 4. Select "JSON" format 5. Click "Create" -6. Save file as `scripts/versioning/service-account-key.json` +6. Save file as `scripts/service-account-key.json` ### 5. Share Spreadsheet @@ -81,7 +81,7 @@ Uses version-specific tab `v0.5.0` with snapshot data. ### 6. Install Dependencies ```bash -cd scripts/versioning +cd scripts npm install ``` diff --git a/scripts/versioning/README.md b/scripts/VERSIONING-README.md similarity index 95% rename from scripts/versioning/README.md rename to scripts/VERSIONING-README.md index a88e9c0d..e03ec89b 100644 --- a/scripts/versioning/README.md +++ b/scripts/VERSIONING-README.md @@ -90,12 +90,12 @@ Each product can be versioned independently. The version manager auto-detects th 1. **Google Sheets API Access** - Service account key saved as `service-account-key.json` - - See [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/versioning/GSHEET-SETUP.md) for detailed setup + - See [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/GSHEET-SETUP.md) for detailed setup 2. **Install Dependencies** ```bash - cd scripts/versioning + cd scripts npm install ``` @@ -104,7 +104,7 @@ Each product can be versioned independently. The version manager auto-detects th Run the version manager to freeze the current version in a chosen docs subdirectory (e.g., `evm`, `sdk`, `ibc`) and start a new one. The flow is fully interactive by default: ```bash -cd scripts/versioning +cd scripts npm run freeze ``` @@ -231,7 +231,7 @@ Navigation structure cleanup utility. ## Google Sheets Integration -EIP compatibility data is versioned through Google Sheets tabs. See [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/versioning/GSHEET-SETUP.md) for setup and configuration. +EIP compatibility data is versioned through Google Sheets tabs. See [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/GSHEET-SETUP.md) for setup and configuration. ### Shared Component @@ -325,7 +325,7 @@ See [Mintlify Constraints](../../CLAUDE.md) for details. ### 1. Google Sheets API Setup -Follow [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/versioning/GSHEET-SETUP.md) to: +Follow [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/GSHEET-SETUP.md) to: 1. Create a Google Cloud project 2. Enable Sheets API @@ -336,7 +336,7 @@ Follow [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/versio ### 2. Install Dependencies ```bash -cd scripts/versioning +cd scripts npm install ``` @@ -345,7 +345,7 @@ npm install Save your service account key as: ```sh -scripts/versioning/service-account-key.json +scripts/service-account-key.json ``` ### 4. Test Connection @@ -369,7 +369,7 @@ console.log('✓ Google Sheets API configured'); ```bash # Start the version freeze process -cd scripts/versioning && npm run freeze +cd scripts && npm run freeze # Enter prompts Enter the docs subdirectory to version [evm, sdk, ibc]: evm @@ -380,10 +380,10 @@ Enter the new development version (e.g., v0.5.0): v0.5.0 ```bash # Fetch latest release notes into docs/evm/next -node scripts/versioning/release-notes.js latest evm +node scripts/release-notes.js latest evm # Or fetch specific release into docs/evm/next -node scripts/versioning/release-notes.js v0.4.1 evm +node scripts/release-notes.js v0.4.1 evm ``` ### Manual Navigation Update @@ -441,7 +441,7 @@ rm -rf docs//v0.5.0/ ## File Structure ``` -scripts/versioning/ +scripts/ ├── README.md # This file ├── GSHEET-SETUP.md # Google Sheets API setup guide ├── version-manager.js # Main orchestration (ESM) @@ -458,5 +458,5 @@ scripts/versioning/ - [Main README](../../README.md) - Project overview - [CLAUDE.md](../../CLAUDE.md) - AI assistant context -- [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/versioning/GSHEET-SETUP.md) - Google Sheets API setup +- [GSHEET-SETUP.md](https://github.com/cosmos/docs/blob/main/scripts/GSHEET-SETUP.md) - Google Sheets API setup - [Mintlify Documentation](https://mintlify.com/docs) - MDX reference diff --git a/scripts/convert-docusaurus-to-mintlify.js b/scripts/convert-docusaurus-to-mintlify.js new file mode 100755 index 00000000..5231752a --- /dev/null +++ b/scripts/convert-docusaurus-to-mintlify.js @@ -0,0 +1,405 @@ +#!/usr/bin/env node + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import readline from 'readline'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Create readline interface for prompts +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +const prompt = (question) => new Promise((resolve) => rl.question(question, resolve)); + +/** + * Parse Docusaurus frontmatter + */ +function parseDocusaurusFrontmatter(content) { + const lines = content.split('\n'); + const frontmatter = {}; + let contentStart = 0; + + if (lines[0] === '---') { + for (let i = 1; i < lines.length; i++) { + if (lines[i] === '---') { + contentStart = i + 1; + break; + } + const match = lines[i].match(/^(\w+):\s*(.*)$/); + if (match) { + const key = match[1]; + let value = match[2]; + // Remove quotes if present + value = value.replace(/^["']|["']$/g, ''); + frontmatter[key] = value; + } + } + } + + return { + frontmatter, + content: lines.slice(contentStart).join('\n') + }; +} + +/** + * Extract title from content (first H1 heading) + */ +function extractTitleFromContent(content) { + const match = content.match(/^#\s+(.+)$/m); + if (match) { + return { + title: match[1].trim(), + content: content.replace(match[0], '').trim() + }; + } + return { title: null, content }; +} + +/** + * Generate description from content + */ +function generateDescription(content, version = 'v0.53') { + // Remove markdown formatting + let plainText = content + .replace(/^#+\s+.*$/gm, '') // Remove headings + .replace(/```[\s\S]*?```/g, '') // Remove code blocks + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Convert links to text + .replace(/[*_`]/g, '') // Remove formatting + .trim(); + + // Find first non-empty paragraph + const paragraphs = plainText.split(/\n\n+/); + for (const para of paragraphs) { + const cleaned = para.trim(); + if (cleaned && cleaned.length > 20) { + return cleaned.length > 150 ? cleaned.substring(0, 147) + '...' : cleaned; + } + } + + return `Cosmos SDK ${version} Documentation`; +} + +/** + * Convert Docusaurus admonitions to Mintlify callouts + */ +function convertAdmonitions(content) { + const admonitionMap = { + 'note': 'Note', + 'tip': 'Tip', + 'info': 'Info', + 'warning': 'Warning', + 'danger': 'Warning', + 'caution': 'Warning', + 'important': 'Info', + 'success': 'Check' + }; + + let result = content; + + // Match multiline admonitions + const admonitionRegex = /:::(note|tip|info|warning|danger|caution|important|success)(?:\s+(.+?))?\n([\s\S]*?)\n:::/gi; + + result = result.replace(admonitionRegex, (match, type, title, content) => { + const component = admonitionMap[type.toLowerCase()] || 'Note'; + const titleLine = title ? `**${title}**\n` : ''; + return `<${component}>\n${titleLine}${content.trim()}\n`; + }); + + // Also handle single-line admonitions + const singleLineRegex = /:::(note|tip|info|warning|danger|caution|important|success)\s+(.+?)\s*:::/gi; + + result = result.replace(singleLineRegex, (match, type, content) => { + const component = admonitionMap[type.toLowerCase()] || 'Note'; + return `<${component}>${content.trim()}`; + }); + + return result; +} + +/** + * Convert code blocks to Mintlify format with expandable for long blocks + */ +function convertCodeBlocks(content) { + const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g; + + return content.replace(codeBlockRegex, (match, lang, code) => { + const lines = code.split('\n'); + const lineCount = lines.length; + + // If more than 10 lines, make it expandable + if (lineCount > 10) { + // Get first few lines for preview + const preview = lines.slice(0, 3).join('\n'); + const title = lang ? `${lang} code` : 'Code'; + + return ` +\`\`\`${lang} +${code}\`\`\` +`; + } + + // Otherwise keep as regular code block + return match; + }); +} + +/** + * Fix internal documentation links + */ +function fixInternalLinks(content, version) { + let result = content; + + // Fix v0.53 links + result = result.replace(/\]\(\/v0\.53\/learn\/advanced\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/learn\/beginner\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/learn\/intro\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/build\/building-modules\//g, '](/docs/sdk/v0.53/module-anatomy-keepers/'); + result = result.replace(/\]\(\/v0\.53\/build\/building-apps\//g, '](/docs/sdk/v0.53/app-wiring-runtime/'); + result = result.replace(/\]\(\/v0\.53\/build\/modules\//g, '](/docs/sdk/v0.53/module-reference/'); + result = result.replace(/\]\(\/v0\.53\/build\/abci\//g, '](/docs/sdk/v0.53/runtime-abci/'); + result = result.replace(/\]\(\/v0\.53\/tutorials\//g, '](/docs/sdk/v0.53/tutorials/'); + result = result.replace(/\]\(\/v0\.53\/user\//g, '](/docs/sdk/v0.53/node-operations/'); + + // Fix v0.50 links + result = result.replace(/\]\(\/v0\.50\/learn\//g, '](/docs/sdk/v0.50/learn/'); + result = result.replace(/\]\(\/v0\.50\/build\//g, '](/docs/sdk/v0.50/build/'); + result = result.replace(/\]\(\/v0\.50\/user\//g, '](/docs/sdk/v0.50/user/'); + + // Fix v0.47 links + result = result.replace(/\]\(\/v0\.47\/learn\//g, '](/docs/sdk/v0.47/learn/'); + result = result.replace(/\]\(\/v0\.47\/build\//g, '](/docs/sdk/v0.47/build/'); + result = result.replace(/\]\(\/v0\.47\/user\//g, '](/docs/sdk/v0.47/user/'); + + // Remove Docusaurus-specific "Direct link" anchors + result = result.replace(/\[​\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, ''); + + // Remove heading anchors {#anchor} + result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1'); + + // Fix relative links (../ or ./) + result = result.replace(/\]\(\.\.\//g, ']('); + result = result.replace(/\]\(\.\//g, ']('); + + return result; +} + +/** + * Convert a single Docusaurus file to Mintlify format + */ +function convertDocusaurusToMintlify(content, options = {}) { + const { version = 'v0.53', keepTitle = false } = options; + + // Parse frontmatter and content + const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); + + // Extract or generate title + let title = frontmatter.title || frontmatter.sidebar_label; + let processedContent = mainContent; + + if (!title) { + const extracted = extractTitleFromContent(processedContent); + title = extracted.title || 'Documentation'; + processedContent = extracted.content; + } else if (!keepTitle) { + // Remove H1 if we have title from frontmatter + const extracted = extractTitleFromContent(processedContent); + if (extracted.title) { + processedContent = extracted.content; + } + } + + // Generate or use description + const description = frontmatter.description || generateDescription(processedContent, version); + + // Apply conversions + processedContent = convertAdmonitions(processedContent); + processedContent = convertCodeBlocks(processedContent); + processedContent = fixInternalLinks(processedContent, version); + + // Build Mintlify frontmatter + const mintlifyFrontmatter = { + title, + description + }; + + // Add icon if specified + if (frontmatter.icon) { + mintlifyFrontmatter.icon = frontmatter.icon; + } + + // Build final content + let finalContent = '---\n'; + for (const [key, value] of Object.entries(mintlifyFrontmatter)) { + finalContent += `${key}: "${value}"\n`; + } + finalContent += '---\n\n'; + finalContent += processedContent; + + // Clean up multiple empty lines + finalContent = finalContent.replace(/\n{3,}/g, '\n\n'); + + return { + content: finalContent, + metadata: { + title, + sidebarPosition: frontmatter.sidebar_position || frontmatter.sidebarPosition || 999 + } + }; +} + +/** + * Process a directory of Docusaurus files + */ +async function processDirectory(sourceDir, targetDir, version) { + const files = []; + + // Recursively find all .md and .mdx files + function findFiles(dir, baseDir = '') { + const items = fs.readdirSync(dir); + + for (const item of items) { + const fullPath = path.join(dir, item); + const relativePath = path.join(baseDir, item); + const stat = fs.statSync(fullPath); + + if (stat.isDirectory()) { + findFiles(fullPath, relativePath); + } else if (item.endsWith('.md') || item.endsWith('.mdx')) { + files.push({ + source: fullPath, + relative: relativePath, + name: item + }); + } + } + } + + findFiles(sourceDir); + + console.log(`Found ${files.length} files to convert`); + + const converted = []; + + for (const file of files) { + console.log(`Converting: ${file.relative}`); + + const content = fs.readFileSync(file.source, 'utf-8'); + const result = convertDocusaurusToMintlify(content, { version }); + + // Determine target path + const targetPath = path.join(targetDir, file.relative.replace('.md', '.mdx')); + const targetSubdir = path.dirname(targetPath); + + // Ensure target directory exists + if (!fs.existsSync(targetSubdir)) { + fs.mkdirSync(targetSubdir, { recursive: true }); + } + + // Write converted file + fs.writeFileSync(targetPath, result.content); + + converted.push({ + path: targetPath, + relativePath: file.relative.replace('.md', '.mdx'), + ...result.metadata + }); + } + + return converted; +} + +/** + * Update docs.json with new navigation entries + */ +async function updateDocsJson(files, version, product = 'SDK') { + const docsJsonPath = path.join(__dirname, '../docs.json'); + const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8')); + + // Sort files by sidebar position + files.sort((a, b) => a.sidebarPosition - b.sidebarPosition); + + console.log('\nWould you like to update docs.json navigation? (y/n)'); + const updateNav = await prompt('> '); + + if (updateNav.toLowerCase() === 'y') { + // Find the product and version in navigation + // Implementation depends on your specific docs.json structure + console.log('Navigation update feature to be implemented based on your docs.json structure'); + } +} + +/** + * Main interactive flow + */ +async function main() { + console.log('=== Docusaurus to Mintlify Converter ===\n'); + + // Get source directory + const defaultSource = '/Users/cordt/repos/cosmos-sdk-docs/versioned_docs'; + console.log(`Enter source directory (default: ${defaultSource}):`); + let sourceBase = await prompt('> '); + sourceBase = sourceBase.trim() || defaultSource; + + // List available versions + if (fs.existsSync(sourceBase)) { + const versions = fs.readdirSync(sourceBase) + .filter(d => d.startsWith('version-')) + .map(d => d.replace('version-', '')); + + console.log(`\nAvailable versions: ${versions.join(', ')}`); + console.log('Enter version to convert (e.g., 0.53):'); + const versionInput = await prompt('> '); + const sourceVersion = `version-${versionInput.trim()}`; + const sourceDir = path.join(sourceBase, sourceVersion); + + if (!fs.existsSync(sourceDir)) { + console.error(`Source directory not found: ${sourceDir}`); + process.exit(1); + } + + // Get target directory + const defaultTarget = `/Users/cordt/repos/docs/docs/sdk/v${versionInput.trim()}`; + console.log(`\nEnter target directory (default: ${defaultTarget}):`); + let targetDir = await prompt('> '); + targetDir = targetDir.trim() || defaultTarget; + + // Confirm before proceeding + console.log('\n=== Conversion Summary ==='); + console.log(`Source: ${sourceDir}`); + console.log(`Target: ${targetDir}`); + console.log(`Version: v${versionInput.trim()}`); + console.log('\nProceed with conversion? (y/n)'); + + const confirm = await prompt('> '); + if (confirm.toLowerCase() !== 'y') { + console.log('Conversion cancelled'); + process.exit(0); + } + + // Process files + console.log('\nProcessing files...\n'); + const convertedFiles = await processDirectory(sourceDir, targetDir, `v${versionInput.trim()}`); + + console.log(`\n✅ Successfully converted ${convertedFiles.length} files`); + + // Optionally update navigation + await updateDocsJson(convertedFiles, `v${versionInput.trim()}`); + + } else { + console.error(`Source directory not found: ${sourceBase}`); + process.exit(1); + } + + rl.close(); +} + +// Run if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch(console.error); +} \ No newline at end of file diff --git a/scripts/docusaurus-to-mintlify.js b/scripts/docusaurus-to-mintlify.js new file mode 100644 index 00000000..ed929814 --- /dev/null +++ b/scripts/docusaurus-to-mintlify.js @@ -0,0 +1,405 @@ +#!/usr/bin/env node + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import readline from 'readline'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Create readline interface for prompts +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +const prompt = (question) => new Promise((resolve) => rl.question(question, resolve)); + +/** + * Parse Docusaurus frontmatter + */ +function parseDocusaurusFrontmatter(content) { + const lines = content.split('\n'); + const frontmatter = {}; + let contentStart = 0; + + if (lines[0] === '---') { + for (let i = 1; i < lines.length; i++) { + if (lines[i] === '---') { + contentStart = i + 1; + break; + } + const match = lines[i].match(/^(\w+):\s*(.*)$/); + if (match) { + const key = match[1]; + let value = match[2]; + // Remove quotes if present + value = value.replace(/^["']|["']$/g, ''); + frontmatter[key] = value; + } + } + } + + return { + frontmatter, + content: lines.slice(contentStart).join('\n') + }; +} + +/** + * Extract title from content (first H1 heading) + */ +function extractTitleFromContent(content) { + const match = content.match(/^#\s+(.+)$/m); + if (match) { + return { + title: match[1].trim(), + content: content.replace(match[0], '').trim() + }; + } + return { title: null, content }; +} + +/** + * Generate description from content + */ +function generateDescription(content, version = 'v0.53') { + // Remove markdown formatting + let plainText = content + .replace(/^#+\s+.*$/gm, '') // Remove headings + .replace(/```[\s\S]*?```/g, '') // Remove code blocks + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Convert links to text + .replace(/[*_`]/g, '') // Remove formatting + .trim(); + + // Find first non-empty paragraph + const paragraphs = plainText.split(/\n\n+/); + for (const para of paragraphs) { + const cleaned = para.trim(); + if (cleaned && cleaned.length > 20) { + return cleaned.length > 150 ? cleaned.substring(0, 147) + '...' : cleaned; + } + } + + return `Cosmos SDK ${version} Documentation`; +} + +/** + * Convert Docusaurus admonitions to Mintlify callouts + */ +function convertAdmonitions(content) { + const admonitionMap = { + 'note': 'Note', + 'tip': 'Tip', + 'info': 'Info', + 'warning': 'Warning', + 'danger': 'Warning', + 'caution': 'Warning', + 'important': 'Info', + 'success': 'Check' + }; + + let result = content; + + // Match multiline admonitions + const admonitionRegex = /:::(note|tip|info|warning|danger|caution|important|success)(?:\s+(.+?))?\n([\s\S]*?)\n:::/gi; + + result = result.replace(admonitionRegex, (match, type, title, content) => { + const component = admonitionMap[type.toLowerCase()] || 'Note'; + const titleLine = title ? `**${title}**\n` : ''; + return `<${component}>\n${titleLine}${content.trim()}\n`; + }); + + // Also handle single-line admonitions + const singleLineRegex = /:::(note|tip|info|warning|danger|caution|important|success)\s+(.+?)\s*:::/gi; + + result = result.replace(singleLineRegex, (match, type, content) => { + const component = admonitionMap[type.toLowerCase()] || 'Note'; + return `<${component}>${content.trim()}`; + }); + + return result; +} + +/** + * Convert code blocks to Mintlify format with expandable for long blocks + */ +function convertCodeBlocks(content) { + const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g; + + return content.replace(codeBlockRegex, (match, lang, code) => { + const lines = code.split('\n'); + const lineCount = lines.length; + + // If more than 10 lines, make it expandable + if (lineCount > 10) { + // Get first few lines for preview + const preview = lines.slice(0, 3).join('\n'); + const title = lang ? `${lang} code` : 'Code'; + + return ` +\`\`\`${lang} +${code}\`\`\` +`; + } + + // Otherwise keep as regular code block + return match; + }); +} + +/** + * Fix internal documentation links + */ +function fixInternalLinks(content, version) { + let result = content; + + // Fix v0.53 links + result = result.replace(/\]\(\/v0\.53\/learn\/advanced\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/learn\/beginner\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/learn\/intro\//g, '](/docs/sdk/v0.53/core-concepts/'); + result = result.replace(/\]\(\/v0\.53\/build\/building-modules\//g, '](/docs/sdk/v0.53/module-anatomy-keepers/'); + result = result.replace(/\]\(\/v0\.53\/build\/building-apps\//g, '](/docs/sdk/v0.53/app-wiring-runtime/'); + result = result.replace(/\]\(\/v0\.53\/build\/modules\//g, '](/docs/sdk/v0.53/module-reference/'); + result = result.replace(/\]\(\/v0\.53\/build\/abci\//g, '](/docs/sdk/v0.53/runtime-abci/'); + result = result.replace(/\]\(\/v0\.53\/tutorials\//g, '](/docs/sdk/v0.53/tutorials/'); + result = result.replace(/\]\(\/v0\.53\/user\//g, '](/docs/sdk/v0.53/node-operations/'); + + // Fix v0.50 links + result = result.replace(/\]\(\/v0\.50\/learn\//g, '](/docs/sdk/v0.50/learn/'); + result = result.replace(/\]\(\/v0\.50\/build\//g, '](/docs/sdk/v0.50/build/'); + result = result.replace(/\]\(\/v0\.50\/user\//g, '](/docs/sdk/v0.50/user/'); + + // Fix v0.47 links + result = result.replace(/\]\(\/v0\.47\/learn\//g, '](/docs/sdk/v0.47/learn/'); + result = result.replace(/\]\(\/v0\.47\/build\//g, '](/docs/sdk/v0.47/build/'); + result = result.replace(/\]\(\/v0\.47\/user\//g, '](/docs/sdk/v0.47/user/'); + + // Remove Docusaurus-specific "Direct link" anchors + result = result.replace(/\[​\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, ''); + + // Remove heading anchors {#anchor} + result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1'); + + // Fix relative links (../ or ./) + result = result.replace(/\]\(\.\.\//g, ']('); + result = result.replace(/\]\(\.\//g, ']('); + + return result; +} + +/** + * Convert a single Docusaurus file to Mintlify format + */ +function convertDocusaurusToMintlify(content, options = {}) { + const { version = 'v0.53', keepTitle = false } = options; + + // Parse frontmatter and content + const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); + + // Extract or generate title + let title = frontmatter.title || frontmatter.sidebar_label; + let processedContent = mainContent; + + if (!title) { + const extracted = extractTitleFromContent(processedContent); + title = extracted.title || 'Documentation'; + processedContent = extracted.content; + } else if (!keepTitle) { + // Remove H1 if we have title from frontmatter + const extracted = extractTitleFromContent(processedContent); + if (extracted.title) { + processedContent = extracted.content; + } + } + + // Generate or use description + const description = frontmatter.description || generateDescription(processedContent, version); + + // Apply conversions + processedContent = convertAdmonitions(processedContent); + processedContent = convertCodeBlocks(processedContent); + processedContent = fixInternalLinks(processedContent, version); + + // Build Mintlify frontmatter + const mintlifyFrontmatter = { + title, + description + }; + + // Add icon if specified + if (frontmatter.icon) { + mintlifyFrontmatter.icon = frontmatter.icon; + } + + // Build final content + let finalContent = '---\n'; + for (const [key, value] of Object.entries(mintlifyFrontmatter)) { + finalContent += `${key}: "${value}"\n`; + } + finalContent += '---\n\n'; + finalContent += processedContent; + + // Clean up multiple empty lines + finalContent = finalContent.replace(/\n{3,}/g, '\n\n'); + + return { + content: finalContent, + metadata: { + title, + sidebarPosition: frontmatter.sidebar_position || frontmatter.sidebarPosition || 999 + } + }; +} + +/** + * Process a directory of Docusaurus files + */ +async function processDirectory(sourceDir, targetDir, version) { + const files = []; + + // Recursively find all .md and .mdx files + function findFiles(dir, baseDir = '') { + const items = fs.readdirSync(dir); + + for (const item of items) { + const fullPath = path.join(dir, item); + const relativePath = path.join(baseDir, item); + const stat = fs.statSync(fullPath); + + if (stat.isDirectory()) { + findFiles(fullPath, relativePath); + } else if (item.endsWith('.md') || item.endsWith('.mdx')) { + files.push({ + source: fullPath, + relative: relativePath, + name: item + }); + } + } + } + + findFiles(sourceDir); + + console.log(`Found ${files.length} files to convert`); + + const converted = []; + + for (const file of files) { + console.log(`Converting: ${file.relative}`); + + const content = fs.readFileSync(file.source, 'utf-8'); + const result = convertDocusaurusToMintlify(content, { version }); + + // Determine target path + const targetPath = path.join(targetDir, file.relative.replace('.md', '.mdx')); + const targetSubdir = path.dirname(targetPath); + + // Ensure target directory exists + if (!fs.existsSync(targetSubdir)) { + fs.mkdirSync(targetSubdir, { recursive: true }); + } + + // Write converted file + fs.writeFileSync(targetPath, result.content); + + converted.push({ + path: targetPath, + relativePath: file.relative.replace('.md', '.mdx'), + ...result.metadata + }); + } + + return converted; +} + +/** + * Update docs.json with new navigation entries + */ +async function updateDocsJson(files, version, product = 'SDK') { + const docsJsonPath = path.join(__dirname, '../../docs.json'); + const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8')); + + // Sort files by sidebar position + files.sort((a, b) => a.sidebarPosition - b.sidebarPosition); + + console.log('\nWould you like to update docs.json navigation? (y/n)'); + const updateNav = await prompt('> '); + + if (updateNav.toLowerCase() === 'y') { + // Find the product and version in navigation + // Implementation depends on your specific docs.json structure + console.log('Navigation update feature to be implemented based on your docs.json structure'); + } +} + +/** + * Main interactive flow + */ +async function main() { + console.log('=== Docusaurus to Mintlify Converter ===\n'); + + // Get source directory + const defaultSource = '/Users/cordt/repos/cosmos-sdk-docs/versioned_docs'; + console.log(`Enter source directory (default: ${defaultSource}):`); + let sourceBase = await prompt('> '); + sourceBase = sourceBase.trim() || defaultSource; + + // List available versions + if (fs.existsSync(sourceBase)) { + const versions = fs.readdirSync(sourceBase) + .filter(d => d.startsWith('version-')) + .map(d => d.replace('version-', '')); + + console.log(`\nAvailable versions: ${versions.join(', ')}`); + console.log('Enter version to convert (e.g., 0.53):'); + const versionInput = await prompt('> '); + const sourceVersion = `version-${versionInput.trim()}`; + const sourceDir = path.join(sourceBase, sourceVersion); + + if (!fs.existsSync(sourceDir)) { + console.error(`Source directory not found: ${sourceDir}`); + process.exit(1); + } + + // Get target directory + const defaultTarget = `/Users/cordt/repos/docs/docs/sdk/v${versionInput.trim()}`; + console.log(`\nEnter target directory (default: ${defaultTarget}):`); + let targetDir = await prompt('> '); + targetDir = targetDir.trim() || defaultTarget; + + // Confirm before proceeding + console.log('\n=== Conversion Summary ==='); + console.log(`Source: ${sourceDir}`); + console.log(`Target: ${targetDir}`); + console.log(`Version: v${versionInput.trim()}`); + console.log('\nProceed with conversion? (y/n)'); + + const confirm = await prompt('> '); + if (confirm.toLowerCase() !== 'y') { + console.log('Conversion cancelled'); + process.exit(0); + } + + // Process files + console.log('\nProcessing files...\n'); + const convertedFiles = await processDirectory(sourceDir, targetDir, `v${versionInput.trim()}`); + + console.log(`\n✅ Successfully converted ${convertedFiles.length} files`); + + // Optionally update navigation + await updateDocsJson(convertedFiles, `v${versionInput.trim()}`); + + } else { + console.error(`Source directory not found: ${sourceBase}`); + process.exit(1); + } + + rl.close(); +} + +// Run if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch(console.error); +} \ No newline at end of file diff --git a/scripts/versioning/package-lock.json b/scripts/package-lock.json similarity index 98% rename from scripts/versioning/package-lock.json rename to scripts/package-lock.json index 9b93b441..53404ca2 100644 --- a/scripts/versioning/package-lock.json +++ b/scripts/package-lock.json @@ -1,11 +1,11 @@ { - "name": "cosmos-docs-versioning", + "name": "cosmos-docs-scripts", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "cosmos-docs-versioning", + "name": "cosmos-docs-scripts", "version": "1.0.0", "dependencies": { "googleapis": "^128.0.0" @@ -88,9 +88,9 @@ } }, "node_modules/debug": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", - "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", "dependencies": { "ms": "^2.1.3" diff --git a/scripts/package.json b/scripts/package.json new file mode 100644 index 00000000..ba3e277c --- /dev/null +++ b/scripts/package.json @@ -0,0 +1,24 @@ +{ + "name": "cosmos-docs-scripts", + "version": "1.0.0", + "description": "Scripts for Cosmos documentation management, versioning, and conversion", + "type": "module", + "private": true, + "scripts": { + "freeze": "node version-manager.js", + "release-notes": "node release-notes.js", + "sheets": "node sheets-manager.js", + "test-versioning": "node test-versioning.js", + "convert-docs": "node convert-docusaurus-to-mintlify.js", + "fix-frontmatter": "./fix-frontmatter.sh", + "generate-rpc-docs": "node generate-evm-rpc-docs.js", + "generate-rpc-openapi": "node generate-evm-rpc-openapi.js", + "parse-changelog": "node parse-evm-changelog.js" + }, + "dependencies": { + "googleapis": "^128.0.0" + }, + "engines": { + "node": ">=18.0.0" + } +} \ No newline at end of file diff --git a/scripts/versioning/release-notes.js b/scripts/release-notes.js similarity index 100% rename from scripts/versioning/release-notes.js rename to scripts/release-notes.js diff --git a/scripts/versioning/sheets-manager.js b/scripts/sheets-manager.js similarity index 98% rename from scripts/versioning/sheets-manager.js rename to scripts/sheets-manager.js index ed6c7d4b..af59ef9c 100644 --- a/scripts/versioning/sheets-manager.js +++ b/scripts/sheets-manager.js @@ -130,7 +130,7 @@ async function createSheetSnapshot(version) { console.error('\n Setup Instructions:'); console.error('1. Enable Google Sheets API in Google Cloud Console'); console.error('2. Create service account and download key'); - console.error('3. Save key as scripts/versioning/service-account-key.json'); + console.error('3. Save key as scripts/service-account-key.json'); console.error('4. Share spreadsheet with service account email'); console.error('5. See GSHEET-SETUP.md for detailed instructions'); } diff --git a/scripts/versioning/version-manager.js b/scripts/version-manager.js similarity index 94% rename from scripts/versioning/version-manager.js rename to scripts/version-manager.js index b8d606da..26a90ba2 100644 --- a/scripts/versioning/version-manager.js +++ b/scripts/version-manager.js @@ -44,7 +44,7 @@ async function prompt(question) { } function listDocsSubdirs() { - const docsRoot = path.join(__dirname, '..', '..', 'docs'); + const docsRoot = path.join(__dirname, '..', 'docs'); if (!fs.existsSync(docsRoot)) return []; return fs .readdirSync(docsRoot, { withFileTypes: true }) @@ -55,7 +55,7 @@ function listDocsSubdirs() { // --- Versions registry helpers (per-product) --- function loadVersionsRegistry() { - const versionsPath = path.join(__dirname, '..', '..', 'versions.json'); + const versionsPath = path.join(__dirname, '..', 'versions.json'); let data = {}; if (fs.existsSync(versionsPath)) { try { @@ -74,7 +74,7 @@ function loadVersionsRegistry() { const products = {}; const subdirs = listDocsSubdirs(); for (const subdir of subdirs) { - const base = path.join(__dirname, '..', '..', 'docs', subdir); + const base = path.join(__dirname, '..', 'docs', subdir); const entries = fs.readdirSync(base, { withFileTypes: true }) .filter(d => d.isDirectory()) .map(d => d.name); @@ -164,7 +164,7 @@ function includesVersionInReleaseNotes(content, version) { } async function checkReleaseNotes(currentVersion, subdir) { - const releaseNotesPath = path.join(__dirname, '..', '..', 'docs', subdir, 'next', 'changelog', 'release-notes.mdx'); + const releaseNotesPath = path.join(__dirname, '..', 'docs', subdir, 'next', 'changelog', 'release-notes.mdx'); if (!fs.existsSync(releaseNotesPath)) return false; const content = fs.readFileSync(releaseNotesPath, 'utf8'); return includesVersionInReleaseNotes(content, currentVersion); @@ -177,7 +177,7 @@ function updateVersionsRegistry({ subdir, freezeVersion, newVersion }) { const product = data.products[subdir]; // Ensure 'next' appears if folder exists - const nextPath = path.join(__dirname, '..', '..', 'docs', subdir, 'next'); + const nextPath = path.join(__dirname, '..', 'docs', subdir, 'next'); if (fs.existsSync(nextPath) && !product.versions.includes('next')) { product.versions.push('next'); } @@ -199,7 +199,7 @@ function updateVersionsRegistry({ subdir, freezeVersion, newVersion }) { } function updateNavigation(version, subdir) { - const docsJsonPath = path.join(__dirname, '..', '..', 'docs.json'); + const docsJsonPath = path.join(__dirname, '..', 'docs.json'); const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf8')); // Resolve dropdown label from subdir @@ -265,8 +265,8 @@ function copyAndUpdateDocs(currentVersion, subdir) { printInfo('Creating version directory...'); // Copy docs//next/ to docs/// (contents only) - const sourcePath = path.join(__dirname, '..', '..', 'docs', subdir, 'next'); - const targetPath = path.join(__dirname, '..', '..', 'docs', subdir, currentVersion); + const sourcePath = path.join(__dirname, '..', 'docs', subdir, 'next'); + const targetPath = path.join(__dirname, '..', 'docs', subdir, currentVersion); // reset target to avoid nested 'next/' execSync(`rm -rf "${targetPath}" && mkdir -p "${targetPath}"`); execSync(`cp -R "${sourcePath}/." "${targetPath}/"`); @@ -284,8 +284,8 @@ function copyAndUpdateDocs(currentVersion, subdir) { } function createVersionMetadata(currentVersion, newVersion, subdir) { - const metadataPath = path.join(__dirname, '..', '..', 'docs', subdir, currentVersion, '.version-metadata.json'); - const frozenPath = path.join(__dirname, '..', '..', 'docs', subdir, currentVersion, '.version-frozen'); + const metadataPath = path.join(__dirname, '..', 'docs', subdir, currentVersion, '.version-metadata.json'); + const frozenPath = path.join(__dirname, '..', 'docs', subdir, currentVersion, '.version-frozen'); const metadata = { version: currentVersion, diff --git a/scripts/versioning/package.json b/scripts/versioning/package.json deleted file mode 100644 index 4cb1e409..00000000 --- a/scripts/versioning/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "cosmos-docs-versioning", - "version": "1.0.0", - "description": "Version management scripts for Cosmos EVM documentation", - "type": "module", - "private": true, - "scripts": { - "freeze": "node version-manager.js", - "release-notes": "node release-notes.js", - "sheets": "node sheets-manager.js", - "test": "node test-versioning.js" - }, - "dependencies": { - "googleapis": "^128.0.0" - }, - "engines": { - "node": ">=18.0.0" - } -} \ No newline at end of file diff --git a/scripts/versioning/restructure-navigation.js b/scripts/versioning/restructure-navigation.js deleted file mode 100755 index e56746e6..00000000 --- a/scripts/versioning/restructure-navigation.js +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env node - -/** - * Restructures docs.json to have a cleaner navigation structure - * Ensures main/development version is clear and versions are properly organized - */ - -const fs = require('fs'); -const path = require('path'); - -const docsJsonPath = path.join(__dirname, '..', '..', 'docs.json'); -const versionsJsonPath = path.join(__dirname, '..', '..', 'versions.json'); - -// Read current configurations -const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf8')); -const versionsJson = JSON.parse(fs.readFileSync(versionsJsonPath, 'utf8')); - -// Restructure navigation -function restructureNavigation() { - // New navigation structure uses dropdowns per product; no restructuring needed. - if (docsJson.navigation && Array.isArray(docsJson.navigation.dropdowns)) { - console.log(' Detected dropdowns-based navigation; no restructuring required.'); - return; - } - - // Legacy fallback: convert root tabs to versions array - if (!docsJson.navigation.versions) { - docsJson.navigation.versions = []; - } - - let mainIndex = docsJson.navigation.versions.findIndex(v => v.version === 'main'); - const currentTabs = docsJson.navigation.tabs; - - if (currentTabs) { - const mainVersion = { - version: 'main', - tabs: currentTabs - }; - - if (mainIndex >= 0) { - docsJson.navigation.versions[mainIndex] = mainVersion; - } else { - docsJson.navigation.versions.push(mainVersion); - } - delete docsJson.navigation.tabs; - } - - // Simple sort helper for vX.Y[.Z] - const parseVersion = (v) => { - const match = v.match(/v(\d+)\.(\d+)(?:\.(\d+))?/); - if (!match) return [0, 0, 0]; - return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3] || '0')]; - }; - - docsJson.navigation.versions.sort((a, b) => { - if (a.version === 'main') return 1; - if (b.version === 'main') return -1; - const [aMajor, aMinor, aPatch] = parseVersion(a.version); - const [bMajor, bMinor, bPatch] = parseVersion(b.version); - if (bMajor !== aMajor) return bMajor - aMajor; - if (bMinor !== aMinor) return bMinor - aMinor; - return bPatch - aPatch; - }); - - console.log(' Navigation structure updated for legacy format.'); -} - -// Run the restructuring -restructureNavigation(); - -// Write the updated docs.json -fs.writeFileSync(docsJsonPath, JSON.stringify(docsJson, null, 2) + '\n'); -console.log(' Navigation restructured successfully'); -console.log(' docs.json updated'); - -// Provide guidance -console.log('\n Navigation structure explanation:'); -console.log(' - For dropdown-based navigation, manage versions per product in docs.json'); -if (versionsJson.products) { - console.log(' - versions.json now tracks products and their versions'); -} else { - console.log(' - Legacy versions.json detected'); -} diff --git a/scripts/versioning/test-versioning.js b/scripts/versioning/test-versioning.js deleted file mode 100644 index 46eeafef..00000000 --- a/scripts/versioning/test-versioning.js +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env node - -/** - * Test script for versioning system - * Validates setup without making actual changes - */ - -import fs from 'fs'; -import path from 'path'; -import { fileURLToPath } from 'url'; -import { execSync } from 'child_process'; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); - -console.log('='.repeat(50)); -console.log(' Testing Versioning System'); -console.log('='.repeat(50)); -console.log(''); - -// Test 1: Check dependencies -console.log('1. Checking dependencies...'); -try { - const nodeModulesPath = path.join(__dirname, 'node_modules'); - if (!fs.existsSync(nodeModulesPath)) { - throw new Error('Dependencies missing - run: cd scripts/versioning && npm install'); - } - - // Check for googleapis specifically - if (!fs.existsSync(path.join(nodeModulesPath, 'googleapis'))) { - throw new Error('googleapis dependency missing'); - } - - console.log(' ✓ Dependencies installed'); -} catch (error) { - console.log(' ✗ ' + error.message); - process.exit(1); -} - -// Test 2: Check Google Sheets API setup -console.log('2. Checking Google Sheets API setup...'); -const serviceAccountPath = path.join(__dirname, 'service-account-key.json'); - -if (!fs.existsSync(serviceAccountPath)) { - console.log(' ✗ Service account key not found'); - console.log(' ERROR: Google Sheets API credentials are required'); - console.log(' See GSHEET-SETUP.md for setup instructions'); - process.exit(1); -} - -console.log(' ✓ Service account key found'); - -// Test 3: Test Google Sheets connection -console.log(' Testing Google Sheets connection...'); -try { - execSync(`node sheets-manager.js test-version`, { - cwd: __dirname, - stdio: 'pipe' - }); - console.log(' ✓ Google Sheets test successful'); - console.log(' ! Remember to delete the "test-version" tab from Google Sheets'); -} catch (error) { - console.log(' ✗ Google Sheets test failed'); - console.log(' ERROR: Check API credentials and spreadsheet permissions'); - process.exit(1); -} - -// Test 4: Test release notes fetching -console.log('3. Testing release notes...'); -try { - execSync(`node release-notes.js latest evm`, { - cwd: __dirname, - stdio: 'pipe' - }); - console.log(' ✓ Release notes fetch successful'); -} catch (error) { - console.log(' Release notes test failed (may be network issue)'); -} - -console.log(''); -console.log('='.repeat(50)); -console.log(' Test Summary'); -console.log('='.repeat(50)); -console.log(''); -console.log(' All critical tests passed!'); -console.log(''); -console.log('Ready to use:'); -console.log(' npm run freeze # Freeze current version'); -console.log(' npm run release-notes [version] # Update release notes'); -console.log(' npm run sheets # Manage Google Sheets'); -console.log(''); From 6537ed56bbcbec5916591890be5e44899cc16d63 Mon Sep 17 00:00:00 2001 From: Cordt Date: Mon, 15 Sep 2025 17:02:35 -0600 Subject: [PATCH 3/5] update with restructure and cleanup --- docs.json | 803 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 785 insertions(+), 18 deletions(-) diff --git a/docs.json b/docs.json index 1ea454ad..39d4196c 100644 --- a/docs.json +++ b/docs.json @@ -669,8 +669,6 @@ "group": "Building Apps", "pages": [ "docs/sdk/v0.50/build/building-apps/app-go", - "docs/sdk/v0.50/build/building-apps/runtime", - "docs/sdk/v0.50/build/building-apps/app-go-di", "docs/sdk/v0.50/build/building-apps/app-mempool", "docs/sdk/v0.50/build/building-apps/app-upgrade", "docs/sdk/v0.50/build/building-apps/vote-extensions", @@ -947,12 +945,8 @@ "group": "Building Apps", "pages": [ "docs/sdk/v0.47/build/building-apps/app-go", - "docs/sdk/v0.47/build/building-apps/runtime", - "docs/sdk/v0.47/build/building-apps/app-go-di", "docs/sdk/v0.47/build/building-apps/app-mempool", "docs/sdk/v0.47/build/building-apps/app-upgrade", - "docs/sdk/v0.47/build/building-apps/vote-extensions", - "docs/sdk/v0.47/build/building-apps/app-testnet" ] }, { @@ -983,7 +977,6 @@ "docs/sdk/v0.47/build/abci/introduction", "docs/sdk/v0.47/build/abci/prepare-proposal", "docs/sdk/v0.47/build/abci/process-proposal", - "docs/sdk/v0.47/build/abci/vote-extensions", "docs/sdk/v0.47/build/abci/checktx" ] }, @@ -1176,11 +1169,26 @@ { "group": "Integration", "pages": [ - { "group": "App Wiring & Runtime", "pages": [] }, - { "group": "Module Wiring", "pages": [] }, - { "group": "Upgrades & Migrations", "pages": [] }, - { "group": "Messaging Integration", "pages": [] }, - { "group": "Vote Extensions (End-to-End)", "pages": [] } + { + "group": "App Wiring & Runtime", + "pages": [] + }, + { + "group": "Module Wiring", + "pages": [] + }, + { + "group": "Upgrades & Migrations", + "pages": [] + }, + { + "group": "Messaging Integration", + "pages": [] + }, + { + "group": "Vote Extensions (End-to-End)", + "pages": [] + } ] }, { @@ -1242,23 +1250,782 @@ "icon": "book-open-text", "versions": [ { + "version": "v10.1.x", "tabs": [ { "tab": "Documentation", - "pages": [ - "docs/ibc/v0.2.0/index" + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v10.1.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v10.1.x/ibc/overview", + "docs/ibc/v10.1.x/ibc/integration", + "docs/ibc/v10.1.x/ibc/relayer", + "docs/ibc/v10.1.x/ibc/best-practices", + "docs/ibc/v10.1.x/ibc/permissioning", + "docs/ibc/v10.1.x/ibc/apps/apps", + "docs/ibc/v10.1.x/ibc/middleware/overview", + "docs/ibc/v10.1.x/ibc/upgrades/quick-guide", + "docs/ibc/v10.1.x/ibc/apps/ibcmodule", + "docs/ibc/v10.1.x/ibc/middleware/developIBCv2", + "docs/ibc/v10.1.x/ibc/upgrades/developer-guide", + "docs/ibc/v10.1.x/ibc/apps/bindports", + "docs/ibc/v10.1.x/ibc/middleware/develop", + "docs/ibc/v10.1.x/ibc/upgrades/genesis-restart", + "docs/ibc/v10.1.x/ibc/apps/keeper", + "docs/ibc/v10.1.x/ibc/middleware/integration", + "docs/ibc/v10.1.x/ibc/apps/packets_acks", + "docs/ibc/v10.1.x/ibc/apps/routing", + "docs/ibc/v10.1.x/ibc/apps/ibcv2apps", + "docs/ibc/v10.1.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v10.1.x/migrations/support-denoms-with-slashes", + "docs/ibc/v10.1.x/migrations/sdk-to-v1", + "docs/ibc/v10.1.x/migrations/v1-to-v2", + "docs/ibc/v10.1.x/migrations/v2-to-v3", + "docs/ibc/v10.1.x/migrations/v3-to-v4", + "docs/ibc/v10.1.x/migrations/v4-to-v5", + "docs/ibc/v10.1.x/migrations/v5-to-v6", + "docs/ibc/v10.1.x/migrations/v6-to-v7", + "docs/ibc/v10.1.x/migrations/v7-to-v7_1", + "docs/ibc/v10.1.x/migrations/v7_2-to-v7_3", + "docs/ibc/v10.1.x/migrations/v7-to-v8", + "docs/ibc/v10.1.x/migrations/v8-to-v8_1", + "docs/ibc/v10.1.x/migrations/v8_1-to-v10", + "docs/ibc/v10.1.x/migrations/migration.template" + ] + }, + { + "group": "Light Clients", + "pages": [ + "docs/ibc/v10.1.x/light-clients/proposals", + "docs/ibc/v10.1.x/light-clients/developer-guide/overview", + "docs/ibc/v10.1.x/light-clients/localhost/overview", + "docs/ibc/v10.1.x/light-clients/solomachine/solomachine", + "docs/ibc/v10.1.x/light-clients/tendermint/overview", + "docs/ibc/v10.1.x/light-clients/wasm/overview", + "docs/ibc/v10.1.x/light-clients/developer-guide/light-client-module", + "docs/ibc/v10.1.x/light-clients/localhost/integration", + "docs/ibc/v10.1.x/light-clients/solomachine/concepts", + "docs/ibc/v10.1.x/light-clients/wasm/concepts", + "docs/ibc/v10.1.x/light-clients/developer-guide/client-state", + "docs/ibc/v10.1.x/light-clients/localhost/client-state", + "docs/ibc/v10.1.x/light-clients/solomachine/state", + "docs/ibc/v10.1.x/light-clients/wasm/integration", + "docs/ibc/v10.1.x/light-clients/developer-guide/consensus-state", + "docs/ibc/v10.1.x/light-clients/localhost/connection", + "docs/ibc/v10.1.x/light-clients/solomachine/state_transitions", + "docs/ibc/v10.1.x/light-clients/wasm/messages", + "docs/ibc/v10.1.x/light-clients/developer-guide/updates-and-misbehaviour", + "docs/ibc/v10.1.x/light-clients/localhost/state-verification", + "docs/ibc/v10.1.x/light-clients/wasm/governance", + "docs/ibc/v10.1.x/light-clients/developer-guide/upgrades", + "docs/ibc/v10.1.x/light-clients/wasm/events", + "docs/ibc/v10.1.x/light-clients/developer-guide/proofs", + "docs/ibc/v10.1.x/light-clients/wasm/client", + "docs/ibc/v10.1.x/light-clients/developer-guide/proposals", + "docs/ibc/v10.1.x/light-clients/wasm/contracts", + "docs/ibc/v10.1.x/light-clients/developer-guide/setup", + "docs/ibc/v10.1.x/light-clients/wasm/migrations" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v10.1.x/apps/interchain-accounts/overview", + "docs/ibc/v10.1.x/apps/transfer/overview", + "docs/ibc/v10.1.x/apps/interchain-accounts/development", + "docs/ibc/v10.1.x/apps/transfer/state", + "docs/ibc/v10.1.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v10.1.x/apps/transfer/state-transitions", + "docs/ibc/v10.1.x/apps/interchain-accounts/integration", + "docs/ibc/v10.1.x/apps/transfer/messages", + "docs/ibc/v10.1.x/apps/interchain-accounts/messages", + "docs/ibc/v10.1.x/apps/transfer/events", + "docs/ibc/v10.1.x/apps/interchain-accounts/parameters", + "docs/ibc/v10.1.x/apps/transfer/metrics", + "docs/ibc/v10.1.x/apps/interchain-accounts/tx-encoding", + "docs/ibc/v10.1.x/apps/transfer/params", + "docs/ibc/v10.1.x/apps/interchain-accounts/client", + "docs/ibc/v10.1.x/apps/transfer/authorizations", + "docs/ibc/v10.1.x/apps/interchain-accounts/active-channels", + "docs/ibc/v10.1.x/apps/transfer/client", + "docs/ibc/v10.1.x/apps/transfer/IBCv2-transfer", + "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/auth-modules", + "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/integration", + "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/keeper-api" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v10.1.x/middleware/callbacks/overview", + "docs/ibc/v10.1.x/middleware/callbacks/integration", + "docs/ibc/v10.1.x/middleware/callbacks/interfaces", + "docs/ibc/v10.1.x/middleware/callbacks/events", + "docs/ibc/v10.1.x/middleware/callbacks/end-users", + "docs/ibc/v10.1.x/middleware/callbacks/gas", + "docs/ibc/v10.1.x/middleware/callbacks/callbacks-IBCv2" + ] + } + ] + } + ] + }, + { + "version": "v4.6.x", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v4.6.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v4.6.x/ibc/overview", + "docs/ibc/v4.6.x/ibc/integration", + "docs/ibc/v4.6.x/ibc/proposals", + "docs/ibc/v4.6.x/ibc/relayer", + "docs/ibc/v4.6.x/ibc/proto-docs", + "docs/ibc/v4.6.x/ibc/roadmap", + "docs/ibc/v4.6.x/ibc/apps/apps", + "docs/ibc/v4.6.x/ibc/middleware/develop", + "docs/ibc/v4.6.x/ibc/upgrades/quick-guide", + "docs/ibc/v4.6.x/ibc/apps/ibcmodule", + "docs/ibc/v4.6.x/ibc/middleware/integration", + "docs/ibc/v4.6.x/ibc/upgrades/developer-guide", + "docs/ibc/v4.6.x/ibc/apps/bindports", + "docs/ibc/v4.6.x/ibc/upgrades/genesis-restart", + "docs/ibc/v4.6.x/ibc/apps/keeper", + "docs/ibc/v4.6.x/ibc/apps/packets_acks", + "docs/ibc/v4.6.x/ibc/apps/routing", + "docs/ibc/v4.6.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v4.6.x/migrations/support-denoms-with-slashes", + "docs/ibc/v4.6.x/migrations/sdk-to-v1", + "docs/ibc/v4.6.x/migrations/v1-to-v2", + "docs/ibc/v4.6.x/migrations/v2-to-v3", + "docs/ibc/v4.6.x/migrations/v3-to-v4" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v4.6.x/apps/interchain-accounts/overview", + "docs/ibc/v4.6.x/apps/transfer/overview", + "docs/ibc/v4.6.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v4.6.x/apps/transfer/state", + "docs/ibc/v4.6.x/apps/interchain-accounts/active-channels", + "docs/ibc/v4.6.x/apps/transfer/state-transitions", + "docs/ibc/v4.6.x/apps/interchain-accounts/integration", + "docs/ibc/v4.6.x/apps/transfer/messages", + "docs/ibc/v4.6.x/apps/interchain-accounts/parameters", + "docs/ibc/v4.6.x/apps/transfer/events", + "docs/ibc/v4.6.x/apps/interchain-accounts/transactions", + "docs/ibc/v4.6.x/apps/transfer/metrics", + "docs/ibc/v4.6.x/apps/transfer/params" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v4.6.x/middleware/ics29-fee/overview", + "docs/ibc/v4.6.x/middleware/ics29-fee/integration", + "docs/ibc/v4.6.x/middleware/ics29-fee/msgs", + "docs/ibc/v4.6.x/middleware/ics29-fee/fee-distribution", + "docs/ibc/v4.6.x/middleware/ics29-fee/events", + "docs/ibc/v4.6.x/middleware/ics29-fee/end-users" + ] + } + ] + } + ] + }, + { + "version": "v5.4.x", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v5.4.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v5.4.x/ibc/overview", + "docs/ibc/v5.4.x/ibc/integration", + "docs/ibc/v5.4.x/ibc/proposals", + "docs/ibc/v5.4.x/ibc/relayer", + "docs/ibc/v5.4.x/ibc/proto-docs", + "docs/ibc/v5.4.x/ibc/roadmap", + "docs/ibc/v5.4.x/ibc/apps/apps", + "docs/ibc/v5.4.x/ibc/middleware/develop", + "docs/ibc/v5.4.x/ibc/upgrades/quick-guide", + "docs/ibc/v5.4.x/ibc/apps/ibcmodule", + "docs/ibc/v5.4.x/ibc/middleware/integration", + "docs/ibc/v5.4.x/ibc/upgrades/developer-guide", + "docs/ibc/v5.4.x/ibc/apps/bindports", + "docs/ibc/v5.4.x/ibc/upgrades/genesis-restart", + "docs/ibc/v5.4.x/ibc/apps/keeper", + "docs/ibc/v5.4.x/ibc/apps/packets_acks", + "docs/ibc/v5.4.x/ibc/apps/routing", + "docs/ibc/v5.4.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v5.4.x/migrations/support-denoms-with-slashes", + "docs/ibc/v5.4.x/migrations/sdk-to-v1", + "docs/ibc/v5.4.x/migrations/v1-to-v2", + "docs/ibc/v5.4.x/migrations/v2-to-v3", + "docs/ibc/v5.4.x/migrations/v3-to-v4" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v5.4.x/apps/interchain-accounts/overview", + "docs/ibc/v5.4.x/apps/transfer/overview", + "docs/ibc/v5.4.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v5.4.x/apps/transfer/state", + "docs/ibc/v5.4.x/apps/interchain-accounts/active-channels", + "docs/ibc/v5.4.x/apps/transfer/state-transitions", + "docs/ibc/v5.4.x/apps/interchain-accounts/integration", + "docs/ibc/v5.4.x/apps/transfer/messages", + "docs/ibc/v5.4.x/apps/interchain-accounts/parameters", + "docs/ibc/v5.4.x/apps/transfer/events", + "docs/ibc/v5.4.x/apps/interchain-accounts/transactions", + "docs/ibc/v5.4.x/apps/transfer/metrics", + "docs/ibc/v5.4.x/apps/transfer/params" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v5.4.x/middleware/ics29-fee/overview", + "docs/ibc/v5.4.x/middleware/ics29-fee/integration", + "docs/ibc/v5.4.x/middleware/ics29-fee/msgs", + "docs/ibc/v5.4.x/middleware/ics29-fee/fee-distribution", + "docs/ibc/v5.4.x/middleware/ics29-fee/events", + "docs/ibc/v5.4.x/middleware/ics29-fee/end-users" + ] + } ] } - ], - "version": "v0.2.0" + ] + }, + { + "version": "v6.3.x", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v6.3.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v6.3.x/ibc/overview", + "docs/ibc/v6.3.x/ibc/integration", + "docs/ibc/v6.3.x/ibc/proposals", + "docs/ibc/v6.3.x/ibc/relayer", + "docs/ibc/v6.3.x/ibc/proto-docs", + "docs/ibc/v6.3.x/ibc/roadmap", + "docs/ibc/v6.3.x/ibc/apps/apps", + "docs/ibc/v6.3.x/ibc/middleware/develop", + "docs/ibc/v6.3.x/ibc/upgrades/quick-guide", + "docs/ibc/v6.3.x/ibc/apps/ibcmodule", + "docs/ibc/v6.3.x/ibc/middleware/integration", + "docs/ibc/v6.3.x/ibc/upgrades/developer-guide", + "docs/ibc/v6.3.x/ibc/apps/bindports", + "docs/ibc/v6.3.x/ibc/upgrades/genesis-restart", + "docs/ibc/v6.3.x/ibc/apps/keeper", + "docs/ibc/v6.3.x/ibc/apps/packets_acks", + "docs/ibc/v6.3.x/ibc/apps/routing", + "docs/ibc/v6.3.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v6.3.x/migrations/support-denoms-with-slashes", + "docs/ibc/v6.3.x/migrations/sdk-to-v1", + "docs/ibc/v6.3.x/migrations/v1-to-v2", + "docs/ibc/v6.3.x/migrations/v2-to-v3", + "docs/ibc/v6.3.x/migrations/v3-to-v4", + "docs/ibc/v6.3.x/migrations/v4-to-v5", + "docs/ibc/v6.3.x/migrations/v5-to-v6" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v6.3.x/apps/interchain-accounts/overview", + "docs/ibc/v6.3.x/apps/transfer/overview", + "docs/ibc/v6.3.x/apps/interchain-accounts/development", + "docs/ibc/v6.3.x/apps/transfer/state", + "docs/ibc/v6.3.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v6.3.x/apps/transfer/state-transitions", + "docs/ibc/v6.3.x/apps/interchain-accounts/integration", + "docs/ibc/v6.3.x/apps/transfer/messages", + "docs/ibc/v6.3.x/apps/interchain-accounts/messages", + "docs/ibc/v6.3.x/apps/transfer/events", + "docs/ibc/v6.3.x/apps/interchain-accounts/parameters", + "docs/ibc/v6.3.x/apps/transfer/metrics", + "docs/ibc/v6.3.x/apps/interchain-accounts/client", + "docs/ibc/v6.3.x/apps/transfer/params", + "docs/ibc/v6.3.x/apps/interchain-accounts/active-channels", + "docs/ibc/v6.3.x/apps/transfer/authorizations", + "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/auth-modules", + "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/integration", + "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/keeper-api" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v6.3.x/middleware/ics29-fee/overview", + "docs/ibc/v6.3.x/middleware/ics29-fee/integration", + "docs/ibc/v6.3.x/middleware/ics29-fee/msgs", + "docs/ibc/v6.3.x/middleware/ics29-fee/fee-distribution", + "docs/ibc/v6.3.x/middleware/ics29-fee/events", + "docs/ibc/v6.3.x/middleware/ics29-fee/end-users" + ] + } + ] + } + ] + }, + { + "version": "v7.8.x", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v7.8.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v7.8.x/ibc/overview", + "docs/ibc/v7.8.x/ibc/integration", + "docs/ibc/v7.8.x/ibc/proposals", + "docs/ibc/v7.8.x/ibc/relayer", + "docs/ibc/v7.8.x/ibc/proto-docs", + "docs/ibc/v7.8.x/ibc/roadmap", + "docs/ibc/v7.8.x/ibc/troubleshooting", + "docs/ibc/v7.8.x/ibc/apps/apps", + "docs/ibc/v7.8.x/ibc/middleware/develop", + "docs/ibc/v7.8.x/ibc/upgrades/quick-guide", + "docs/ibc/v7.8.x/ibc/apps/ibcmodule", + "docs/ibc/v7.8.x/ibc/middleware/integration", + "docs/ibc/v7.8.x/ibc/upgrades/developer-guide", + "docs/ibc/v7.8.x/ibc/apps/bindports", + "docs/ibc/v7.8.x/ibc/upgrades/genesis-restart", + "docs/ibc/v7.8.x/ibc/apps/keeper", + "docs/ibc/v7.8.x/ibc/apps/packets_acks", + "docs/ibc/v7.8.x/ibc/apps/routing", + "docs/ibc/v7.8.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v7.8.x/migrations/support-denoms-with-slashes", + "docs/ibc/v7.8.x/migrations/sdk-to-v1", + "docs/ibc/v7.8.x/migrations/v1-to-v2", + "docs/ibc/v7.8.x/migrations/v2-to-v3", + "docs/ibc/v7.8.x/migrations/v3-to-v4", + "docs/ibc/v7.8.x/migrations/v4-to-v5", + "docs/ibc/v7.8.x/migrations/v5-to-v6", + "docs/ibc/v7.8.x/migrations/v6-to-v7", + "docs/ibc/v7.8.x/migrations/v7-to-v7_1", + "docs/ibc/v7.8.x/migrations/v7_2-to-v7_3" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v7.8.x/apps/interchain-accounts/overview", + "docs/ibc/v7.8.x/apps/transfer/overview", + "docs/ibc/v7.8.x/apps/interchain-accounts/development", + "docs/ibc/v7.8.x/apps/transfer/state", + "docs/ibc/v7.8.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v7.8.x/apps/transfer/state-transitions", + "docs/ibc/v7.8.x/apps/interchain-accounts/integration", + "docs/ibc/v7.8.x/apps/transfer/messages", + "docs/ibc/v7.8.x/apps/interchain-accounts/messages", + "docs/ibc/v7.8.x/apps/transfer/events", + "docs/ibc/v7.8.x/apps/interchain-accounts/parameters", + "docs/ibc/v7.8.x/apps/transfer/metrics", + "docs/ibc/v7.8.x/apps/interchain-accounts/tx-encoding", + "docs/ibc/v7.8.x/apps/transfer/params", + "docs/ibc/v7.8.x/apps/interchain-accounts/client", + "docs/ibc/v7.8.x/apps/transfer/authorizations", + "docs/ibc/v7.8.x/apps/interchain-accounts/active-channels", + "docs/ibc/v7.8.x/apps/transfer/client", + "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/auth-modules", + "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/integration", + "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/keeper-api" + ] + }, + { + "group": "Light Clients", + "pages": [ + "docs/ibc/v7.8.x/light-clients/developer-guide/overview", + "docs/ibc/v7.8.x/light-clients/localhost/overview", + "docs/ibc/v7.8.x/light-clients/solomachine/solomachine", + "docs/ibc/v7.8.x/light-clients/wasm/overview", + "docs/ibc/v7.8.x/light-clients/developer-guide/client-state", + "docs/ibc/v7.8.x/light-clients/localhost/integration", + "docs/ibc/v7.8.x/light-clients/solomachine/concepts", + "docs/ibc/v7.8.x/light-clients/wasm/concepts", + "docs/ibc/v7.8.x/light-clients/developer-guide/consensus-state", + "docs/ibc/v7.8.x/light-clients/localhost/client-state", + "docs/ibc/v7.8.x/light-clients/solomachine/state", + "docs/ibc/v7.8.x/light-clients/wasm/integration", + "docs/ibc/v7.8.x/light-clients/developer-guide/updates-and-misbehaviour", + "docs/ibc/v7.8.x/light-clients/localhost/connection", + "docs/ibc/v7.8.x/light-clients/solomachine/state_transitions", + "docs/ibc/v7.8.x/light-clients/wasm/messages", + "docs/ibc/v7.8.x/light-clients/developer-guide/upgrades", + "docs/ibc/v7.8.x/light-clients/localhost/state-verification", + "docs/ibc/v7.8.x/light-clients/wasm/governance", + "docs/ibc/v7.8.x/light-clients/developer-guide/proofs", + "docs/ibc/v7.8.x/light-clients/wasm/events", + "docs/ibc/v7.8.x/light-clients/developer-guide/proposals", + "docs/ibc/v7.8.x/light-clients/wasm/client", + "docs/ibc/v7.8.x/light-clients/developer-guide/genesis", + "docs/ibc/v7.8.x/light-clients/wasm/contracts", + "docs/ibc/v7.8.x/light-clients/developer-guide/setup" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v7.8.x/middleware/callbacks/overview", + "docs/ibc/v7.8.x/middleware/ics29-fee/overview", + "docs/ibc/v7.8.x/middleware/callbacks/integration", + "docs/ibc/v7.8.x/middleware/ics29-fee/integration", + "docs/ibc/v7.8.x/middleware/callbacks/interfaces", + "docs/ibc/v7.8.x/middleware/ics29-fee/msgs", + "docs/ibc/v7.8.x/middleware/callbacks/events", + "docs/ibc/v7.8.x/middleware/ics29-fee/fee-distribution", + "docs/ibc/v7.8.x/middleware/callbacks/end-users", + "docs/ibc/v7.8.x/middleware/ics29-fee/events", + "docs/ibc/v7.8.x/middleware/callbacks/gas", + "docs/ibc/v7.8.x/middleware/ics29-fee/end-users" + ] + } + ] + } + ] + }, + { + "version": "v8.5.x", + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/v8.5.x/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/v8.5.x/ibc/overview", + "docs/ibc/v8.5.x/ibc/integration", + "docs/ibc/v8.5.x/ibc/channel-upgrades", + "docs/ibc/v8.5.x/ibc/proposals", + "docs/ibc/v8.5.x/ibc/relayer", + "docs/ibc/v8.5.x/ibc/proto-docs", + "docs/ibc/v8.5.x/ibc/roadmap", + "docs/ibc/v8.5.x/ibc/troubleshooting", + "docs/ibc/v8.5.x/ibc/capability-module", + "docs/ibc/v8.5.x/ibc/apps/apps", + "docs/ibc/v8.5.x/ibc/middleware/overview", + "docs/ibc/v8.5.x/ibc/upgrades/quick-guide", + "docs/ibc/v8.5.x/ibc/apps/ibcmodule", + "docs/ibc/v8.5.x/ibc/middleware/develop", + "docs/ibc/v8.5.x/ibc/upgrades/developer-guide", + "docs/ibc/v8.5.x/ibc/apps/bindports", + "docs/ibc/v8.5.x/ibc/middleware/integration", + "docs/ibc/v8.5.x/ibc/upgrades/genesis-restart", + "docs/ibc/v8.5.x/ibc/apps/keeper", + "docs/ibc/v8.5.x/ibc/apps/packets_acks", + "docs/ibc/v8.5.x/ibc/apps/routing", + "docs/ibc/v8.5.x/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/v8.5.x/migrations/support-denoms-with-slashes", + "docs/ibc/v8.5.x/migrations/sdk-to-v1", + "docs/ibc/v8.5.x/migrations/v1-to-v2", + "docs/ibc/v8.5.x/migrations/v2-to-v3", + "docs/ibc/v8.5.x/migrations/v3-to-v4", + "docs/ibc/v8.5.x/migrations/v4-to-v5", + "docs/ibc/v8.5.x/migrations/v5-to-v6", + "docs/ibc/v8.5.x/migrations/v6-to-v7", + "docs/ibc/v8.5.x/migrations/v7-to-v7_1", + "docs/ibc/v8.5.x/migrations/v7_2-to-v7_3", + "docs/ibc/v8.5.x/migrations/v7-to-v8", + "docs/ibc/v8.5.x/migrations/v8-to-v8_1", + "docs/ibc/v8.5.x/migrations/migration.template" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/v8.5.x/apps/interchain-accounts/overview", + "docs/ibc/v8.5.x/apps/transfer/overview", + "docs/ibc/v8.5.x/apps/interchain-accounts/development", + "docs/ibc/v8.5.x/apps/transfer/state", + "docs/ibc/v8.5.x/apps/interchain-accounts/auth-modules", + "docs/ibc/v8.5.x/apps/transfer/state-transitions", + "docs/ibc/v8.5.x/apps/interchain-accounts/integration", + "docs/ibc/v8.5.x/apps/transfer/messages", + "docs/ibc/v8.5.x/apps/interchain-accounts/messages", + "docs/ibc/v8.5.x/apps/transfer/events", + "docs/ibc/v8.5.x/apps/interchain-accounts/parameters", + "docs/ibc/v8.5.x/apps/transfer/metrics", + "docs/ibc/v8.5.x/apps/interchain-accounts/tx-encoding", + "docs/ibc/v8.5.x/apps/transfer/params", + "docs/ibc/v8.5.x/apps/interchain-accounts/client", + "docs/ibc/v8.5.x/apps/transfer/authorizations", + "docs/ibc/v8.5.x/apps/interchain-accounts/active-channels", + "docs/ibc/v8.5.x/apps/transfer/client", + "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/auth-modules", + "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/integration", + "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/keeper-api" + ] + }, + { + "group": "Light Clients", + "pages": [ + "docs/ibc/v8.5.x/light-clients/developer-guide/overview", + "docs/ibc/v8.5.x/light-clients/localhost/overview", + "docs/ibc/v8.5.x/light-clients/solomachine/solomachine", + "docs/ibc/v8.5.x/light-clients/wasm/overview", + "docs/ibc/v8.5.x/light-clients/developer-guide/client-state", + "docs/ibc/v8.5.x/light-clients/localhost/integration", + "docs/ibc/v8.5.x/light-clients/solomachine/concepts", + "docs/ibc/v8.5.x/light-clients/wasm/concepts", + "docs/ibc/v8.5.x/light-clients/developer-guide/consensus-state", + "docs/ibc/v8.5.x/light-clients/localhost/client-state", + "docs/ibc/v8.5.x/light-clients/solomachine/state", + "docs/ibc/v8.5.x/light-clients/wasm/integration", + "docs/ibc/v8.5.x/light-clients/developer-guide/updates-and-misbehaviour", + "docs/ibc/v8.5.x/light-clients/localhost/connection", + "docs/ibc/v8.5.x/light-clients/solomachine/state_transitions", + "docs/ibc/v8.5.x/light-clients/wasm/messages", + "docs/ibc/v8.5.x/light-clients/developer-guide/upgrades", + "docs/ibc/v8.5.x/light-clients/localhost/state-verification", + "docs/ibc/v8.5.x/light-clients/wasm/governance", + "docs/ibc/v8.5.x/light-clients/developer-guide/proofs", + "docs/ibc/v8.5.x/light-clients/wasm/events", + "docs/ibc/v8.5.x/light-clients/developer-guide/proposals", + "docs/ibc/v8.5.x/light-clients/wasm/client", + "docs/ibc/v8.5.x/light-clients/developer-guide/genesis", + "docs/ibc/v8.5.x/light-clients/wasm/contracts", + "docs/ibc/v8.5.x/light-clients/developer-guide/setup", + "docs/ibc/v8.5.x/light-clients/wasm/migrations" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/v8.5.x/middleware/callbacks/overview", + "docs/ibc/v8.5.x/middleware/ics29-fee/overview", + "docs/ibc/v8.5.x/middleware/callbacks/integration", + "docs/ibc/v8.5.x/middleware/ics29-fee/integration", + "docs/ibc/v8.5.x/middleware/callbacks/interfaces", + "docs/ibc/v8.5.x/middleware/ics29-fee/msgs", + "docs/ibc/v8.5.x/middleware/callbacks/events", + "docs/ibc/v8.5.x/middleware/ics29-fee/fee-distribution", + "docs/ibc/v8.5.x/middleware/callbacks/end-users", + "docs/ibc/v8.5.x/middleware/ics29-fee/events", + "docs/ibc/v8.5.x/middleware/callbacks/gas", + "docs/ibc/v8.5.x/middleware/ics29-fee/end-users" + ] + } + ] + } + ] }, { "version": "next", "tabs": [ { "tab": "Documentation", - "pages": [ - "docs/ibc/next/index" + "groups": [ + { + "group": "IBC", + "pages": [ + "docs/ibc/next/intro" + ] + }, + { + "group": "Ibc", + "pages": [ + "docs/ibc/next/ibc/overview", + "docs/ibc/next/ibc/integration", + "docs/ibc/next/ibc/relayer", + "docs/ibc/next/ibc/best-practices", + "docs/ibc/next/ibc/permissioning", + "docs/ibc/next/ibc/apps/apps", + "docs/ibc/next/ibc/middleware/overview", + "docs/ibc/next/ibc/upgrades/quick-guide", + "docs/ibc/next/ibc/apps/ibcmodule", + "docs/ibc/next/ibc/middleware/developIBCv2", + "docs/ibc/next/ibc/upgrades/developer-guide", + "docs/ibc/next/ibc/apps/bindports", + "docs/ibc/next/ibc/middleware/develop", + "docs/ibc/next/ibc/upgrades/genesis-restart", + "docs/ibc/next/ibc/apps/keeper", + "docs/ibc/next/ibc/middleware/integration", + "docs/ibc/next/ibc/apps/packets_acks", + "docs/ibc/next/ibc/apps/routing", + "docs/ibc/next/ibc/apps/ibcv2apps", + "docs/ibc/next/ibc/upgrades/intro" + ] + }, + { + "group": "Migrations", + "pages": [ + "docs/ibc/next/migrations/support-denoms-with-slashes", + "docs/ibc/next/migrations/support-stackbuilder", + "docs/ibc/next/migrations/sdk-to-v1", + "docs/ibc/next/migrations/v1-to-v2", + "docs/ibc/next/migrations/v2-to-v3", + "docs/ibc/next/migrations/v3-to-v4", + "docs/ibc/next/migrations/v4-to-v5", + "docs/ibc/next/migrations/v5-to-v6", + "docs/ibc/next/migrations/v6-to-v7", + "docs/ibc/next/migrations/v7-to-v7_1", + "docs/ibc/next/migrations/v7_2-to-v7_3", + "docs/ibc/next/migrations/v7-to-v8", + "docs/ibc/next/migrations/v8-to-v8_1", + "docs/ibc/next/migrations/v8_1-to-v10", + "docs/ibc/next/migrations/v10-to-v11", + "docs/ibc/next/migrations/migration.template" + ] + }, + { + "group": "Light Clients", + "pages": [ + "docs/ibc/next/light-clients/proposals", + "docs/ibc/next/light-clients/developer-guide/overview", + "docs/ibc/next/light-clients/localhost/overview", + "docs/ibc/next/light-clients/solomachine/solomachine", + "docs/ibc/next/light-clients/tendermint/overview", + "docs/ibc/next/light-clients/wasm/overview", + "docs/ibc/next/light-clients/developer-guide/light-client-module", + "docs/ibc/next/light-clients/localhost/integration", + "docs/ibc/next/light-clients/solomachine/concepts", + "docs/ibc/next/light-clients/wasm/concepts", + "docs/ibc/next/light-clients/developer-guide/client-state", + "docs/ibc/next/light-clients/localhost/client-state", + "docs/ibc/next/light-clients/solomachine/state", + "docs/ibc/next/light-clients/wasm/integration", + "docs/ibc/next/light-clients/developer-guide/consensus-state", + "docs/ibc/next/light-clients/localhost/connection", + "docs/ibc/next/light-clients/solomachine/state_transitions", + "docs/ibc/next/light-clients/wasm/messages", + "docs/ibc/next/light-clients/developer-guide/updates-and-misbehaviour", + "docs/ibc/next/light-clients/localhost/state-verification", + "docs/ibc/next/light-clients/wasm/governance", + "docs/ibc/next/light-clients/developer-guide/upgrades", + "docs/ibc/next/light-clients/wasm/events", + "docs/ibc/next/light-clients/developer-guide/proofs", + "docs/ibc/next/light-clients/wasm/client", + "docs/ibc/next/light-clients/developer-guide/proposals", + "docs/ibc/next/light-clients/wasm/contracts", + "docs/ibc/next/light-clients/developer-guide/setup", + "docs/ibc/next/light-clients/wasm/migrations" + ] + }, + { + "group": "Apps", + "pages": [ + "docs/ibc/next/apps/interchain-accounts/overview", + "docs/ibc/next/apps/transfer/overview", + "docs/ibc/next/apps/interchain-accounts/development", + "docs/ibc/next/apps/transfer/state", + "docs/ibc/next/apps/interchain-accounts/auth-modules", + "docs/ibc/next/apps/transfer/state-transitions", + "docs/ibc/next/apps/interchain-accounts/integration", + "docs/ibc/next/apps/transfer/messages", + "docs/ibc/next/apps/interchain-accounts/messages", + "docs/ibc/next/apps/transfer/events", + "docs/ibc/next/apps/interchain-accounts/parameters", + "docs/ibc/next/apps/transfer/metrics", + "docs/ibc/next/apps/interchain-accounts/tx-encoding", + "docs/ibc/next/apps/transfer/params", + "docs/ibc/next/apps/interchain-accounts/client", + "docs/ibc/next/apps/transfer/authorizations", + "docs/ibc/next/apps/interchain-accounts/active-channels", + "docs/ibc/next/apps/transfer/client", + "docs/ibc/next/apps/transfer/IBCv2-transfer", + "docs/ibc/next/apps/interchain-accounts/legacy/auth-modules", + "docs/ibc/next/apps/interchain-accounts/legacy/integration", + "docs/ibc/next/apps/interchain-accounts/legacy/keeper-api" + ] + }, + { + "group": "Middleware", + "pages": [ + "docs/ibc/next/middleware/callbacks/overview", + "docs/ibc/next/middleware/packet-forward-middleware/integration", + "docs/ibc/next/middleware/rate-limit-middleware/overview", + "docs/ibc/next/middleware/callbacks/integration", + "docs/ibc/next/middleware/packet-forward-middleware/overview", + "docs/ibc/next/middleware/rate-limit-middleware/integration", + "docs/ibc/next/middleware/callbacks/interfaces", + "docs/ibc/next/middleware/packet-forward-middleware/example-usage", + "docs/ibc/next/middleware/rate-limit-middleware/setting-limits", + "docs/ibc/next/middleware/callbacks/events", + "docs/ibc/next/middleware/callbacks/end-users", + "docs/ibc/next/middleware/callbacks/gas", + "docs/ibc/next/middleware/callbacks/callbacks-IBCv2" + ] + } ] } ] From b5b477c653b54066347e8d39b5704c32ef7f988f Mon Sep 17 00:00:00 2001 From: Cordt Date: Mon, 15 Sep 2025 17:11:04 -0600 Subject: [PATCH 4/5] update with restructure and cleanup --- docs.json | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/docs.json b/docs.json index 39d4196c..d50c8a88 100644 --- a/docs.json +++ b/docs.json @@ -48,7 +48,7 @@ "tab": "Documentation", "groups": [ { - "group": "EVM", + "group": "Cosmos EVM", "pages": [ "docs/evm/v0.4.x/documentation/overview", { @@ -353,10 +353,13 @@ "tabs": [ { "tab": "Documentation", - "pages": [ - "docs/sdk/v0.53/overview" - ], "groups": [ + { + "group": "Cosmos-SDK", + "pages": [ + "docs/sdk/v0.53/overview" + ] + }, { "group": "Core Concepts", "pages": [ @@ -607,6 +610,12 @@ { "tab": "Learn", "groups": [ + { + "group": "Cosmos-SDK", + "pages": [ + "docs/sdk/v0.50/overview" + ] + }, { "group": "Learn", "pages": [ @@ -883,6 +892,12 @@ { "tab": "Learn", "groups": [ + { + "group": "Cosmos-SDK", + "pages": [ + "docs/sdk/v0.47/overview" + ] + }, { "group": "Learn", "pages": [ @@ -946,7 +961,7 @@ "pages": [ "docs/sdk/v0.47/build/building-apps/app-go", "docs/sdk/v0.47/build/building-apps/app-mempool", - "docs/sdk/v0.47/build/building-apps/app-upgrade", + "docs/sdk/v0.47/build/building-apps/app-upgrade" ] }, { @@ -1156,6 +1171,12 @@ { "tab": "Documentation", "groups": [ + { + "group": "Cosmos-SDK", + "pages": [ + "docs/sdk/next/overview" + ] + }, { "group": "Transactions & Fees", "pages": [] From dcf33196443e11d1188a3d2066cb65082c0c0f6e Mon Sep 17 00:00:00 2001 From: Cordt Date: Tue, 16 Sep 2025 14:38:00 -0600 Subject: [PATCH 5/5] clean up sdk, fix all redirects, organize nav sructure with cleanup --- docs.json | 2502 ++++++----------- docs/ibc/next/changelog/release-notes.mdx | 9 - docs/ibc/next/index.mdx | 11 - docs/ibc/next/link-rewrite-test.mdx | 14 - docs/sdk/index.mdx | 55 - docs/sdk/next/learn/advanced/autocli.mdx | 272 ++ docs/sdk/next/learn/advanced/baseapp.mdx | 543 ++++ docs/sdk/next/learn/advanced/cli.mdx | 209 ++ docs/sdk/next/learn/advanced/config.mdx | 25 + docs/sdk/next/learn/advanced/context.mdx | 104 + docs/sdk/next/learn/advanced/encoding.mdx | 291 ++ docs/sdk/next/learn/advanced/events.mdx | 158 ++ docs/sdk/next/learn/advanced/grpc_rest.mdx | 103 + docs/sdk/next/learn/advanced/node.mdx | 95 + docs/sdk/next/learn/advanced/ocap.mdx | 79 + docs/sdk/next/learn/advanced/proto-docs.mdx | 5 + .../next/learn/advanced/runtx_middleware.mdx | 70 + docs/sdk/next/learn/advanced/simulation.mdx | 94 + docs/sdk/next/learn/advanced/store.mdx | 287 ++ docs/sdk/next/learn/advanced/telemetry.mdx | 126 + docs/sdk/next/learn/advanced/transactions.mdx | 228 ++ docs/sdk/next/learn/advanced/upgrade.mdx | 163 ++ docs/sdk/next/learn/beginner/accounts.mdx | 305 ++ docs/sdk/next/learn/beginner/app-anatomy.mdx | 277 ++ docs/sdk/next/learn/beginner/gas-fees.mdx | 101 + .../next/learn/beginner/query-lifecycle.mdx | 146 + docs/sdk/next/learn/beginner/tx-lifecycle.mdx | 283 ++ docs/sdk/next/learn/intro/overview.mdx | 40 + .../next/learn/intro/sdk-app-architecture.mdx | 91 + docs/sdk/next/learn/intro/sdk-design.mdx | 61 + .../sdk/next/learn/intro/why-app-specific.mdx | 81 + docs/sdk/next/learn/learn.mdx | 9 + docs/sdk/next/overview.mdx | 44 + .../transactions/building-a-transaction.mdx | 192 ++ .../tutorials/tutorials.mdx} | 6 +- .../demo-of-mitigating-front-running.mdx | 78 +- .../auction-frontrunning/getting-started.mdx | 27 +- ...ing-front-running-with-vote-extensions.mdx | 379 +++ ...ting-front-running-with-vote-extesions.mdx | 379 +++ .../understanding-frontrunning.mdx | 23 +- .../oracle/getting-started.mdx | 21 +- .../oracle/implementing-vote-extensions.mdx | 253 ++ .../vote-extensions/oracle/testing-oracle.mdx | 29 +- .../oracle/what-is-an-oracle.mdx | 8 +- docs/sdk/next/user/run-node/interact-node.mdx | 298 ++ docs/sdk/next/user/run-node/keyring.mdx | 143 + docs/sdk/next/user/run-node/rosetta.mdx | 154 + docs/sdk/next/user/run-node/run-node.mdx | 217 ++ .../sdk/next/user/run-node/run-production.mdx | 267 ++ docs/sdk/next/user/run-node/run-testnet.mdx | 97 + docs/sdk/next/user/run-node/txs.mdx | 461 +++ docs/sdk/next/user/user.mdx | 12 + docs/sdk/proposed-nav-next.json | 37 - docs/sdk/proposed-nav-v0.47.json | 8 - docs/sdk/proposed-nav-v0.50.json | 8 - docs/sdk/proposed-nav-v0.53.json | 224 -- docs/sdk/sdk-categorization.json | 210 -- docs/sdk/v0.47/build.mdx | 20 +- docs/sdk/v0.47/changelog/release-notes.mdx | 403 +-- docs/sdk/v0.47/learn.mdx | 9 +- docs/sdk/v0.47/learn/advanced/autocli.mdx | 259 ++ docs/sdk/v0.47/learn/advanced/baseapp.mdx | 4 +- docs/sdk/v0.47/learn/advanced/cli.mdx | 4 +- docs/sdk/v0.47/learn/advanced/events.mdx | 4 +- docs/sdk/v0.47/learn/advanced/grpc_rest.mdx | 2 +- docs/sdk/v0.47/learn/beginner/app-anatomy.mdx | 279 ++ .../v0.47/learn/beginner/query-lifecycle.mdx | 4 +- docs/sdk/v0.47/overview.mdx | 44 + docs/sdk/v0.47/tutorials.mdx | 29 + docs/sdk/v0.47/user.mdx | 6 +- docs/sdk/v0.47/user/run-node/run-node.mdx | 4 +- .../v0.47/user/run-node/run-production.mdx | 4 +- docs/sdk/v0.47/user/run-node/txs.mdx | 4 +- docs/sdk/v0.50/changelog/release-notes.mdx | 504 +--- docs/sdk/v0.50/learn/advanced/autocli.mdx | 8 +- docs/sdk/v0.50/learn/advanced/baseapp.mdx | 4 +- docs/sdk/v0.50/learn/advanced/cli.mdx | 4 +- docs/sdk/v0.50/learn/advanced/events.mdx | 4 +- docs/sdk/v0.50/learn/advanced/grpc_rest.mdx | 6 +- .../v0.50/learn/beginner/query-lifecycle.mdx | 4 +- docs/sdk/v0.50/overview.mdx | 44 + docs/sdk/v0.50/tutorials.mdx | 29 +- .../transactions/building-a-transaction.mdx | 54 - .../demo-of-mitigating-front-running.mdx | 68 - .../auction-frontrunning/getting-started.mdx | 43 - ...ing-front-running-with-vote-extensions.mdx | 118 - ...ting-front-running-with-vote-extesions.mdx | 118 - .../understanding-frontrunning.mdx | 44 - .../oracle/implementing-vote-extensions.mdx | 96 - docs/sdk/v0.50/user/run-node/run-node.mdx | 4 +- .../v0.50/user/run-node/run-production.mdx | 4 +- docs/sdk/v0.50/user/run-node/txs.mdx | 4 +- docs/sdk/v0.53/apis-clients/autocli.mdx | 8 +- docs/sdk/v0.53/apis-clients/cli.mdx | 4 +- docs/sdk/v0.53/apis-clients/grpc_rest.mdx | 6 +- .../v0.53/app-wiring-runtime/app-go-di.mdx | 6 +- .../v0.53/app-wiring-runtime/app-mempool.mdx | 2 + .../v0.53/app-wiring-runtime/app-testnet.mdx | 189 +- .../v0.53/app-wiring-runtime/app-upgrade.mdx | 51 +- docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx | 4 +- docs/sdk/v0.53/app-wiring-runtime/runtime.mdx | 18 +- .../app-wiring-runtime/vote-extensions.mdx | 39 +- docs/sdk/v0.53/build.mdx | 12 - docs/sdk/v0.53/changelog/release-notes.mdx | 504 +--- docs/sdk/v0.53/core-concepts/events.mdx | 4 +- docs/sdk/v0.53/learn.mdx | 8 - .../messages-and-queries.mdx | 16 +- .../v0.53/messaging-queries/msg-services.mdx | 11 +- .../messaging-queries/query-lifecycle.mdx | 4 +- .../v0.53/module-anatomy-keepers/errors.mdx | 2 +- .../module-anatomy-keepers/invariants.mdx | 4 +- .../v0.53/module-anatomy-keepers/keeper.mdx | 18 +- .../module-interfaces.mdx | 8 +- .../module-anatomy-keepers/module-manager.mdx | 2 +- .../v0.53/module-anatomy-keepers/preblock.mdx | 2 +- .../module-anatomy-keepers/structure.mdx | 24 +- docs/sdk/v0.53/module-reference/auth.mdx | 49 +- docs/sdk/v0.53/module-reference/authz.mdx | 21 +- docs/sdk/v0.53/module-reference/bank.mdx | 181 +- docs/sdk/v0.53/module-reference/crisis.mdx | 6 +- .../v0.53/module-reference/distribution.mdx | 109 +- docs/sdk/v0.53/module-reference/epochs.mdx | 48 +- docs/sdk/v0.53/module-reference/evidence.mdx | 110 +- docs/sdk/v0.53/module-reference/feegrant.mdx | 40 +- docs/sdk/v0.53/module-reference/gov.mdx | 458 +-- docs/sdk/v0.53/module-reference/group.mdx | 264 +- docs/sdk/v0.53/module-reference/mint.mdx | 98 +- .../v0.53/module-reference/protocolpool.mdx | 8 +- docs/sdk/v0.53/module-reference/slashing.mdx | 120 +- docs/sdk/v0.53/module-reference/staking.mdx | 454 +-- docs/sdk/v0.53/module-reference/upgrade.mdx | 99 +- docs/sdk/v0.53/node-operations/run-node.mdx | 4 +- .../v0.53/node-operations/run-production.mdx | 4 +- docs/sdk/v0.53/node-operations/txs.mdx | 4 +- docs/sdk/v0.53/overview.mdx | 108 +- docs/sdk/v0.53/release-notes.mdx | 39 - docs/sdk/v0.53/runtime-abci/checktx.mdx | 3 +- .../v0.53/runtime-abci/prepare-proposal.mdx | 5 +- .../v0.53/runtime-abci/process-proposal.mdx | 5 +- .../v0.53/testing-simulation/simulator.mdx | 2 +- docs/sdk/v0.53/testing-simulation/testing.mdx | 10 +- docs/sdk/v0.53/tutorials.mdx | 29 +- .../transactions/building-a-transaction.mdx | 54 - ...ing-front-running-with-vote-extensions.mdx | 118 - ...ting-front-running-with-vote-extesions.mdx | 118 - .../oracle/getting-started.mdx | 39 - .../oracle/implementing-vote-extensions.mdx | 96 - .../vote-extensions/oracle/testing-oracle.mdx | 60 - .../upgrades-migrations/module-upgrade.mdx | 14 +- docs/sdk/v0.53/user.mdx.bak | 10 - scripts/MIGRATION_README.md | 169 ++ scripts/code-formatter.js | 250 ++ scripts/convert-docusaurus-to-mintlify.js | 405 --- scripts/docusaurus-to-mintlify.js | 405 --- scripts/migrate-docusaurus.js | 1197 ++++++++ scripts/migrate-single-file.js | 550 ++++ scripts/package-lock.json | 889 +++++- scripts/package.json | 9 +- tmp/changelog.md | 88 - tmp/release-notes.mdx | 87 - versions.json | 20 +- 161 files changed, 13449 insertions(+), 7004 deletions(-) delete mode 100644 docs/ibc/next/changelog/release-notes.mdx delete mode 100644 docs/ibc/next/index.mdx delete mode 100644 docs/ibc/next/link-rewrite-test.mdx delete mode 100644 docs/sdk/index.mdx create mode 100644 docs/sdk/next/learn/advanced/autocli.mdx create mode 100644 docs/sdk/next/learn/advanced/baseapp.mdx create mode 100644 docs/sdk/next/learn/advanced/cli.mdx create mode 100644 docs/sdk/next/learn/advanced/config.mdx create mode 100644 docs/sdk/next/learn/advanced/context.mdx create mode 100644 docs/sdk/next/learn/advanced/encoding.mdx create mode 100644 docs/sdk/next/learn/advanced/events.mdx create mode 100644 docs/sdk/next/learn/advanced/grpc_rest.mdx create mode 100644 docs/sdk/next/learn/advanced/node.mdx create mode 100644 docs/sdk/next/learn/advanced/ocap.mdx create mode 100644 docs/sdk/next/learn/advanced/proto-docs.mdx create mode 100644 docs/sdk/next/learn/advanced/runtx_middleware.mdx create mode 100644 docs/sdk/next/learn/advanced/simulation.mdx create mode 100644 docs/sdk/next/learn/advanced/store.mdx create mode 100644 docs/sdk/next/learn/advanced/telemetry.mdx create mode 100644 docs/sdk/next/learn/advanced/transactions.mdx create mode 100644 docs/sdk/next/learn/advanced/upgrade.mdx create mode 100644 docs/sdk/next/learn/beginner/accounts.mdx create mode 100644 docs/sdk/next/learn/beginner/app-anatomy.mdx create mode 100644 docs/sdk/next/learn/beginner/gas-fees.mdx create mode 100644 docs/sdk/next/learn/beginner/query-lifecycle.mdx create mode 100644 docs/sdk/next/learn/beginner/tx-lifecycle.mdx create mode 100644 docs/sdk/next/learn/intro/overview.mdx create mode 100644 docs/sdk/next/learn/intro/sdk-app-architecture.mdx create mode 100644 docs/sdk/next/learn/intro/sdk-design.mdx create mode 100644 docs/sdk/next/learn/intro/why-app-specific.mdx create mode 100644 docs/sdk/next/learn/learn.mdx create mode 100644 docs/sdk/next/overview.mdx create mode 100644 docs/sdk/next/tutorials/transactions/building-a-transaction.mdx rename docs/sdk/{v0.53/tutorials.mdx.bak => next/tutorials/tutorials.mdx} (88%) rename docs/sdk/{v0.53 => next}/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx (54%) rename docs/sdk/{v0.53 => next}/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx (64%) create mode 100644 docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx create mode 100644 docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx rename docs/sdk/{v0.53 => next}/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx (76%) rename docs/sdk/{v0.50 => next}/tutorials/vote-extensions/oracle/getting-started.mdx (64%) create mode 100644 docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx rename docs/sdk/{v0.50 => next}/tutorials/vote-extensions/oracle/testing-oracle.mdx (78%) rename docs/sdk/{v0.50 => next}/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx (82%) create mode 100644 docs/sdk/next/user/run-node/interact-node.mdx create mode 100644 docs/sdk/next/user/run-node/keyring.mdx create mode 100644 docs/sdk/next/user/run-node/rosetta.mdx create mode 100644 docs/sdk/next/user/run-node/run-node.mdx create mode 100644 docs/sdk/next/user/run-node/run-production.mdx create mode 100644 docs/sdk/next/user/run-node/run-testnet.mdx create mode 100644 docs/sdk/next/user/run-node/txs.mdx create mode 100644 docs/sdk/next/user/user.mdx delete mode 100644 docs/sdk/proposed-nav-next.json delete mode 100644 docs/sdk/proposed-nav-v0.47.json delete mode 100644 docs/sdk/proposed-nav-v0.50.json delete mode 100644 docs/sdk/proposed-nav-v0.53.json delete mode 100644 docs/sdk/sdk-categorization.json create mode 100644 docs/sdk/v0.47/learn/advanced/autocli.mdx create mode 100644 docs/sdk/v0.47/learn/beginner/app-anatomy.mdx create mode 100644 docs/sdk/v0.47/overview.mdx create mode 100644 docs/sdk/v0.47/tutorials.mdx create mode 100644 docs/sdk/v0.50/overview.mdx delete mode 100644 docs/sdk/v0.50/tutorials/transactions/building-a-transaction.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx delete mode 100644 docs/sdk/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx delete mode 100644 docs/sdk/v0.53/build.mdx delete mode 100644 docs/sdk/v0.53/learn.mdx delete mode 100644 docs/sdk/v0.53/release-notes.mdx delete mode 100644 docs/sdk/v0.53/tutorials/transactions/building-a-transaction.mdx delete mode 100644 docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx delete mode 100644 docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx delete mode 100644 docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started.mdx delete mode 100644 docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx delete mode 100644 docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle.mdx delete mode 100644 docs/sdk/v0.53/user.mdx.bak create mode 100644 scripts/MIGRATION_README.md create mode 100644 scripts/code-formatter.js delete mode 100755 scripts/convert-docusaurus-to-mintlify.js delete mode 100644 scripts/docusaurus-to-mintlify.js create mode 100755 scripts/migrate-docusaurus.js create mode 100755 scripts/migrate-single-file.js delete mode 100644 tmp/changelog.md delete mode 100644 tmp/release-notes.mdx diff --git a/docs.json b/docs.json index d50c8a88..3811c1ee 100644 --- a/docs.json +++ b/docs.json @@ -34,7 +34,420 @@ "vscode" ] }, - "redirects": [], + "redirects": [ + { + "source": "/docs/sdk/*/build/build.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/build.md" + }, + { + "source": "/docs/sdk/*/build/architecture/README.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/README.md" + }, + { + "source": "/docs/sdk/*/build/building-apps/app-go-v2.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-apps/01-app-go-di.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/beginblock-endblock.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/06-beginblock-endblock.md" + }, + { + "source": "/docs/sdk/*/build/migrations/intro.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/migrations/intro.md" + }, + { + "source": "/docs/sdk/*/build/packages/depinject.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/packages/depinject.md" + }, + { + "source": "/docs/sdk/*/build/rfc/README.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/rfc/README.md" + }, + { + "source": "/docs/sdk/*/build/tooling/autocli.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/autocli.md" + }, + { + "source": "/docs/sdk/*/build/modules/README.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/modules/README.md" + }, + { + "source": "/docs/sdk/*/build/spec/SPEC_MODULE.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/spec/SPEC_MODULE.md" + }, + { + "source": "/docs/sdk/*/build/building-apps/app-go.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-apps/00-app-go.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/depinject.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/15-depinject.md" + }, + { + "source": "/docs/sdk/*/build/tooling/confix.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/confix.md" + }, + { + "source": "/docs/sdk/*/build/spec/SPEC_STANDARD.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/spec/SPEC_STANDARD.md" + }, + { + "source": "/docs/sdk/*/build/building-apps/app-mempool.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-apps/02-app-mempool.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/errors.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/12-errors.md" + }, + { + "source": "/docs/sdk/*/build/tooling/cosmovisor.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/cosmovisor.md" + }, + { + "source": "/docs/sdk/*/build/building-apps/app-upgrade.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-apps/03-app-upgrade.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/genesis.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/08-genesis.md" + }, + { + "source": "/docs/sdk/*/build/tooling/depinject.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/depinject.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/intro.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/00-intro.md" + }, + { + "source": "/docs/sdk/*/build/tooling/hubl.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/hubl.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/invariants.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/07-invariants.md" + }, + { + "source": "/docs/sdk/*/build/tooling/protobuf.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/protobuf.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/keeper.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/06-keeper.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/messages-and-queries.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/02-messages-and-queries.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/module-interfaces.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/09-module-interfaces.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/module-manager.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/01-module-manager.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/msg-services.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/03-msg-services.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/query-services.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/04-query-services.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/simulator.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/14-simulator.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/structure.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/11-structure.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/testing.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/16-testing.md" + }, + { + "source": "/docs/sdk/*/build/building-modules/upgrade.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/building-modules/13-upgrade.md" + }, + { + "source": "/docs/sdk/*/build/migrations/upgrading.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/migrations/upgrading.md" + }, + { + "source": "/docs/sdk/*/build/packages/collections.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/packages/collections.md" + }, + { + "source": "/docs/sdk/*/build/rfc/PROCESS.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/rfc/PROCESS.md" + }, + { + "source": "/docs/sdk/*/build/tooling/README.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/tooling/README.md" + }, + { + "source": "/docs/sdk/*/build/packages/orm.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/packages/orm.md" + }, + { + "source": "/docs/sdk/*/build/rfc/rfc-001-tx-validation.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/rfc/rfc-001-tx-validation.md" + }, + { + "source": "/docs/sdk/*/build/packages/README.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/packages/README.md" + }, + { + "source": "/docs/sdk/*/build/rfc/rfc-template.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/rfc/rfc-template.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-002-docs-structure.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-002-docs-structure.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-003-dynamic-capability-store.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-003-dynamic-capability-store.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-004-split-denomination-keys.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-004-split-denomination-keys.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-006-secret-store-replacement.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-006-secret-store-replacement.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-007-specialization-groups.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-007-specialization-groups.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-008-dCERT-group.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-008-dCERT-group.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-009-evidence-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-009-evidence-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-010-modular-antehandler.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-010-modular-antehandler.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-011-generalize-genesis-accounts.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-011-generalize-genesis-accounts.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-012-state-accessors.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-012-state-accessors.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-013-metrics.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-013-metrics.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-014-proportional-slashing.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-014-proportional-slashing.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-016-validator-consensus-key-rotation.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-016-validator-consensus-key-rotation.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-017-historical-header-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-017-historical-header-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-018-extendable-voting-period.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-018-extendable-voting-period.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-019-protobuf-state-encoding.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-019-protobuf-state-encoding.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-020-protobuf-transaction-encoding.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-020-protobuf-transaction-encoding.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-021-protobuf-query-encoding.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-021-protobuf-query-encoding.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-022-custom-panic-handling.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-022-custom-panic-handling.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-023-protobuf-naming.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-023-protobuf-naming.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-024-coin-metadata.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-024-coin-metadata.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-027-deterministic-protobuf-serialization.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-027-deterministic-protobuf-serialization.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-028-public-key-addresses.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-028-public-key-addresses.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-029-fee-grant-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-029-fee-grant-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-030-authz-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-030-authz-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-031-msg-service.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-031-msg-service.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-032-typed-events.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-032-typed-events.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-033-protobuf-inter-module-comm.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-033-protobuf-inter-module-comm.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-034-account-rekeying.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-034-account-rekeying.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-035-rosetta-api-support.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-035-rosetta-api-support.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-036-arbitrary-signature.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-036-arbitrary-signature.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-037-gov-split-vote.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-037-gov-split-vote.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-038-state-listening.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-038-state-listening.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-039-epoched-staking.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-039-epoched-staking.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-040-storage-and-smt-state-commitments.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-040-storage-and-smt-state-commitments.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-041-in-place-store-migrations.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-041-in-place-store-migrations.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-042-group-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-042-group-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-043-nft-module.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-043-nft-module.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-044-protobuf-updates-guidelines.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-044-protobuf-updates-guidelines.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-045-check-delivertx-middlewares.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-045-check-delivertx-middlewares.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-046-module-params.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-046-module-params.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-047-extend-upgrade-plan.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-047-extend-upgrade-plan.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-048-consensus-fees.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-048-consensus-fees.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-049-state-sync-hooks.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-049-state-sync-hooks.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-050-sign-mode-textual-annex1.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-050-sign-mode-textual-annex1.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-050-sign-mode-textual-annex2.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-050-sign-mode-textual-annex2.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-050-sign-mode-textual.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-050-sign-mode-textual.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-053-go-module-refactoring.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-053-go-module-refactoring.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-054-semver-compatible-modules.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-054-semver-compatible-modules.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-055-orm.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-055-orm.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-057-app-wiring.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-057-app-wiring.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-058-auto-generated-cli.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-058-auto-generated-cli.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-059-test-scopes.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-059-test-scopes.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-060-abci-1.0.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-060-abci-1.0.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-061-liquid-staking.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-061-liquid-staking.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-062-collections-state-layer.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-062-collections-state-layer.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-063-core-module-api.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-063-core-module-api.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-064-abci-2.0.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-064-abci-2.0.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-065-store-v2.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-065-store-v2.md" + }, + { + "source": "/docs/sdk/*/build/architecture/adr-template.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/adr-template.md" + }, + { + "source": "/docs/sdk/*/build/architecture/PROCESS.md", + "destination": "https://github.com/cosmos/cosmos-sdk-docs/blob/main/docs/build/architecture/PROCESS.md" + } + ], "navigation": { "dropdowns": [ { @@ -349,1702 +762,589 @@ "icon": "book-open-text", "versions": [ { - "version": "v0.53", + "version": "0.47", "tabs": [ { "tab": "Documentation", "groups": [ { - "group": "Cosmos-SDK", - "pages": [ - "docs/sdk/v0.53/overview" - ] - }, - { - "group": "Core Concepts", - "pages": [ - { - "group": "Fundamentals", - "pages": [ - "docs/sdk/v0.53/core-concepts/overview", - "docs/sdk/v0.53/core-concepts/why-app-specific", - "docs/sdk/v0.53/core-concepts/sdk-app-architecture", - "docs/sdk/v0.53/core-concepts/sdk-design", - "docs/sdk/v0.53/core-concepts/app-anatomy" - ] - }, - { - "group": "Core Components", - "pages": [ - "docs/sdk/v0.53/core-concepts/accounts", - "docs/sdk/v0.53/core-concepts/context", - "docs/sdk/v0.53/core-concepts/node", - "docs/sdk/v0.53/core-concepts/events", - "docs/sdk/v0.53/core-concepts/telemetry" - ] - }, - { - "group": "Advanced Concepts", - "pages": [ - "docs/sdk/v0.53/core-concepts/ocap", - "docs/sdk/v0.53/core-concepts/config", - "docs/sdk/v0.53/core-concepts/what-is-an-oracle" - ] - } - ] - }, - { - "group": "Building Apps", - "pages": [ - { - "group": "App Basics", - "pages": [ - "docs/sdk/v0.53/app-wiring-runtime/app-go", - "docs/sdk/v0.53/app-wiring-runtime/runtime", - "docs/sdk/v0.53/app-wiring-runtime/app-go-di", - "docs/sdk/v0.53/app-wiring-runtime/baseapp" - ] - }, - { - "group": "Advanced Features", - "pages": [ - "docs/sdk/v0.53/app-wiring-runtime/runtx_middleware", - "docs/sdk/v0.53/app-wiring-runtime/app-mempool", - "docs/sdk/v0.53/app-wiring-runtime/app-upgrade", - "docs/sdk/v0.53/app-wiring-runtime/vote-extensions", - "docs/sdk/v0.53/app-wiring-runtime/app-testnet" - ] - } - ] - }, - { - "group": "Building Modules", - "pages": [ - { - "group": "Module Basics", - "pages": [ - "docs/sdk/v0.53/module-anatomy-keepers/module-manager", - "docs/sdk/v0.53/module-anatomy-keepers/module-interfaces", - "docs/sdk/v0.53/module-anatomy-keepers/structure", - "docs/sdk/v0.53/module-anatomy-keepers/keeper" - ] - }, - { - "group": "Module Lifecycle", - "pages": [ - "docs/sdk/v0.53/module-anatomy-keepers/genesis", - "docs/sdk/v0.53/module-anatomy-keepers/invariants", - "docs/sdk/v0.53/module-anatomy-keepers/errors", - "docs/sdk/v0.53/module-anatomy-keepers/preblock" - ] - } - ] - }, - { - "group": "Transactions & Queries", - "pages": [ - { - "group": "Transactions", - "pages": [ - "docs/sdk/v0.53/transactions-fees/tx-lifecycle", - "docs/sdk/v0.53/transactions-fees/transactions", - "docs/sdk/v0.53/transactions-fees/gas-fees" - ] - }, - { - "group": "Messages & Queries", - "pages": [ - "docs/sdk/v0.53/messaging-queries/messages-and-queries", - "docs/sdk/v0.53/messaging-queries/msg-services", - "docs/sdk/v0.53/messaging-queries/query-services", - "docs/sdk/v0.53/messaging-queries/query-lifecycle" - ] - } - ] - }, - { - "group": "ABCI & State Machine", - "pages": [ - { - "group": "ABCI", - "pages": [ - "docs/sdk/v0.53/runtime-abci/introduction", - "docs/sdk/v0.53/runtime-abci/prepare-proposal", - "docs/sdk/v0.53/runtime-abci/process-proposal", - "docs/sdk/v0.53/runtime-abci/checktx" - ] - }, - { - "group": "State Management", - "pages": [ - "docs/sdk/v0.53/state-store/store" - ] - } - ] - }, - { - "group": "Encoding & Protocol", - "pages": [ - "docs/sdk/v0.53/encoding-protobuf/encoding", - "docs/sdk/v0.53/encoding-protobuf/proto-docs", - "docs/sdk/v0.53/encoding-protobuf/protobuf-annotations" - ] - }, - { - "group": "Testing & Upgrades", - "pages": [ - { - "group": "Testing", - "pages": [ - "docs/sdk/v0.53/testing-simulation/simulation", - "docs/sdk/v0.53/testing-simulation/testing", - "docs/sdk/v0.53/testing-simulation/simulator" - ] - }, - { - "group": "Upgrades", - "pages": [ - "docs/sdk/v0.53/upgrades-migrations/upgrade", - "docs/sdk/v0.53/upgrades-migrations/module-upgrade" - ] - } - ] + "group": "SDK", + "pages": [] }, { - "group": "API & CLI", + "group": "Validate", "pages": [ - "docs/sdk/v0.53/apis-clients/cli", - "docs/sdk/v0.53/apis-clients/grpc_rest", - "docs/sdk/v0.53/apis-clients/autocli" + "docs/sdk/0.47/validate/run-testnet" ] }, { - "group": "Node Operations", + "group": "Learn", "pages": [ - "docs/sdk/v0.53/node-operations/user", - "docs/sdk/v0.53/node-operations/interact-node", - "docs/sdk/v0.53/node-operations/run-testnet", - "docs/sdk/v0.53/node-operations/run-node", - "docs/sdk/v0.53/node-operations/txs", - "docs/sdk/v0.53/node-operations/keyring", - "docs/sdk/v0.53/node-operations/run-production" + "docs/sdk/0.47/learn/glossary", + "docs/sdk/0.47/learn/learn", + "docs/sdk/0.47/learn/advanced/cli", + "docs/sdk/0.47/learn/beginner/accounts", + "docs/sdk/0.47/learn/intro/overview", + "docs/sdk/0.47/learn/advanced/config", + "docs/sdk/0.47/learn/beginner/gas-fees", + "docs/sdk/0.47/learn/intro/sdk-app-architecture", + "docs/sdk/0.47/learn/advanced/context", + "docs/sdk/0.47/learn/beginner/overview-app", + "docs/sdk/0.47/learn/intro/sdk-design", + "docs/sdk/0.47/learn/advanced/encoding", + "docs/sdk/0.47/learn/beginner/query-lifecycle", + "docs/sdk/0.47/learn/intro/why-app-specific", + "docs/sdk/0.47/learn/advanced/events", + "docs/sdk/0.47/learn/beginner/tx-lifecycle", + "docs/sdk/0.47/learn/advanced/grpc_rest", + "docs/sdk/0.47/learn/advanced/interblock-cache", + "docs/sdk/0.47/learn/advanced/node", + "docs/sdk/0.47/learn/advanced/ocap", + "docs/sdk/0.47/learn/advanced/proto-docs", + "docs/sdk/0.47/learn/advanced/runtx_middleware", + "docs/sdk/0.47/learn/advanced/simulation", + "docs/sdk/0.47/learn/advanced/store", + "docs/sdk/0.47/learn/advanced/telemetry", + "docs/sdk/0.47/learn/advanced/upgrade", + "docs/sdk/0.47/learn/advanced/baseapp", + "docs/sdk/0.47/learn/advanced/transactions" ] }, { - "group": "Module Reference", - "pages": [ - "docs/sdk/v0.53/module-reference/auth", - "docs/sdk/v0.53/module-reference/authz", - "docs/sdk/v0.53/module-reference/bank", - "docs/sdk/v0.53/module-reference/consensus", - "docs/sdk/v0.53/module-reference/crisis", - "docs/sdk/v0.53/module-reference/distribution", - "docs/sdk/v0.53/module-reference/epochs", - "docs/sdk/v0.53/module-reference/evidence", - "docs/sdk/v0.53/module-reference/feegrant", - "docs/sdk/v0.53/module-reference/gov", - "docs/sdk/v0.53/module-reference/group", - "docs/sdk/v0.53/module-reference/mint", - "docs/sdk/v0.53/module-reference/nft", - "docs/sdk/v0.53/module-reference/params", - "docs/sdk/v0.53/module-reference/protocolpool", - "docs/sdk/v0.53/module-reference/slashing", - "docs/sdk/v0.53/module-reference/staking", - "docs/sdk/v0.53/module-reference/upgrade" - ] - } - ] - }, - { - "tab": "Tutorials", - "groups": [ - { - "group": "Vote Extensions", + "group": "Build", "pages": [ - { - "group": "Auction Front-Running", - "pages": [ - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running" - ] - }, - { - "group": "Oracle", - "pages": [ - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle" - ] - } + "docs/sdk/0.47/build/architecture/PROCESS", + "docs/sdk/0.47/build/modules/auth/README", + "docs/sdk/0.47/build/modules/authz/README", + "docs/sdk/0.47/build/modules/bank/README", + "docs/sdk/0.47/build/modules/consensus/README", + "docs/sdk/0.47/build/modules/crisis/README", + "docs/sdk/0.47/build/modules/distribution/README", + "docs/sdk/0.47/build/modules/evidence/README", + "docs/sdk/0.47/build/modules/feegrant/README", + "docs/sdk/0.47/build/modules/gov/README", + "docs/sdk/0.47/build/modules/group/README", + "docs/sdk/0.47/build/modules/mint/README", + "docs/sdk/0.47/build/modules/nft/README", + "docs/sdk/0.47/build/modules/params/README", + "docs/sdk/0.47/build/modules/slashing/README", + "docs/sdk/0.47/build/modules/staking/README", + "docs/sdk/0.47/build/modules/upgrade/README", + "docs/sdk/0.47/build/modules/accounts/accounts", + "docs/sdk/0.47/build/modules/circuit/README", + "docs/sdk/0.47/build/modules/genutil/README", + "docs/sdk/0.47/build/spec/addresses/bech32", + "docs/sdk/0.47/build/spec/ics/ics-030-signed-messages", + "docs/sdk/0.47/build/modules/auth/tx", + "docs/sdk/0.47/build/spec/addresses/README", + "docs/sdk/0.47/build/spec/ics/README", + "docs/sdk/0.47/build/modules/auth/vesting" ] }, { - "group": "Transactions", + "group": "User", "pages": [ - "docs/sdk/v0.53/tutorials/transactions/building-a-transaction" + "docs/sdk/0.47/user/user", + "docs/sdk/0.47/user/run-node/interact-node", + "docs/sdk/0.47/user/run-node/keyring", + "docs/sdk/0.47/user/run-node/multisig-guide", + "docs/sdk/0.47/user/run-node/rosetta", + "docs/sdk/0.47/user/run-node/run-node", + "docs/sdk/0.47/user/run-node/run-production", + "docs/sdk/0.47/user/run-node/run-testnet", + "docs/sdk/0.47/user/run-node/txs" ] } ] - }, - { - "tab": "API Reference", - "pages": [ - "docs/sdk/v0.53/apis-clients/grpc_rest", - "docs/sdk/v0.53/encoding-protobuf/proto-docs" - ] - }, - { - "tab": "Release Notes", - "pages": [ - "docs/sdk/v0.53/changelog/release-notes" - ] } ] }, { - "version": "v0.50", + "version": "0.5", "tabs": [ { - "tab": "Learn", + "tab": "Documentation", "groups": [ { - "group": "Cosmos-SDK", - "pages": [ - "docs/sdk/v0.50/overview" - ] - }, - { - "group": "Learn", - "pages": [ - "docs/sdk/v0.50/learn" - ] - }, - { - "group": "Introduction", - "pages": [ - "docs/sdk/v0.50/learn/intro/overview", - "docs/sdk/v0.50/learn/intro/why-app-specific", - "docs/sdk/v0.50/learn/intro/sdk-app-architecture", - "docs/sdk/v0.50/learn/intro/sdk-design" - ] - }, - { - "group": "Beginner", - "pages": [ - "docs/sdk/v0.50/learn/beginner/app-anatomy", - "docs/sdk/v0.50/learn/beginner/tx-lifecycle", - "docs/sdk/v0.50/learn/beginner/query-lifecycle", - "docs/sdk/v0.50/learn/beginner/accounts", - "docs/sdk/v0.50/learn/beginner/gas-fees" - ] + "group": "SDK", + "pages": [] }, - { - "group": "Advanced", - "pages": [ - "docs/sdk/v0.50/learn/advanced/baseapp", - "docs/sdk/v0.50/learn/advanced/transactions", - "docs/sdk/v0.50/learn/advanced/context", - "docs/sdk/v0.50/learn/advanced/node", - "docs/sdk/v0.50/learn/advanced/store", - "docs/sdk/v0.50/learn/advanced/encoding", - "docs/sdk/v0.50/learn/advanced/grpc_rest", - "docs/sdk/v0.50/learn/advanced/cli", - "docs/sdk/v0.50/learn/advanced/events", - "docs/sdk/v0.50/learn/advanced/telemetry", - "docs/sdk/v0.50/learn/advanced/ocap", - "docs/sdk/v0.50/learn/advanced/runtx_middleware", - "docs/sdk/v0.50/learn/advanced/simulation", - "docs/sdk/v0.50/learn/advanced/proto-docs", - "docs/sdk/v0.50/learn/advanced/upgrade", - "docs/sdk/v0.50/learn/advanced/config", - "docs/sdk/v0.50/learn/advanced/autocli" - ] - } - ] - }, - { - "tab": "Build", - "groups": [ { "group": "Build", "pages": [ - "docs/sdk/v0.50/build" - ] - }, - { - "group": "Building Apps", - "pages": [ - "docs/sdk/v0.50/build/building-apps/app-go", - "docs/sdk/v0.50/build/building-apps/app-mempool", - "docs/sdk/v0.50/build/building-apps/app-upgrade", - "docs/sdk/v0.50/build/building-apps/vote-extensions", - "docs/sdk/v0.50/build/building-apps/app-testnet" - ] - }, - { - "group": "Building Modules", - "pages": [ - "docs/sdk/v0.50/build/building-modules/module-manager", - "docs/sdk/v0.50/build/building-modules/messages-and-queries", - "docs/sdk/v0.50/build/building-modules/msg-services", - "docs/sdk/v0.50/build/building-modules/query-services", - "docs/sdk/v0.50/build/building-modules/protobuf-annotations", - "docs/sdk/v0.50/build/building-modules/beginblock-endblock", - "docs/sdk/v0.50/build/building-modules/keeper", - "docs/sdk/v0.50/build/building-modules/invariants", - "docs/sdk/v0.50/build/building-modules/genesis", - "docs/sdk/v0.50/build/building-modules/module-interfaces", - "docs/sdk/v0.50/build/building-modules/structure", - "docs/sdk/v0.50/build/building-modules/errors", - "docs/sdk/v0.50/build/building-modules/upgrade", - "docs/sdk/v0.50/build/building-modules/simulator", - "docs/sdk/v0.50/build/building-modules/depinject", - "docs/sdk/v0.50/build/building-modules/testing", - "docs/sdk/v0.50/build/building-modules/preblock" - ] - }, - { - "group": "ABCI", - "pages": [ - "docs/sdk/v0.50/build/abci/introduction", - "docs/sdk/v0.50/build/abci/prepare-proposal", - "docs/sdk/v0.50/build/abci/process-proposal", - "docs/sdk/v0.50/build/abci/vote-extensions", - "docs/sdk/v0.50/build/abci/checktx" - ] - }, - { - "group": "Modules", - "pages": [ - "docs/sdk/v0.50/build/modules", - { - "group": "x/auth", - "pages": [ - "docs/sdk/v0.50/build/modules/auth", - "docs/sdk/v0.50/build/modules/auth/vesting", - "docs/sdk/v0.50/build/modules/auth/tx" - ] - }, - "docs/sdk/v0.50/build/modules/authz", - "docs/sdk/v0.50/build/modules/bank", - "docs/sdk/v0.50/build/modules/consensus", - "docs/sdk/v0.50/build/modules/crisis", - "docs/sdk/v0.50/build/modules/distribution", - "docs/sdk/v0.50/build/modules/epochs", - "docs/sdk/v0.50/build/modules/evidence", - "docs/sdk/v0.50/build/modules/feegrant", - "docs/sdk/v0.50/build/modules/gov", - "docs/sdk/v0.50/build/modules/group", - "docs/sdk/v0.50/build/modules/mint", - "docs/sdk/v0.50/build/modules/nft", - "docs/sdk/v0.50/build/modules/params", - "docs/sdk/v0.50/build/modules/protocolpool", - "docs/sdk/v0.50/build/modules/slashing", - "docs/sdk/v0.50/build/modules/staking", - "docs/sdk/v0.50/build/modules/upgrade", - "docs/sdk/v0.50/build/modules/circuit", - "docs/sdk/v0.50/build/modules/genutil" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/sdk/v0.50/build/migrations/intro", - "docs/sdk/v0.50/build/migrations/upgrade-reference", - "docs/sdk/v0.50/build/migrations/upgrade-guide" - ] - }, - { - "group": "Packages", - "pages": [ - "docs/sdk/v0.50/build/packages", - "docs/sdk/v0.50/build/packages/depinject", - "docs/sdk/v0.50/build/packages/collections" - ] - }, - { - "group": "Tooling", - "pages": [ - "docs/sdk/v0.50/build/tooling", - "docs/sdk/v0.50/build/tooling/protobuf", - "docs/sdk/v0.50/build/tooling/cosmovisor", - "docs/sdk/v0.50/build/tooling/confix" - ] - }, - { - "group": "RFC", - "pages": [ - "docs/sdk/v0.50/build/rfc", - "docs/sdk/v0.50/build/rfc/PROCESS", - "docs/sdk/v0.50/build/rfc/rfc-001-tx-validation", - "docs/sdk/v0.50/build/rfc/rfc-template" - ] - }, - { - "group": "Specifications", - "pages": [ - "docs/sdk/v0.50/build/spec", - "docs/sdk/v0.50/build/spec/SPEC_MODULE", - "docs/sdk/v0.50/build/spec/SPEC_STANDARD", - { - "group": "Addresses spec", - "pages": [ - "docs/sdk/v0.50/build/spec/addresses", - "docs/sdk/v0.50/build/spec/addresses/bech32" - ] - }, - { - "group": "Store", - "pages": [ - "docs/sdk/v0.50/build/spec/store", - "docs/sdk/v0.50/build/spec/store/interblock-cache" - ] - } - ] - } - ] - }, - { - "tab": "User Guides", - "groups": [ - { - "group": "User Guides", - "pages": [ - "docs/sdk/v0.50/user" + "docs/sdk/0.5/build/build", + "docs/sdk/0.5/build/architecture/README", + "docs/sdk/0.5/build/building-apps/app-go-v2", + "docs/sdk/0.5/build/building-modules/beginblock-endblock", + "docs/sdk/0.5/build/migrations/intro", + "docs/sdk/0.5/build/packages/depinject", + "docs/sdk/0.5/build/rfc/README", + "docs/sdk/0.5/build/spec/README", + "docs/sdk/0.5/build/tooling/confix", + "docs/sdk/0.5/build/abci/introduction", + "docs/sdk/0.5/build/modules/README", + "docs/sdk/0.5/build/building-apps/app-go", + "docs/sdk/0.5/build/building-modules/depinject", + "docs/sdk/0.5/build/tooling/cosmovisor", + "docs/sdk/0.5/build/abci/prepare-proposal", + "docs/sdk/0.5/build/building-apps/app-mempool", + "docs/sdk/0.5/build/building-modules/errors", + "docs/sdk/0.5/build/tooling/hubl", + "docs/sdk/0.5/build/abci/process-proposal", + "docs/sdk/0.5/build/building-apps/app-testnet", + "docs/sdk/0.5/build/building-modules/genesis", + "docs/sdk/0.5/build/tooling/protobuf", + "docs/sdk/0.5/build/abci/vote-extensions", + "docs/sdk/0.5/build/building-apps/app-upgrade", + "docs/sdk/0.5/build/building-modules/intro", + "docs/sdk/0.5/build/building-apps/vote-extensions", + "docs/sdk/0.5/build/building-modules/invariants", + "docs/sdk/0.5/build/building-modules/keeper", + "docs/sdk/0.5/build/building-modules/messages-and-queries", + "docs/sdk/0.5/build/building-modules/module-interfaces", + "docs/sdk/0.5/build/building-modules/module-manager", + "docs/sdk/0.5/build/building-modules/msg-services", + "docs/sdk/0.5/build/building-modules/preblock", + "docs/sdk/0.5/build/building-modules/protobuf-annotations", + "docs/sdk/0.5/build/building-modules/query-services", + "docs/sdk/0.5/build/building-modules/simulator", + "docs/sdk/0.5/build/building-modules/structure", + "docs/sdk/0.5/build/building-modules/testing", + "docs/sdk/0.5/build/building-modules/upgrade", + "docs/sdk/0.5/build/architecture/adr-002-docs-structure", + "docs/sdk/0.5/build/migrations/upgrade-guide", + "docs/sdk/0.5/build/packages/collections", + "docs/sdk/0.5/build/rfc/PROCESS", + "docs/sdk/0.5/build/spec/SPEC_MODULE", + "docs/sdk/0.5/build/tooling/README", + "docs/sdk/0.5/build/architecture/adr-003-dynamic-capability-store", + "docs/sdk/0.5/build/migrations/upgrade-reference", + "docs/sdk/0.5/build/packages/README", + "docs/sdk/0.5/build/rfc/rfc-001-tx-validation", + "docs/sdk/0.5/build/spec/SPEC_STANDARD", + "docs/sdk/0.5/build/architecture/adr-004-split-denomination-keys", + "docs/sdk/0.5/build/migrations/upgrading", + "docs/sdk/0.5/build/rfc/rfc-template", + "docs/sdk/0.5/build/architecture/PROCESS", + "docs/sdk/0.5/build/modules/auth/README", + "docs/sdk/0.5/build/modules/authz/README", + "docs/sdk/0.5/build/modules/bank/README", + "docs/sdk/0.5/build/modules/consensus/README", + "docs/sdk/0.5/build/modules/crisis/README", + "docs/sdk/0.5/build/modules/distribution/README", + "docs/sdk/0.5/build/modules/epochs/README", + "docs/sdk/0.5/build/modules/evidence/README", + "docs/sdk/0.5/build/modules/feegrant/README", + "docs/sdk/0.5/build/modules/gov/README", + "docs/sdk/0.5/build/modules/group/README", + "docs/sdk/0.5/build/modules/mint/README", + "docs/sdk/0.5/build/modules/nft/README", + "docs/sdk/0.5/build/modules/params/README", + "docs/sdk/0.5/build/modules/protocolpool/README", + "docs/sdk/0.5/build/modules/slashing/README", + "docs/sdk/0.5/build/modules/staking/README", + "docs/sdk/0.5/build/modules/upgrade/README", + "docs/sdk/0.5/build/modules/circuit/README", + "docs/sdk/0.5/build/modules/genutil/README", + "docs/sdk/0.5/build/spec/_ics/ics-030-signed-messages", + "docs/sdk/0.5/build/spec/addresses/bech32", + "docs/sdk/0.5/build/spec/store/interblock-cache", + "docs/sdk/0.5/build/modules/auth/tx", + "docs/sdk/0.5/build/spec/_ics/README", + "docs/sdk/0.5/build/spec/addresses/README", + "docs/sdk/0.5/build/spec/store/README", + "docs/sdk/0.5/build/modules/auth/vesting", + "docs/sdk/0.5/build/rfc/rfc/PROCESS", + "docs/sdk/0.5/build/rfc/rfc/rfc-001-tx-validation", + "docs/sdk/0.5/build/rfc/rfc/rfc-template" ] }, { - "group": "Running a Node, API and CLI", + "group": "Learn", "pages": [ - "docs/sdk/v0.50/user/run-node/keyring", - "docs/sdk/v0.50/user/run-node/run-node", - "docs/sdk/v0.50/user/run-node/interact-node", - "docs/sdk/v0.50/user/run-node/txs", - "docs/sdk/v0.50/user/run-node/run-testnet", - "docs/sdk/v0.50/user/run-node/run-production" + "docs/sdk/0.5/learn/learn", + "docs/sdk/0.5/learn/advanced/autocli", + "docs/sdk/0.5/learn/beginner/accounts", + "docs/sdk/0.5/learn/intro/overview", + "docs/sdk/0.5/learn/advanced/baseapp", + "docs/sdk/0.5/learn/beginner/app-anatomy", + "docs/sdk/0.5/learn/intro/sdk-app-architecture", + "docs/sdk/0.5/learn/advanced/cli", + "docs/sdk/0.5/learn/beginner/gas-fees", + "docs/sdk/0.5/learn/intro/sdk-design", + "docs/sdk/0.5/learn/advanced/config", + "docs/sdk/0.5/learn/beginner/query-lifecycle", + "docs/sdk/0.5/learn/intro/why-app-specific", + "docs/sdk/0.5/learn/advanced/context", + "docs/sdk/0.5/learn/beginner/tx-lifecycle", + "docs/sdk/0.5/learn/advanced/encoding", + "docs/sdk/0.5/learn/advanced/events", + "docs/sdk/0.5/learn/advanced/grpc_rest", + "docs/sdk/0.5/learn/advanced/node", + "docs/sdk/0.5/learn/advanced/ocap", + "docs/sdk/0.5/learn/advanced/proto-docs", + "docs/sdk/0.5/learn/advanced/runtx_middleware", + "docs/sdk/0.5/learn/advanced/simulation", + "docs/sdk/0.5/learn/advanced/store", + "docs/sdk/0.5/learn/advanced/telemetry", + "docs/sdk/0.5/learn/advanced/transactions", + "docs/sdk/0.5/learn/advanced/upgrade" ] }, - { - "group": "User", - "pages": [ - "docs/sdk/v0.50/user" - ] - } - ] - }, - { - "tab": "Tutorials", - "groups": [ { "group": "Tutorials", "pages": [ - "docs/sdk/v0.50/tutorials" - ] - }, - { - "group": "Vote Extensions Tutorials", - "pages": [ - { - "group": "Mitigating Auction Front-Running Tutorial", - "pages": [ - "docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/getting-started", - "docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", - "docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", - "docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", - "docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running" - ] - }, - { - "group": "Oracle Tutorial", - "pages": [ - "docs/sdk/v0.50/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle", - "docs/sdk/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions", - "docs/sdk/v0.50/tutorials/vote-extensions/oracle/testing-oracle" - ] - } + "docs/sdk/0.5/tutorials/tutorials", + "docs/sdk/0.5/tutorials/transactions/building-a-transaction", + "docs/sdk/0.5/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running", + "docs/sdk/0.5/tutorials/vote-extensions/oracle/getting-started", + "docs/sdk/0.5/tutorials/vote-extensions/auction-frontrunning/getting-started", + "docs/sdk/0.5/tutorials/vote-extensions/oracle/implementing-vote-extensions", + "docs/sdk/0.5/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", + "docs/sdk/0.5/tutorials/vote-extensions/oracle/testing-oracle", + "docs/sdk/0.5/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", + "docs/sdk/0.5/tutorials/vote-extensions/oracle/what-is-an-oracle", + "docs/sdk/0.5/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning" ] }, { - "group": "Transaction Tutorials", + "group": "User", "pages": [ - "docs/sdk/v0.50/tutorials/transactions/building-a-transaction" + "docs/sdk/0.5/user/user", + "docs/sdk/0.5/user/run-node/interact-node", + "docs/sdk/0.5/user/run-node/keyring", + "docs/sdk/0.5/user/run-node/run-node", + "docs/sdk/0.5/user/run-node/run-production", + "docs/sdk/0.5/user/run-node/run-testnet", + "docs/sdk/0.5/user/run-node/txs", + "docs/sdk/0.5/user/run-node/rosetta" ] } ] - }, - { - "tab": "API Reference", - "pages": [] - }, - { - "tab": "Release Notes", - "pages": [] } ] }, { - "version": "v0.47", + "version": "0.53", "tabs": [ { - "tab": "Learn", + "tab": "Documentation", "groups": [ { - "group": "Cosmos-SDK", - "pages": [ - "docs/sdk/v0.47/overview" - ] + "group": "SDK", + "pages": [] }, { - "group": "Learn", + "group": "Build", "pages": [ - "docs/sdk/v0.47/learn" + "docs/sdk/0.53/build/build", + "docs/sdk/0.53/build/architecture/README", + "docs/sdk/0.53/build/building-apps/app-go-di", + "docs/sdk/0.53/build/building-modules/beginblock-endblock", + "docs/sdk/0.53/build/migrations/intro", + "docs/sdk/0.53/build/packages/depinject", + "docs/sdk/0.53/build/rfc/README", + "docs/sdk/0.53/build/spec/README", + "docs/sdk/0.53/build/tooling/confix", + "docs/sdk/0.53/build/abci/checktx", + "docs/sdk/0.53/build/modules/README", + "docs/sdk/0.53/build/building-apps/app-go", + "docs/sdk/0.53/build/building-modules/depinject", + "docs/sdk/0.53/build/tooling/cosmovisor", + "docs/sdk/0.53/build/abci/introduction", + "docs/sdk/0.53/build/building-apps/app-mempool", + "docs/sdk/0.53/build/building-modules/errors", + "docs/sdk/0.53/build/tooling/protobuf", + "docs/sdk/0.53/build/abci/prepare-proposal", + "docs/sdk/0.53/build/building-apps/app-testnet", + "docs/sdk/0.53/build/building-modules/genesis", + "docs/sdk/0.53/build/abci/process-proposal", + "docs/sdk/0.53/build/building-apps/app-upgrade", + "docs/sdk/0.53/build/building-modules/intro", + "docs/sdk/0.53/build/abci/vote-extensions", + "docs/sdk/0.53/build/building-apps/runtime", + "docs/sdk/0.53/build/building-modules/invariants", + "docs/sdk/0.53/build/building-apps/vote-extensions", + "docs/sdk/0.53/build/building-modules/keeper", + "docs/sdk/0.53/build/building-modules/messages-and-queries", + "docs/sdk/0.53/build/building-modules/module-interfaces", + "docs/sdk/0.53/build/building-modules/module-manager", + "docs/sdk/0.53/build/building-modules/msg-services", + "docs/sdk/0.53/build/building-modules/preblock", + "docs/sdk/0.53/build/building-modules/protobuf-annotations", + "docs/sdk/0.53/build/building-modules/query-services", + "docs/sdk/0.53/build/building-modules/simulator", + "docs/sdk/0.53/build/building-modules/structure", + "docs/sdk/0.53/build/building-modules/testing", + "docs/sdk/0.53/build/building-modules/upgrade", + "docs/sdk/0.53/build/architecture/adr-002-docs-structure", + "docs/sdk/0.53/build/migrations/upgrade-guide", + "docs/sdk/0.53/build/packages/collections", + "docs/sdk/0.53/build/rfc/PROCESS", + "docs/sdk/0.53/build/spec/SPEC_MODULE", + "docs/sdk/0.53/build/tooling/README", + "docs/sdk/0.53/build/architecture/adr-003-dynamic-capability-store", + "docs/sdk/0.53/build/migrations/upgrade-reference", + "docs/sdk/0.53/build/packages/README", + "docs/sdk/0.53/build/rfc/rfc-001-tx-validation", + "docs/sdk/0.53/build/spec/SPEC_STANDARD", + "docs/sdk/0.53/build/architecture/adr-004-split-denomination-keys", + "docs/sdk/0.53/build/architecture/PROCESS", + "docs/sdk/0.53/build/modules/auth/README", + "docs/sdk/0.53/build/modules/authz/README", + "docs/sdk/0.53/build/modules/bank/README", + "docs/sdk/0.53/build/modules/consensus/README", + "docs/sdk/0.53/build/modules/crisis/README", + "docs/sdk/0.53/build/modules/distribution/README", + "docs/sdk/0.53/build/modules/epochs/README", + "docs/sdk/0.53/build/modules/evidence/README", + "docs/sdk/0.53/build/modules/feegrant/README", + "docs/sdk/0.53/build/modules/gov/README", + "docs/sdk/0.53/build/modules/group/README", + "docs/sdk/0.53/build/modules/mint/README", + "docs/sdk/0.53/build/modules/nft/README", + "docs/sdk/0.53/build/modules/params/README", + "docs/sdk/0.53/build/modules/protocolpool/README", + "docs/sdk/0.53/build/modules/slashing/README", + "docs/sdk/0.53/build/modules/staking/README", + "docs/sdk/0.53/build/modules/upgrade/README", + "docs/sdk/0.53/build/modules/circuit/README", + "docs/sdk/0.53/build/modules/genutil/README", + "docs/sdk/0.53/build/spec/_ics/ics-030-signed-messages", + "docs/sdk/0.53/build/spec/addresses/bech32", + "docs/sdk/0.53/build/spec/store/interblock-cache", + "docs/sdk/0.53/build/modules/auth/tx", + "docs/sdk/0.53/build/spec/_ics/README", + "docs/sdk/0.53/build/spec/addresses/README", + "docs/sdk/0.53/build/spec/store/README", + "docs/sdk/0.53/build/modules/auth/vesting" ] }, { - "group": "Introduction", + "group": "Learn", "pages": [ - "docs/sdk/v0.47/learn/intro/overview", - "docs/sdk/v0.47/learn/intro/why-app-specific", - "docs/sdk/v0.47/learn/intro/sdk-app-architecture", - "docs/sdk/v0.47/learn/intro/sdk-design" + "docs/sdk/0.53/learn/learn", + "docs/sdk/0.53/learn/advanced/autocli", + "docs/sdk/0.53/learn/beginner/accounts", + "docs/sdk/0.53/learn/intro/overview", + "docs/sdk/0.53/learn/advanced/baseapp", + "docs/sdk/0.53/learn/beginner/app-anatomy", + "docs/sdk/0.53/learn/intro/sdk-app-architecture", + "docs/sdk/0.53/learn/advanced/cli", + "docs/sdk/0.53/learn/beginner/gas-fees", + "docs/sdk/0.53/learn/intro/sdk-design", + "docs/sdk/0.53/learn/advanced/config", + "docs/sdk/0.53/learn/beginner/query-lifecycle", + "docs/sdk/0.53/learn/intro/why-app-specific", + "docs/sdk/0.53/learn/advanced/context", + "docs/sdk/0.53/learn/beginner/tx-lifecycle", + "docs/sdk/0.53/learn/advanced/encoding", + "docs/sdk/0.53/learn/advanced/events", + "docs/sdk/0.53/learn/advanced/grpc_rest", + "docs/sdk/0.53/learn/advanced/node", + "docs/sdk/0.53/learn/advanced/ocap", + "docs/sdk/0.53/learn/advanced/proto-docs", + "docs/sdk/0.53/learn/advanced/runtx_middleware", + "docs/sdk/0.53/learn/advanced/simulation", + "docs/sdk/0.53/learn/advanced/store", + "docs/sdk/0.53/learn/advanced/telemetry", + "docs/sdk/0.53/learn/advanced/transactions", + "docs/sdk/0.53/learn/advanced/upgrade" ] }, { - "group": "Beginner", + "group": "Tutorials", "pages": [ - "docs/sdk/v0.47/learn/beginner/app-anatomy", - "docs/sdk/v0.47/learn/beginner/tx-lifecycle", - "docs/sdk/v0.47/learn/beginner/query-lifecycle", - "docs/sdk/v0.47/learn/beginner/accounts", - "docs/sdk/v0.47/learn/beginner/gas-fees" + "docs/sdk/0.53/tutorials/tutorials", + "docs/sdk/0.53/tutorials/transactions/building-a-transaction", + "docs/sdk/0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running", + "docs/sdk/0.53/tutorials/vote-extensions/oracle/getting-started", + "docs/sdk/0.53/tutorials/vote-extensions/auction-frontrunning/getting-started", + "docs/sdk/0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions", + "docs/sdk/0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", + "docs/sdk/0.53/tutorials/vote-extensions/oracle/testing-oracle", + "docs/sdk/0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", + "docs/sdk/0.53/tutorials/vote-extensions/oracle/what-is-an-oracle", + "docs/sdk/0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning" ] }, { - "group": "Advanced", + "group": "User", "pages": [ - "docs/sdk/v0.47/learn/advanced/baseapp", - "docs/sdk/v0.47/learn/advanced/transactions", - "docs/sdk/v0.47/learn/advanced/context", - "docs/sdk/v0.47/learn/advanced/node", - "docs/sdk/v0.47/learn/advanced/store", - "docs/sdk/v0.47/learn/advanced/encoding", - "docs/sdk/v0.47/learn/advanced/grpc_rest", - "docs/sdk/v0.47/learn/advanced/cli", - "docs/sdk/v0.47/learn/advanced/events", - "docs/sdk/v0.47/learn/advanced/telemetry", - "docs/sdk/v0.47/learn/advanced/ocap", - "docs/sdk/v0.47/learn/advanced/runtx_middleware", - "docs/sdk/v0.47/learn/advanced/simulation", - "docs/sdk/v0.47/learn/advanced/proto-docs", - "docs/sdk/v0.47/learn/advanced/upgrade", - "docs/sdk/v0.47/learn/advanced/config", - "docs/sdk/v0.47/learn/advanced/autocli" + "docs/sdk/0.53/user/user", + "docs/sdk/0.53/user/run-node/interact-node", + "docs/sdk/0.53/user/run-node/keyring", + "docs/sdk/0.53/user/run-node/run-node", + "docs/sdk/0.53/user/run-node/run-production", + "docs/sdk/0.53/user/run-node/run-testnet", + "docs/sdk/0.53/user/run-node/txs" ] } ] - }, + } + ] + }, + { + "version": "next", + "tabs": [ { - "tab": "Build", + "tab": "Documentation", "groups": [ { - "group": "Build", - "pages": [ - "docs/sdk/v0.47/build" - ] - }, - { - "group": "Building Apps", - "pages": [ - "docs/sdk/v0.47/build/building-apps/app-go", - "docs/sdk/v0.47/build/building-apps/app-mempool", - "docs/sdk/v0.47/build/building-apps/app-upgrade" - ] + "group": "SDK", + "pages": [] }, { - "group": "Building Modules", + "group": "Build", "pages": [ - "docs/sdk/v0.47/build/building-modules/module-manager", - "docs/sdk/v0.47/build/building-modules/messages-and-queries", - "docs/sdk/v0.47/build/building-modules/msg-services", - "docs/sdk/v0.47/build/building-modules/query-services", - "docs/sdk/v0.47/build/building-modules/protobuf-annotations", - "docs/sdk/v0.47/build/building-modules/beginblock-endblock", - "docs/sdk/v0.47/build/building-modules/keeper", - "docs/sdk/v0.47/build/building-modules/invariants", - "docs/sdk/v0.47/build/building-modules/genesis", - "docs/sdk/v0.47/build/building-modules/module-interfaces", - "docs/sdk/v0.47/build/building-modules/structure", - "docs/sdk/v0.47/build/building-modules/errors", - "docs/sdk/v0.47/build/building-modules/upgrade", - "docs/sdk/v0.47/build/building-modules/simulator", - "docs/sdk/v0.47/build/building-modules/depinject", - "docs/sdk/v0.47/build/building-modules/testing", - "docs/sdk/v0.47/build/building-modules/preblock" + "docs/sdk/next/build/build", + "docs/sdk/next/build/architecture/README", + "docs/sdk/next/build/building-apps/app-go-di", + "docs/sdk/next/build/building-modules/beginblock-endblock", + "docs/sdk/next/build/migrations/intro", + "docs/sdk/next/build/packages/depinject", + "docs/sdk/next/build/rfc/README", + "docs/sdk/next/build/spec/README", + "docs/sdk/next/build/tooling/confix", + "docs/sdk/next/build/abci/checktx", + "docs/sdk/next/build/modules/README", + "docs/sdk/next/build/building-apps/app-go", + "docs/sdk/next/build/building-modules/depinject", + "docs/sdk/next/build/tooling/cosmovisor", + "docs/sdk/next/build/abci/introduction", + "docs/sdk/next/build/building-apps/app-mempool", + "docs/sdk/next/build/building-modules/errors", + "docs/sdk/next/build/tooling/hubl", + "docs/sdk/next/build/abci/prepare-proposal", + "docs/sdk/next/build/building-apps/app-testnet", + "docs/sdk/next/build/building-modules/genesis", + "docs/sdk/next/build/tooling/protobuf", + "docs/sdk/next/build/abci/process-proposal", + "docs/sdk/next/build/building-apps/app-upgrade", + "docs/sdk/next/build/building-modules/intro", + "docs/sdk/next/build/abci/vote-extensions", + "docs/sdk/next/build/building-apps/runtime", + "docs/sdk/next/build/building-modules/invariants", + "docs/sdk/next/build/building-apps/vote-extensions", + "docs/sdk/next/build/building-modules/keeper", + "docs/sdk/next/build/building-modules/messages-and-queries", + "docs/sdk/next/build/building-modules/module-interfaces", + "docs/sdk/next/build/building-modules/module-manager", + "docs/sdk/next/build/building-modules/msg-services", + "docs/sdk/next/build/building-modules/preblock", + "docs/sdk/next/build/building-modules/protobuf-annotations", + "docs/sdk/next/build/building-modules/query-services", + "docs/sdk/next/build/building-modules/simulator", + "docs/sdk/next/build/building-modules/structure", + "docs/sdk/next/build/building-modules/testing", + "docs/sdk/next/build/building-modules/upgrade", + "docs/sdk/next/build/architecture/adr-002-docs-structure", + "docs/sdk/next/build/migrations/upgrade-guide", + "docs/sdk/next/build/packages/collections", + "docs/sdk/next/build/rfc/PROCESS", + "docs/sdk/next/build/spec/SPEC_MODULE", + "docs/sdk/next/build/tooling/README", + "docs/sdk/next/build/architecture/adr-003-dynamic-capability-store", + "docs/sdk/next/build/migrations/upgrade-reference", + "docs/sdk/next/build/packages/README", + "docs/sdk/next/build/rfc/rfc-001-tx-validation", + "docs/sdk/next/build/spec/SPEC_STANDARD", + "docs/sdk/next/build/architecture/adr-004-split-denomination-keys", + "docs/sdk/next/build/migrations/upgrading", + "docs/sdk/next/build/architecture/PROCESS", + "docs/sdk/next/build/modules/auth/README", + "docs/sdk/next/build/modules/authz/README", + "docs/sdk/next/build/modules/bank/README", + "docs/sdk/next/build/modules/consensus/README", + "docs/sdk/next/build/modules/crisis/README", + "docs/sdk/next/build/modules/distribution/README", + "docs/sdk/next/build/modules/epochs/README", + "docs/sdk/next/build/modules/evidence/README", + "docs/sdk/next/build/modules/feegrant/README", + "docs/sdk/next/build/modules/gov/README", + "docs/sdk/next/build/modules/group/README", + "docs/sdk/next/build/modules/mint/README", + "docs/sdk/next/build/modules/nft/README", + "docs/sdk/next/build/modules/params/README", + "docs/sdk/next/build/modules/protocolpool/README", + "docs/sdk/next/build/modules/slashing/README", + "docs/sdk/next/build/modules/staking/README", + "docs/sdk/next/build/modules/upgrade/README", + "docs/sdk/next/build/rfc/rfc/README", + "docs/sdk/next/build/modules/circuit/README", + "docs/sdk/next/build/modules/genutil/README", + "docs/sdk/next/build/spec/_ics/ics-030-signed-messages", + "docs/sdk/next/build/spec/addresses/bech32", + "docs/sdk/next/build/spec/store/interblock-cache", + "docs/sdk/next/build/modules/auth/tx", + "docs/sdk/next/build/spec/_ics/README", + "docs/sdk/next/build/spec/addresses/README", + "docs/sdk/next/build/spec/store/README", + "docs/sdk/next/build/modules/auth/vesting", + "docs/sdk/next/build/rfc/rfc/PROCESS", + "docs/sdk/next/build/rfc/rfc/rfc-001-tx-validation", + "docs/sdk/next/build/rfc/rfc/rfc-template" ] }, { - "group": "ABCI", + "group": "Learn", "pages": [ - "docs/sdk/v0.47/build/abci/introduction", - "docs/sdk/v0.47/build/abci/prepare-proposal", - "docs/sdk/v0.47/build/abci/process-proposal", - "docs/sdk/v0.47/build/abci/checktx" + "docs/sdk/next/learn/learn", + "docs/sdk/next/learn/advanced/autocli", + "docs/sdk/next/learn/beginner/accounts", + "docs/sdk/next/learn/intro/overview", + "docs/sdk/next/learn/advanced/baseapp", + "docs/sdk/next/learn/beginner/app-anatomy", + "docs/sdk/next/learn/intro/sdk-app-architecture", + "docs/sdk/next/learn/advanced/cli", + "docs/sdk/next/learn/beginner/gas-fees", + "docs/sdk/next/learn/intro/sdk-design", + "docs/sdk/next/learn/advanced/config", + "docs/sdk/next/learn/beginner/query-lifecycle", + "docs/sdk/next/learn/intro/why-app-specific", + "docs/sdk/next/learn/advanced/context", + "docs/sdk/next/learn/beginner/tx-lifecycle", + "docs/sdk/next/learn/advanced/encoding", + "docs/sdk/next/learn/advanced/events", + "docs/sdk/next/learn/advanced/grpc_rest", + "docs/sdk/next/learn/advanced/node", + "docs/sdk/next/learn/advanced/ocap", + "docs/sdk/next/learn/advanced/proto-docs", + "docs/sdk/next/learn/advanced/runtx_middleware", + "docs/sdk/next/learn/advanced/simulation", + "docs/sdk/next/learn/advanced/store", + "docs/sdk/next/learn/advanced/telemetry", + "docs/sdk/next/learn/advanced/transactions", + "docs/sdk/next/learn/advanced/upgrade" ] }, { - "group": "Modules", + "group": "Tutorials", "pages": [ - "docs/sdk/v0.47/build/modules", - { - "group": "x/auth", - "pages": [ - "docs/sdk/v0.47/build/modules/auth", - "docs/sdk/v0.47/build/modules/auth/vesting", - "docs/sdk/v0.47/build/modules/auth/tx" - ] - }, - "docs/sdk/v0.47/build/modules/authz", - "docs/sdk/v0.47/build/modules/bank", - "docs/sdk/v0.47/build/modules/consensus", - "docs/sdk/v0.47/build/modules/crisis", - "docs/sdk/v0.47/build/modules/distribution", - "docs/sdk/v0.47/build/modules/epochs", - "docs/sdk/v0.47/build/modules/evidence", - "docs/sdk/v0.47/build/modules/feegrant", - "docs/sdk/v0.47/build/modules/gov", - "docs/sdk/v0.47/build/modules/group", - "docs/sdk/v0.47/build/modules/mint", - "docs/sdk/v0.47/build/modules/nft", - "docs/sdk/v0.47/build/modules/params", - "docs/sdk/v0.47/build/modules/protocolpool", - "docs/sdk/v0.47/build/modules/slashing", - "docs/sdk/v0.47/build/modules/staking", - "docs/sdk/v0.47/build/modules/upgrade", - "docs/sdk/v0.47/build/modules/circuit", - "docs/sdk/v0.47/build/modules/genutil" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/sdk/v0.47/build/migrations/intro", - "docs/sdk/v0.47/build/migrations/upgrade-reference", - "docs/sdk/v0.47/build/migrations/upgrade-guide" - ] - }, - { - "group": "Packages", - "pages": [ - "docs/sdk/v0.47/build/packages", - "docs/sdk/v0.47/build/packages/depinject", - "docs/sdk/v0.47/build/packages/collections" - ] - }, - { - "group": "Tooling", - "pages": [ - "docs/sdk/v0.47/build/tooling", - "docs/sdk/v0.47/build/tooling/protobuf", - "docs/sdk/v0.47/build/tooling/cosmovisor", - "docs/sdk/v0.47/build/tooling/confix" - ] - }, - { - "group": "RFC", - "pages": [ - "docs/sdk/v0.47/build/rfc", - "docs/sdk/v0.47/build/rfc/PROCESS", - "docs/sdk/v0.47/build/rfc/rfc-001-tx-validation", - "docs/sdk/v0.47/build/rfc/rfc-template" - ] - }, - { - "group": "Specifications", - "pages": [ - "docs/sdk/v0.47/build/spec", - "docs/sdk/v0.47/build/spec/SPEC_MODULE", - "docs/sdk/v0.47/build/spec/SPEC_STANDARD", - { - "group": "Addresses spec", - "pages": [ - "docs/sdk/v0.47/build/spec/addresses", - "docs/sdk/v0.47/build/spec/addresses/bech32" - ] - }, - { - "group": "Store", - "pages": [ - "docs/sdk/v0.47/build/spec/store", - "docs/sdk/v0.47/build/spec/store/interblock-cache" - ] - } - ] - } - ] - }, - { - "tab": "User Guides", - "groups": [ - { - "group": "User Guides", - "pages": [ - "docs/sdk/v0.47/user" - ] - }, - { - "group": "Running a Node, API and CLI", - "pages": [ - "docs/sdk/v0.47/user/run-node/keyring", - "docs/sdk/v0.47/user/run-node/run-node", - "docs/sdk/v0.47/user/run-node/interact-node", - "docs/sdk/v0.47/user/run-node/txs", - "docs/sdk/v0.47/user/run-node/run-testnet", - "docs/sdk/v0.47/user/run-node/run-production" + "docs/sdk/next/tutorials/tutorials", + "docs/sdk/next/tutorials/transactions/building-a-transaction", + "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running", + "docs/sdk/next/tutorials/vote-extensions/oracle/getting-started", + "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/getting-started", + "docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions", + "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", + "docs/sdk/next/tutorials/vote-extensions/oracle/testing-oracle", + "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", + "docs/sdk/next/tutorials/vote-extensions/oracle/what-is-an-oracle", + "docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning" ] }, { "group": "User", "pages": [ - "docs/sdk/v0.47/user" - ] - } - ] - }, - { - "tab": "Tutorials", - "groups": [ - { - "group": "Tutorials", - "pages": [ - "docs/sdk/v0.47/tutorials" - ] - }, - { - "group": "Vote Extensions Tutorials", - "pages": [ - { - "group": "Mitigating Auction Front-Running Tutorial", - "pages": [ - "docs/sdk/v0.47/tutorials/vote-extensions/auction-frontrunning/getting-started", - "docs/sdk/v0.47/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", - "docs/sdk/v0.47/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", - "docs/sdk/v0.47/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", - "docs/sdk/v0.47/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running" - ] - }, - { - "group": "Oracle Tutorial", - "pages": [ - "docs/sdk/v0.47/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/v0.47/tutorials/vote-extensions/oracle/what-is-an-oracle", - "docs/sdk/v0.47/tutorials/vote-extensions/oracle/implementing-vote-extensions", - "docs/sdk/v0.47/tutorials/vote-extensions/oracle/testing-oracle" - ] - } - ] - }, - { - "group": "Transaction Tutorials", - "pages": [ - "docs/sdk/v0.47/tutorials/transactions/building-a-transaction" - ] - } - ] - }, - { - "tab": "API Reference", - "pages": [] - }, - { - "tab": "Release Notes", - "pages": [] - } - ] - }, - { - "version": "next", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "Cosmos-SDK", - "pages": [ - "docs/sdk/next/overview" - ] - }, - { - "group": "Transactions & Fees", - "pages": [] - }, - { - "group": "Messaging & Queries", - "pages": [ - "docs/sdk/next/build/building-modules/messaging-and-queries" - ] - }, - { - "group": "Integration", - "pages": [ - { - "group": "App Wiring & Runtime", - "pages": [] - }, - { - "group": "Module Wiring", - "pages": [] - }, - { - "group": "Upgrades & Migrations", - "pages": [] - }, - { - "group": "Messaging Integration", - "pages": [] - }, - { - "group": "Vote Extensions (End-to-End)", - "pages": [] - } - ] - }, - { - "group": "Module Anatomy & Keepers", - "pages": [] - }, - { - "group": "Runtime & ABCI", - "pages": [ - "docs/sdk/next/build/abci/index" - ] - }, - { - "group": "State & Store", - "pages": [] - }, - { - "group": "Encoding & Protobuf", - "pages": [] - }, - { - "group": "Testing & Simulation", - "pages": [] - }, - { - "group": "Core Concepts", - "pages": [ - "docs/sdk/next/index" - ] - }, - { - "group": "Node Operations", - "pages": [] - }, - { - "group": "Tooling", - "pages": [] - } - ] - }, - { - "tab": "Module Reference", - "groups": [] - }, - { - "tab": "API Reference", - "pages": [] - }, - { - "tab": "Release Notes", - "pages": [] - } - ] - } - ] - }, - { - "dropdown": "IBC", - "icon": "book-open-text", - "versions": [ - { - "version": "v10.1.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v10.1.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v10.1.x/ibc/overview", - "docs/ibc/v10.1.x/ibc/integration", - "docs/ibc/v10.1.x/ibc/relayer", - "docs/ibc/v10.1.x/ibc/best-practices", - "docs/ibc/v10.1.x/ibc/permissioning", - "docs/ibc/v10.1.x/ibc/apps/apps", - "docs/ibc/v10.1.x/ibc/middleware/overview", - "docs/ibc/v10.1.x/ibc/upgrades/quick-guide", - "docs/ibc/v10.1.x/ibc/apps/ibcmodule", - "docs/ibc/v10.1.x/ibc/middleware/developIBCv2", - "docs/ibc/v10.1.x/ibc/upgrades/developer-guide", - "docs/ibc/v10.1.x/ibc/apps/bindports", - "docs/ibc/v10.1.x/ibc/middleware/develop", - "docs/ibc/v10.1.x/ibc/upgrades/genesis-restart", - "docs/ibc/v10.1.x/ibc/apps/keeper", - "docs/ibc/v10.1.x/ibc/middleware/integration", - "docs/ibc/v10.1.x/ibc/apps/packets_acks", - "docs/ibc/v10.1.x/ibc/apps/routing", - "docs/ibc/v10.1.x/ibc/apps/ibcv2apps", - "docs/ibc/v10.1.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v10.1.x/migrations/support-denoms-with-slashes", - "docs/ibc/v10.1.x/migrations/sdk-to-v1", - "docs/ibc/v10.1.x/migrations/v1-to-v2", - "docs/ibc/v10.1.x/migrations/v2-to-v3", - "docs/ibc/v10.1.x/migrations/v3-to-v4", - "docs/ibc/v10.1.x/migrations/v4-to-v5", - "docs/ibc/v10.1.x/migrations/v5-to-v6", - "docs/ibc/v10.1.x/migrations/v6-to-v7", - "docs/ibc/v10.1.x/migrations/v7-to-v7_1", - "docs/ibc/v10.1.x/migrations/v7_2-to-v7_3", - "docs/ibc/v10.1.x/migrations/v7-to-v8", - "docs/ibc/v10.1.x/migrations/v8-to-v8_1", - "docs/ibc/v10.1.x/migrations/v8_1-to-v10", - "docs/ibc/v10.1.x/migrations/migration.template" - ] - }, - { - "group": "Light Clients", - "pages": [ - "docs/ibc/v10.1.x/light-clients/proposals", - "docs/ibc/v10.1.x/light-clients/developer-guide/overview", - "docs/ibc/v10.1.x/light-clients/localhost/overview", - "docs/ibc/v10.1.x/light-clients/solomachine/solomachine", - "docs/ibc/v10.1.x/light-clients/tendermint/overview", - "docs/ibc/v10.1.x/light-clients/wasm/overview", - "docs/ibc/v10.1.x/light-clients/developer-guide/light-client-module", - "docs/ibc/v10.1.x/light-clients/localhost/integration", - "docs/ibc/v10.1.x/light-clients/solomachine/concepts", - "docs/ibc/v10.1.x/light-clients/wasm/concepts", - "docs/ibc/v10.1.x/light-clients/developer-guide/client-state", - "docs/ibc/v10.1.x/light-clients/localhost/client-state", - "docs/ibc/v10.1.x/light-clients/solomachine/state", - "docs/ibc/v10.1.x/light-clients/wasm/integration", - "docs/ibc/v10.1.x/light-clients/developer-guide/consensus-state", - "docs/ibc/v10.1.x/light-clients/localhost/connection", - "docs/ibc/v10.1.x/light-clients/solomachine/state_transitions", - "docs/ibc/v10.1.x/light-clients/wasm/messages", - "docs/ibc/v10.1.x/light-clients/developer-guide/updates-and-misbehaviour", - "docs/ibc/v10.1.x/light-clients/localhost/state-verification", - "docs/ibc/v10.1.x/light-clients/wasm/governance", - "docs/ibc/v10.1.x/light-clients/developer-guide/upgrades", - "docs/ibc/v10.1.x/light-clients/wasm/events", - "docs/ibc/v10.1.x/light-clients/developer-guide/proofs", - "docs/ibc/v10.1.x/light-clients/wasm/client", - "docs/ibc/v10.1.x/light-clients/developer-guide/proposals", - "docs/ibc/v10.1.x/light-clients/wasm/contracts", - "docs/ibc/v10.1.x/light-clients/developer-guide/setup", - "docs/ibc/v10.1.x/light-clients/wasm/migrations" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v10.1.x/apps/interchain-accounts/overview", - "docs/ibc/v10.1.x/apps/transfer/overview", - "docs/ibc/v10.1.x/apps/interchain-accounts/development", - "docs/ibc/v10.1.x/apps/transfer/state", - "docs/ibc/v10.1.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v10.1.x/apps/transfer/state-transitions", - "docs/ibc/v10.1.x/apps/interchain-accounts/integration", - "docs/ibc/v10.1.x/apps/transfer/messages", - "docs/ibc/v10.1.x/apps/interchain-accounts/messages", - "docs/ibc/v10.1.x/apps/transfer/events", - "docs/ibc/v10.1.x/apps/interchain-accounts/parameters", - "docs/ibc/v10.1.x/apps/transfer/metrics", - "docs/ibc/v10.1.x/apps/interchain-accounts/tx-encoding", - "docs/ibc/v10.1.x/apps/transfer/params", - "docs/ibc/v10.1.x/apps/interchain-accounts/client", - "docs/ibc/v10.1.x/apps/transfer/authorizations", - "docs/ibc/v10.1.x/apps/interchain-accounts/active-channels", - "docs/ibc/v10.1.x/apps/transfer/client", - "docs/ibc/v10.1.x/apps/transfer/IBCv2-transfer", - "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/auth-modules", - "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/integration", - "docs/ibc/v10.1.x/apps/interchain-accounts/legacy/keeper-api" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v10.1.x/middleware/callbacks/overview", - "docs/ibc/v10.1.x/middleware/callbacks/integration", - "docs/ibc/v10.1.x/middleware/callbacks/interfaces", - "docs/ibc/v10.1.x/middleware/callbacks/events", - "docs/ibc/v10.1.x/middleware/callbacks/end-users", - "docs/ibc/v10.1.x/middleware/callbacks/gas", - "docs/ibc/v10.1.x/middleware/callbacks/callbacks-IBCv2" - ] - } - ] - } - ] - }, - { - "version": "v4.6.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v4.6.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v4.6.x/ibc/overview", - "docs/ibc/v4.6.x/ibc/integration", - "docs/ibc/v4.6.x/ibc/proposals", - "docs/ibc/v4.6.x/ibc/relayer", - "docs/ibc/v4.6.x/ibc/proto-docs", - "docs/ibc/v4.6.x/ibc/roadmap", - "docs/ibc/v4.6.x/ibc/apps/apps", - "docs/ibc/v4.6.x/ibc/middleware/develop", - "docs/ibc/v4.6.x/ibc/upgrades/quick-guide", - "docs/ibc/v4.6.x/ibc/apps/ibcmodule", - "docs/ibc/v4.6.x/ibc/middleware/integration", - "docs/ibc/v4.6.x/ibc/upgrades/developer-guide", - "docs/ibc/v4.6.x/ibc/apps/bindports", - "docs/ibc/v4.6.x/ibc/upgrades/genesis-restart", - "docs/ibc/v4.6.x/ibc/apps/keeper", - "docs/ibc/v4.6.x/ibc/apps/packets_acks", - "docs/ibc/v4.6.x/ibc/apps/routing", - "docs/ibc/v4.6.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v4.6.x/migrations/support-denoms-with-slashes", - "docs/ibc/v4.6.x/migrations/sdk-to-v1", - "docs/ibc/v4.6.x/migrations/v1-to-v2", - "docs/ibc/v4.6.x/migrations/v2-to-v3", - "docs/ibc/v4.6.x/migrations/v3-to-v4" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v4.6.x/apps/interchain-accounts/overview", - "docs/ibc/v4.6.x/apps/transfer/overview", - "docs/ibc/v4.6.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v4.6.x/apps/transfer/state", - "docs/ibc/v4.6.x/apps/interchain-accounts/active-channels", - "docs/ibc/v4.6.x/apps/transfer/state-transitions", - "docs/ibc/v4.6.x/apps/interchain-accounts/integration", - "docs/ibc/v4.6.x/apps/transfer/messages", - "docs/ibc/v4.6.x/apps/interchain-accounts/parameters", - "docs/ibc/v4.6.x/apps/transfer/events", - "docs/ibc/v4.6.x/apps/interchain-accounts/transactions", - "docs/ibc/v4.6.x/apps/transfer/metrics", - "docs/ibc/v4.6.x/apps/transfer/params" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v4.6.x/middleware/ics29-fee/overview", - "docs/ibc/v4.6.x/middleware/ics29-fee/integration", - "docs/ibc/v4.6.x/middleware/ics29-fee/msgs", - "docs/ibc/v4.6.x/middleware/ics29-fee/fee-distribution", - "docs/ibc/v4.6.x/middleware/ics29-fee/events", - "docs/ibc/v4.6.x/middleware/ics29-fee/end-users" - ] - } - ] - } - ] - }, - { - "version": "v5.4.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v5.4.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v5.4.x/ibc/overview", - "docs/ibc/v5.4.x/ibc/integration", - "docs/ibc/v5.4.x/ibc/proposals", - "docs/ibc/v5.4.x/ibc/relayer", - "docs/ibc/v5.4.x/ibc/proto-docs", - "docs/ibc/v5.4.x/ibc/roadmap", - "docs/ibc/v5.4.x/ibc/apps/apps", - "docs/ibc/v5.4.x/ibc/middleware/develop", - "docs/ibc/v5.4.x/ibc/upgrades/quick-guide", - "docs/ibc/v5.4.x/ibc/apps/ibcmodule", - "docs/ibc/v5.4.x/ibc/middleware/integration", - "docs/ibc/v5.4.x/ibc/upgrades/developer-guide", - "docs/ibc/v5.4.x/ibc/apps/bindports", - "docs/ibc/v5.4.x/ibc/upgrades/genesis-restart", - "docs/ibc/v5.4.x/ibc/apps/keeper", - "docs/ibc/v5.4.x/ibc/apps/packets_acks", - "docs/ibc/v5.4.x/ibc/apps/routing", - "docs/ibc/v5.4.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v5.4.x/migrations/support-denoms-with-slashes", - "docs/ibc/v5.4.x/migrations/sdk-to-v1", - "docs/ibc/v5.4.x/migrations/v1-to-v2", - "docs/ibc/v5.4.x/migrations/v2-to-v3", - "docs/ibc/v5.4.x/migrations/v3-to-v4" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v5.4.x/apps/interchain-accounts/overview", - "docs/ibc/v5.4.x/apps/transfer/overview", - "docs/ibc/v5.4.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v5.4.x/apps/transfer/state", - "docs/ibc/v5.4.x/apps/interchain-accounts/active-channels", - "docs/ibc/v5.4.x/apps/transfer/state-transitions", - "docs/ibc/v5.4.x/apps/interchain-accounts/integration", - "docs/ibc/v5.4.x/apps/transfer/messages", - "docs/ibc/v5.4.x/apps/interchain-accounts/parameters", - "docs/ibc/v5.4.x/apps/transfer/events", - "docs/ibc/v5.4.x/apps/interchain-accounts/transactions", - "docs/ibc/v5.4.x/apps/transfer/metrics", - "docs/ibc/v5.4.x/apps/transfer/params" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v5.4.x/middleware/ics29-fee/overview", - "docs/ibc/v5.4.x/middleware/ics29-fee/integration", - "docs/ibc/v5.4.x/middleware/ics29-fee/msgs", - "docs/ibc/v5.4.x/middleware/ics29-fee/fee-distribution", - "docs/ibc/v5.4.x/middleware/ics29-fee/events", - "docs/ibc/v5.4.x/middleware/ics29-fee/end-users" - ] - } - ] - } - ] - }, - { - "version": "v6.3.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v6.3.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v6.3.x/ibc/overview", - "docs/ibc/v6.3.x/ibc/integration", - "docs/ibc/v6.3.x/ibc/proposals", - "docs/ibc/v6.3.x/ibc/relayer", - "docs/ibc/v6.3.x/ibc/proto-docs", - "docs/ibc/v6.3.x/ibc/roadmap", - "docs/ibc/v6.3.x/ibc/apps/apps", - "docs/ibc/v6.3.x/ibc/middleware/develop", - "docs/ibc/v6.3.x/ibc/upgrades/quick-guide", - "docs/ibc/v6.3.x/ibc/apps/ibcmodule", - "docs/ibc/v6.3.x/ibc/middleware/integration", - "docs/ibc/v6.3.x/ibc/upgrades/developer-guide", - "docs/ibc/v6.3.x/ibc/apps/bindports", - "docs/ibc/v6.3.x/ibc/upgrades/genesis-restart", - "docs/ibc/v6.3.x/ibc/apps/keeper", - "docs/ibc/v6.3.x/ibc/apps/packets_acks", - "docs/ibc/v6.3.x/ibc/apps/routing", - "docs/ibc/v6.3.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v6.3.x/migrations/support-denoms-with-slashes", - "docs/ibc/v6.3.x/migrations/sdk-to-v1", - "docs/ibc/v6.3.x/migrations/v1-to-v2", - "docs/ibc/v6.3.x/migrations/v2-to-v3", - "docs/ibc/v6.3.x/migrations/v3-to-v4", - "docs/ibc/v6.3.x/migrations/v4-to-v5", - "docs/ibc/v6.3.x/migrations/v5-to-v6" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v6.3.x/apps/interchain-accounts/overview", - "docs/ibc/v6.3.x/apps/transfer/overview", - "docs/ibc/v6.3.x/apps/interchain-accounts/development", - "docs/ibc/v6.3.x/apps/transfer/state", - "docs/ibc/v6.3.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v6.3.x/apps/transfer/state-transitions", - "docs/ibc/v6.3.x/apps/interchain-accounts/integration", - "docs/ibc/v6.3.x/apps/transfer/messages", - "docs/ibc/v6.3.x/apps/interchain-accounts/messages", - "docs/ibc/v6.3.x/apps/transfer/events", - "docs/ibc/v6.3.x/apps/interchain-accounts/parameters", - "docs/ibc/v6.3.x/apps/transfer/metrics", - "docs/ibc/v6.3.x/apps/interchain-accounts/client", - "docs/ibc/v6.3.x/apps/transfer/params", - "docs/ibc/v6.3.x/apps/interchain-accounts/active-channels", - "docs/ibc/v6.3.x/apps/transfer/authorizations", - "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/auth-modules", - "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/integration", - "docs/ibc/v6.3.x/apps/interchain-accounts/legacy/keeper-api" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v6.3.x/middleware/ics29-fee/overview", - "docs/ibc/v6.3.x/middleware/ics29-fee/integration", - "docs/ibc/v6.3.x/middleware/ics29-fee/msgs", - "docs/ibc/v6.3.x/middleware/ics29-fee/fee-distribution", - "docs/ibc/v6.3.x/middleware/ics29-fee/events", - "docs/ibc/v6.3.x/middleware/ics29-fee/end-users" - ] - } - ] - } - ] - }, - { - "version": "v7.8.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v7.8.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v7.8.x/ibc/overview", - "docs/ibc/v7.8.x/ibc/integration", - "docs/ibc/v7.8.x/ibc/proposals", - "docs/ibc/v7.8.x/ibc/relayer", - "docs/ibc/v7.8.x/ibc/proto-docs", - "docs/ibc/v7.8.x/ibc/roadmap", - "docs/ibc/v7.8.x/ibc/troubleshooting", - "docs/ibc/v7.8.x/ibc/apps/apps", - "docs/ibc/v7.8.x/ibc/middleware/develop", - "docs/ibc/v7.8.x/ibc/upgrades/quick-guide", - "docs/ibc/v7.8.x/ibc/apps/ibcmodule", - "docs/ibc/v7.8.x/ibc/middleware/integration", - "docs/ibc/v7.8.x/ibc/upgrades/developer-guide", - "docs/ibc/v7.8.x/ibc/apps/bindports", - "docs/ibc/v7.8.x/ibc/upgrades/genesis-restart", - "docs/ibc/v7.8.x/ibc/apps/keeper", - "docs/ibc/v7.8.x/ibc/apps/packets_acks", - "docs/ibc/v7.8.x/ibc/apps/routing", - "docs/ibc/v7.8.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v7.8.x/migrations/support-denoms-with-slashes", - "docs/ibc/v7.8.x/migrations/sdk-to-v1", - "docs/ibc/v7.8.x/migrations/v1-to-v2", - "docs/ibc/v7.8.x/migrations/v2-to-v3", - "docs/ibc/v7.8.x/migrations/v3-to-v4", - "docs/ibc/v7.8.x/migrations/v4-to-v5", - "docs/ibc/v7.8.x/migrations/v5-to-v6", - "docs/ibc/v7.8.x/migrations/v6-to-v7", - "docs/ibc/v7.8.x/migrations/v7-to-v7_1", - "docs/ibc/v7.8.x/migrations/v7_2-to-v7_3" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v7.8.x/apps/interchain-accounts/overview", - "docs/ibc/v7.8.x/apps/transfer/overview", - "docs/ibc/v7.8.x/apps/interchain-accounts/development", - "docs/ibc/v7.8.x/apps/transfer/state", - "docs/ibc/v7.8.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v7.8.x/apps/transfer/state-transitions", - "docs/ibc/v7.8.x/apps/interchain-accounts/integration", - "docs/ibc/v7.8.x/apps/transfer/messages", - "docs/ibc/v7.8.x/apps/interchain-accounts/messages", - "docs/ibc/v7.8.x/apps/transfer/events", - "docs/ibc/v7.8.x/apps/interchain-accounts/parameters", - "docs/ibc/v7.8.x/apps/transfer/metrics", - "docs/ibc/v7.8.x/apps/interchain-accounts/tx-encoding", - "docs/ibc/v7.8.x/apps/transfer/params", - "docs/ibc/v7.8.x/apps/interchain-accounts/client", - "docs/ibc/v7.8.x/apps/transfer/authorizations", - "docs/ibc/v7.8.x/apps/interchain-accounts/active-channels", - "docs/ibc/v7.8.x/apps/transfer/client", - "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/auth-modules", - "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/integration", - "docs/ibc/v7.8.x/apps/interchain-accounts/legacy/keeper-api" - ] - }, - { - "group": "Light Clients", - "pages": [ - "docs/ibc/v7.8.x/light-clients/developer-guide/overview", - "docs/ibc/v7.8.x/light-clients/localhost/overview", - "docs/ibc/v7.8.x/light-clients/solomachine/solomachine", - "docs/ibc/v7.8.x/light-clients/wasm/overview", - "docs/ibc/v7.8.x/light-clients/developer-guide/client-state", - "docs/ibc/v7.8.x/light-clients/localhost/integration", - "docs/ibc/v7.8.x/light-clients/solomachine/concepts", - "docs/ibc/v7.8.x/light-clients/wasm/concepts", - "docs/ibc/v7.8.x/light-clients/developer-guide/consensus-state", - "docs/ibc/v7.8.x/light-clients/localhost/client-state", - "docs/ibc/v7.8.x/light-clients/solomachine/state", - "docs/ibc/v7.8.x/light-clients/wasm/integration", - "docs/ibc/v7.8.x/light-clients/developer-guide/updates-and-misbehaviour", - "docs/ibc/v7.8.x/light-clients/localhost/connection", - "docs/ibc/v7.8.x/light-clients/solomachine/state_transitions", - "docs/ibc/v7.8.x/light-clients/wasm/messages", - "docs/ibc/v7.8.x/light-clients/developer-guide/upgrades", - "docs/ibc/v7.8.x/light-clients/localhost/state-verification", - "docs/ibc/v7.8.x/light-clients/wasm/governance", - "docs/ibc/v7.8.x/light-clients/developer-guide/proofs", - "docs/ibc/v7.8.x/light-clients/wasm/events", - "docs/ibc/v7.8.x/light-clients/developer-guide/proposals", - "docs/ibc/v7.8.x/light-clients/wasm/client", - "docs/ibc/v7.8.x/light-clients/developer-guide/genesis", - "docs/ibc/v7.8.x/light-clients/wasm/contracts", - "docs/ibc/v7.8.x/light-clients/developer-guide/setup" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v7.8.x/middleware/callbacks/overview", - "docs/ibc/v7.8.x/middleware/ics29-fee/overview", - "docs/ibc/v7.8.x/middleware/callbacks/integration", - "docs/ibc/v7.8.x/middleware/ics29-fee/integration", - "docs/ibc/v7.8.x/middleware/callbacks/interfaces", - "docs/ibc/v7.8.x/middleware/ics29-fee/msgs", - "docs/ibc/v7.8.x/middleware/callbacks/events", - "docs/ibc/v7.8.x/middleware/ics29-fee/fee-distribution", - "docs/ibc/v7.8.x/middleware/callbacks/end-users", - "docs/ibc/v7.8.x/middleware/ics29-fee/events", - "docs/ibc/v7.8.x/middleware/callbacks/gas", - "docs/ibc/v7.8.x/middleware/ics29-fee/end-users" - ] - } - ] - } - ] - }, - { - "version": "v8.5.x", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/v8.5.x/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/v8.5.x/ibc/overview", - "docs/ibc/v8.5.x/ibc/integration", - "docs/ibc/v8.5.x/ibc/channel-upgrades", - "docs/ibc/v8.5.x/ibc/proposals", - "docs/ibc/v8.5.x/ibc/relayer", - "docs/ibc/v8.5.x/ibc/proto-docs", - "docs/ibc/v8.5.x/ibc/roadmap", - "docs/ibc/v8.5.x/ibc/troubleshooting", - "docs/ibc/v8.5.x/ibc/capability-module", - "docs/ibc/v8.5.x/ibc/apps/apps", - "docs/ibc/v8.5.x/ibc/middleware/overview", - "docs/ibc/v8.5.x/ibc/upgrades/quick-guide", - "docs/ibc/v8.5.x/ibc/apps/ibcmodule", - "docs/ibc/v8.5.x/ibc/middleware/develop", - "docs/ibc/v8.5.x/ibc/upgrades/developer-guide", - "docs/ibc/v8.5.x/ibc/apps/bindports", - "docs/ibc/v8.5.x/ibc/middleware/integration", - "docs/ibc/v8.5.x/ibc/upgrades/genesis-restart", - "docs/ibc/v8.5.x/ibc/apps/keeper", - "docs/ibc/v8.5.x/ibc/apps/packets_acks", - "docs/ibc/v8.5.x/ibc/apps/routing", - "docs/ibc/v8.5.x/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/v8.5.x/migrations/support-denoms-with-slashes", - "docs/ibc/v8.5.x/migrations/sdk-to-v1", - "docs/ibc/v8.5.x/migrations/v1-to-v2", - "docs/ibc/v8.5.x/migrations/v2-to-v3", - "docs/ibc/v8.5.x/migrations/v3-to-v4", - "docs/ibc/v8.5.x/migrations/v4-to-v5", - "docs/ibc/v8.5.x/migrations/v5-to-v6", - "docs/ibc/v8.5.x/migrations/v6-to-v7", - "docs/ibc/v8.5.x/migrations/v7-to-v7_1", - "docs/ibc/v8.5.x/migrations/v7_2-to-v7_3", - "docs/ibc/v8.5.x/migrations/v7-to-v8", - "docs/ibc/v8.5.x/migrations/v8-to-v8_1", - "docs/ibc/v8.5.x/migrations/migration.template" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/v8.5.x/apps/interchain-accounts/overview", - "docs/ibc/v8.5.x/apps/transfer/overview", - "docs/ibc/v8.5.x/apps/interchain-accounts/development", - "docs/ibc/v8.5.x/apps/transfer/state", - "docs/ibc/v8.5.x/apps/interchain-accounts/auth-modules", - "docs/ibc/v8.5.x/apps/transfer/state-transitions", - "docs/ibc/v8.5.x/apps/interchain-accounts/integration", - "docs/ibc/v8.5.x/apps/transfer/messages", - "docs/ibc/v8.5.x/apps/interchain-accounts/messages", - "docs/ibc/v8.5.x/apps/transfer/events", - "docs/ibc/v8.5.x/apps/interchain-accounts/parameters", - "docs/ibc/v8.5.x/apps/transfer/metrics", - "docs/ibc/v8.5.x/apps/interchain-accounts/tx-encoding", - "docs/ibc/v8.5.x/apps/transfer/params", - "docs/ibc/v8.5.x/apps/interchain-accounts/client", - "docs/ibc/v8.5.x/apps/transfer/authorizations", - "docs/ibc/v8.5.x/apps/interchain-accounts/active-channels", - "docs/ibc/v8.5.x/apps/transfer/client", - "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/auth-modules", - "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/integration", - "docs/ibc/v8.5.x/apps/interchain-accounts/legacy/keeper-api" - ] - }, - { - "group": "Light Clients", - "pages": [ - "docs/ibc/v8.5.x/light-clients/developer-guide/overview", - "docs/ibc/v8.5.x/light-clients/localhost/overview", - "docs/ibc/v8.5.x/light-clients/solomachine/solomachine", - "docs/ibc/v8.5.x/light-clients/wasm/overview", - "docs/ibc/v8.5.x/light-clients/developer-guide/client-state", - "docs/ibc/v8.5.x/light-clients/localhost/integration", - "docs/ibc/v8.5.x/light-clients/solomachine/concepts", - "docs/ibc/v8.5.x/light-clients/wasm/concepts", - "docs/ibc/v8.5.x/light-clients/developer-guide/consensus-state", - "docs/ibc/v8.5.x/light-clients/localhost/client-state", - "docs/ibc/v8.5.x/light-clients/solomachine/state", - "docs/ibc/v8.5.x/light-clients/wasm/integration", - "docs/ibc/v8.5.x/light-clients/developer-guide/updates-and-misbehaviour", - "docs/ibc/v8.5.x/light-clients/localhost/connection", - "docs/ibc/v8.5.x/light-clients/solomachine/state_transitions", - "docs/ibc/v8.5.x/light-clients/wasm/messages", - "docs/ibc/v8.5.x/light-clients/developer-guide/upgrades", - "docs/ibc/v8.5.x/light-clients/localhost/state-verification", - "docs/ibc/v8.5.x/light-clients/wasm/governance", - "docs/ibc/v8.5.x/light-clients/developer-guide/proofs", - "docs/ibc/v8.5.x/light-clients/wasm/events", - "docs/ibc/v8.5.x/light-clients/developer-guide/proposals", - "docs/ibc/v8.5.x/light-clients/wasm/client", - "docs/ibc/v8.5.x/light-clients/developer-guide/genesis", - "docs/ibc/v8.5.x/light-clients/wasm/contracts", - "docs/ibc/v8.5.x/light-clients/developer-guide/setup", - "docs/ibc/v8.5.x/light-clients/wasm/migrations" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/v8.5.x/middleware/callbacks/overview", - "docs/ibc/v8.5.x/middleware/ics29-fee/overview", - "docs/ibc/v8.5.x/middleware/callbacks/integration", - "docs/ibc/v8.5.x/middleware/ics29-fee/integration", - "docs/ibc/v8.5.x/middleware/callbacks/interfaces", - "docs/ibc/v8.5.x/middleware/ics29-fee/msgs", - "docs/ibc/v8.5.x/middleware/callbacks/events", - "docs/ibc/v8.5.x/middleware/ics29-fee/fee-distribution", - "docs/ibc/v8.5.x/middleware/callbacks/end-users", - "docs/ibc/v8.5.x/middleware/ics29-fee/events", - "docs/ibc/v8.5.x/middleware/callbacks/gas", - "docs/ibc/v8.5.x/middleware/ics29-fee/end-users" - ] - } - ] - } - ] - }, - { - "version": "next", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "IBC", - "pages": [ - "docs/ibc/next/intro" - ] - }, - { - "group": "Ibc", - "pages": [ - "docs/ibc/next/ibc/overview", - "docs/ibc/next/ibc/integration", - "docs/ibc/next/ibc/relayer", - "docs/ibc/next/ibc/best-practices", - "docs/ibc/next/ibc/permissioning", - "docs/ibc/next/ibc/apps/apps", - "docs/ibc/next/ibc/middleware/overview", - "docs/ibc/next/ibc/upgrades/quick-guide", - "docs/ibc/next/ibc/apps/ibcmodule", - "docs/ibc/next/ibc/middleware/developIBCv2", - "docs/ibc/next/ibc/upgrades/developer-guide", - "docs/ibc/next/ibc/apps/bindports", - "docs/ibc/next/ibc/middleware/develop", - "docs/ibc/next/ibc/upgrades/genesis-restart", - "docs/ibc/next/ibc/apps/keeper", - "docs/ibc/next/ibc/middleware/integration", - "docs/ibc/next/ibc/apps/packets_acks", - "docs/ibc/next/ibc/apps/routing", - "docs/ibc/next/ibc/apps/ibcv2apps", - "docs/ibc/next/ibc/upgrades/intro" - ] - }, - { - "group": "Migrations", - "pages": [ - "docs/ibc/next/migrations/support-denoms-with-slashes", - "docs/ibc/next/migrations/support-stackbuilder", - "docs/ibc/next/migrations/sdk-to-v1", - "docs/ibc/next/migrations/v1-to-v2", - "docs/ibc/next/migrations/v2-to-v3", - "docs/ibc/next/migrations/v3-to-v4", - "docs/ibc/next/migrations/v4-to-v5", - "docs/ibc/next/migrations/v5-to-v6", - "docs/ibc/next/migrations/v6-to-v7", - "docs/ibc/next/migrations/v7-to-v7_1", - "docs/ibc/next/migrations/v7_2-to-v7_3", - "docs/ibc/next/migrations/v7-to-v8", - "docs/ibc/next/migrations/v8-to-v8_1", - "docs/ibc/next/migrations/v8_1-to-v10", - "docs/ibc/next/migrations/v10-to-v11", - "docs/ibc/next/migrations/migration.template" - ] - }, - { - "group": "Light Clients", - "pages": [ - "docs/ibc/next/light-clients/proposals", - "docs/ibc/next/light-clients/developer-guide/overview", - "docs/ibc/next/light-clients/localhost/overview", - "docs/ibc/next/light-clients/solomachine/solomachine", - "docs/ibc/next/light-clients/tendermint/overview", - "docs/ibc/next/light-clients/wasm/overview", - "docs/ibc/next/light-clients/developer-guide/light-client-module", - "docs/ibc/next/light-clients/localhost/integration", - "docs/ibc/next/light-clients/solomachine/concepts", - "docs/ibc/next/light-clients/wasm/concepts", - "docs/ibc/next/light-clients/developer-guide/client-state", - "docs/ibc/next/light-clients/localhost/client-state", - "docs/ibc/next/light-clients/solomachine/state", - "docs/ibc/next/light-clients/wasm/integration", - "docs/ibc/next/light-clients/developer-guide/consensus-state", - "docs/ibc/next/light-clients/localhost/connection", - "docs/ibc/next/light-clients/solomachine/state_transitions", - "docs/ibc/next/light-clients/wasm/messages", - "docs/ibc/next/light-clients/developer-guide/updates-and-misbehaviour", - "docs/ibc/next/light-clients/localhost/state-verification", - "docs/ibc/next/light-clients/wasm/governance", - "docs/ibc/next/light-clients/developer-guide/upgrades", - "docs/ibc/next/light-clients/wasm/events", - "docs/ibc/next/light-clients/developer-guide/proofs", - "docs/ibc/next/light-clients/wasm/client", - "docs/ibc/next/light-clients/developer-guide/proposals", - "docs/ibc/next/light-clients/wasm/contracts", - "docs/ibc/next/light-clients/developer-guide/setup", - "docs/ibc/next/light-clients/wasm/migrations" - ] - }, - { - "group": "Apps", - "pages": [ - "docs/ibc/next/apps/interchain-accounts/overview", - "docs/ibc/next/apps/transfer/overview", - "docs/ibc/next/apps/interchain-accounts/development", - "docs/ibc/next/apps/transfer/state", - "docs/ibc/next/apps/interchain-accounts/auth-modules", - "docs/ibc/next/apps/transfer/state-transitions", - "docs/ibc/next/apps/interchain-accounts/integration", - "docs/ibc/next/apps/transfer/messages", - "docs/ibc/next/apps/interchain-accounts/messages", - "docs/ibc/next/apps/transfer/events", - "docs/ibc/next/apps/interchain-accounts/parameters", - "docs/ibc/next/apps/transfer/metrics", - "docs/ibc/next/apps/interchain-accounts/tx-encoding", - "docs/ibc/next/apps/transfer/params", - "docs/ibc/next/apps/interchain-accounts/client", - "docs/ibc/next/apps/transfer/authorizations", - "docs/ibc/next/apps/interchain-accounts/active-channels", - "docs/ibc/next/apps/transfer/client", - "docs/ibc/next/apps/transfer/IBCv2-transfer", - "docs/ibc/next/apps/interchain-accounts/legacy/auth-modules", - "docs/ibc/next/apps/interchain-accounts/legacy/integration", - "docs/ibc/next/apps/interchain-accounts/legacy/keeper-api" - ] - }, - { - "group": "Middleware", - "pages": [ - "docs/ibc/next/middleware/callbacks/overview", - "docs/ibc/next/middleware/packet-forward-middleware/integration", - "docs/ibc/next/middleware/rate-limit-middleware/overview", - "docs/ibc/next/middleware/callbacks/integration", - "docs/ibc/next/middleware/packet-forward-middleware/overview", - "docs/ibc/next/middleware/rate-limit-middleware/integration", - "docs/ibc/next/middleware/callbacks/interfaces", - "docs/ibc/next/middleware/packet-forward-middleware/example-usage", - "docs/ibc/next/middleware/rate-limit-middleware/setting-limits", - "docs/ibc/next/middleware/callbacks/events", - "docs/ibc/next/middleware/callbacks/end-users", - "docs/ibc/next/middleware/callbacks/gas", - "docs/ibc/next/middleware/callbacks/callbacks-IBCv2" + "docs/sdk/next/user/user", + "docs/sdk/next/user/run-node/interact-node", + "docs/sdk/next/user/run-node/keyring", + "docs/sdk/next/user/run-node/run-node", + "docs/sdk/next/user/run-node/run-production", + "docs/sdk/next/user/run-node/run-testnet", + "docs/sdk/next/user/run-node/txs", + "docs/sdk/next/user/run-node/rosetta" ] } ] diff --git a/docs/ibc/next/changelog/release-notes.mdx b/docs/ibc/next/changelog/release-notes.mdx deleted file mode 100644 index 7c743f40..00000000 --- a/docs/ibc/next/changelog/release-notes.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: "Release Notes" -description: "Cosmos IBC release notes and changelog" -mode: "custom" ---- - - - - Placeholder release notes - diff --git a/docs/ibc/next/index.mdx b/docs/ibc/next/index.mdx deleted file mode 100644 index 5140437c..00000000 --- a/docs/ibc/next/index.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: "IBC Overview" -description: "IBC-specific integration docs (coming soon)" ---- - - -The IBC documentation is under active development and will appear here soon. - - -For now, see EVM IBC references in Concepts and Precompiles. - diff --git a/docs/ibc/next/link-rewrite-test.mdx b/docs/ibc/next/link-rewrite-test.mdx deleted file mode 100644 index ed5080e7..00000000 --- a/docs/ibc/next/link-rewrite-test.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: "Link Rewrite Test" -description: "Test page to verify versioned link rewriting during freeze" ---- - -This page verifies that absolute doc links are rewritten from `next` to the frozen version. - -- Markdown link: [Go to IBC index](/docs/ibc/next/index) -- Anchor link: IBC Index -- Legacy doc path: Old doc path - - Release Notes (markdown): [IBC Release Notes](/docs/ibc/next/changelog/release-notes) - - Release Notes (anchor): IBC Release Notes - -If rewriting succeeds, in the frozen version these should point to `/docs/ibc/v0.1.0/...`. diff --git a/docs/sdk/index.mdx b/docs/sdk/index.mdx deleted file mode 100644 index 13e1d0bc..00000000 --- a/docs/sdk/index.mdx +++ /dev/null @@ -1,55 +0,0 @@ -
-

- Explore the SDK -

-

- Cosmos SDK is the world’s most popular framework for building application-specific blockchains. -

-
- - - - Get an introduction to the Cosmos SDK, its modular architecture, and developer-friendly tools. - - - - Learn how to build a custom blockchain application using the Cosmos SDK. - - - - Dive deeper into the Cosmos SDK and create custom modules to extend functionality. - - - - Learn how to set up, operate, and maintain a full node in the Cosmos network. - - - - Hands-on guides like implementing oracles, vote extensions, and mitigating front-running. - - - - Explore practical guides for key management, transactions, CLI, and running in production. - - diff --git a/docs/sdk/next/learn/advanced/autocli.mdx b/docs/sdk/next/learn/advanced/autocli.mdx new file mode 100644 index 00000000..bbf9bc48 --- /dev/null +++ b/docs/sdk/next/learn/advanced/autocli.mdx @@ -0,0 +1,272 @@ +--- +title: AutoCLI +--- + +**Synopsis** +This document details how to build CLI and REST interfaces for a module. Examples from various Cosmos SDK modules are included. + + + +**Pre-requisite Readings** + +* [CLI](https://docs.cosmos.network/main/core/cli) + + + +The `autocli` (also known as `client/v2`) package is a [Go library](https://pkg.go.dev/cosmossdk.io/client/v2/autocli) for generating CLI (command line interface) interfaces for Cosmos SDK-based applications. It provides a simple way to add CLI commands to your application by generating them automatically based on your gRPC service definitions. Autocli generates CLI commands and flags directly from your protobuf messages, including options, input parameters, and output parameters. This means that you can easily add a CLI interface to your application without having to manually create and manage commands. + +## Overview + +`autocli` generates CLI commands and flags for each method defined in your gRPC service. By default, it generates commands for each gRPC services. The commands are named based on the name of the service method. + +For example, given the following protobuf definition for a service: + +```protobuf +service MyService { + rpc MyMethod(MyRequest) returns (MyResponse) {} +} +``` + +For instance, `autocli` would generate a command named `my-method` for the `MyMethod` method. The command will have flags for each field in the `MyRequest` message. + +It is possible to customize the generation of transactions and queries by defining options for each service. + +## Application Wiring + +Here are the steps to use AutoCLI: + +1. Ensure your app's modules implements the `appmodule.AppModule` interface. +2. (optional) Configure how behave `autocli` command generation, by implementing the `func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions` method on the module. +3. Use the `autocli.AppOptions` struct to specify the modules you defined. If you are using `depinject`, it can automatically create an instance of `autocli.AppOptions` based on your app's configuration. +4. Use the `EnhanceRootCommand()` method provided by `autocli` to add the CLI commands for the specified modules to your root command. + + +AutoCLI is additive only, meaning *enhancing* the root command will only add subcommands that are not already registered. This means that you can use AutoCLI alongside other custom commands within your app. + + +Here's an example of how to use `autocli` in your app: + +```go expandable +// Define your app's modules + testModules := map[string]appmodule.AppModule{ + "testModule": &TestModule{ +}, +} + +// Define the autocli AppOptions + autoCliOpts := autocli.AppOptions{ + Modules: testModules, +} + +// Create the root command + rootCmd := &cobra.Command{ + Use: "app", +} + if err := appOptions.EnhanceRootCommand(rootCmd); err != nil { + return err +} + +// Run the root command + if err := rootCmd.Execute(); err != nil { + return err +} +``` + +### Keyring + +`autocli` uses a keyring for key name resolving names and signing transactions. + + +AutoCLI provides a better UX than normal CLI as it allows to resolve key names directly from the keyring in all transactions and commands. + +```sh + q bank balances alice + tx bank send alice bob 1000denom +``` + + + +The keyring used for resolving names and signing transactions is provided via the `client.Context`. +The keyring is then converted to the `client/v2/autocli/keyring` interface. +If no keyring is provided, the `autocli` generated command will not be able to sign transactions, but will still be able to query the chain. + + +The Cosmos SDK keyring implements the `client/v2/autocli/keyring` interface, thanks to the following wrapper: + +```go +keyring.NewAutoCLIKeyring(kb) +``` + + + +## Signing + +`autocli` supports signing transactions with the keyring. +The [`cosmos.msg.v1.signer` protobuf annotation](https://docs.cosmos.network/main/build/building-modules/protobuf-annotations) defines the signer field of the message. +This field is automatically filled when using the `--from` flag or defining the signer as a positional argument. + + +AutoCLI currently supports only one signer per transaction. + + +## Module wiring & Customization + +The `AutoCLIOptions()` method on your module allows to specify custom commands, sub-commands or flags for each service, as it was a `cobra.Command` instance, within the `RpcCommandOptions` struct. Defining such options will customize the behavior of the `autocli` command generation, which by default generates a command for each method in your gRPC service. + +```go +*autocliv1.RpcCommandOptions{ + RpcMethod: "Params", // The name of the gRPC service + Use: "params", // Command usage that is displayed in the help + Short: "Query the parameters of the governance process", // Short description of the command + Long: "Query the parameters of the governance process. Specify specific param types (voting|tallying|deposit) + +to filter results.", // Long description of the command + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + { + ProtoField: "params_type", + Optional: true +}, // Transform a flag into a positional argument +}, +} +``` + + +AutoCLI can create a gov proposal of any tx by simply setting the `GovProposal` field to `true` in the `autocli.RpcCommandOptions` struct. +Users can however use the `--no-proposal` flag to disable the proposal creation (which is useful if the authority isn't the gov module on a chain). + + +### Specifying Subcommands + +By default, `autocli` generates a command for each method in your gRPC service. However, you can specify subcommands to group related commands together. To specify subcommands, use the `autocliv1.ServiceCommandDescriptor` struct. + +This example shows how to use the `autocliv1.ServiceCommandDescriptor` struct to group related commands together and specify subcommands in your gRPC service by defining an instance of `autocliv1.ModuleOptions` in your `autocli.go`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/x/gov/autocli.go#L94-L97 +``` + +### Positional Arguments + +By default `autocli` generates a flag for each field in your protobuf message. However, you can choose to use positional arguments instead of flags for certain fields. + +To add positional arguments to a command, use the `autocliv1.PositionalArgDescriptor` struct, as seen in the example below. Specify the `ProtoField` parameter, which is the name of the protobuf field that should be used as the positional argument. In addition, if the parameter is a variable-length argument, you can specify the `Varargs` parameter as `true`. This can only be applied to the last positional parameter, and the `ProtoField` must be a repeated field. + +Here's an example of how to define a positional argument for the `Account` method of the `auth` service: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/x/auth/autocli.go#L25-L30 +``` + +Then the command can be used as follows, instead of having to specify the `--address` flag: + +```bash + query auth account cosmos1abcd...xyz +``` + +#### Flattened Fields in Positional Arguments + +AutoCLI also supports flattening nested message fields as positional arguments. This means you can access nested fields +using dot notation in the `ProtoField` parameter. This is particularly useful when you want to directly set nested +message fields as positional arguments. + +For example, if you have a nested message structure like this: + +```protobuf +message Permissions { + string level = 1; + repeated string limit_type_urls = 2; +} + +message MsgAuthorizeCircuitBreaker { + string grantee = 1; + Permissions permissions = 2; +} +``` + +You can flatten the fields in your AutoCLI configuration: + +```go +{ + RpcMethod: "AuthorizeCircuitBreaker", + Use: "authorize ", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + { + ProtoField: "grantee" +}, + { + ProtoField: "permissions.level" +}, + { + ProtoField: "permissions.limit_type_urls" +}, +}, +} +``` + +This allows users to provide values for nested fields directly as positional arguments: + +```bash + tx circuit authorize cosmos1... super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend" +``` + +Instead of having to provide a complex JSON structure for nested fields, flattening makes the CLI more user-friendly by allowing direct access to nested fields. + +#### Customising Flag Names + +By default, `autocli` generates flag names based on the names of the fields in your protobuf message. However, you can customise the flag names by providing a `FlagOptions`. This parameter allows you to specify custom names for flags based on the names of the message fields. + +For example, if you have a message with the fields `test` and `test1`, you can use the following naming options to customise the flags: + +```go +autocliv1.RpcCommandOptions{ + FlagOptions: map[string]*autocliv1.FlagOptions{ + "test": { + Name: "custom_name", +}, + "test1": { + Name: "other_name", +}, +}, +} +``` + +`FlagsOptions` is defined like sub commands in the `AutoCLIOptions()` method on your module. + +### Combining AutoCLI with Other Commands Within A Module + +AutoCLI can be used alongside other commands within a module. For example, the `gov` module uses AutoCLI to generate commands for the `query` subcommand, but also defines custom commands for the `proposer` subcommands. + +In order to enable this behavior, set in `AutoCLIOptions()` the `EnhanceCustomCommand` field to `true`, for the command type (queries and/or transactions) you want to enhance. + +```go +https://github.com/cosmos/cosmos-sdk/blob/fa4d87ef7e6d87aaccc94c337ffd2fe90fcb7a9d/x/gov/autocli.go#L98 +``` + +If not set to true, `AutoCLI` will not generate commands for the module if there are already commands registered for the module (when `GetTxCmd()` or `GetTxCmd()` are defined). + +### Skip a command + +AutoCLI automatically skips unsupported commands when [`cosmos_proto.method_added_in` protobuf annotation](https://docs.cosmos.network/main/build/building-modules/protobuf-annotations) is present. + +Additionally, a command can be manually skipped using the `autocliv1.RpcCommandOptions`: + +```go +*autocliv1.RpcCommandOptions{ + RpcMethod: "Params", // The name of the gRPC service + Skip: true, +} +``` + +### Use AutoCLI for non module commands + +It is possible to use `AutoCLI` for non module commands. The trick is still to implement the `appmodule.Module` interface and append it to the `appOptions.ModuleOptions` map. + +For example, here is how the SDK does it for `cometbft` gRPC commands: + +```go +https://github.com/cosmos/cosmos-sdk/blob/client/v2.0.0-beta.1/client/grpc/cmtservice/autocli.go#L52-L71 +``` + +## Summary + +`autocli` lets you generate CLI for your Cosmos SDK-based applications without any cobra boilerplate. It allows you to easily generate CLI commands and flags from your protobuf messages, and provides many options for customising the behavior of your CLI application. diff --git a/docs/sdk/next/learn/advanced/baseapp.mdx b/docs/sdk/next/learn/advanced/baseapp.mdx new file mode 100644 index 00000000..c150c3b5 --- /dev/null +++ b/docs/sdk/next/learn/advanced/baseapp.mdx @@ -0,0 +1,543 @@ +--- +title: BaseApp +--- + +**Synopsis** +This document describes `BaseApp`, the abstraction that implements the core functionalities of a Cosmos SDK application. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK application](/beginner/00-app-anatomy.md) +* [Lifecycle of a Cosmos SDK transaction](/beginner/01-tx-lifecycle.md) + + + +## Introduction + +`BaseApp` is a base type that implements the core of a Cosmos SDK application, namely: + +* The [Application Blockchain Interface](#main-abci-messages), for the state-machine to communicate with the underlying consensus engine (e.g. CometBFT). +* [Service Routers](#service-routers), to route messages and queries to the appropriate module. +* Different [states](#state-updates), as the state-machine can have different volatile states updated based on the ABCI message received. + +The goal of `BaseApp` is to provide the fundamental layer of a Cosmos SDK application +that developers can easily extend to build their own custom application. Usually, +developers will create a custom type for their application, like so: + +```go +type App struct { + // reference to a BaseApp + *baseapp.BaseApp + + // list of application store keys + + // list of application keepers + + // module manager +} +``` + +Extending the application with `BaseApp` gives the former access to all of `BaseApp`'s methods. +This allows developers to compose their custom application with the modules they want, while not +having to concern themselves with the hard work of implementing the ABCI, the service routers and state +management logic. + +## Type Definition + +The `BaseApp` type holds many important parameters for any Cosmos SDK based application. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L64-L201 +``` + +Let us go through the most important components. + +> **Note**: Not all parameters are described, only the most important ones. Refer to the +> type definition for the full list. + +First, the important parameters that are initialized during the bootstrapping of the application: + +* [`CommitMultiStore`](04-store.md#commitmultistore): This is the main store of the application, + which holds the canonical state that is committed at the [end of each block](#commit). This store + is **not** cached, meaning it is not used to update the application's volatile (un-committed) states. + The `CommitMultiStore` is a multi-store, meaning a store of stores. Each module of the application + uses one or multiple `KVStores` in the multi-store to persist their subset of the state. +* Database: The `db` is used by the `CommitMultiStore` to handle data persistence. +* [`Msg` Service Router](#msg-service-router): The `msgServiceRouter` facilitates the routing of `sdk.Msg` requests to the appropriate + module `Msg` service for processing. Here a `sdk.Msg` refers to the transaction component that needs to be + processed by a service in order to update the application state, and not to ABCI message which implements + the interface between the application and the underlying consensus engine. +* [gRPC Query Router](#grpc-query-router): The `grpcQueryRouter` facilitates the routing of gRPC queries to the + appropriate module for it to be processed. These queries are not ABCI messages themselves, but they + are relayed to the relevant module's gRPC `Query` service. +* [`TxDecoder`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/types#TxDecoder): It is used to decode + raw transaction bytes relayed by the underlying CometBFT engine. +* [`AnteHandler`](#antehandler): This handler is used to handle signature verification, fee payment, + and other pre-message execution checks when a transaction is received. It's executed during + [`CheckTx/RecheckTx`](#checktx) and [`FinalizeBlock`](#finalizeblock). +* [`InitChainer`](/beginner/00-app-anatomy.md#initchainer), [`PreBlocker`](/beginner/00-app-anatomy.md#preblocker), [`BeginBlocker` and `EndBlocker`](/beginner/00-app-anatomy.md#beginblocker-and-endblocker): These are + the functions executed when the application receives the `InitChain` and `FinalizeBlock` + ABCI messages from the underlying CometBFT engine. + +Then, parameters used to define [volatile states](#state-updates) (i.e. cached states): + +* `checkState`: This state is updated during [`CheckTx`](#checktx), and reset on [`Commit`](#commit). +* `finalizeBlockState`: This state is updated during [`FinalizeBlock`](#finalizeblock), and set to `nil` on + [`Commit`](#commit) and gets re-initialized on `FinalizeBlock`. +* `processProposalState`: This state is updated during [`ProcessProposal`](#process-proposal). +* `prepareProposalState`: This state is updated during [`PrepareProposal`](#prepare-proposal). + +Finally, a few more important parameters: + +* `voteInfos`: This parameter carries the list of validators whose precommit is missing, either + because they did not vote or because the proposer did not include their vote. This information is + carried by the [Context](02-context.md) and can be used by the application for various things like + punishing absent validators. +* `minGasPrices`: This parameter defines the minimum gas prices accepted by the node. This is a + **local** parameter, meaning each full-node can set a different `minGasPrices`. It is used in the + `AnteHandler` during [`CheckTx`](#checktx), mainly as a spam protection mechanism. The transaction + enters the [mempool](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#mempool-methods) + only if the gas prices of the transaction are greater than one of the minimum gas price in + `minGasPrices` (e.g. if `minGasPrices == 1uatom,1photon`, the `gas-price` of the transaction must be + greater than `1uatom` OR `1photon`). +* `appVersion`: Version of the application. It is set in the + [application's constructor function](/beginner/00-app-anatomy.md#constructor-function). + +## Constructor + +```go +func NewBaseApp( + name string, logger log.Logger, db dbm.DB, txDecoder sdk.TxDecoder, options ...func(*BaseApp), +) *BaseApp { + + // ... +} +``` + +The `BaseApp` constructor function is pretty straightforward. The only thing worth noting is the +possibility to provide additional [`options`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/options.go) +to the `BaseApp`, which will execute them in order. The `options` are generally `setter` functions +for important parameters, like `SetPruning()` to set pruning options or `SetMinGasPrices()` to set +the node's `min-gas-prices`. + +Naturally, developers can add additional `options` based on their application's needs. + +## State Updates + +The `BaseApp` maintains four primary volatile states and a root or main state. The main state +is the canonical state of the application and the volatile states, `checkState`, `prepareProposalState`, `processProposalState` and `finalizeBlockState` +are used to handle state transitions in-between the main state made during [`Commit`](#commit). + +Internally, there is only a single `CommitMultiStore` which we refer to as the main or root state. +From this root state, we derive four volatile states by using a mechanism called *store branching* (performed by `CacheWrap` function). +The types can be illustrated as follows: + +![Types](baseapp_state.png) + +### InitChain State Updates + +During `InitChain`, the four volatile states, `checkState`, `prepareProposalState`, `processProposalState` +and `finalizeBlockState` are set by branching the root `CommitMultiStore`. Any subsequent reads and writes happen +on branched versions of the `CommitMultiStore`. +To avoid unnecessary roundtrip to the main state, all reads to the branched store are cached. + +![InitChain](baseapp_state-initchain.png) + +### CheckTx State Updates + +During `CheckTx`, the `checkState`, which is based off of the last committed state from the root +store, is used for any reads and writes. Here we only execute the `AnteHandler` and verify a service router +exists for every message in the transaction. Note, when we execute the `AnteHandler`, we branch +the already branched `checkState`. +This has the side effect that if the `AnteHandler` fails, the state transitions won't be reflected in the `checkState` +\-- i.e. `checkState` is only updated on success. + +![CheckTx](baseapp_state-checktx.png) + +### PrepareProposal State Updates + +During `PrepareProposal`, the `prepareProposalState` is set by branching the root `CommitMultiStore`. +The `prepareProposalState` is used for any reads and writes that occur during the `PrepareProposal` phase. +The function uses the `Select()` method of the mempool to iterate over the transactions. `runTx` is then called, +which encodes and validates each transaction and from there the `AnteHandler` is executed. +If successful, valid transactions are returned inclusive of the events, tags, and data generated +during the execution of the proposal. +The described behavior is that of the default handler, applications have the flexibility to define their own +[custom mempool handlers](https://docs.cosmos.network/main/build/building-apps/app-mempool). + +![ProcessProposal](baseapp_state-prepareproposal.png) + +### ProcessProposal State Updates + +During `ProcessProposal`, the `processProposalState` is set based off of the last committed state +from the root store and is used to process a signed proposal received from a validator. +In this state, `runTx` is called and the `AnteHandler` is executed and the context used in this state is built with information +from the header and the main state, including the minimum gas prices, which are also set. +Again we want to highlight that the described behavior is that of the default handler and applications have the flexibility to define their own +[custom mempool handlers](https://docs.cosmos.network/main/build/building-apps/app-mempool). + +![ProcessProposal](baseapp_state-processproposal.png) + +### FinalizeBlock State Updates + +During `FinalizeBlock`, the `finalizeBlockState` is set for use during transaction execution and endblock. The +`finalizeBlockState` is based off of the last committed state from the root store and is branched. +Note, the `finalizeBlockState` is set to `nil` on [`Commit`](#commit). + +The state flow for transaction execution is nearly identical to `CheckTx` except state transitions occur on +the `finalizeBlockState` and messages in a transaction are executed. Similarly to `CheckTx`, state transitions +occur on a doubly branched state -- `finalizeBlockState`. Successful message execution results in +writes being committed to `finalizeBlockState`. Note, if message execution fails, state transitions from +the AnteHandler are persisted. + +### Commit State Updates + +During `Commit` all the state transitions that occurred in the `finalizeBlockState` are finally written to +the root `CommitMultiStore` which in turn is committed to disk and results in a new application +root hash. These state transitions are now considered final. Finally, the `checkState` is set to the +newly committed state and `finalizeBlockState` is set to `nil` to be reset on `FinalizeBlock`. + +![Commit](baseapp_state-commit.png) + +## ParamStore + +During `InitChain`, the `RequestInitChain` provides `ConsensusParams` which contains parameters +related to block execution such as maximum gas and size in addition to evidence parameters. If these +parameters are non-nil, they are set in the BaseApp's `ParamStore`. Behind the scenes, the `ParamStore` +is managed by an `x/consensus_params` module. This allows the parameters to be tweaked via +on-chain governance. + +## Service Routers + +When messages and queries are received by the application, they must be routed to the appropriate module in order to be processed. Routing is done via `BaseApp`, which holds a `msgServiceRouter` for messages, and a `grpcQueryRouter` for queries. + +### `Msg` Service Router + +[`sdk.Msg`s](/../build/building-modules/02-messages-and-queries.md#messages) need to be routed after they are extracted from transactions, which are sent from the underlying CometBFT engine via the [`CheckTx`](#checktx) and [`FinalizeBlock`](#finalizeblock) ABCI messages. To do so, `BaseApp` holds a `msgServiceRouter` which maps fully-qualified service methods (`string`, defined in each module's Protobuf `Msg` service) to the appropriate module's `MsgServer` implementation. + +The [default `msgServiceRouter` included in `BaseApp`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/msg_service_router.go) is stateless. However, some applications may want to make use of more stateful routing mechanisms such as allowing governance to disable certain routes or point them to new modules for upgrade purposes. For this reason, the `sdk.Context` is also passed into each [route handler inside `msgServiceRouter`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/msg_service_router.go#L35-L36). For a stateless router that doesn't want to make use of this, you can just ignore the `ctx`. + +The application's `msgServiceRouter` is initialized with all the routes using the application's [module manager](/../build/building-modules/01-module-manager.md#manager) (via the `RegisterServices` method), which itself is initialized with all the application's modules in the application's [constructor](/beginner/00-app-anatomy.md#constructor-function). + +### gRPC Query Router + +Similar to `sdk.Msg`s, [`queries`](/../build/building-modules/02-messages-and-queries.md#queries) need to be routed to the appropriate module's [`Query` service](/../build/building-modules/04-query-services.md). To do so, `BaseApp` holds a `grpcQueryRouter`, which maps modules' fully-qualified service methods (`string`, defined in their Protobuf `Query` gRPC) to their `QueryServer` implementation. The `grpcQueryRouter` is called during the initial stages of query processing, which can be either by directly sending a gRPC query to the gRPC endpoint, or via the [`Query` ABCI message](#query) on the CometBFT RPC endpoint. + +Just like the `msgServiceRouter`, the `grpcQueryRouter` is initialized with all the query routes using the application's [module manager](/../build/building-modules/01-module-manager.md) (via the `RegisterServices` method), which itself is initialized with all the application's modules in the application's [constructor](/beginner/00-app-anatomy.md#app-constructor). + +## Main ABCI 2.0 Messages + +The [Application-Blockchain Interface](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md) (ABCI) is a generic interface that connects a state-machine with a consensus engine to form a functional full-node. It can be wrapped in any language, and needs to be implemented by each application-specific blockchain built on top of an ABCI-compatible consensus engine like CometBFT. + +The consensus engine handles two main tasks: + +* The networking logic, which mainly consists in gossiping block parts, transactions and consensus votes. +* The consensus logic, which results in the deterministic ordering of transactions in the form of blocks. + +It is **not** the role of the consensus engine to define the state or the validity of transactions. Generally, transactions are handled by the consensus engine in the form of `[]bytes`, and relayed to the application via the ABCI to be decoded and processed. At keys moments in the networking and consensus processes (e.g. beginning of a block, commit of a block, reception of an unconfirmed transaction, ...), the consensus engine emits ABCI messages for the state-machine to act on. + +Developers building on top of the Cosmos SDK need not implement the ABCI themselves, as `BaseApp` comes with a built-in implementation of the interface. Let us go through the main ABCI messages that `BaseApp` implements: + +* [`Prepare Proposal`](#prepare-proposal) +* [`Process Proposal`](#process-proposal) +* [`CheckTx`](#checktx) +* [`FinalizeBlock`](#finalizeblock) +* [`ExtendVote`](#extendvote) +* [`VerifyVoteExtension`](#verifyvoteextension) + +### Prepare Proposal + +The `PrepareProposal` function is part of the new methods introduced in Application Blockchain Interface (ABCI++) in CometBFT and is an important part of the application's overall governance system. In the Cosmos SDK, it allows the application to have more fine-grained control over the transactions that are processed, and ensures that only valid transactions are committed to the blockchain. + +Here is how the `PrepareProposal` function can be implemented: + +1. Extract the `sdk.Msg`s from the transaction. +2. Perform *stateful* checks by calling `Validate()` on each of the `sdk.Msg`'s. This is done after *stateless* checks as *stateful* checks are more computationally expensive. If `Validate()` fails, `PrepareProposal` returns before running further checks, which saves resources. +3. Perform any additional checks that are specific to the application, such as checking account balances, or ensuring that certain conditions are met before a transaction is proposed.hey are processed by the consensus engine, if necessary. +4. Return the updated transactions to be processed by the consensus engine + +Note that, unlike `CheckTx()`, `PrepareProposal` process `sdk.Msg`s, so it can directly update the state. However, unlike `FinalizeBlock()`, it does not commit the state updates. It's important to exercise caution when using `PrepareProposal` as incorrect coding could affect the overall liveness of the network. + +It's important to note that `PrepareProposal` complements the `ProcessProposal` method which is executed after this method. The combination of these two methods means that it is possible to guarantee that no invalid transactions are ever committed. Furthermore, such a setup can give rise to other interesting use cases such as Oracles, threshold decryption and more. + +`PrepareProposal` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: + +* `Code (uint32)`: Response Code. `0` if successful. +* `Data ([]byte)`: Result bytes, if any. +* `Log (string):` The output of the application's logger. May be non-deterministic. +* `Info (string):` Additional information. May be non-deterministic. + +### Process Proposal + +The `ProcessProposal` function is called by the BaseApp as part of the ABCI message flow, and is executed during the `FinalizeBlock` phase of the consensus process. The purpose of this function is to give more control to the application for block validation, allowing it to check all transactions in a proposed block before the validator sends the prevote for the block. It allows a validator to perform application-dependent work in a proposed block, enabling features such as immediate block execution, and allows the Application to reject invalid blocks. + +The `ProcessProposal` function performs several key tasks, including: + +1. Validating the proposed block by checking all transactions in it. +2. Checking the proposed block against the current state of the application, to ensure that it is valid and that it can be executed. +3. Updating the application's state based on the proposal, if it is valid and passes all checks. +4. Returning a response to CometBFT indicating the result of the proposal processing. + +The `ProcessProposal` is an important part of the application's overall governance system. It is used to manage the network's parameters and other key aspects of its operation. It also ensures that the coherence property is adhered to i.e. all honest validators must accept a proposal by an honest proposer. + +It's important to note that `ProcessProposal` complements the `PrepareProposal` method which enables the application to have more fine-grained transaction control by allowing it to reorder, drop, delay, modify, and even add transactions as they see necessary. The combination of these two methods means that it is possible to guarantee that no invalid transactions are ever committed. Furthermore, such a setup can give rise to other interesting use cases such as Oracles, threshold decryption and more. + +CometBFT calls it when it receives a proposal and the CometBFT algorithm has not locked on a value. The Application cannot modify the proposal at this point but can reject it if it is invalid. If that is the case, CometBFT will prevote `nil` on the proposal, which has strong liveness implications for CometBFT. As a general rule, the Application SHOULD accept a prepared proposal passed via `ProcessProposal`, even if a part of the proposal is invalid (e.g., an invalid transaction); the Application can ignore the invalid part of the prepared proposal at block execution time. + +However, developers must exercise greater caution when using these methods. Incorrectly coding these methods could affect liveness as CometBFT is unable to receive 2/3 valid precommits to finalize a block. + +`ProcessProposal` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: + +* `Code (uint32)`: Response Code. `0` if successful. +* `Data ([]byte)`: Result bytes, if any. +* `Log (string):` The output of the application's logger. May be non-deterministic. +* `Info (string):` Additional information. May be non-deterministic. + +### CheckTx + +`CheckTx` is sent by the underlying consensus engine when a new unconfirmed (i.e. not yet included in a valid block) +transaction is received by a full-node. The role of `CheckTx` is to guard the full-node's mempool +(where unconfirmed transactions are stored until they are included in a block) from spam transactions. +Unconfirmed transactions are relayed to peers only if they pass `CheckTx`. + +`CheckTx()` can perform both *stateful* and *stateless* checks, but developers should strive to +make the checks **lightweight** because gas fees are not charged for the resources (CPU, data load...) used during the `CheckTx`. + +In the Cosmos SDK, after [decoding transactions](05-encoding.md), `CheckTx()` is implemented +to do the following checks: + +1. Extract the `sdk.Msg`s from the transaction. +2. **Optionally** perform *stateless* checks by calling `ValidateBasic()` on each of the `sdk.Msg`s. This is done + first, as *stateless* checks are less computationally expensive than *stateful* checks. If + `ValidateBasic()` fail, `CheckTx` returns before running *stateful* checks, which saves resources. + This check is still performed for messages that have not yet migrated to the new message validation mechanism defined in [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) and still have a `ValidateBasic()` method. +3. Perform non-module related *stateful* checks on the [account](/beginner/03-accounts.md). This step is mainly about checking + that the `sdk.Msg` signatures are valid, that enough fees are provided and that the sending account + has enough funds to pay for said fees. Note that no precise [`gas`](/beginner/04-gas-fees.md) counting occurs here, + as `sdk.Msg`s are not processed. Usually, the [`AnteHandler`](/beginner/04-gas-fees.md#antehandler) will check that the `gas` provided + with the transaction is superior to a minimum reference gas amount based on the raw transaction size, + in order to avoid spam with transactions that provide 0 gas. + +`CheckTx` does **not** process `sdk.Msg`s - they only need to be processed when the canonical state needs to be updated, which happens during `FinalizeBlock`. + +Steps 2. and 3. are performed by the [`AnteHandler`](/beginner/04-gas-fees.md#antehandler) in the [`RunTx()`](#runtx-antehandler-and-runmsgs) +function, which `CheckTx()` calls with the `runTxModeCheck` mode. During each step of `CheckTx()`, a +special [volatile state](#state-updates) called `checkState` is updated. This state is used to keep +track of the temporary changes triggered by the `CheckTx()` calls of each transaction without modifying +the [main canonical state](#main-state). For example, when a transaction goes through `CheckTx()`, the +transaction's fees are deducted from the sender's account in `checkState`. If a second transaction is +received from the same account before the first is processed, and the account has consumed all its +funds in `checkState` during the first transaction, the second transaction will fail `CheckTx`() and +be rejected. In any case, the sender's account will not actually pay the fees until the transaction +is actually included in a block, because `checkState` never gets committed to the main state. The +`checkState` is reset to the latest state of the main state each time a blocks gets [committed](#commit). + +`CheckTx` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#checktx). +The response contains: + +* `Code (uint32)`: Response Code. `0` if successful. +* `Data ([]byte)`: Result bytes, if any. +* `Log (string):` The output of the application's logger. May be non-deterministic. +* `Info (string):` Additional information. May be non-deterministic. +* `GasWanted (int64)`: Amount of gas requested for transaction. It is provided by users when they generate the transaction. +* `GasUsed (int64)`: Amount of gas consumed by transaction. During `CheckTx`, this value is computed by multiplying the standard cost of a transaction byte by the size of the raw transaction. Next is an example: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/ante/basic.go#L104 +``` + +* `Events ([]cmn.KVPair)`: Key-Value tags for filtering and indexing transactions (eg. by account). See [`event`s](08-events.md) for more. +* `Codespace (string)`: Namespace for the Code. + +#### RecheckTx + +After `Commit`, `CheckTx` is run again on all transactions that remain in the node's local mempool +excluding the transactions that are included in the block. To prevent the mempool from rechecking all transactions +every time a block is committed, the configuration option `mempool.recheck=false` can be set. As of +Tendermint v0.32.1, an additional `Type` parameter is made available to the `CheckTx` function that +indicates whether an incoming transaction is new (`CheckTxType_New`), or a recheck (`CheckTxType_Recheck`). +This allows certain checks like signature verification can be skipped during `CheckTxType_Recheck`. + +## RunTx, AnteHandler, RunMsgs, PostHandler + +### RunTx + +`RunTx` is called from `CheckTx`/`Finalizeblock` to handle the transaction, with `execModeCheck` or `execModeFinalize` as parameter to differentiate between the two modes of execution. Note that when `RunTx` receives a transaction, it has already been decoded. + +The first thing `RunTx` does upon being called is to retrieve the `context`'s `CacheMultiStore` by calling the `getContextForTx()` function with the appropriate mode (either `runTxModeCheck` or `execModeFinalize`). This `CacheMultiStore` is a branch of the main store, with cache functionality (for query requests), instantiated during `FinalizeBlock` for transaction execution and during the `Commit` of the previous block for `CheckTx`. After that, two `defer func()` are called for [`gas`](/beginner/04-gas-fees.md) management. They are executed when `runTx` returns and make sure `gas` is actually consumed, and will throw errors, if any. + +After that, `RunTx()` calls `ValidateBasic()`, when available and for backward compatibility, on each `sdk.Msg`in the `Tx`, which runs preliminary *stateless* validity checks. If any `sdk.Msg` fails to pass `ValidateBasic()`, `RunTx()` returns with an error. + +Then, the [`anteHandler`](#antehandler) of the application is run (if it exists). In preparation of this step, both the `checkState`/`finalizeBlockState`'s `context` and `context`'s `CacheMultiStore` are branched using the `cacheTxContext()` function. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L706-L722 +``` + +This allows `RunTx` not to commit the changes made to the state during the execution of `anteHandler` if it ends up failing. It also prevents the module implementing the `anteHandler` from writing to state, which is an important part of the [object-capabilities](10-ocap.md) of the Cosmos SDK. + +Finally, the [`RunMsgs()`](#runmsgs) function is called to process the `sdk.Msg`s in the `Tx`. In preparation of this step, just like with the `anteHandler`, both the `checkState`/`finalizeBlockState`'s `context` and `context`'s `CacheMultiStore` are branched using the `cacheTxContext()` function. + +### AnteHandler + +The `AnteHandler` is a special handler that implements the `AnteHandler` interface and is used to authenticate the transaction before the transaction's internal messages are processed. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/handler.go#L3-L5 +``` + +The `AnteHandler` is theoretically optional, but still a very important component of public blockchain networks. It serves 3 primary purposes: + +* Be a primary line of defense against spam and second line of defense (the first one being the mempool) against transaction replay with fees deduction and [`sequence`](01-transactions.md#transaction-generation) checking. +* Perform preliminary *stateful* validity checks like ensuring signatures are valid or that the sender has enough funds to pay for fees. +* Play a role in the incentivization of stakeholders via the collection of transaction fees. + +`BaseApp` holds an `anteHandler` as parameter that is initialized in the [application's constructor](/beginner/00-app-anatomy.md#application-constructor). The most widely used `anteHandler` is the [`auth` module](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/ante/ante.go). + +Click [here](/beginner/04-gas-fees.md#antehandler) for more on the `anteHandler`. + +### RunMsgs + +`RunMsgs` is called from `RunTx` with `runTxModeCheck` as parameter to check the existence of a route for each message the transaction, and with `execModeFinalize` to actually process the `sdk.Msg`s. + +First, it retrieves the `sdk.Msg`'s fully-qualified type name, by checking the `type_url` of the Protobuf `Any` representing the `sdk.Msg`. Then, using the application's [`msgServiceRouter`](#msg-service-router), it checks for the existence of `Msg` service method related to that `type_url`. At this point, if `mode == runTxModeCheck`, `RunMsgs` returns. Otherwise, if `mode == execModeFinalize`, the [`Msg` service](/../build/building-modules/03-msg-services.md) RPC is executed, before `RunMsgs` returns. + +### PostHandler + +`PostHandler` is similar to `AnteHandler`, but it, as the name suggests, executes custom post tx processing logic after [`RunMsgs`](#runmsgs) is called. `PostHandler` receives the `Result` of the `RunMsgs` in order to enable this customizable behavior. + +Like `AnteHandler`s, `PostHandler`s are theoretically optional. + +Other use cases like unused gas refund can also be enabled by `PostHandler`s. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/posthandler/post.go#L1-L15 +``` + +Note, when `PostHandler`s fail, the state from `runMsgs` is also reverted, effectively making the transaction fail. + +## Other ABCI Messages + +### InitChain + +The [`InitChain` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#method-overview) is sent from the underlying CometBFT engine when the chain is first started. It is mainly used to **initialize** parameters and state like: + +* [Consensus Parameters](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_app_requirements.md#consensus-parameters) via `setConsensusParams`. +* [`checkState` and `finalizeBlockState`](#state-updates) via `setState`. +* The [block gas meter](/beginner/04-gas-fees.md#block-gas-meter), with infinite gas to process genesis transactions. + +Finally, the `InitChain(req abci.InitChainRequest)` method of `BaseApp` calls the [`initChainer()`](/beginner/00-app-anatomy.md#initchainer) of the application in order to initialize the main state of the application from the `genesis file` and, if defined, call the [`InitGenesis`](/../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. + +### FinalizeBlock + +The [`FinalizeBlock` ABCI message](https://github.com/cometbft/cometbft/blob/v0.38.x/spec/abci/abci++_basic_concepts.md#method-overview) is sent from the underlying CometBFT engine when a block proposal created by the correct proposer is received. The previous `BeginBlock, DeliverTx and Endblock` calls are private methods on the BaseApp struct. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci.go#L869 +``` + +#### PreBlock + +* Run the application's [`preBlocker()`](/beginner/00-app-anatomy.md#preblocker), which mainly runs the [`PreBlocker()`](/../build/building-modules/17-preblock.md#preblock) method of each of the modules. + +#### BeginBlock + +* Initialize [`finalizeBlockState`](#state-updates) with the latest header using the `req abci.FinalizeBlockRequest` passed as parameter via the `setState` function. + + ```go + https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L746-L770 + ``` + + This function also resets the [main gas meter](/beginner/04-gas-fees.md#main-gas-meter). + +* Initialize the [block gas meter](/beginner/04-gas-fees.md#block-gas-meter) with the `maxGas` limit. The `gas` consumed within the block cannot go above `maxGas`. This parameter is defined in the application's consensus parameters. + +* Run the application's [`beginBlocker()`](/beginner/00-app-anatomy.md#beginblocker-and-endblocker), which mainly runs the [`BeginBlocker()`](/../build/building-modules/06-beginblock-endblock.md#beginblock) method of each of the modules. + +* Set the [`VoteInfos`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#voteinfo) of the application, i.e. the list of validators whose *precommit* for the previous block was included by the proposer of the current block. This information is carried into the [`Context`](02-context.md) so that it can be used during transaction execution and EndBlock. + +#### Transaction Execution + +When the underlying consensus engine receives a block proposal, each transaction in the block needs to be processed by the application. To that end, the underlying consensus engine sends the transactions in FinalizeBlock message to the application for each transaction in a sequential order. + +Before the first transaction of a given block is processed, a [volatile state](#state-updates) called `finalizeBlockState` is initialized during FinalizeBlock. This state is updated each time a transaction is processed via `FinalizeBlock`, and committed to the [main state](#main-state) when the block is [committed](#commit), after what it is set to `nil`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L772-L807 +``` + +Transaction execution within `FinalizeBlock` performs the **exact same steps as `CheckTx`**, with a little caveat at step 3 and the addition of a fifth step: + +1. The `AnteHandler` does **not** check that the transaction's `gas-prices` is sufficient. That is because the `min-gas-prices` value `gas-prices` is checked against is local to the node, and therefore what is enough for one full-node might not be for another. This means that the proposer can potentially include transactions for free, although they are not incentivized to do so, as they earn a bonus on the total fee of the block they propose. +2. For each `sdk.Msg` in the transaction, route to the appropriate module's Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md). Additional *stateful* checks are performed, and the branched multistore held in `finalizeBlockState`'s `context` is updated by the module's `keeper`. If the `Msg` service returns successfully, the branched multistore held in `context` is written to `finalizeBlockState` `CacheMultiStore`. + +During the additional fifth step outlined in (2), each read/write to the store increases the value of `GasConsumed`. You can find the default cost of each operation: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/gas.go#L230-L241 +``` + +At any point, if `GasConsumed > GasWanted`, the function returns with `Code != 0` and the execution fails. + +Each transactions returns a response to the underlying consensus engine of type [`abci.ExecTxResult`](https://github.com/cometbft/cometbft/blob/v0.38.0-rc1/spec/abci/abci%2B%2B_methods.md#exectxresult). The response contains: + +* `Code (uint32)`: Response Code. `0` if successful. +* `Data ([]byte)`: Result bytes, if any. +* `Log (string):` The output of the application's logger. May be non-deterministic. +* `Info (string):` Additional information. May be non-deterministic. +* `GasWanted (int64)`: Amount of gas requested for transaction. It is provided by users when they generate the transaction. +* `GasUsed (int64)`: Amount of gas consumed by transaction. During transaction execution, this value is computed by multiplying the standard cost of a transaction byte by the size of the raw transaction, and by adding gas each time a read/write to the store occurs. +* `Events ([]cmn.KVPair)`: Key-Value tags for filtering and indexing transactions (eg. by account). See [`event`s](08-events.md) for more. +* `Codespace (string)`: Namespace for the Code. + +#### EndBlock + +EndBlock is run after transaction execution completes. It allows developers to have logic be executed at the end of each block. In the Cosmos SDK, the bulk EndBlock() method is to run the application's EndBlocker(), which mainly runs the EndBlocker() method of each of the application's modules. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L811-L833 +``` + +### Commit + +The [`Commit` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#method-overview) is sent from the underlying CometBFT engine after the full-node has received *precommits* from 2/3+ of validators (weighted by voting power). On the `BaseApp` end, the `Commit(res abci.CommitResponse)` function is implemented to commit all the valid state transitions that occurred during `FinalizeBlock` and to reset state for the next block. + +To commit state-transitions, the `Commit` function calls the `Write()` function on `finalizeBlockState.ms`, where `finalizeBlockState.ms` is a branched multistore of the main store `app.cms`. Then, the `Commit` function sets `checkState` to the latest header (obtained from `finalizeBlockState.ctx.BlockHeader`) and `finalizeBlockState` to `nil`. + +Finally, `Commit` returns the hash of the commitment of `app.cms` back to the underlying consensus engine. This hash is used as a reference in the header of the next block. + +### Info + +The [`Info` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#info-methods) is a simple query from the underlying consensus engine, notably used to sync the latter with the application during a handshake that happens on startup. When called, the `Info(res abci.InfoResponse)` function from `BaseApp` will return the application's name, version and the hash of the last commit of `app.cms`. + +### Query + +The [`Query` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#info-methods) is used to serve queries received from the underlying consensus engine, including queries received via RPC like CometBFT RPC. It used to be the main entrypoint to build interfaces with the application, but with the introduction of [gRPC queries](/../build/building-modules/04-query-services.md) in Cosmos SDK v0.40, its usage is more limited. The application must respect a few rules when implementing the `Query` method, which are outlined [here](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_app_requirements.md#query). + +Each CometBFT `query` comes with a `path`, which is a `string` which denotes what to query. If the `path` matches a gRPC fully-qualified service method, then `BaseApp` will defer the query to the `grpcQueryRouter` and let it handle it like explained [above](#grpc-query-router). Otherwise, the `path` represents a query that is not (yet) handled by the gRPC router. `BaseApp` splits the `path` string with the `/` delimiter. By convention, the first element of the split string (`split[0]`) contains the category of `query` (`app`, `p2p`, `store` or `custom` ). The `BaseApp` implementation of the `Query(req abci.QueryRequest)` method is a simple dispatcher serving these 4 main categories of queries: + +* Application-related queries like querying the application's version, which are served via the `handleQueryApp` method. +* Direct queries to the multistore, which are served by the `handlerQueryStore` method. These direct queries are different from custom queries which go through `app.queryRouter`, and are mainly used by third-party service provider like block explorers. +* P2P queries, which are served via the `handleQueryP2P` method. These queries return either `app.addrPeerFilter` or `app.ipPeerFilter` that contain the list of peers filtered by address or IP respectively. These lists are first initialized via `options` in `BaseApp`'s [constructor](#constructor). + +### ExtendVote + +`ExtendVote` allows an application to extend a pre-commit vote with arbitrary data. This process does NOT have to be deterministic and the data returned can be unique to the validator process. + +In the Cosmos-SDK this is implemented as a NoOp: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci_utils.go#L444-L450 +``` + +### VerifyVoteExtension + +`VerifyVoteExtension` allows an application to verify that the data returned by `ExtendVote` is valid. This process MUST be deterministic. Moreover, the value of ResponseVerifyVoteExtension.status MUST exclusively depend on the parameters passed in the call to RequestVerifyVoteExtension, and the last committed Application state. + +In the Cosmos-SDK this is implemented as a NoOp: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci_utils.go#L452-L458 +``` diff --git a/docs/sdk/next/learn/advanced/cli.mdx b/docs/sdk/next/learn/advanced/cli.mdx new file mode 100644 index 00000000..fd738077 --- /dev/null +++ b/docs/sdk/next/learn/advanced/cli.mdx @@ -0,0 +1,209 @@ +--- +title: Command-Line Interface +--- + +**Synopsis** +This document describes how command-line interface (CLI) works on a high-level, for an [**application**](/beginner/00-app-anatomy.md). A separate document for implementing a CLI for a Cosmos SDK [**module**](/../build/building-modules/00-intro.md) can be found [here](/../build/building-modules/09-module-interfaces.md#cli). + + +## Command-Line Interface + +### Example Command + +There is no set way to create a CLI, but Cosmos SDK modules typically use the [Cobra Library](https://github.com/spf13/cobra). Building a CLI with Cobra entails defining commands, arguments, and flags. [**Commands**](#root-command) understand the actions users wish to take, such as `tx` for creating a transaction and `query` for querying the application. Each command can also have nested subcommands, necessary for naming the specific transaction type. Users also supply **Arguments**, such as account numbers to send coins to, and [**Flags**](#flags) to modify various aspects of the commands, such as gas prices or which node to broadcast to. + +Here is an example of a command a user might enter to interact with the simapp CLI `simd` in order to send some tokens: + +```bash +simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --gas auto --gas-prices +``` + +The first four strings specify the command: + +* The root command for the entire application `simd`. +* The subcommand `tx`, which contains all commands that let users create transactions. +* The subcommand `bank` to indicate which module to route the command to ([`x/bank`](/../build/modules/bank/README.md) module in this case). +* The type of transaction `send`. + +The next two strings are arguments: the `from_address` the user wishes to send from, the `to_address` of the recipient, and the `amount` they want to send. Finally, the last few strings of the command are optional flags to indicate how much the user is willing to pay in fees (calculated using the amount of gas used to execute the transaction and the gas prices provided by the user). + +The CLI interacts with a [node](03-node.md) to handle this command. The interface itself is defined in a `main.go` file. + +### Building the CLI + +The `main.go` file needs to have a `main()` function that creates a root command, to which all the application commands will be added as subcommands. The root command additionally handles: + +* **setting configurations** by reading in configuration files (e.g. the Cosmos SDK config file). +* **adding any flags** to it, such as `--chain-id`. +* **instantiating the `codec`** by injecting the application codecs. The [`codec`](05-encoding.md) is used to encode and decode data structures for the application - stores can only persist `[]byte`s so the developer must define a serialization format for their data structures or use the default, Protobuf. +* **adding subcommand** for all the possible user interactions, including [transaction commands](#transaction-commands) and [query commands](#query-commands). + +The `main()` function finally creates an executor and [execute](https://pkg.go.dev/github.com/spf13/cobra#Command.Execute) the root command. See an example of `main()` function from the `simapp` application: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/main.go#L14-L24 +``` + +The rest of the document will detail what needs to be implemented for each step and include smaller portions of code from the `simapp` CLI files. + +## Adding Commands to the CLI + +Every application CLI first constructs a root command, then adds functionality by aggregating subcommands (often with further nested subcommands) using `rootCmd.AddCommand()`. The bulk of an application's unique capabilities lies in its transaction and query commands, called `TxCmd` and `QueryCmd` respectively. + +### Root Command + +The root command (called `rootCmd`) is what the user first types into the command line to indicate which application they wish to interact with. The string used to invoke the command (the "Use" field) is typically the name of the application suffixed with `-d`, e.g. `simd` or `gaiad`. The root command typically includes the following commands to support basic functionality in the application. + +* **Status** command from the Cosmos SDK rpc client tools, which prints information about the status of the connected [`Node`](03-node.md). The Status of a node includes `NodeInfo`,`SyncInfo` and `ValidatorInfo`. +* **Keys** [commands](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/keys) from the Cosmos SDK client tools, which includes a collection of subcommands for using the key functions in the Cosmos SDK crypto tools, including adding a new key and saving it to the keyring, listing all public keys stored in the keyring, and deleting a key. For example, users can type `simd keys add ` to add a new key and save an encrypted copy to the keyring, using the flag `--recover` to recover a private key from a seed phrase or the flag `--multisig` to group multiple keys together to create a multisig key. For full details on the `add` key command, see the code [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/keys/add.go). For more details about usage of `--keyring-backend` for storage of key credentials look at the [keyring docs](/../user/run-node/00-keyring.md). +* **Server** commands from the Cosmos SDK server package. These commands are responsible for providing the mechanisms necessary to start an ABCI CometBFT application and provides the CLI framework (based on [cobra](https://github.com/spf13/cobra)) necessary to fully bootstrap an application. The package exposes two core functions: `StartCmd` and `ExportCmd` which creates commands to start the application and export state respectively. + Learn more [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server). +* [**Transaction**](#transaction-commands) commands. +* [**Query**](#query-commands) commands. + +Next is an example `rootCmd` function from the `simapp` application. It instantiates the root command, adds a [*persistent* flag](#flags) and `PreRun` function to be run before every execution, and adds all of the necessary subcommands. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L47-L130 +``` + + +Use the `EnhanceRootCommand()` from the AutoCLI options to automatically add auto-generated commands from the modules to the root command. +Additionally it adds all manually defined modules commands (`tx` and `query`) as well. +Read more about [AutoCLI](https://docs.cosmos.network/main/core/autocli) in its dedicated section. + + +`rootCmd` has a function called `initAppConfig()` which is useful for setting the application's custom configs. +By default app uses CometBFT app config template from Cosmos SDK, which can be over-written via `initAppConfig()`. +Here's an example code to override default `app.toml` template. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L144-L199 +``` + +The `initAppConfig()` also allows overriding the default Cosmos SDK's [server config](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/config/config.go#L231). One example is the `min-gas-prices` config, which defines the minimum gas prices a validator is willing to accept for processing a transaction. By default, the Cosmos SDK sets this parameter to `""` (empty string), which forces all validators to tweak their own `app.toml` and set a non-empty value, or else the node will halt on startup. This might not be the best UX for validators, so the chain developer can set a default `app.toml` value for validators inside this `initAppConfig()` function. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L164-L180 +``` + +The root-level `status` and `keys` subcommands are common across most applications and do not interact with application state. The bulk of an application's functionality - what users can actually *do* with it - is enabled by its `tx` and `query` commands. + +### Transaction Commands + +[Transactions](01-transactions.md) are objects wrapping [`Msg`s](/../build/building-modules/02-messages-and-queries.md#messages) that trigger state changes. To enable the creation of transactions using the CLI interface, a function `txCommand` is generally added to the `rootCmd`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L222-L229 +``` + +This `txCommand` function adds all the transaction available to end-users for the application. This typically includes: + +* **Sign command** from the [`auth`](/../build/modules/auth/README.md) module that signs messages in a transaction. To enable multisig, add the `auth` module's `MultiSign` command. Since every transaction requires some sort of signature in order to be valid, the signing command is necessary for every application. +* **Broadcast command** from the Cosmos SDK client tools, to broadcast transactions. +* **All [module transaction commands](/../build/building-modules/09-module-interfaces.md#transaction-commands)** the application is dependent on, retrieved by using the [basic module manager's](/../build/building-modules/01-module-manager.md#basic-manager) `AddTxCommands()` function, or enhanced by [AutoCLI](https://docs.cosmos.network/main/core/autocli). + +Here is an example of a `txCommand` aggregating these subcommands from the `simapp` application: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L270-L292 +``` + + +When using AutoCLI to generate module transaction commands, `EnhanceRootCommand()` automatically adds the module `tx` command to the root command. +Read more about [AutoCLI](https://docs.cosmos.network/main/core/autocli) in its dedicated section. + + +### Query Commands + +[**Queries**](/../build/building-modules/02-messages-and-queries.md#queries) are objects that allow users to retrieve information about the application's state. To enable the creation of queries using the CLI interface, a function `queryCommand` is generally added to the `rootCmd`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L222-L229 +``` + +This `queryCommand` function adds all the queries available to end-users for the application. This typically includes: + +* **QueryTx** and/or other transaction query commands from the `auth` module which allow the user to search for a transaction by inputting its hash, a list of tags, or a block height. These queries allow users to see if transactions have been included in a block. +* **Account command** from the `auth` module, which displays the state (e.g. account balance) of an account given an address. +* **Validator command** from the Cosmos SDK rpc client tools, which displays the validator set of a given height. +* **Block command** from the Cosmos SDK RPC client tools, which displays the block data for a given height. +* **All [module query commands](/../build/building-modules/09-module-interfaces.md#query-commands)** the application is dependent on, retrieved by using the [basic module manager's](/../build/building-modules/01-module-manager.md#basic-manager) `AddQueryCommands()` function, or enhanced by [AutoCLI](https://docs.cosmos.network/main/core/autocli). + +Here is an example of a `queryCommand` aggregating subcommands from the `simapp` application: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L249-L268 +``` + + +When using AutoCLI to generate module query commands, `EnhanceRootCommand()` automatically adds the module `query` command to the root command. +Read more about [AutoCLI](https://docs.cosmos.network/main/core/autocli) in its dedicated section. + + +## Flags + +Flags are used to modify commands; developers can include them in a `flags.go` file with their CLI. Users can explicitly include them in commands or pre-configure them by inside their [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). Commonly pre-configured flags include the `--node` to connect to and `--chain-id` of the blockchain the user wishes to interact with. + +A *persistent* flag (as opposed to a *local* flag) added to a command transcends all of its children: subcommands will inherit the configured values for these flags. Additionally, all flags have default values when they are added to commands; some toggle an option off but others are empty values that the user needs to override to create valid commands. A flag can be explicitly marked as *required* so that an error is automatically thrown if the user does not provide a value, but it is also acceptable to handle unexpected missing flags differently. + +Flags are added to commands directly (generally in the [module's CLI file](/../build/building-modules/09-module-interfaces.md#flags) where module commands are defined) and no flag except for the `rootCmd` persistent flags has to be added at application level. It is common to add a *persistent* flag for `--chain-id`, the unique identifier of the blockchain the application pertains to, to the root command. Adding this flag can be done in the `main()` function. Adding this flag makes sense as the chain ID should not be changing across commands in this application CLI. + +## Environment variables + +Each flag is bound to its respective named environment variable. The name of the environment variable consist of two parts - capital case `basename` followed by flag name of the flag. `-` must be substituted with `_`. For example flag `--node` for application with basename `GAIA` is bound to `GAIA_NODE`. It allows reducing the amount of flags typed for routine operations. For example instead of: + +```shell +gaia --home=./ --node= --chain-id="testchain-1" --keyring-backend=test tx ... --from= +``` + +this will be more convenient: + +```shell +# define env variables in .env, .envrc etc +GAIA_HOME= +GAIA_NODE= +GAIA_CHAIN_ID="testchain-1" +GAIA_KEYRING_BACKEND="test" + +# and later just use +gaia tx ... --from= +``` + +## Configurations + +It is vital that the root command of an application uses `PersistentPreRun()` cobra command property for executing the command, so all child commands have access to the server and client contexts. These contexts are set as their default values initially and may be modified, scoped to the command, in their respective `PersistentPreRun()` functions. Note that the `client.Context` is typically pre-populated with "default" values that may be useful for all commands to inherit and override if necessary. + +Here is an example of an `PersistentPreRun()` function from `simapp`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L81-L120 +``` + +The `SetCmdClientContextHandler` call reads persistent flags via `ReadPersistentCommandFlags` which creates a `client.Context` and sets that on the root command's `Context`. + +The `InterceptConfigsPreRunHandler` call creates a viper literal, default `server.Context`, and a logger and sets that on the root command's `Context`. The `server.Context` will be modified and saved to disk. The internal `interceptConfigs` call reads or creates a CometBFT configuration based on the home path provided. In addition, `interceptConfigs` also reads and loads the application configuration, `app.toml`, and binds that to the `server.Context` viper literal. This is vital so the application can get access to not only the CLI flags, but also to the application configuration values provided by this file. + + +When willing to configure which logger is used, do not use `InterceptConfigsPreRunHandler`, which sets the default SDK logger, but instead use `InterceptConfigsAndCreateContext` and set the server context and the logger manually: + +```diff expandable +-return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig) + ++serverCtx, err := server.InterceptConfigsAndCreateContext(cmd, customAppTemplate, customAppConfig, customCMTConfig) ++if err != nil { ++ return err ++} + ++// overwrite default server logger ++logger, err := server.CreateSDKLogger(serverCtx, cmd.OutOrStdout()) ++if err != nil { ++ return err ++} ++serverCtx.Logger = logger.With(log.ModuleKey, "server") + ++// set server context ++return server.SetCmdServerContext(cmd, serverCtx) +``` + + diff --git a/docs/sdk/next/learn/advanced/config.mdx b/docs/sdk/next/learn/advanced/config.mdx new file mode 100644 index 00000000..107a6905 --- /dev/null +++ b/docs/sdk/next/learn/advanced/config.mdx @@ -0,0 +1,25 @@ +--- +title: Configuration +description: >- + This documentation refers to the app.toml, if you'd like to read about the + config.toml please visit CometBFT docs. +--- +This documentation refers to the app.toml, if you'd like to read about the config.toml please visit [CometBFT docs](https://docs.cometbft.com/v0.37/). + +{/\* the following is not a python reference, however syntax coloring makes the file more readable in the docs \*/} + +```python +https://github.com/cosmos/cosmos-sdk/blob/main/tools/confix/data/v0.47-app.toml +``` + +## inter-block-cache + +This feature will consume more ram than a normal node, if enabled. + +## iavl-cache-size + +Using this feature will increase ram consumption + +## iavl-lazy-loading + +This feature is to be used for archive nodes, allowing them to have a faster start up time. diff --git a/docs/sdk/next/learn/advanced/context.mdx b/docs/sdk/next/learn/advanced/context.mdx new file mode 100644 index 00000000..d611c829 --- /dev/null +++ b/docs/sdk/next/learn/advanced/context.mdx @@ -0,0 +1,104 @@ +--- +title: Context +--- + +**Synopsis** +The `context` is a data structure intended to be passed from function to function that carries information about the current state of the application. It provides access to a branched storage (a safe branch of the entire state) as well as useful objects and information like `gasMeter`, `block height`, `consensus parameters` and more. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](/beginner/00-app-anatomy.md) +* [Lifecycle of a Transaction](/beginner/01-tx-lifecycle.md) + + + +## Context Definition + +The Cosmos SDK `Context` is a custom data structure that contains Go's stdlib [`context`](https://pkg.go.dev/context) as its base, and has many additional types within its definition that are specific to the Cosmos SDK. The `Context` is integral to transaction processing in that it allows modules to easily access their respective [store](04-store.md#base-layer-kvstores) in the [`multistore`](04-store.md#multistore) and retrieve transactional context such as the block header and gas meter. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/context.go#L40-L67 +``` + +* **Base Context:** The base type is a Go [Context](https://pkg.go.dev/context), which is explained further in the [Go Context Package](#go-context-package) section below. +* **Multistore:** Every application's `BaseApp` contains a [`CommitMultiStore`](04-store.md#multistore) which is provided when a `Context` is created. Calling the `KVStore()` and `TransientStore()` methods allows modules to fetch their respective [`KVStore`](04-store.md#base-layer-kvstores) using their unique `StoreKey`. +* **Header:** The [header](https://docs.cometbft.com/v0.37/spec/core/data_structures#header) is a Blockchain type. It carries important information about the state of the blockchain, such as block height and proposer of the current block. +* **Header Hash:** The current block header hash, obtained during `abci.FinalizeBlock`. +* **Chain ID:** The unique identification number of the blockchain a block pertains to. +* **Transaction Bytes:** The `[]byte` representation of a transaction being processed using the context. Every transaction is processed by various parts of the Cosmos SDK and consensus engine (e.g. CometBFT) throughout its [lifecycle](/beginner/01-tx-lifecycle.md), some of which do not have any understanding of transaction types. Thus, transactions are marshaled into the generic `[]byte` type using some kind of [encoding format](05-encoding.md) such as [Amino](05-encoding.md). +* **Logger:** A `logger` from the CometBFT libraries. Learn more about logs [here](https://docs.cometbft.com/v0.37/core/configuration). Modules call this method to create their own unique module-specific logger. +* **VoteInfo:** A list of the ABCI type [`VoteInfo`](https://docs.cometbft.com/main/spec/abci/abci++_methods.html#voteinfo), which includes the name of a validator and a boolean indicating whether they have signed the block. +* **Gas Meters:** Specifically, a [`gasMeter`](/beginner/04-gas-fees.md#main-gas-meter) for the transaction currently being processed using the context and a [`blockGasMeter`](/beginner/04-gas-fees.md#block-gas-meter) for the entire block it belongs to. Users specify how much in fees they wish to pay for the execution of their transaction; these gas meters keep track of how much [gas](/beginner/04-gas-fees.md) has been used in the transaction or block so far. If the gas meter runs out, execution halts. +* **CheckTx Mode:** A boolean value indicating whether a transaction should be processed in `CheckTx` or `DeliverTx` mode. +* **Min Gas Price:** The minimum [gas](/beginner/04-gas-fees.md) price a node is willing to take in order to include a transaction in its block. This price is a local value configured by each node individually, and should therefore **not be used in any functions used in sequences leading to state-transitions**. +* **Consensus Params:** The ABCI type [Consensus Parameters](https://docs.cometbft.com/v0.37/spec/abci/abci++_app_requirements#consensus-parameters), which specify certain limits for the blockchain, such as maximum gas for a block. +* **Event Manager:** The event manager allows any caller with access to a `Context` to emit [`Events`](08-events.md). Modules may define module specific + `Events` by defining various `Types` and `Attributes` or use the common definitions found in `types/`. Clients can subscribe or query for these `Events`. These `Events` are collected throughout `FinalizeBlock` and are returned to CometBFT for indexing. +* **Priority:** The transaction priority, only relevant in `CheckTx`. +* **KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the `KVStore`. +* **Transient KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the transient `KVStore`. +* **StreamingManager:** The streamingManager field provides access to the streaming manager, which allows modules to subscribe to state changes emitted by the blockchain. The streaming manager is used by the state listening API, which is described in [ADR 038](https://docs.cosmos.network/main/architecture/adr-038-state-listening). +* **CometInfo:** A lightweight field that contains information about the current block, such as the block height, time, and hash. This information can be used for validating evidence, providing historical data, and enhancing the user experience. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/comet/service.go#L14). +* **HeaderInfo:** The `headerInfo` field contains information about the current block header, such as the chain ID, gas limit, and timestamp. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/header/service.go#L14). + +## Go Context Package + +A basic `Context` is defined in the [Golang Context Package](https://pkg.go.dev/context). A `Context` +is an immutable data structure that carries request-scoped data across APIs and processes. Contexts +are also designed to enable concurrency and to be used in goroutines. + +Contexts are intended to be **immutable**; they should never be edited. Instead, the convention is +to create a child context from its parent using a `With` function. For example: + +```go +childCtx = parentCtx.WithBlockHeader(header) +``` + +The [Golang Context Package](https://pkg.go.dev/context) documentation instructs developers to +explicitly pass a context `ctx` as the first argument of a process. + +## Store branching + +The `Context` contains a `MultiStore`, which allows for branching and caching functionality using `CacheMultiStore` +(queries in `CacheMultiStore` are cached to avoid future round trips). +Each `KVStore` is branched in a safe and isolated ephemeral storage. Processes are free to write changes to +the `CacheMultiStore`. If a state-transition sequence is performed without issue, the store branch can +be committed to the underlying store at the end of the sequence or disregard them if something +goes wrong. The pattern of usage for a Context is as follows: + +1. A process receives a Context `ctx` from its parent process, which provides information needed to + perform the process. +2. The `ctx.ms` is a **branched store**, i.e. a branch of the [multistore](04-store.md#multistore) is made so that the process can make changes to the state as it executes, without changing the original `ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution. +3. The process may read and write from `ctx` as it is executing. It may call a subprocess and pass + `ctx` to it as needed. +4. When a subprocess returns, it checks if the result is a success or failure. If a failure, nothing + needs to be done - the branch `ctx` is simply discarded. If successful, the changes made to + the `CacheMultiStore` can be committed to the original `ctx.ms` via `Write()`. + +For example, here is a snippet from the [`runTx`](00-baseapp.md#runtx-antehandler-runmsgs-posthandler) function in [`baseapp`](00-baseapp.md): + +```go +runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes) + +result = app.runMsgs(runMsgCtx, msgs, mode) + +result.GasWanted = gasWanted + if mode != runTxModeDeliver { + return result +} + if result.IsOK() { + msCache.Write() +} +``` + +Here is the process: + +1. Prior to calling `runMsgs` on the message(s) in the transaction, it uses `app.cacheTxContext()` + to branch and cache the context and multistore. +2. `runMsgCtx` - the context with branched store, is used in `runMsgs` to return a result. +3. If the process is running in [`checkTxMode`](00-baseapp.md#checktx), there is no need to write the + changes - the result is returned immediately. +4. If the process is running in [`deliverTxMode`](00-baseapp.md#delivertx) and the result indicates + a successful run over all the messages, the branched multistore is written back to the original. diff --git a/docs/sdk/next/learn/advanced/encoding.mdx b/docs/sdk/next/learn/advanced/encoding.mdx new file mode 100644 index 00000000..86babec8 --- /dev/null +++ b/docs/sdk/next/learn/advanced/encoding.mdx @@ -0,0 +1,291 @@ +--- +title: Encoding +--- + +**Synopsis** +While encoding in the Cosmos SDK used to be mainly handled by `go-amino` codec, the Cosmos SDK is moving towards using `gogoprotobuf` for both state and client-side encoding. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK application](/beginner/00-app-anatomy.md) + + + +## Encoding + +The Cosmos SDK utilizes two binary wire encoding protocols, [Amino](https://github.com/tendermint/go-amino/) which is an object encoding specification and [Protocol Buffers](https://developers.google.com/protocol-buffers), a subset of Proto3 with an extension for +interface support. See the [Proto3 spec](https://developers.google.com/protocol-buffers/docs/sdk/next/proto3) +for more information on Proto3, which Amino is largely compatible with (but not with Proto2). + +Due to Amino having significant performance drawbacks, being reflection-based, and +not having any meaningful cross-language/client support, Protocol Buffers, specifically +[gogoprotobuf](https://github.com/cosmos/gogoproto/), is being used in place of Amino. +Note, this process of using Protocol Buffers over Amino is still an ongoing process. + +Binary wire encoding of types in the Cosmos SDK can be broken down into two main +categories, client encoding and store encoding. Client encoding mainly revolves +around transaction processing and signing, whereas store encoding revolves around +types used in state-machine transitions and what is ultimately stored in the Merkle +tree. + +For store encoding, protobuf definitions can exist for any type and will typically +have an Amino-based "intermediary" type. Specifically, the protobuf-based type +definition is used for serialization and persistence, whereas the Amino-based type +is used for business logic in the state-machine where they may convert back-n-forth. +Note, the Amino-based types may slowly be phased-out in the future, so developers +should take note to use the protobuf message definitions where possible. + +In the `codec` package, there exists two core interfaces, `BinaryCodec` and `JSONCodec`, +where the former encapsulates the current Amino interface except it operates on +types implementing the latter instead of generic `interface{}` types. + +The `ProtoCodec`, where both binary and JSON serialization is handled +via Protobuf. This means that modules may use Protobuf encoding, but the types must +implement `ProtoMarshaler`. If modules wish to avoid implementing this interface +for their types, this is autogenerated via [buf](https://buf.build/) + +If modules use [Collections](/../build/packages/02-collections.md), encoding and decoding are handled, marshal and unmarshal should not be handled manually unless for specific cases identified by the developer. + +### Gogoproto + +Modules are encouraged to utilize Protobuf encoding for their respective types. In the Cosmos SDK, we use the [Gogoproto](https://github.com/cosmos/gogoproto) specific implementation of the Protobuf spec that offers speed and DX improvements compared to the official [Google protobuf implementation](https://github.com/protocolbuffers/protobuf). + +### Guidelines for protobuf message definitions + +In addition to [following official Protocol Buffer guidelines](https://developers.google.com/protocol-buffers/docs/sdk/next/proto3#simple), we recommend using these annotations in .proto files when dealing with interfaces: + +* use `cosmos_proto.accepts_interface` to annotate `Any` fields that accept interfaces + * pass the same fully qualified name as `protoName` to `InterfaceRegistry.RegisterInterface` + * example: `(cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content"` (and not just `Content`) +* annotate interface implementations with `cosmos_proto.implements_interface` + * pass the same fully qualified name as `protoName` to `InterfaceRegistry.RegisterInterface` + * example: `(cosmos_proto.implements_interface) = "cosmos.authz.v1beta1.Authorization"` (and not just `Authorization`) + +Code generators can then match the `accepts_interface` and `implements_interface` annotations to know whether some Protobuf messages are allowed to be packed in a given `Any` field or not. + +### Transaction Encoding + +Another important use of Protobuf is the encoding and decoding of +[transactions](01-transactions.md). Transactions are defined by the application or +the Cosmos SDK but are then passed to the underlying consensus engine to be relayed to +other peers. Since the underlying consensus engine is agnostic to the application, +the consensus engine accepts only transactions in the form of raw bytes. + +* The `TxEncoder` object performs the encoding. +* The `TxDecoder` object performs the decoding. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/tx_msg.go#L109-L113 +``` + +A standard implementation of both these objects can be found in the [`auth/tx` module](/../build/modules/auth/2-tx.md): + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/auth/tx/decoder.go +``` + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/auth/tx/encoder.go +``` + +See [ADR-020](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/docs/sdk/next/architecture/adr-020-protobuf-transaction-encoding.md) for details of how a transaction is encoded. + +### Interface Encoding and Usage of `Any` + +The Protobuf DSL is strongly typed, which can make inserting variable-typed fields difficult. Imagine we want to create a `Profile` protobuf message that serves as a wrapper over [an account](/beginner/03-accounts.md): + +```protobuf +message Profile { + // account is the account associated to a profile. + cosmos.auth.v1beta1.BaseAccount account = 1; + // bio is a short description of the account. + string bio = 4; +} +``` + +In this `Profile` example, we hardcoded `account` as a `BaseAccount`. However, there are several other types of [user accounts related to vesting](/../build/modules/auth/1-vesting.md), such as `BaseVestingAccount` or `ContinuousVestingAccount`. All of these accounts are different, but they all implement the `AccountI` interface. How would you create a `Profile` that allows all these types of accounts with an `account` field that accepts an `AccountI` interface? + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/account.go#L15-L32 +``` + +In [ADR-019](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/docs/sdk/next/architecture/adr-019-protobuf-state-encoding.md), it has been decided to use [`Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto)s to encode interfaces in protobuf. An `Any` contains an arbitrary serialized message as bytes, along with a URL that acts as a globally unique identifier for and resolves to that message's type. This strategy allows us to pack arbitrary Go types inside protobuf messages. Our new `Profile` then looks like: + +```protobuf +message Profile { + // account is the account associated to a profile. + google.protobuf.Any account = 1 [ + (cosmos_proto.accepts_interface) = "cosmos.auth.v1beta1.AccountI"; // Asserts that this field only accepts Go types implementing `AccountI`. It is purely informational for now. + ]; + // bio is a short description of the account. + string bio = 4; +} +``` + +To add an account inside a profile, we need to "pack" it inside an `Any` first, using `codectypes.NewAnyWithValue`: + +```go expandable +var myAccount AccountI +myAccount = ... // Can be a BaseAccount, a ContinuousVestingAccount or any struct implementing `AccountI` + +// Pack the account into an Any +accAny, err := codectypes.NewAnyWithValue(myAccount) + if err != nil { + return nil, err +} + +// Create a new Profile with the any. + profile := Profile { + Account: accAny, + Bio: "some bio", +} + +// We can then marshal the profile as usual. +bz, err := cdc.Marshal(profile) + +jsonBz, err := cdc.MarshalJSON(profile) +``` + +To summarize, to encode an interface, you must 1/ pack the interface into an `Any` and 2/ marshal the `Any`. For convenience, the Cosmos SDK provides a `MarshalInterface` method to bundle these two steps. Have a look at [a real-life example in the x/auth module](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/auth/keeper/keeper.go#L239-L242). + +The reverse operation of retrieving the concrete Go type from inside an `Any`, called "unpacking", is done with the `GetCachedValue()` on `Any`. + +```go expandable +profileBz := ... // The proto-encoded bytes of a Profile, e.g. retrieved through gRPC. +var myProfile Profile +// Unmarshal the bytes into the myProfile struct. + err := cdc.Unmarshal(profilebz, &myProfile) + +// Let's see the types of the Account field. +fmt.Printf("%T\n", myProfile.Account) // Prints "Any" +fmt.Printf("%T\n", myProfile.Account.GetCachedValue()) // Prints "BaseAccount", "ContinuousVestingAccount" or whatever was initially packed in the Any. + +// Get the address of the account. + accAddr := myProfile.Account.GetCachedValue().(AccountI).GetAddress() +``` + +It is important to note that for `GetCachedValue()` to work, `Profile` (and any other structs embedding `Profile`) must implement the `UnpackInterfaces` method: + +```go +func (p *Profile) + +UnpackInterfaces(unpacker codectypes.AnyUnpacker) + +error { + if p.Account != nil { + var account AccountI + return unpacker.UnpackAny(p.Account, &account) +} + +return nil +} +``` + +The `UnpackInterfaces` gets called recursively on all structs implementing this method, to allow all `Any`s to have their `GetCachedValue()` correctly populated. + +For more information about interface encoding, and especially on `UnpackInterfaces` and how the `Any`'s `type_url` gets resolved using the `InterfaceRegistry`, please refer to [ADR-019](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/docs/sdk/next/architecture/adr-019-protobuf-state-encoding.md). + +#### `Any` Encoding in the Cosmos SDK + +The above `Profile` example is a fictive example used for educational purposes. In the Cosmos SDK, we use `Any` encoding in several places (non-exhaustive list): + +* the `cryptotypes.PubKey` interface for encoding different types of public keys, +* the `sdk.Msg` interface for encoding different `Msg`s in a transaction, +* the `AccountI` interface for encoding different types of accounts (similar to the above example) in the x/auth query responses, +* the `EvidenceI` interface for encoding different types of evidences in the x/evidence module, +* the `AuthorizationI` interface for encoding different types of x/authz authorizations, +* the [`Validator`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/staking/types/staking.pb.go#L340-L375) struct that contains information about a validator. + +A real-life example of encoding the pubkey as `Any` inside the Validator struct in x/staking is shown in the following example: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/staking/types/validator.go#L43-L66 +``` + +#### `Any`'s TypeURL + +When packing a protobuf message inside an `Any`, the message's type is uniquely defined by its type URL, which is the message's fully qualified name prefixed by a `/` (slash) character. In some implementations of `Any`, like the gogoproto one, there's generally [a resolvable prefix, e.g. `type.googleapis.com`](https://github.com/gogo/protobuf/blob/b03c65ea87cdc3521ede29f62fe3ce239267c1bc/protobuf/google/protobuf/any.proto#L87-L91). However, in the Cosmos SDK, we made the decision to not include such prefix, to have shorter type URLs. The Cosmos SDK's own `Any` implementation can be found in `github.com/cosmos/cosmos-sdk/codec/types`. + +The Cosmos SDK is also switching away from gogoproto to the official `google.golang.org/protobuf` (known as the Protobuf API v2). Its default `Any` implementation also contains the [`type.googleapis.com`](https://github.com/protocolbuffers/protobuf-go/blob/v1.28.1/types/known/anypb/any.pb.go#L266) prefix. To maintain compatibility with the SDK, the following methods from `"google.golang.org/protobuf/types/known/anypb"` should not be used: + +* `anypb.New` +* `anypb.MarshalFrom` +* `anypb.Any#MarshalFrom` + +Instead, the Cosmos SDK provides helper functions in `"github.com/cosmos/cosmos-proto/anyutil"`, which create an official `anypb.Any` without inserting the prefixes: + +* `anyutil.New` +* `anyutil.MarshalFrom` + +For example, to pack a `sdk.Msg` called `internalMsg`, use: + +```diff +import ( +- "google.golang.org/protobuf/types/known/anypb" ++ "github.com/cosmos/cosmos-proto/anyutil" +) + +- anyMsg, err := anypb.New(internalMsg.Message().Interface()) ++ anyMsg, err := anyutil.New(internalMsg.Message().Interface()) + +- fmt.Println(anyMsg.TypeURL) // type.googleapis.com/cosmos.bank.v1beta1.MsgSend ++ fmt.Println(anyMsg.TypeURL) // /cosmos.bank.v1beta1.MsgSend +``` + +## FAQ + +### How to create modules using protobuf encoding + +#### Defining module types + +Protobuf types can be defined to encode: + +* state +* [`Msg`s](/../build/building-modules/02-messages-and-queries.md#messages) +* [Query services](/../build/building-modules/04-query-services.md) +* [genesis](/../build/building-modules/08-genesis.md) + +#### Naming and conventions + +We encourage developers to follow industry guidelines: [Protocol Buffers style guide](https://developers.google.com/protocol-buffers/docs/sdk/next/style) +and [Buf](https://buf.build/docs/sdk/next/style-guide), see more details in [ADR 023](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/docs/sdk/next/architecture/adr-023-protobuf-naming.md) + +### How to update modules to protobuf encoding + +If modules do not contain any interfaces (e.g. `Account` or `Content`), then they +may simply migrate any existing types that +are encoded and persisted via their concrete Amino codec to Protobuf (see 1. for further guidelines) and accept a `Marshaler` as the codec which is implemented via the `ProtoCodec` +without any further customization. + +However, if a module type composes an interface, it must wrap it in the `sdk.Any` (from `/types` package) type. To do that, a module-level .proto file must use [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto) for respective message type interface types. + +For example, in the `x/evidence` module defines an `Evidence` interface, which is used by the `MsgSubmitEvidence`. The structure definition must use `sdk.Any` to wrap the evidence file. In the proto file we define it as follows: + +```protobuf +// proto/cosmos/evidence/v1beta1/tx.proto + +message MsgSubmitEvidence { + string submitter = 1; + google.protobuf.Any evidence = 2 [(cosmos_proto.accepts_interface) = "cosmos.evidence.v1beta1.Evidence"]; +} +``` + +The Cosmos SDK `codec.Codec` interface provides support methods `MarshalInterface` and `UnmarshalInterface` for easy encoding of state to `Any`. + +Module should register interfaces using `InterfaceRegistry` which provides a mechanism for registering interfaces: `RegisterInterface(protoName string, iface interface{}, impls ...proto.Message)` and implementations: `RegisterImplementations(iface interface{}, impls ...proto.Message)` that can be safely unpacked from Any, similarly to type registration with Amino: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/codec/types/interface_registry.go#L40-L87 +``` + +In addition, an `UnpackInterfaces` phase should be introduced to deserialization to unpack interfaces before they're needed. Protobuf types that contain a protobuf `Any` either directly or via one of their members should implement the `UnpackInterfacesMessage` interface: + +```go +type UnpackInterfacesMessage interface { + UnpackInterfaces(InterfaceUnpacker) + +error +} +``` diff --git a/docs/sdk/next/learn/advanced/events.mdx b/docs/sdk/next/learn/advanced/events.mdx new file mode 100644 index 00000000..6e30c0d6 --- /dev/null +++ b/docs/sdk/next/learn/advanced/events.mdx @@ -0,0 +1,158 @@ +--- +title: Events +--- + +**Synopsis** +`Event`s are objects that contain information about the execution of the application. They are mainly used by service providers like block explorers and wallet to track the execution of various messages and index transactions. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK application](/beginner/00-app-anatomy.md) +* [CometBFT Documentation on Events](https://docs.cometbft.com/v0.37/spec/abci/abci++_basic_concepts#events) + + + +## Events + +Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and +take the form of: `{eventType}.{attributeKey}={attributeValue}`. + +```protobuf +https://github.com/cometbft/cometbft/blob/v0.37.0/proto/tendermint/abci/types.proto#L334-L343 +``` + +An Event contains: + +* A `type` to categorize the Event at a high-level; for example, the Cosmos SDK uses the `"message"` type to filter Events by `Msg`s. +* A list of `attributes` are key-value pairs that give more information about the categorized Event. For example, for the `"message"` type, we can filter Events by key-value pairs using `message.action={some_action}`, `message.module={some_module}` or `message.sender={some_sender}`. +* A `msg_index` to identify which messages relate to the same transaction + + +To parse the attribute values as strings, make sure to add `'` (single quotes) around each attribute value. + + +*Typed Events* are Protobuf-defined [messages](/../../architecture/adr-032-typed-events.md) used by the Cosmos SDK +for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`. +*Legacy Events* are defined on a **per-module basis** in the module's `/types/events.go` file. +They are triggered from the module's Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md) +by using the [`EventManager`](#eventmanager). + +In addition, each module documents its events under in the `Events` sections of its specs (x/`{moduleName}`/`README.md`). + +Lastly, Events are returned to the underlying consensus engine in the response of the following ABCI messages: + +* [`BeginBlock`](00-baseapp.md#beginblock) +* [`EndBlock`](00-baseapp.md#endblock) +* [`CheckTx`](00-baseapp.md#checktx) +* [`Transaction Execution`](00-baseapp.md#transactionexecution) + +### Examples + +The following examples show how to query Events using the Cosmos SDK. + +| Event | Description | +| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tx.height=23` | Query all transactions at height 23 | +| `message.action='/cosmos.bank.v1beta1.Msg/Send'` | Query all transactions containing a x/bank `Send` [Service `Msg`](/../build/building-modules/03-msg-services.md). Note the `'`s around the value. | +| `message.module='bank'` | Query all transactions containing messages from the x/bank module. Note the `'`s around the value. | +| `create_validator.validator='cosmosval1...'` | x/staking-specific Event, see [x/staking SPEC](/../../../x/staking/README.md). | + +## EventManager + +In Cosmos SDK applications, Events are managed by an abstraction called the `EventManager`. +Internally, the `EventManager` tracks a list of Events for the entire execution flow of `FinalizeBlock` +(i.e. transaction execution, `BeginBlock`, `EndBlock`). + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/events.go#L18-L25 +``` + +The `EventManager` comes with a set of useful methods to manage Events. The method +that is used most by module and application developers is `EmitTypedEvent` or `EmitEvent` that tracks +an Event in the `EventManager`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/events.go#L51-L60 +``` + +Module developers should handle Event emission via the `EventManager#EmitTypedEvent` or `EventManager#EmitEvent` in each message +`Handler` and in each `BeginBlock`/`EndBlock` handler. The `EventManager` is accessed via +the [`Context`](02-context.md), where Event should be already registered, and emitted like this: + +**Typed events:** + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/group/keeper/msg_server.go#L95-L97 +``` + +**Legacy events:** + +```go +ctx.EventManager().EmitEvent( + sdk.NewEvent(eventType, sdk.NewAttribute(attributeKey, attributeValue)), +) +``` + +Where the `EventManager` is accessed via the [`Context`](02-context.md). + +See the [`Msg` services](/../build/building-modules/03-msg-services.md) concept doc for a more detailed +view on how to typically implement Events and use the `EventManager` in modules. + +## Subscribing to Events + +You can use CometBFT's [Websocket](https://docs.cometbft.com/v0.37/core/subscription) to subscribe to Events by calling the `subscribe` RPC method: + +```json +{ + "jsonrpc": "2.0", + "method": "subscribe", + "id": "0", + "params": { + "query": "tm.event='eventCategory' AND eventType.eventAttribute='attributeValue'" + } +} +``` + +The main `eventCategory` you can subscribe to are: + +* `NewBlock`: Contains Events triggered during `BeginBlock` and `EndBlock`. +* `Tx`: Contains Events triggered during `DeliverTx` (i.e. transaction processing). +* `ValidatorSetUpdates`: Contains validator set updates for the block. + +These Events are triggered from the `state` package after a block is committed. You can get the +full list of Event categories [on the CometBFT Go documentation](https://pkg.go.dev/github.com/cometbft/cometbft/types#pkg-constants). + +The `type` and `attribute` value of the `query` allow you to filter the specific Event you are looking for. For example, a `Mint` transaction triggers an Event of type `EventMint` and has an `Id` and an `Owner` as `attributes` (as defined in the [`events.proto` file of the `NFT` module](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/proto/cosmos/nft/v1beta1/event.proto#L21-L31)). + +Subscribing to this Event would be done like so: + +```json +{ + "jsonrpc": "2.0", + "method": "subscribe", + "id": "0", + "params": { + "query": "tm.event='Tx' AND mint.owner='ownerAddress'" + } +} +``` + +where `ownerAddress` is an address following the [`AccAddress`](/beginner/03-accounts.md#addresses) format. + +The same way can be used to subscribe to [legacy events](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/bank/types/events.go). + +## Default Events + +There are a few events that are automatically emitted for all messages, directly from `baseapp`. + +* `message.action`: The name of the message type. +* `message.sender`: The address of the message signer. +* `message.module`: The name of the module that emitted the message. + + +The module name is assumed by `baseapp` to be the second element of the message route: `"cosmos.bank.v1beta1.MsgSend" -> "bank"`. +In case a module does not follow the standard message path, (e.g. IBC), it is advised to keep emitting the module name event. +`Baseapp` only emits that event if the module have not already done so. + diff --git a/docs/sdk/next/learn/advanced/grpc_rest.mdx b/docs/sdk/next/learn/advanced/grpc_rest.mdx new file mode 100644 index 00000000..34fbea15 --- /dev/null +++ b/docs/sdk/next/learn/advanced/grpc_rest.mdx @@ -0,0 +1,103 @@ +--- +title: 'gRPC, REST, and CometBFT Endpoints' +--- + +**Synopsis** +This document presents an overview of all the endpoints a node exposes: gRPC, REST as well as some other endpoints. + + +## An Overview of All Endpoints + +Each node exposes the following endpoints for users to interact with a node, each endpoint is served on a different port. Details on how to configure each endpoint is provided in the endpoint's own section. + +* the gRPC server (default port: `9090`), +* the REST server (default port: `1317`), +* the CometBFT RPC endpoint (default port: `26657`). + + +The node also exposes some other endpoints, such as the CometBFT P2P endpoint, or the [Prometheus endpoint](https://docs.cometbft.com/v0.37/core/metrics), which are not directly related to the Cosmos SDK. Please refer to the [CometBFT documentation](https://docs.cometbft.com/v0.37/core/configuration) for more information about these endpoints. + + + +All endpoints are defaulted to localhost and must be modified to be exposed to the public internet. + + +## gRPC Server + +In the Cosmos SDK, Protobuf is the main [encoding](05-encoding.md) library. This brings a wide range of Protobuf-based tools that can be plugged into the Cosmos SDK. One such tool is [gRPC](https://grpc.io), a modern open-source high performance RPC framework that has decent client support in several languages. + +Each module exposes a [Protobuf `Query` service](/../build/building-modules/02-messages-and-queries.md#queries) that defines state queries. The `Query` services and a transaction service used to broadcast transactions are hooked up to the gRPC server via the following function inside the application: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/server/types/app.go#L46-L48 +``` + +Note: It is not possible to expose any [Protobuf `Msg` service](/../build/building-modules/02-messages-and-queries.md#messages) endpoints via gRPC. Transactions must be generated and signed using the CLI or programmatically before they can be broadcasted using gRPC. See [Generating, Signing, and Broadcasting Transactions](/../user/run-node/03-txs.md) for more information. + +The `grpc.Server` is a concrete gRPC server, which spawns and serves all gRPC query requests and a broadcast transaction request. This server can be configured inside `~/.simapp/config/app.toml`: + +* `grpc.enable = true|false` field defines if the gRPC server should be enabled. Defaults to `true`. +* `grpc.address = {string}` field defines the `ip:port` the server should bind to. Defaults to `localhost:9090`. + + +`~/.simapp` is the directory where the node's configuration and databases are stored. By default, it's set to `~/.{app_name}`. + + +Once the gRPC server is started, you can send requests to it using a gRPC client. Some examples are given in our [Interact with the Node](/../user/run-node/02-interact-node.md#using-grpc) tutorial. + +An overview of all available gRPC endpoints shipped with the Cosmos SDK is [Protobuf documentation](https://buf.build/cosmos/cosmos-sdk). + +## REST Server + +Cosmos SDK supports REST routes via gRPC-gateway. + +All routes are configured under the following fields in `~/.simapp/config/app.toml`: + +* `api.enable = true|false` field defines if the REST server should be enabled. Defaults to `false`. +* `api.address = {string}` field defines the `ip:port` the server should bind to. Defaults to `tcp://localhost:1317`. +* some additional API configuration options are defined in `~/.simapp/config/app.toml`, along with comments, please refer to that file directly. + +### gRPC-gateway REST Routes + +If, for various reasons, you cannot use gRPC (for example, you are building a web application, and browsers don't support HTTP2 on which gRPC is built), then the Cosmos SDK offers REST routes via gRPC-gateway. + +[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway `"/cosmos/bank/v1beta1/balances/{address}"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/proto/cosmos/bank/v1beta1/query.proto#L23-L30 +``` + +For application developers, gRPC-gateway REST routes needs to be wired up to the REST server, this is done by calling the `RegisterGRPCGatewayRoutes` function on the ModuleManager. + +### Swagger + +A [Swagger](https://swagger.io/) (or OpenAPIv2) specification file is exposed under the `/swagger` route on the API server. Swagger is an open specification describing the API endpoints a server serves, including description, input arguments, return types and much more about each endpoint. + +Enabling the `/swagger` endpoint is configurable inside `~/.simapp/config/app.toml` via the `api.swagger` field, which is set to false by default. + +For application developers, you may want to generate your own Swagger definitions based on your custom modules. +The Cosmos SDK's [Swagger generation script](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/scripts/protoc-swagger-gen.sh) is a good place to start. + +## CometBFT RPC + +Independently from the Cosmos SDK, CometBFT also exposes a RPC server. This RPC server can be configured by tuning parameters under the `rpc` table in the `~/.simapp/config/config.toml`, the default listening address is `tcp://localhost:26657`. An OpenAPI specification of all CometBFT RPC endpoints is available [here](https://docs.cometbft.com/main/rpc/). + +Some CometBFT RPC endpoints are directly related to the Cosmos SDK: + +* `/abci_query`: this endpoint will query the application for state. As the `path` parameter, you can send the following strings: + * any Protobuf fully-qualified service method, such as `/cosmos.bank.v1beta1.Query/AllBalances`. The `data` field should then include the method's request parameter(s) encoded as bytes using Protobuf. + * `/app/simulate`: this will simulate a transaction, and return some information such as gas used. + * `/app/version`: this will return the application's version. + * `/store/{storeName}/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. + * `/store/{storeName}/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. + * `/p2p/filter/addr/{port}`: this will return a filtered list of the node's P2P peers by address port. + * `/p2p/filter/id/{id}`: this will return a filtered list of the node's P2P peers by ID. +* `/broadcast_tx_{sync,async,commit}`: these 3 endpoints will broadcast a transaction to other peers. CLI, gRPC and REST expose [a way to broadcast transactions](01-transactions.md#broadcasting-the-transaction), but they all use these 3 CometBFT RPCs under the hood. + +## Comparison Table + +| Name | Advantages | Disadvantages | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| gRPC | - can use code-generated stubs in various languages
- supports streaming and bidirectional communication (HTTP2)
- small wire binary sizes, faster transmission | - based on HTTP2, not available in browsers
- learning curve (mostly due to Protobuf) | +| REST | - ubiquitous
- client libraries in all languages, faster implementation
| - only supports unary request-response communication (HTTP1.1)
- bigger over-the-wire message sizes (JSON) | +| CometBFT RPC | - easy to use | - bigger over-the-wire message sizes (JSON) | diff --git a/docs/sdk/next/learn/advanced/node.mdx b/docs/sdk/next/learn/advanced/node.mdx new file mode 100644 index 00000000..1ce0ae3e --- /dev/null +++ b/docs/sdk/next/learn/advanced/node.mdx @@ -0,0 +1,95 @@ +--- +title: Node Client (Daemon) +--- + +**Synopsis** +The main endpoint of a Cosmos SDK application is the daemon client, otherwise known as the full-node client. The full-node runs the state-machine, starting from a genesis file. It connects to peers running the same client in order to receive and relay transactions, block proposals and signatures. The full-node is constituted of the application, defined with the Cosmos SDK, and of a consensus engine connected to the application via the ABCI. + + + +**Pre-requisite Readings** + +* [Anatomy of an SDK application](/beginner/00-app-anatomy.md) + + + +## `main` function + +The full-node client of any Cosmos SDK application is built by running a `main` function. The client is generally named by appending the `-d` suffix to the application name (e.g. `appd` for an application named `app`), and the `main` function is defined in a `./appd/cmd/main.go` file. Running this function creates an executable `appd` that comes with a set of commands. For an app named `app`, the main command is [`appd start`](#start-command), which starts the full-node. + +In general, developers will implement the `main.go` function with the following structure: + +* First, an [`encodingCodec`](05-encoding.md) is instantiated for the application. +* Then, the `config` is retrieved and config parameters are set. This mainly involves setting the Bech32 prefixes for [addresses](/beginner/03-accounts.md#addresses). + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/config.go#L14-L29 +``` + +* Using [cobra](https://github.com/spf13/cobra), the root command of the full-node client is created. After that, all the custom commands of the application are added using the `AddCommand()` method of `rootCmd`. +* Add default server commands to `rootCmd` using the `server.AddCommands()` method. These commands are separated from the ones added above since they are standard and defined at Cosmos SDK level. They should be shared by all Cosmos SDK-based applications. They include the most important command: the [`start` command](#start-command). +* Prepare and execute the `executor`. + +```go +https://github.com/cometbft/cometbft/blob/v0.37.0/libs/cli/setup.go#L74-L78 +``` + +See an example of `main` function from the `simapp` application, the Cosmos SDK's application for demo purposes: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/main.go +``` + +## `start` command + +The `start` command is defined in the `/server` folder of the Cosmos SDK. It is added to the root command of the full-node client in the [`main` function](#main-function) and called by the end-user to start their node: + +```bash +# For an example app named "app", the following command starts the full-node. +appd start + +# Using the Cosmos SDK's own simapp, the following commands start the simapp node. +simd start +``` + +As a reminder, the full-node is composed of three conceptual layers: the networking layer, the consensus layer and the application layer. The first two are generally bundled together in an entity called the consensus engine (CometBFT by default), while the third is the state-machine defined with the help of the Cosmos SDK. Currently, the Cosmos SDK uses CometBFT as the default consensus engine, meaning the start command is implemented to boot up a CometBFT node. + +The flow of the `start` command is pretty straightforward. First, it retrieves the `config` from the `context` in order to open the `db` (a [`leveldb`](https://github.com/syndtr/goleveldb) instance by default). This `db` contains the latest known state of the application (empty if the application is started from the first time. + +With the `db`, the `start` command creates a new instance of the application using an `appCreator` function: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/start.go#L1007 +``` + +Note that an `appCreator` is a function that fulfills the `AppCreator` signature: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/types/app.go#L69 +``` + +In practice, the [constructor of the application](/beginner/00-app-anatomy.md#constructor-function) is passed as the `appCreator`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L294-L308 +``` + +Then, the instance of `app` is used to instantiate a new CometBFT node: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/start.go#L361-L400 +``` + +The CometBFT node can be created with `app` because the latter satisfies the [`abci.Application` interface](https://github.com/cometbft/cometbft/blob/v0.37.0/abci/types/application.go#L9-L35) (given that `app` extends [`baseapp`](00-baseapp.md)). As part of the `node.New` method, CometBFT makes sure that the height of the application (i.e. number of blocks since genesis) is equal to the height of the CometBFT node. The difference between these two heights should always be negative or null. If it is strictly negative, `node.New` will replay blocks until the height of the application reaches the height of the CometBFT node. Finally, if the height of the application is `0`, the CometBFT node will call [`InitChain`](00-baseapp.md#initchain) on the application to initialize the state from the genesis file. + +Once the CometBFT node is instantiated and in sync with the application, the node can be started: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/start.go#L373-L374 +``` + +Upon starting, the node will bootstrap its RPC and P2P server and start dialing peers. During handshake with its peers, if the node realizes they are ahead, it will query all the blocks sequentially in order to catch up. Then, it will wait for new block proposals and block signatures from validators in order to make progress. + +## Other commands + +To discover how to concretely run a node and interact with it, please refer to our [Running a Node, API and CLI](/../user/run-node/01-run-node.md) guide. diff --git a/docs/sdk/next/learn/advanced/ocap.mdx b/docs/sdk/next/learn/advanced/ocap.mdx new file mode 100644 index 00000000..56dcb1be --- /dev/null +++ b/docs/sdk/next/learn/advanced/ocap.mdx @@ -0,0 +1,79 @@ +--- +title: Object-Capability Model +description: >- + When thinking about security, it is good to start with a specific threat + model. Our threat model is the following: +--- +## Intro + +When thinking about security, it is good to start with a specific threat model. Our threat model is the following: + +> We assume that a thriving ecosystem of Cosmos SDK modules that are easy to compose into a blockchain application will contain faulty or malicious modules. + +The Cosmos SDK is designed to address this threat by being the +foundation of an object capability system. + +> The structural properties of object capability systems favor +> modularity in code design and ensure reliable encapsulation in +> code implementation. +> +> These structural properties facilitate the analysis of some +> security properties of an object-capability program or operating +> system. Some of these — in particular, information flow properties +> — can be analyzed at the level of object references and +> connectivity, independent of any knowledge or analysis of the code +> that determines the behavior of the objects. +> +> As a consequence, these security properties can be established +> and maintained in the presence of new objects that contain unknown +> and possibly malicious code. +> +> These structural properties stem from the two rules governing +> access to existing objects: +> +> 1. An object A can send a message to B only if object A holds a +> reference to B. +> 2. An object A can obtain a reference to C only +> if object A receives a message containing a reference to C. As a +> consequence of these two rules, an object can obtain a reference +> to another object only through a preexisting chain of references. +> In short, "Only connectivity begets connectivity." + +For an introduction to object-capabilities, see this [Wikipedia article](https://en.wikipedia.org/wiki/Object-capability_model). + +## Ocaps in practice + +The idea is to only reveal what is necessary to get the work done. + +For example, the following code snippet violates the object capabilities +principle: + +```go +type AppAccount struct {... +} + account := &AppAccount{ + Address: pub.Address(), + Coins: sdk.Coins{ + sdk.NewInt64Coin("ATM", 100) +}, +} + sumValue := externalModule.ComputeSumValue(account) +``` + +The method `ComputeSumValue` implies a pure function, yet the implied +capability of accepting a pointer value is the capability to modify that +value. The preferred method signature should take a copy instead. + +```go +sumValue := externalModule.ComputeSumValue(*account) +``` + +In the Cosmos SDK, you can see the application of this principle in simapp. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app.go +``` + +The following diagram shows the current dependencies between keepers. + +![Keeper dependencies](https://raw.githubusercontent.com/cosmos/cosmos-sdk/release/v0.46.x/docs/uml/svg/keeper_dependencies.svg) diff --git a/docs/sdk/next/learn/advanced/proto-docs.mdx b/docs/sdk/next/learn/advanced/proto-docs.mdx new file mode 100644 index 00000000..4e174d20 --- /dev/null +++ b/docs/sdk/next/learn/advanced/proto-docs.mdx @@ -0,0 +1,5 @@ +--- +title: Protobuf Documentation +description: See Cosmos SDK Buf Proto-docs +--- +See [Cosmos SDK Buf Proto-docs](https://buf.build/cosmos/cosmos-sdk/docs/sdk/next/main) diff --git a/docs/sdk/next/learn/advanced/runtx_middleware.mdx b/docs/sdk/next/learn/advanced/runtx_middleware.mdx new file mode 100644 index 00000000..107d759f --- /dev/null +++ b/docs/sdk/next/learn/advanced/runtx_middleware.mdx @@ -0,0 +1,70 @@ +--- +title: RunTx recovery middleware +--- +`BaseApp.runTx()` function handles Go panics that might occur during transactions execution, for example, keeper has faced an invalid state and panicked. +Depending on the panic type different handler is used, for instance the default one prints an error log message. +Recovery middleware is used to add custom panic recovery for Cosmos SDK application developers. + +More context can found in the corresponding [ADR-022](/../build/architecture/adr-022-custom-panic-handling.md) and the implementation in [recovery.go](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/baseapp/recovery.go). + +## Interface + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/baseapp/recovery.go#L14-L17 +``` + +`recoveryObj` is a return value for `recover()` function from the `building` Go package. + +**Contract:** + +* RecoveryHandler returns `nil` if `recoveryObj` wasn't handled and should be passed to the next recovery middleware; +* RecoveryHandler returns a non-nil `error` if `recoveryObj` was handled; + +## Custom RecoveryHandler register + +`BaseApp.AddRunTxRecoveryHandler(handlers ...RecoveryHandler)` + +BaseApp method adds recovery middleware to the default recovery chain. + +## Example + +Lets assume we want to emit the "Consensus failure" chain state if some particular error occurred. + +We have a module keeper that panics: + +```go +func (k FooKeeper) + +Do(obj interface{ +}) { + if obj == nil { + // that shouldn't happen, we need to crash the app + err := errorsmod.Wrap(fooTypes.InternalError, "obj is nil") + +panic(err) +} +} +``` + +By default that panic would be recovered and an error message will be printed to log. To override that behavior we should register a custom RecoveryHandler: + +```go expandable +// Cosmos SDK application constructor + customHandler := func(recoveryObj interface{ +}) + +error { + err, ok := recoveryObj.(error) + if !ok { + return nil +} + if fooTypes.InternalError.Is(err) { + panic(fmt.Errorf("FooKeeper did panic with error: %w", err)) +} + +return nil +} + baseApp := baseapp.NewBaseApp(...) + +baseApp.AddRunTxRecoveryHandler(customHandler) +``` diff --git a/docs/sdk/next/learn/advanced/simulation.mdx b/docs/sdk/next/learn/advanced/simulation.mdx new file mode 100644 index 00000000..bbbb925b --- /dev/null +++ b/docs/sdk/next/learn/advanced/simulation.mdx @@ -0,0 +1,94 @@ +--- +title: Cosmos Blockchain Simulator +description: >- + The Cosmos SDK offers a full fledged simulation framework to fuzz test every + message defined by a module. +--- +The Cosmos SDK offers a full fledged simulation framework to fuzz test every +message defined by a module. + +On the Cosmos SDK, this functionality is provided by [`SimApp`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_di.go), which is a +`Baseapp` application that is used for running the [`simulation`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/simulation) module. +This module defines all the simulation logic as well as the operations for +randomized parameters like accounts, balances etc. + +## Goals + +The blockchain simulator tests how the blockchain application would behave under +real life circumstances by generating and sending randomized messages. +The goal of this is to detect and debug failures that could halt a live chain, +by providing logs and statistics about the operations run by the simulator as +well as exporting the latest application state when a failure was found. + +Its main difference with integration testing is that the simulator app allows +you to pass parameters to customize the chain that's being simulated. +This comes in handy when trying to reproduce bugs that were generated in the +provided operations (randomized or not). + +## Simulation commands + +The simulation app has different commands, each of which tests a different +failure type: + +* `AppImportExport`: The simulator exports the initial app state and then it + creates a new app with the exported `genesis.json` as an input, checking for + inconsistencies between the stores. +* `AppSimulationAfterImport`: Queues two simulations together. The first one provides the app state (*i.e* genesis) to the second. Useful to test software upgrades or hard-forks from a live chain. +* `AppStateDeterminism`: Checks that all the nodes return the same values, in the same order. +* `FullAppSimulation`: General simulation mode. Runs the chain and the specified operations for a given number of blocks. Tests that there're no `panics` on the simulation. + +Each simulation must receive a set of inputs (*i.e* flags) such as the number of +blocks that the simulation is run, seed, block size, etc. +Check the full list of flags [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/simulation/client/cli/flags.go#L43-L70). + +## Simulator Modes + +In addition to the various inputs and commands, the simulator runs in three modes: + +1. Completely random where the initial state, module parameters and simulation + parameters are **pseudo-randomly generated**. +2. From a `genesis.json` file where the initial state and the module parameters are defined. + This mode is helpful for running simulations on a known state such as a live network export where a new (mostly likely breaking) version of the application needs to be tested. +3. From a `params.json` file where the initial state is pseudo-randomly generated but the module and simulation parameters can be provided manually. + This allows for a more controlled and deterministic simulation setup while allowing the state space to still be pseudo-randomly simulated. + The list of available parameters are listed [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/simulation/client/cli/flags.go#L72-L90). + + +These modes are not mutually exclusive. So you can for example run a randomly +generated genesis state (`1`) with manually generated simulation params (`3`). + + +## Usage + +This is a general example of how simulations are run. For more specific examples +check the Cosmos SDK [Makefile](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/Makefile#L285-L320). + +```bash + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestApp \ + ... + -v -timeout 24h +``` + +## Debugging Tips + +Here are some suggestions when encountering a simulation failure: + +* Export the app state at the height where the failure was found. You can do this + by passing the `-ExportStatePath` flag to the simulator. +* Use `-Verbose` logs. They could give you a better hint on all the operations + involved. +* Try using another `-Seed`. If it can reproduce the same error and if it fails + sooner, you will spend less time running the simulations. +* Reduce the `-NumBlocks` . How's the app state at the height previous to the + failure? +* Try adding logs to operations that are not logged. You will have to define a + [Logger](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/x/staking/keeper/keeper.go#L77-L81) on your `Keeper`. + +## Use simulation in your Cosmos SDK-based application + +Learn how you can build the simulation into your Cosmos SDK-based application: + +* Application Simulation Manager +* [Building modules: Simulator](/../build/building-modules/14-simulator.md) +* Simulator tests diff --git a/docs/sdk/next/learn/advanced/store.mdx b/docs/sdk/next/learn/advanced/store.mdx new file mode 100644 index 00000000..5afa6e25 --- /dev/null +++ b/docs/sdk/next/learn/advanced/store.mdx @@ -0,0 +1,287 @@ +--- +title: Store +--- + +**Synopsis** +A store is a data structure that holds the state of the application. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK application](/beginner/00-app-anatomy.md) + + + +## Introduction to Cosmos SDK Stores + +The Cosmos SDK comes with a large set of stores to persist the state of applications. By default, the main store of Cosmos SDK applications is a `multistore`, i.e. a store of stores. Developers can add any number of key-value stores to the multistore, depending on their application needs. The multistore exists to support the modularity of the Cosmos SDK, as it lets each module declare and manage their own subset of the state. Key-value stores in the multistore can only be accessed with a specific capability `key`, which is typically held in the [`keeper`](/../build/building-modules/06-keeper.md) of the module that declared the store. + +```text expandable ++-----------------------------------------------------+ +| | +| +--------------------------------------------+ | +| | | | +| | KVStore 1 - Manage by keeper of Module 1 | +| | | | +| +--------------------------------------------+ | +| | +| +--------------------------------------------+ | +| | | | +| | KVStore 2 - Manage by keeper of Module 2 | | +| | | | +| +--------------------------------------------+ | +| | +| +--------------------------------------------+ | +| | | | +| | KVStore 3 - Manage by keeper of Module 2 | | +| | | | +| +--------------------------------------------+ | +| | +| +--------------------------------------------+ | +| | | | +| | KVStore 4 - Manage by keeper of Module 3 | | +| | | | +| +--------------------------------------------+ | +| | +| +--------------------------------------------+ | +| | | | +| | KVStore 5 - Manage by keeper of Module 4 | | +| | | | +| +--------------------------------------------+ | +| | +| Main Multistore | +| | ++-----------------------------------------------------+ + + Application's State +``` + +### Store Interface + +At its very core, a Cosmos SDK `store` is an object that holds a `CacheWrapper` and has a `GetStoreType()` method: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L17-L20 +``` + +The `GetStoreType` is a simple method that returns the type of store, whereas a `CacheWrapper` is a simple interface that implements store read caching and write branching through `Write` method: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L285-L317 +``` + +Branching and cache is used ubiquitously in the Cosmos SDK and required to be implemented on every store type. A storage branch creates an isolated, ephemeral branch of a store that can be passed around and updated without affecting the main underlying store. This is used to trigger temporary state-transitions that may be reverted later should an error occur. Read more about it in [context](02-context.md#Store-branching) + +### Commit Store + +A commit store is a store that has the ability to commit changes made to the underlying tree or db. The Cosmos SDK differentiates simple stores from commit stores by extending the basic store interfaces with a `Committer`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L34-L38 +``` + +The `Committer` is an interface that defines methods to persist changes to disk: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L22-L32 +``` + +The `CommitID` is a deterministic commit of the state tree. Its hash is returned to the underlying consensus engine and stored in the block header. Note that commit store interfaces exist for various purposes, one of which is to make sure not every object can commit the store. As part of the [object-capabilities model](10-ocap.md) of the Cosmos SDK, only `baseapp` should have the ability to commit stores. For example, this is the reason why the `ctx.KVStore()` method by which modules typically access stores returns a `KVStore` and not a `CommitKVStore`. + +The Cosmos SDK comes with many types of stores, the most used being [`CommitMultiStore`](#multistore), [`KVStore`](#kvstore) and [`GasKv` store](#gaskv-store). [Other types of stores](#other-stores) include `Transient` and `TraceKV` stores. + +## Multistore + +### Multistore Interface + +Each Cosmos SDK application holds a multistore at its root to persist its state. The multistore is a store of `KVStores` that follows the `Multistore` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L115-L147 +``` + +If tracing is enabled, then branching the multistore will firstly wrap all the underlying `KVStore` in [`TraceKv.Store`](#tracekv-store). + +### CommitMultiStore + +The main type of `Multistore` used in the Cosmos SDK is `CommitMultiStore`, which is an extension of the `Multistore` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L155-L225 +``` + +As for concrete implementation, the \[`rootMulti.Store`] is the go-to implementation of the `CommitMultiStore` interface. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/rootmulti/store.go#L56-L82 +``` + +The `rootMulti.Store` is a base-layer multistore built around a `db` on top of which multiple `KVStores` can be mounted, and is the default multistore store used in [`baseapp`](00-baseapp.md). + +### CacheMultiStore + +Whenever the `rootMulti.Store` needs to be branched, a [`cachemulti.Store`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/cachemulti/store.go) is used. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/cachemulti/store.go#L20-L34 +``` + +`cachemulti.Store` branches all substores (creates a virtual store for each substore) in its constructor and hold them in `Store.stores`. Moreover caches all read queries. `Store.GetKVStore()` returns the store from `Store.stores`, and `Store.Write()` recursively calls `CacheWrap.Write()` on all the substores. + +## Base-layer KVStores + +### `KVStore` and `CommitKVStore` Interfaces + +A `KVStore` is a simple key-value store used to store and retrieve data. A `CommitKVStore` is a `KVStore` that also implements a `Committer`. By default, stores mounted in `baseapp`'s main `CommitMultiStore` are `CommitKVStore`s. The `KVStore` interface is primarily used to restrict modules from accessing the committer. + +Individual `KVStore`s are used by modules to manage a subset of the global state. `KVStores` can be accessed by objects that hold a specific key. This `key` should only be exposed to the [`keeper`](/../build/building-modules/06-keeper.md) of the module that defines the store. + +`CommitKVStore`s are declared by proxy of their respective `key` and mounted on the application's [multistore](#multistore) in the [main application file](/beginner/00-app-anatomy.md#core-application-file). In the same file, the `key` is also passed to the module's `keeper` that is responsible for managing the store. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/store.go#L227-L264 +``` + +Apart from the traditional `Get` and `Set` methods, that a `KVStore` must implement via the `BasicKVStore` interface; a `KVStore` must provide an `Iterator(start, end)` method which returns an `Iterator` object. It is used to iterate over a range of keys, typically keys that share a common prefix. Below is an example from the bank's module keeper, used to iterate over all account balances: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/bank/keeper/view.go#L121-L137 +``` + +### `IAVL` Store + +The default implementation of `KVStore` and `CommitKVStore` used in `baseapp` is the `iavl.Store`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/iavl/store.go#L36-L41 +``` + +`iavl` stores are based around an [IAVL Tree](https://github.com/cosmos/iavl), a self-balancing binary tree which guarantees that: + +* `Get` and `Set` operations are O(log n), where n is the number of elements in the tree. +* Iteration efficiently returns the sorted elements within the range. +* Each tree version is immutable and can be retrieved even after a commit (depending on the pruning settings). + +The documentation on the IAVL Tree is located [here](https://github.com/cosmos/iavl/blob/master/docs/sdk/next/overview.md). + +### `DbAdapter` Store + +`dbadapter.Store` is an adapter for `dbm.DB` making it fulfilling the `KVStore` interface. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/dbadapter/store.go#L13-L16 +``` + +`dbadapter.Store` embeds `dbm.DB`, meaning most of the `KVStore` interface functions are implemented. The other functions (mostly miscellaneous) are manually implemented. This store is primarily used within [Transient Stores](#transient-store) + +### `Transient` Store + +`Transient.Store` is a base-layer `KVStore` which is automatically discarded at the end of the block. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/transient/store.go#L16-L19 +``` + +`Transient.Store` is a `dbadapter.Store` with a `dbm.NewMemDB()`. All `KVStore` methods are reused. When `Store.Commit()` is called, a new `dbadapter.Store` is assigned, discarding previous reference and making it garbage collected. + +This type of store is useful to persist information that is only relevant per-block. One example would be to store parameter changes (i.e. a bool set to `true` if a parameter changed in a block). + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/params/types/subspace.go#L22-L32 +``` + +Transient stores are typically accessed via the [`context`](02-context.md) via the `TransientStore()` method: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/context.go#L347-L350 +``` + +## KVStore Wrappers + +### CacheKVStore + +`cachekv.Store` is a wrapper `KVStore` which provides buffered writing / cached reading functionalities over the underlying `KVStore`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/cachekv/store.go#L26-L36 +``` + +This is the type used whenever an IAVL Store needs to be branched to create an isolated store (typically when we need to mutate a state that might be reverted later). + +#### `Get` + +`Store.Get()` firstly checks if `Store.cache` has an associated value with the key. If the value exists, the function returns it. If not, the function calls `Store.parent.Get()`, caches the result in `Store.cache`, and returns it. + +#### `Set` + +`Store.Set()` sets the key-value pair to the `Store.cache`. `cValue` has the field dirty bool which indicates whether the cached value is different from the underlying value. When `Store.Set()` caches a new pair, the `cValue.dirty` is set `true` so when `Store.Write()` is called it can be written to the underlying store. + +#### `Iterator` + +`Store.Iterator()` has to traverse on both cached items and the original items. In `Store.iterator()`, two iterators are generated for each of them, and merged. `memIterator` is essentially a slice of the `KVPairs`, used for cached items. `mergeIterator` is a combination of two iterators, where traverse happens ordered on both iterators. + +### `GasKv` Store + +Cosmos SDK applications use [`gas`](/beginner/04-gas-fees.md) to track resources usage and prevent spam. [`GasKv.Store`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/gaskv/store.go) is a `KVStore` wrapper that enables automatic gas consumption each time a read or write to the store is made. It is the solution of choice to track storage usage in Cosmos SDK applications. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/gaskv/store.go#L11-L17 +``` + +When methods of the parent `KVStore` are called, `GasKv.Store` automatically consumes appropriate amount of gas depending on the `Store.gasConfig`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/gas.go#L219-L228 +``` + +By default, all `KVStores` are wrapped in `GasKv.Stores` when retrieved. This is done in the `KVStore()` method of the [`context`](02-context.md): + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/context.go#L342-L345 +``` + +In this case, the gas configuration set in the `context` is used. The gas configuration can be set using the `WithKVGasConfig` method of the `context`. +Otherwise it uses the following default: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/types/gas.go#L230-L241 +``` + +### `TraceKv` Store + +`tracekv.Store` is a wrapper `KVStore` which provides operation tracing functionalities over the underlying `KVStore`. It is applied automatically by the Cosmos SDK on all `KVStore` if tracing is enabled on the parent `MultiStore`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/tracekv/store.go#L20-L43 +``` + +When each `KVStore` methods are called, `tracekv.Store` automatically logs `traceOperation` to the `Store.writer`. `traceOperation.Metadata` is filled with `Store.context` when it is not nil. `TraceContext` is a `map[string]interface{}`. + +### `Prefix` Store + +`prefix.Store` is a wrapper `KVStore` which provides automatic key-prefixing functionalities over the underlying `KVStore`. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/prefix/store.go#L15-L21 +``` + +When `Store.{Get, Set}()` is called, the store forwards the call to its parent, with the key prefixed with the `Store.prefix`. + +When `Store.Iterator()` is called, it does not simply prefix the `Store.prefix`, since it does not work as intended. In that case, some of the elements are traversed even if they are not starting with the prefix. + +### `ListenKv` Store + +`listenkv.Store` is a wrapper `KVStore` which provides state listening capabilities over the underlying `KVStore`. +It is applied automatically by the Cosmos SDK on any `KVStore` whose `StoreKey` is specified during state streaming configuration. +Additional information about state streaming configuration can be found in the [store/streaming/README.md](https://github.com/cosmos/cosmos-sdk/tree/v0.53.0/store/streaming). + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/store/listenkv/store.go#L11-L18 +``` + +When `KVStore.Set` or `KVStore.Delete` methods are called, `listenkv.Store` automatically writes the operations to the set of `Store.listeners`. + +## `BasicKVStore` interface + +An interface providing only the basic CRUD functionality (`Get`, `Set`, `Has`, and `Delete` methods), without iteration or caching. This is used to partially expose components of a larger store. diff --git a/docs/sdk/next/learn/advanced/telemetry.mdx b/docs/sdk/next/learn/advanced/telemetry.mdx new file mode 100644 index 00000000..76feb0a7 --- /dev/null +++ b/docs/sdk/next/learn/advanced/telemetry.mdx @@ -0,0 +1,126 @@ +--- +title: Telemetry +--- + +**Synopsis** +Gather relevant insights about your application and modules with custom metrics and telemetry. + + +The Cosmos SDK enables operators and developers to gain insight into the performance and behavior of +their application through the use of the `telemetry` package. To enable telemetry, set `telemetry.enabled = true` in the app.toml config file. + +The Cosmos SDK currently supports enabling in-memory and prometheus as telemetry sinks. In-memory sink is always attached (when the telemetry is enabled) with 10 second interval and 1 minute retention. This means that metrics will be aggregated over 10 seconds, and metrics will be kept alive for 1 minute. + +To query active metrics (see retention note above) you have to enable API server (`api.enabled = true` in the app.toml). Single API endpoint is exposed: `http://localhost:1317/metrics?format={text|prometheus}`, the default being `text`. + +## Emitting metrics + +If telemetry is enabled via configuration, a single global metrics collector is registered via the +[go-metrics](https://github.com/hashicorp/go-metrics) library. This allows emitting and collecting +metrics through simple [API](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/telemetry/wrapper.go). Example: + +```go +func EndBlocker(ctx sdk.Context, k keeper.Keeper) { + defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) + + // ... +} +``` + +Developers may use the `telemetry` package directly, which provides wrappers around metric APIs +that include adding useful labels, or they must use the `go-metrics` library directly. It is preferable +to add as much context and adequate dimensionality to metrics as possible, so the `telemetry` package +is advised. Regardless of the package or method used, the Cosmos SDK supports the following metrics +types: + +* gauges +* summaries +* counters + +## Labels + +Certain components of modules will have their name automatically added as a label (e.g. `BeginBlock`). +Operators may also supply the application with a global set of labels that will be applied to all +metrics emitted using the `telemetry` package (e.g. chain-id). Global labels are supplied as a list +of \[name, value] tuples. + +Example: + +```toml +global-labels = [ + ["chain_id", "chain-OfXo4V"], +] +``` + +## Cardinality + +Cardinality is key, specifically label and key cardinality. Cardinality is how many unique values of +something there are. So there is naturally a tradeoff between granularity and how much stress is put +on the telemetry sink in terms of indexing, scrape, and query performance. + +Developers should take care to support metrics with enough dimensionality and granularity to be +useful, but not increase the cardinality beyond the sink's limits. A general rule of thumb is to not +exceed a cardinality of 10. + +Consider the following examples with enough granularity and adequate cardinality: + +* begin/end blocker time +* tx gas used +* block gas used +* amount of tokens minted +* amount of accounts created + +The following examples expose too much cardinality and may not even prove to be useful: + +* transfers between accounts with amount +* voting/deposit amount from unique addresses + +## Supported Metrics + +| Metric | Description | Unit | Type | +|:--------------------------------|:------------------------------------------------------------------------------------------|:----------------|:--------| +| `tx_count` | Total number of txs processed via `DeliverTx` | tx | counter | +| `tx_successful` | Total number of successful txs processed via `DeliverTx` | tx | counter | +| `tx_failed` | Total number of failed txs processed via `DeliverTx` | tx | counter | +| `tx_gas_used` | The total amount of gas used by a tx | gas | gauge | +| `tx_gas_wanted` | The total amount of gas requested by a tx | gas | gauge | +| `tx_msg_send` | The total amount of tokens sent in a `MsgSend` (per denom) | token | gauge | +| `tx_msg_withdraw_reward` | The total amount of tokens withdrawn in a `MsgWithdrawDelegatorReward` (per denom) | token | gauge | +| `tx_msg_withdraw_commission` | The total amount of tokens withdrawn in a `MsgWithdrawValidatorCommission` (per denom) | token | gauge | +| `tx_msg_delegate` | The total amount of tokens delegated in a `MsgDelegate` | token | gauge | +| `tx_msg_begin_unbonding` | The total amount of tokens undelegated in a `MsgUndelegate` | token | gauge | +| `tx_msg_begin_redelegate` | The total amount of tokens redelegated in a `MsgBeginRedelegate` | token | gauge | +| `tx_msg_ibc_transfer` | The total amount of tokens transferred via IBC in a `MsgTransfer` (source or sink chain) | token | gauge | +| `ibc_transfer_packet_receive` | The total amount of tokens received in a `FungibleTokenPacketData` (source or sink chain) | token | gauge | +| `new_account` | Total number of new accounts created | account | counter | +| `gov_proposal` | Total number of governance proposals | proposal | counter | +| `gov_vote` | Total number of governance votes for a proposal | vote | counter | +| `gov_deposit` | Total number of governance deposits for a proposal | deposit | counter | +| `staking_delegate` | Total number of delegations | delegation | counter | +| `staking_undelegate` | Total number of undelegations | undelegation | counter | +| `staking_redelegate` | Total number of redelegations | redelegation | counter | +| `ibc_transfer_send` | Total number of IBC transfers sent from a chain (source or sink) | transfer | counter | +| `ibc_transfer_receive` | Total number of IBC transfers received to a chain (source or sink) | transfer | counter | +| `ibc_client_create` | Total number of clients created | create | counter | +| `ibc_client_update` | Total number of client updates | update | counter | +| `ibc_client_upgrade` | Total number of client upgrades | upgrade | counter | +| `ibc_client_misbehaviour` | Total number of client misbehaviours | misbehaviour | counter | +| `ibc_connection_open-init` | Total number of connection `OpenInit` handshakes | handshake | counter | +| `ibc_connection_open-try` | Total number of connection `OpenTry` handshakes | handshake | counter | +| `ibc_connection_open-ack` | Total number of connection `OpenAck` handshakes | handshake | counter | +| `ibc_connection_open-confirm` | Total number of connection `OpenConfirm` handshakes | handshake | counter | +| `ibc_channel_open-init` | Total number of channel `OpenInit` handshakes | handshake | counter | +| `ibc_channel_open-try` | Total number of channel `OpenTry` handshakes | handshake | counter | +| `ibc_channel_open-ack` | Total number of channel `OpenAck` handshakes | handshake | counter | +| `ibc_channel_open-confirm` | Total number of channel `OpenConfirm` handshakes | handshake | counter | +| `ibc_channel_close-init` | Total number of channel `CloseInit` handshakes | handshake | counter | +| `ibc_channel_close-confirm` | Total number of channel `CloseConfirm` handshakes | handshake | counter | +| `tx_msg_ibc_recv_packet` | Total number of IBC packets received | packet | counter | +| `tx_msg_ibc_acknowledge_packet` | Total number of IBC packets acknowledged | acknowledgement | counter | +| `ibc_timeout_packet` | Total number of IBC timeout packets | timeout | counter | +| `store_iavl_get` | Duration of an IAVL `Store#Get` call | ms | summary | +| `store_iavl_set` | Duration of an IAVL `Store#Set` call | ms | summary | +| `store_iavl_has` | Duration of an IAVL `Store#Has` call | ms | summary | +| `store_iavl_delete` | Duration of an IAVL `Store#Delete` call | ms | summary | +| `store_iavl_commit` | Duration of an IAVL `Store#Commit` call | ms | summary | +| `store_iavl_query` | Duration of an IAVL `Store#Query` call | ms | summary | diff --git a/docs/sdk/next/learn/advanced/transactions.mdx b/docs/sdk/next/learn/advanced/transactions.mdx new file mode 100644 index 00000000..857ecd4a --- /dev/null +++ b/docs/sdk/next/learn/advanced/transactions.mdx @@ -0,0 +1,228 @@ +--- +title: Transactions +--- + +**Synopsis** +`Transactions` are objects created by end-users to trigger state changes in the application. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](/beginner/00-app-anatomy.md) + + + +## Transactions + +Transactions are comprised of metadata held in [contexts](02-context.md) and [`sdk.Msg`s](/../build/building-modules/02-messages-and-queries.md) that trigger state changes within a module through the module's Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md). + +When users want to interact with an application and make state changes (e.g. sending coins), they create transactions. Each of a transaction's `sdk.Msg` must be signed using the private key associated with the appropriate account(s), before the transaction is broadcasted to the network. A transaction must then be included in a block, validated, and approved by the network through the consensus process. To read more about the lifecycle of a transaction, click [here](/beginner/01-tx-lifecycle.md). + +## Type Definition + +Transaction objects are Cosmos SDK types that implement the `Tx` interface + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/tx_msg.go#L53-L58 +``` + +It contains the following methods: + +* **GetMsgs:** unwraps the transaction and returns a list of contained `sdk.Msg`s - one transaction may have one or multiple messages, which are defined by module developers. + +As a developer, you should rarely manipulate `Tx` directly, as `Tx` is an intermediate type used for transaction generation. Instead, developers should prefer the `TxBuilder` interface, which you can learn more about [below](#transaction-generation). + +### Signing Transactions + +Every message in a transaction must be signed by the addresses specified by its `GetSigners`. The Cosmos SDK currently allows signing transactions in two different ways. + +#### `SIGN_MODE_DIRECT` (preferred) + +The most used implementation of the `Tx` interface is the Protobuf `Tx` message, which is used in `SIGN_MODE_DIRECT`: + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/v1beta1/tx.proto#L15-L28 +``` + +Because Protobuf serialization is not deterministic, the Cosmos SDK uses an additional `TxRaw` type to denote the pinned bytes over which a transaction is signed. Any user can generate a valid `body` and `auth_info` for a transaction, and serialize these two messages using Protobuf. `TxRaw` then pins the user's exact binary representation of `body` and `auth_info`, called respectively `body_bytes` and `auth_info_bytes`. The document that is signed by all signers of the transaction is `SignDoc` (deterministically serialized using [ADR-027](/../build/architecture/adr-027-deterministic-protobuf-serialization.md)): + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/v1beta1/tx.proto#L50-L67 +``` + +Once signed by all signers, the `body_bytes`, `auth_info_bytes` and `signatures` are gathered into `TxRaw`, whose serialized bytes are broadcasted over the network. + +#### `SIGN_MODE_LEGACY_AMINO_JSON` + +The legacy implementation of the `Tx` interface is the `StdTx` struct from `x/auth`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/migrations/legacytx/stdtx.go#L82-L89 +``` + +The document signed by all signers is `StdSignDoc`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/migrations/legacytx/stdsign.go#L30-L43 +``` + +which is encoded into bytes using Amino JSON. Once all signatures are gathered into `StdTx`, `StdTx` is serialized using Amino JSON, and these bytes are broadcasted over the network. + +#### Other Sign Modes + +The Cosmos SDK also provides a couple of other sign modes for particular use cases. + +#### `SIGN_MODE_DIRECT_AUX` + +`SIGN_MODE_DIRECT_AUX` is a sign mode released in the Cosmos SDK v0.46 which targets transactions with multiple signers. Whereas `SIGN_MODE_DIRECT` expects each signer to sign over both `TxBody` and `AuthInfo` (which includes all other signers' signer infos, i.e. their account sequence, public key and mode info), `SIGN_MODE_DIRECT_AUX` allows N-1 signers to only sign over `TxBody` and *their own* signer info. Moreover, each auxiliary signer (i.e. a signer using `SIGN_MODE_DIRECT_AUX`) doesn't +need to sign over the fees: + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/v1beta1/tx.proto#L68-L93 +``` + +The use case is a multi-signer transaction, where one of the signers is appointed to gather all signatures, broadcast the signature and pay for fees, and the others only care about the transaction body. This generally allows for a better multi-signing UX. If Alice, Bob and Charlie are part of a 3-signer transaction, then Alice and Bob can both use `SIGN_MODE_DIRECT_AUX` to sign over the `TxBody` and their own signer info (no need an additional step to gather other signers' ones, like in `SIGN_MODE_DIRECT`), without specifying a fee in their SignDoc. Charlie can then gather both signatures from Alice and Bob, and +create the final transaction by appending a fee. Note that the fee payer of the transaction (in our case Charlie) must sign over the fees, so must use `SIGN_MODE_DIRECT` or `SIGN_MODE_LEGACY_AMINO_JSON`. + +#### `SIGN_MODE_TEXTUAL` + +`SIGN_MODE_TEXTUAL` is a new sign mode for delivering a better signing experience on hardware wallets and it is included in the v0.50 release. In this mode, the signer signs over the human-readable string representation of the transaction (CBOR) and makes all data being displayed easier to read. The data is formatted as screens, and each screen is meant to be displayed in its entirety even on small devices like the Ledger Nano. + +There are also *expert* screens, which will only be displayed if the user has chosen that option in its hardware device. These screens contain things like account number, account sequence and the sign data hash. + +Data is formatted using a set of `ValueRenderer` which the SDK provides defaults for all the known messages and value types. Chain developers can also opt to implement their own `ValueRenderer` for a type/message if they'd like to display information differently. + +If you wish to learn more, please refer to [ADR-050](/../build/architecture/adr-050-sign-mode-textual.md). + +#### Custom Sign modes + +There is an opportunity to add your own custom sign mode to the Cosmos-SDK. While we can not accept the implementation of the sign mode to the repository, we can accept a pull request to add the custom signmode to the SignMode enum located [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/signing/v1beta1/signing.proto#L17) + +## Transaction Process + +The process of an end-user sending a transaction is: + +* decide on the messages to put into the transaction, +* generate the transaction using the Cosmos SDK's `TxBuilder`, +* broadcast the transaction using one of the available interfaces. + +The next paragraphs will describe each of these components, in this order. + +### Messages + + +Module `sdk.Msg`s are not to be confused with [ABCI Messages](https://docs.cometbft.com/v0.37/spec/abci/) which define interactions between the CometBFT and application layers. + + +**Messages** (or `sdk.Msg`s) are module-specific objects that trigger state transitions within the scope of the module they belong to. Module developers define the messages for their module by adding methods to the Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md), and also implement the corresponding `MsgServer`. + +Each `sdk.Msg`s is related to exactly one Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md) RPC, defined inside each module's `tx.proto` file. A SDK app router automatically maps every `sdk.Msg` to a corresponding RPC. Protobuf generates a `MsgServer` interface for each module `Msg` service, and the module developer needs to implement this interface. +This design puts more responsibility on module developers, allowing application developers to reuse common functionalities without having to implement state transition logic repetitively. + +To learn more about Protobuf `Msg` services and how to implement `MsgServer`, click [here](/../build/building-modules/03-msg-services.md). + +While messages contain the information for state transition logic, a transaction's other metadata and relevant information are stored in the `TxBuilder` and `Context`. + +### Transaction Generation + +The `TxBuilder` interface contains data closely related with the generation of transactions, which an end-user can set to generate the desired transaction: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/tx_config.go#L39-L57 +``` + +* `Msg`s, the array of [messages](#messages) included in the transaction. +* `GasLimit`, option chosen by the users for how to calculate how much gas they will need to pay. +* `Memo`, a note or comment to send with the transaction. +* `FeeAmount`, the maximum amount the user is willing to pay in fees. +* `TimeoutHeight`, block height until which the transaction is valid. +* `Unordered`, an option indicating this transaction may be executed in any order (requires Sequence to be unset.) +* `TimeoutTimestamp`, the timeout timestamp (unordered nonce) of the transaction (required to be used with Unordered). +* `Signatures`, the array of signatures from all signers of the transaction. + +As there are currently two sign modes for signing transactions, there are also two implementations of `TxBuilder`: + +* [wrapper](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/tx/builder.go#L27-L44) for creating transactions for `SIGN_MODE_DIRECT`, +* [StdTxBuilder](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/migrations/legacytx/stdtx_builder.go#L14-L17) for `SIGN_MODE_LEGACY_AMINO_JSON`. + +However, the two implementations of `TxBuilder` should be hidden away from end-users, as they should prefer using the overarching `TxConfig` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/tx_config.go#L27-L37 +``` + +`TxConfig` is an app-wide configuration for managing transactions. Most importantly, it holds the information about whether to sign each transaction with `SIGN_MODE_DIRECT` or `SIGN_MODE_LEGACY_AMINO_JSON`. By calling `txBuilder := txConfig.NewTxBuilder()`, a new `TxBuilder` will be created with the appropriate sign mode. + +Once `TxBuilder` is correctly populated with the setters exposed above, `TxConfig` will also take care of correctly encoding the bytes (again, either using `SIGN_MODE_DIRECT` or `SIGN_MODE_LEGACY_AMINO_JSON`). Here's a pseudo-code snippet of how to generate and encode a transaction, using the `TxEncoder()` method: + +```go +txBuilder := txConfig.NewTxBuilder() + +txBuilder.SetMsgs(...) // and other setters on txBuilder + +bz, err := txConfig.TxEncoder()(txBuilder.GetTx()) +// bz are bytes to be broadcasted over the network +``` + +### Broadcasting the Transaction + +Once the transaction bytes are generated, there are currently three ways of broadcasting it. + +#### CLI + +Application developers create entry points to the application by creating a [command-line interface](07-cli.md), [gRPC and/or REST interface](06-grpc_rest.md), typically found in the application's `./cmd` folder. These interfaces allow users to interact with the application through command-line. + +For the [command-line interface](/../build/building-modules/09-module-interfaces.md#cli), module developers create subcommands to add as children to the application top-level transaction command `TxCmd`. CLI commands actually bundle all the steps of transaction processing into one simple command: creating messages, generating transactions and broadcasting. For concrete examples, see the [Interacting with a Node](/../user/run-node/02-interact-node.md) section. An example transaction made using CLI looks like: + +```bash +simd tx send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake +``` + +#### gRPC + +[gRPC](https://grpc.io) is the main component for the Cosmos SDK's RPC layer. Its principal usage is in the context of modules' [`Query` services](/../build/building-modules/04-query-services.md). However, the Cosmos SDK also exposes a few other module-agnostic gRPC services, one of them being the `Tx` service: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/v1beta1/service.proto +``` + +The `Tx` service exposes a handful of utility functions, such as simulating a transaction or querying a transaction, and also one method to broadcast transactions. + +Examples of broadcasting and simulating a transaction are shown [here](/../user/run-node/03-txs.md#programmatically-with-go). + +#### REST + +Each gRPC method has its corresponding REST endpoint, generated using [gRPC-gateway](https://github.com/grpc-ecosystem/grpc-gateway). Therefore, instead of using gRPC, you can also use HTTP to broadcast the same transaction, on the `POST /cosmos/tx/v1beta1/txs` endpoint. + +An example can be seen [here](/../user/run-node/03-txs.md#using-rest) + +#### CometBFT RPC + +The three methods presented above are actually higher abstractions over the CometBFT RPC `/broadcast_tx_{async,sync,commit}` endpoints, documented [here](https://docs.cometbft.com/v0.37/core/rpc). This means that you can use the CometBFT RPC endpoints directly to broadcast the transaction, if you wish so. + +### Unordered Transactions + + + +Looking to enable unordered transactions on your chain? +Check out the [v0.53.0 Upgrade Guide](https://docs.cosmos.network/v0.53/build/migrations/upgrade-guide#enable-unordered-transactions-optional) + + + + + +Unordered transactions MUST leave sequence values unset. When a transaction is both unordered and contains a non-zero sequence value, +the transaction will be rejected. Services that operate on prior assumptions about transaction sequence values should be updated to handle unordered transactions. +Services should be aware that when the transaction is unordered, the transaction sequence will always be zero. + + + +Beginning with Cosmos SDK v0.53.0, chains may enable unordered transaction support. +Unordered transactions work by using a timestamp as the transaction's nonce value. The sequence value must NOT be set in the signature(s) of the transaction. +The timestamp must be greater than the current block time and not exceed the chain's configured max unordered timeout timestamp duration. +Senders must use a unique timestamp for each distinct transaction. The difference may be as small as a nanosecond, however. + +These unique timestamps serve as a one-shot nonce, and their lifespan in state is short-lived. +Upon transaction inclusion, an entry consisting of timeout timestamp and account address will be recorded to state. +Once the block time is passed the timeout timestamp value, the entry will be removed. This ensures that unordered nonces do not indefinitely fill up the chain's storage. diff --git a/docs/sdk/next/learn/advanced/upgrade.mdx b/docs/sdk/next/learn/advanced/upgrade.mdx new file mode 100644 index 00000000..6654db20 --- /dev/null +++ b/docs/sdk/next/learn/advanced/upgrade.mdx @@ -0,0 +1,163 @@ +--- +title: In-Place Store Migrations +--- + +Read and understand all the in-place store migration documentation before you run a migration on a live chain. + + + +**Synopsis** +Upgrade your app modules smoothly with custom in-place store migration logic. + + +The Cosmos SDK uses two methods to perform upgrades: + +* Exporting the entire application state to a JSON file using the `export` CLI command, making changes, and then starting a new binary with the changed JSON file as the genesis file. + +* Perform upgrades in place, which significantly decrease the upgrade time for chains with a larger state. Use the [Module Upgrade Guide](/../build/building-modules/13-upgrade.md) to set up your application modules to take advantage of in-place upgrades. + +This document provides steps to use the In-Place Store Migrations upgrade method. + +## Tracking Module Versions + +Each module gets assigned a consensus version by the module developer. The consensus version serves as the breaking change version of the module. The Cosmos SDK keeps track of all module consensus versions in the x/upgrade `VersionMap` store. During an upgrade, the difference between the old `VersionMap` stored in state and the new `VersionMap` is calculated by the Cosmos SDK. For each identified difference, the module-specific migrations are run and the respective consensus version of each upgraded module is incremented. + +### Consensus Version + +The consensus version is defined on each app module by the module developer and serves as the breaking change version of the module. The consensus version informs the Cosmos SDK on which modules need to be upgraded. For example, if the bank module was version 2 and an upgrade introduces bank module 3, the Cosmos SDK upgrades the bank module and runs the "version 2 to 3" migration script. + +### Version Map + +The version map is a mapping of module names to consensus versions. The map is persisted to x/upgrade's state for use during in-place migrations. When migrations finish, the updated version map is persisted in the state. + +## Upgrade Handlers + +Upgrades use an `UpgradeHandler` to facilitate migrations. The `UpgradeHandler` functions implemented by the app developer must conform to the following function signature. These functions retrieve the `VersionMap` from x/upgrade's state and return the new `VersionMap` to be stored in x/upgrade after the upgrade. The diff between the two `VersionMap`s determines which modules need upgrading. + +```go +type UpgradeHandler func(ctx sdk.Context, plan Plan, fromVM VersionMap) (VersionMap, error) +``` + +Inside these functions, you must perform any upgrade logic to include in the provided `plan`. All upgrade handler functions must end with the following line of code: + +```go +return app.mm.RunMigrations(ctx, cfg, fromVM) +``` + +## Running Migrations + +Migrations are run inside of an `UpgradeHandler` using `app.mm.RunMigrations(ctx, cfg, vm)`. The `UpgradeHandler` functions describe the functionality to occur during an upgrade. The `RunMigration` function loops through the `VersionMap` argument and runs the migration scripts for all versions that are less than the versions of the new binary app module. After the migrations are finished, a new `VersionMap` is returned to persist the upgraded module versions to state. + +```go +cfg := module.NewConfigurator(...) + +app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + + // ... + // additional upgrade logic + // ... + + // returns a VersionMap with the updated module ConsensusVersions + return app.mm.RunMigrations(ctx, fromVM) +}) +``` + +To learn more about configuring migration scripts for your modules, see the [Module Upgrade Guide](/../build/building-modules/13-upgrade.md). + +### Order Of Migrations + +By default, all migrations are run in module name alphabetical ascending order, except `x/auth` which is run last. The reason is state dependencies between x/auth and other modules (you can read more in [issue #10606](https://github.com/cosmos/cosmos-sdk/issues/10606)). + +If you want to change the order of migration, then you should call `app.mm.SetOrderMigrations(module1, module2, ...)` in your app.go file. The function will panic if you forget to include a module in the argument list. + +## Adding New Modules During Upgrades + +You can introduce entirely new modules to the application during an upgrade. New modules are recognized because they have not yet been registered in `x/upgrade`'s `VersionMap` store. In this case, `RunMigrations` calls the `InitGenesis` function from the corresponding module to set up its initial state. + +### Add StoreUpgrades for New Modules + +All chains preparing to run in-place store migrations will need to manually add store upgrades for new modules and then configure the store loader to apply those upgrades. This ensures that the new module's stores are added to the multistore before the migrations begin. + +```go expandable +upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { + panic(err) +} + if upgradeInfo.Name == "my-plan" && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + storeUpgrades := storetypes.StoreUpgrades{ + // add store upgrades for new modules + // Example: + // Added: []string{"foo", "bar" +}, + // ... +} + + // configure store loader that checks if version == upgradeHeight and applies store upgrades + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) +} +``` + +## Genesis State + +When starting a new chain, the consensus version of each module MUST be saved to state during the application's genesis. To save the consensus version, add the following line to the `InitChainer` method in `app.go`: + +```diff +func (app *MyApp) InitChainer(ctx sdk.Context, req abci.InitChainRequest) abci.InitChainResponse { + ... ++ app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) + ... +} +``` + +This information is used by the Cosmos SDK to detect when modules with newer versions are introduced to the app. + +For a new module `foo`, `InitGenesis` is called by `RunMigration` only when `foo` is registered in the module manager but it's not set in the `fromVM`. Therefore, if you want to skip `InitGenesis` when a new module is added to the app, then you should set its module version in `fromVM` to the module consensus version: + +```go +app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // ... + + // Set foo's version to the latest ConsensusVersion in the VersionMap. + // This will skip running InitGenesis on Foo + fromVM[foo.ModuleName] = foo.AppModule{ +}.ConsensusVersion() + +return app.mm.RunMigrations(ctx, fromVM) +}) +``` + +### Overwriting Genesis Functions + +The Cosmos SDK offers modules that the application developer can import in their app. These modules often have an `InitGenesis` function already defined. + +You can write your own `InitGenesis` function for an imported module. To do this, manually trigger your custom genesis function in the upgrade handler. + + +You MUST manually set the consensus version in the version map passed to the `UpgradeHandler` function. Without this, the SDK will run the Module's existing `InitGenesis` code even if you triggered your custom function in the `UpgradeHandler`. + + +```go expandable +import foo "github.com/my/module/foo" + +app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + + // Register the consensus version in the version map + // to avoid the SDK from triggering the default + // InitGenesis function. + fromVM["foo"] = foo.AppModule{ +}.ConsensusVersion() + + // Run custom InitGenesis for foo + app.mm["foo"].InitGenesis(ctx, app.appCodec, myCustomGenesisState) + +return app.mm.RunMigrations(ctx, cfg, fromVM) +}) +``` + +## Syncing a Full Node to an Upgraded Blockchain + +You can sync a full node to an existing blockchain which has been upgraded using Cosmovisor + +To successfully sync, you must start with the initial binary that the blockchain started with at genesis. If all Software Upgrade Plans contain binary instruction, then you can run Cosmovisor with auto-download option to automatically handle downloading and switching to the binaries associated with each sequential upgrade. Otherwise, you need to manually provide all binaries to Cosmovisor. + +To learn more about Cosmovisor, see the [Cosmovisor Quick Start](/../../../tools/cosmovisor/README.md). diff --git a/docs/sdk/next/learn/beginner/accounts.mdx b/docs/sdk/next/learn/beginner/accounts.mdx new file mode 100644 index 00000000..8290a9a1 --- /dev/null +++ b/docs/sdk/next/learn/beginner/accounts.mdx @@ -0,0 +1,305 @@ +--- +title: Accounts +--- + +**Synopsis** +This document describes the in-built account and public key system of the Cosmos SDK. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](00-app-anatomy.md) + + + +## Account Definition + +In the Cosmos SDK, an *account* designates a pair of *public key* `PubKey` and *private key* `PrivKey`. The `PubKey` can be derived to generate various `Addresses`, which are used to identify users (among other parties) in the application. `Addresses` are also associated with [`message`s](/../build/building-modules/02-messages-and-queries.md#messages) to identify the sender of the `message`. The `PrivKey` is used to generate [digital signatures](#signatures) to prove that an `Address` associated with the `PrivKey` approved of a given `message`. + +For HD key derivation the Cosmos SDK uses a standard called [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). The BIP32 allows users to create an HD wallet (as specified in [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)) - a set of accounts derived from an initial secret seed. A seed is usually created from a 12- or 24-word mnemonic. A single seed can derive any number of `PrivKey`s using a one-way cryptographic function. Then, a `PubKey` can be derived from the `PrivKey`. Naturally, the mnemonic is the most sensitive information, as private keys can always be re-generated if the mnemonic is preserved. + +```text expandable + Account 0 Account 1 Account 2 + ++------------------+ +------------------+ +------------------+ +| | | | | | +| Address 0 | | Address 1 | | Address 2 | +| ^ | | ^ | | ^ | +| | | | | | | | | +| | | | | | | | | +| | | | | | | | | +| + | | + | | + | +| Public key 0 | | Public key 1 | | Public key 2 | +| ^ | | ^ | | ^ | +| | | | | | | | | +| | | | | | | | | +| | | | | | | | | +| + | | + | | + | +| Private key 0 | | Private key 1 | | Private key 2 | +| ^ | | ^ | | ^ | ++------------------+ +------------------+ +------------------+ + | | | + | | | + | | | + +--------------------------------------------------------------------+ + | + | + +---------+---------+ + | | + | Master PrivKey | + | | + +-------------------+ + | + | + +---------+---------+ + | | + | Mnemonic (Seed) | + | | + +-------------------+ +``` + +In the Cosmos SDK, keys are stored and managed by using an object called a [`Keyring`](#keyring). + +## Keys, accounts, addresses, and signatures + +The principal way of authenticating a user is done using [digital signatures](https://en.wikipedia.org/wiki/Digital_signature). Users sign transactions using their own private key. Signature verification is done with the associated public key. For on-chain signature verification purposes, we store the public key in an `Account` object (alongside other data required for a proper transaction validation). + +In the node, all data is stored using Protocol Buffers serialization. + +The Cosmos SDK supports the following digital key schemes for creating digital signatures: + +* `secp256k1`, as implemented in the [Cosmos SDK's `crypto/keys/secp256k1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/secp256k1/secp256k1.go). +* `secp256r1`, as implemented in the [Cosmos SDK's `crypto/keys/secp256r1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/secp256r1/pubkey.go). +* `tm-ed25519`, as implemented in the [Cosmos SDK `crypto/keys/ed25519` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/ed25519/ed25519.go). This scheme is supported only for the consensus validation. + +| | Address length in bytes | Public key length in bytes | Used for transaction authentication | Used for consensus (cometbft) | +| :----------: | :---------------------: | :------------------------: | :---------------------------------: | :-----------------------------: | +| `secp256k1` | 20 | 33 | yes | no | +| `secp256r1` | 32 | 33 | yes | no | +| `tm-ed25519` | -- not used -- | 32 | no | yes | + +## Addresses + +`Addresses` and `PubKey`s are both public information that identifies actors in the application. `Account` is used to store authentication information. The basic account implementation is provided by a `BaseAccount` object. + +Each account is identified using `Address` which is a sequence of bytes derived from a public key. In the Cosmos SDK, we define 3 types of addresses that specify a context where an account is used: + +* `AccAddress` identifies users (the sender of a `message`). +* `ValAddress` identifies validator operators. +* `ConsAddress` identifies validator nodes that are participating in consensus. Validator nodes are derived using the **`ed25519`** curve. + +These types implement the `Address` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/address.go#L126-L134 +``` + +Address construction algorithm is defined in [ADR-28](https://github.com/cosmos/cosmos-sdk/blob/main/docs/sdk/next/architecture/adr-028-public-key-addresses.md). +Here is the standard way to obtain an account address from a `pub` public key: + +```go +sdk.AccAddress(pub.Address().Bytes()) +``` + +Of note, the `Marshal()` and `Bytes()` method both return the same raw `[]byte` form of the address. `Marshal()` is required for Protobuf compatibility. + +For user interaction, addresses are formatted using [Bech32](https://en.bitcoin.it/wiki/Bech32) and implemented by the `String` method. The Bech32 method is the only supported format to use when interacting with a blockchain. The Bech32 human-readable part (Bech32 prefix) is used to denote an address type. Example: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/address.go#L299-L316 +``` + +| | Address Bech32 Prefix | +| ------------------ | --------------------- | +| Accounts | cosmos | +| Validator Operator | cosmosvaloper | +| Consensus Nodes | cosmosvalcons | + +### Public Keys + +Public keys in Cosmos SDK are defined by `cryptotypes.PubKey` interface. Since public keys are saved in a store, `cryptotypes.PubKey` extends the `proto.Message` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/types/types.go#L8-L17 +``` + +A compressed format is used for `secp256k1` and `secp256r1` serialization. + +* The first byte is a `0x02` byte if the `y`-coordinate is the lexicographically largest of the two associated with the `x`-coordinate. +* Otherwise the first byte is a `0x03`. + +This prefix is followed by the `x`-coordinate. + +Public Keys are not used to reference accounts (or users) and in general are not used when composing transaction messages (with few exceptions: `MsgCreateValidator`, `Validator` and `Multisig` messages). +For user interactions, `PubKey` is formatted using Protobufs JSON ([ProtoMarshalJSON](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/codec/json.go#L14-L34) function). Example: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/keys/output.go#L23-L39 +``` + +## Keyring + +A `Keyring` is an object that stores and manages accounts. In the Cosmos SDK, a `Keyring` implementation follows the `Keyring` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keyring/keyring.go#L58-L106 +``` + +The default implementation of `Keyring` comes from the third-party [`99designs/keyring`](https://github.com/99designs/keyring) library. + +A few notes on the `Keyring` methods: + +* `Sign(uid string, msg []byte) ([]byte, types.PubKey, error)` strictly deals with the signature of the `msg` bytes. You must prepare and encode the transaction into a canonical `[]byte` form. Because protobuf is not deterministic, it has been decided in [ADR-020](/../build/architecture/adr-020-protobuf-transaction-encoding.md) that the canonical `payload` to sign is the `SignDoc` struct, deterministically encoded using [ADR-027](/../build/architecture/adr-027-deterministic-protobuf-serialization.md). Note that signature verification is not implemented in the Cosmos SDK by default, it is deferred to the [`anteHandler`](/advanced/00-baseapp.md#antehandler). + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/v1beta1/tx.proto#L50-L67 +``` + +* `NewAccount(uid, mnemonic, bip39Passphrase, hdPath string, algo SignatureAlgo) (*Record, error)` creates a new account based on the [`bip44 path`](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) and persists it on disk. The `PrivKey` is **never stored unencrypted**, instead it is [encrypted with a passphrase](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/armor.go) before being persisted. In the context of this method, the key type and sequence number refer to the segment of the BIP44 derivation path (for example, `0`, `1`, `2`, ...) that is used to derive a private and a public key from the mnemonic. Using the same mnemonic and derivation path, the same `PrivKey`, `PubKey` and `Address` is generated. The following keys are supported by the keyring: + +* `secp256k1` + +* `ed25519` + +* `ExportPrivKeyArmor(uid, encryptPassphrase string) (armor string, err error)` exports a private key in ASCII-armored encrypted format using the given passphrase. You can then either import the private key again into the keyring using the `ImportPrivKey(uid, armor, passphrase string)` function or decrypt it into a raw private key using the `UnarmorDecryptPrivKey(armorStr string, passphrase string)` function. + +### Create New Key Type + +To create a new key type for using in keyring, `keyring.SignatureAlgo` interface must be fulfilled. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keyring/signing_algorithms.go#L11-L16 +``` + +The interface consists of three methods where `Name()` returns the name of the algorithm as a `hd.PubKeyType` and `Derive()` and `Generate()` must return the following functions respectively: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/hd/algo.go#L28-L31 +``` + +Once the `keyring.SignatureAlgo` has been implemented it must be added to the [list of supported algos](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keyring/keyring.go#L209) of the keyring. + +For simplicity the implementation of a new key type should be done inside the `crypto/hd` package. +There is an example of a working `secp256k1` implementation in [algo.go](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/hd/algo.go#L38). + +#### Implementing secp256r1 algo + +Here is an example of how secp256r1 could be implemented. + +First a new function to create a private key from a secret number is needed in the secp256r1 package. This function could look like this: + +```go expandable +// cosmos-sdk/crypto/keys/secp256r1/privkey.go + +// NewPrivKeyFromSecret creates a private key derived for the secret number +// represented in big-endian. The `secret` must be a valid ECDSA field element. +func NewPrivKeyFromSecret(secret []byte) (*PrivKey, error) { + var d = new(big.Int).SetBytes(secret) + if d.Cmp(secp256r1.Params().N) >= 1 { + return nil, errorsmod.Wrap(errors.ErrInvalidRequest, "secret not in the curve base field") +} + sk := new(ecdsa.PrivKey) + +return &PrivKey{&ecdsaSK{*sk +}}, nil +} +``` + +After that `secp256r1Algo` can be implemented. + +```go expandable +// cosmos-sdk/crypto/hd/secp256r1Algo.go + +package hd + +import ( + + "github.com/cosmos/go-bip39" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1" + "github.com/cosmos/cosmos-sdk/crypto/types" +) + +// Secp256r1Type uses the secp256r1 ECDSA parameters. +const Secp256r1Type = PubKeyType("secp256r1") + +var Secp256r1 = secp256r1Algo{ +} + +type secp256r1Algo struct{ +} + +func (s secp256r1Algo) + +Name() + +PubKeyType { + return Secp256r1Type +} + +// Derive derives and returns the secp256r1 private key for the given seed and HD path. +func (s secp256r1Algo) + +Derive() + +DeriveFn { + return func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) { + seed, err := bip39.NewSeedWithErrorChecking(mnemonic, bip39Passphrase) + if err != nil { + return nil, err +} + +masterPriv, ch := ComputeMastersFromSeed(seed) + if len(hdPath) == 0 { + return masterPriv[:], nil +} + +derivedKey, err := DerivePrivateKeyForPath(masterPriv, ch, hdPath) + +return derivedKey, err +} +} + +// Generate generates a secp256r1 private key from the given bytes. +func (s secp256r1Algo) + +Generate() + +GenerateFn { + return func(bz []byte) + +types.PrivKey { + key, err := secp256r1.NewPrivKeyFromSecret(bz) + if err != nil { + panic(err) +} + +return key +} +} +``` + +Finally, the algo must be added to the list of [supported algos](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keyring/keyring.go#L209) by the keyring. + +```go +// cosmos-sdk/crypto/keyring/keyring.go + +func newKeystore(kr keyring.Keyring, cdc codec.Codec, backend string, opts ...Option) + +keystore { + // Default options for keybase, these can be overwritten using the + // Option function + options := Options{ + SupportedAlgos: SigningAlgoList{ + hd.Secp256k1, hd.Secp256r1 +}, // added here + SupportedAlgosLedger: SigningAlgoList{ + hd.Secp256k1 +}, +} +... +``` + +Hereafter to create new keys using your algo, you must specify it with the flag `--algo` : + +`simd keys add myKey --algo secp256r1` diff --git a/docs/sdk/next/learn/beginner/app-anatomy.mdx b/docs/sdk/next/learn/beginner/app-anatomy.mdx new file mode 100644 index 00000000..87b69b37 --- /dev/null +++ b/docs/sdk/next/learn/beginner/app-anatomy.mdx @@ -0,0 +1,277 @@ +--- +title: Anatomy of a Cosmos SDK Application +--- + +**Synopsis** +This document describes the core parts of a Cosmos SDK application, represented throughout the document as a placeholder application named `app`. + + +## Node Client + +The Daemon, or [Full-Node Client](/advanced/03-node.md), is the core process of a Cosmos SDK-based blockchain. Participants in the network run this process to initialize their state-machine, connect with other full-nodes, and update their state-machine as new blocks come in. + +```text expandable + ^ +-------------------------------+ ^ + | | | | + | | State-machine = Application | | + | | | | Built with Cosmos SDK + | | ^ + | | + | +----------- | ABCI | ----------+ v + | | + v | ^ + | | | | +Blockchain Node | | Consensus | | + | | | | + | +-------------------------------+ | CometBFT + | | | | + | | Networking | | + | | | | + v +-------------------------------+ v +``` + +The blockchain full-node presents itself as a binary, generally suffixed by `-d` for "daemon" (e.g. `appd` for `app` or `gaiad` for `gaia`). This binary is built by running a simple [`main.go`](/advanced/03-node.md#main-function) function placed in `./cmd/appd/`. This operation usually happens through the [Makefile](#dependencies-and-makefile). + +Once the main binary is built, the node can be started by running the [`start` command](/advanced/03-node.md#start-command). This command function primarily does three things: + +1. Create an instance of the state-machine defined in [`app.go`](#core-application-file). +2. Initialize the state-machine with the latest known state, extracted from the `db` stored in the `~/.app/data` folder. At this point, the state-machine is at height `appBlockHeight`. +3. Create and start a new CometBFT instance. Among other things, the node performs a handshake with its peers. It gets the latest `blockHeight` from them and replays blocks to sync to this height if it is greater than the local `appBlockHeight`. The node starts from genesis and CometBFT sends an `InitChain` message via the ABCI to the `app`, which triggers the [`InitChainer`](#initchainer). + + +When starting a CometBFT instance, the genesis file is the `0` height and the state within the genesis file is committed at block height `1`. When querying the state of the node, querying block height 0 will return an error. + + +## Core Application File + +In general, the core of the state-machine is defined in a file called `app.go`. This file mainly contains the **type definition of the application** and functions to **create and initialize it**. + +### Type Definition of the Application + +The first thing defined in `app.go` is the `type` of the application. It is generally comprised of the following parts: + +* **Embedding [runtime.App](/../build/building-apps/00-runtime.md)** The runtime package manages the application's core components and modules through dependency injection. It provides declarative configuration for module management, state storage, and ABCI handling. + * `Runtime` wraps `BaseApp`, meaning when a transaction is relayed by CometBFT to the application, `app` uses `runtime`'s methods to route them to the appropriate module. `BaseApp` implements all the [ABCI methods](https://docs.cometbft.com/v0.38/spec/abci/) and the [routing logic](/advanced/00-baseapp.md#service-routers). + * It automatically configures the **[module manager](/../build/building-modules/01-module-manager.md#manager)** based on the app wiring configuration. The module manager facilitates operations related to these modules, like registering their [`Msg` service](/../build/building-modules/03-msg-services.md) and [gRPC `Query` service](#grpc-query-services), or setting the order of execution between modules for various functions like [`InitChainer`](#initchainer), [`PreBlocker`](#preblocker) and [`BeginBlocker` and `EndBlocker`](#beginblocker-and-endblocker). +* [**An App Wiring configuration file**](/../build/building-apps/00-runtime.md) The app wiring configuration file contains the list of application's modules that `runtime` must instantiate. The instantiation of the modules is done using `depinject`. It also contains the order in which all modules' `InitGenesis` and `Pre/Begin/EndBlocker` methods should be executed. +* **A reference to an [`appCodec`](/advanced/05-encoding.md).** The application's `appCodec` is used to serialize and deserialize data structures in order to store them, as stores can only persist `[]bytes`. The default codec is [Protocol Buffers](/advanced/05-encoding.md). +* **A reference to a [`legacyAmino`](/advanced/05-encoding.md) codec.** Some parts of the Cosmos SDK have not been migrated to use the `appCodec` above, and are still hardcoded to use Amino. Other parts explicitly use Amino for backwards compatibility. For these reasons, the application still holds a reference to the legacy Amino codec. Please note that the Amino codec will be removed from the SDK in the upcoming releases. + +See an example of application type definition from `simapp`, the Cosmos SDK's own app used for demo and testing purposes: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app_di.go#L57-L90 +``` + +### Constructor Function + +Also defined in `app.go` is the constructor function, which constructs a new application of the type defined in the preceding section. The function must fulfill the `AppCreator` signature in order to be used in the [`start` command](/advanced/03-node.md#start-command) of the application's daemon command. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/types/app.go#L67-L69 +``` + +Here are the main actions performed by this function: + +* Instantiate a new [`codec`](/advanced/05-encoding.md) and initialize the `codec` of each of the application's modules using the [basic manager](/../build/building-modules/01-module-manager.md#basicmanager). +* Instantiate a new application with a reference to a `baseapp` instance, a codec, and all the appropriate store keys. +* Instantiate all the [`keeper`](#keeper) objects defined in the application's `type` using the `NewKeeper` function of each of the application's modules. Note that keepers must be instantiated in the correct order, as the `NewKeeper` of one module might require a reference to another module's `keeper`. +* Instantiate the application's [module manager](/../build/building-modules/01-module-manager.md#manager) with the [`AppModule`](#application-module-interface) object of each of the application's modules. +* With the module manager, initialize the application's [`Msg` services](/advanced/00-baseapp.md#msg-services), [gRPC `Query` services](/advanced/00-baseapp.md#grpc-query-services), [legacy `Msg` routes](/advanced/00-baseapp.md#routing), and [legacy query routes](/advanced/00-baseapp.md#query-routing). When a transaction is relayed to the application by CometBFT via the ABCI, it is routed to the appropriate module's [`Msg` service](#msg-services) using the routes defined here. Likewise, when a gRPC query request is received by the application, it is routed to the appropriate module's [`gRPC query service`](#grpc-query-services) using the gRPC routes defined here. The Cosmos SDK still supports legacy `Msg`s and legacy CometBFT queries, which are routed using the legacy `Msg` routes and the legacy query routes, respectively. +* With the module manager, register the [application's modules' invariants](/../build/building-modules/07-invariants.md). Invariants are variables (e.g. total supply of a token) that are evaluated at the end of each block. The process of checking invariants is done via a special module called the [`InvariantsRegistry`](/../build/building-modules/07-invariants.md#invariant-registry). The value of the invariant should be equal to a predicted value defined in the module. Should the value be different than the predicted one, special logic defined in the invariant registry is triggered (usually the chain is halted). This is useful to make sure that no critical bug goes unnoticed, producing long-lasting effects that are hard to fix. +* With the module manager, set the order of execution between the `InitGenesis`, `PreBlocker`, `BeginBlocker`, and `EndBlocker` functions of each of the [application's modules](#application-module-interface). Note that not all modules implement these functions. +* Set the remaining application parameters: + * [`InitChainer`](#initchainer): used to initialize the application when it is first started. + * [`PreBlocker`](#preblocker): called before BeginBlock. + * [`BeginBlocker`, `EndBlocker`](#beginblocker-and-endblocker): called at the beginning and at the end of every block. + * [`anteHandler`](/advanced/00-baseapp.md#antehandler): used to handle fees and signature verification. +* Mount the stores. +* Return the application. + +Note that the constructor function only creates an instance of the app, while the actual state is either carried over from the `~/.app/data` folder if the node is restarted, or generated from the genesis file if the node is started for the first time. + +See an example of application constructor from `simapp`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L190-L708 +``` + +### InitChainer + +The `InitChainer` is a function that initializes the state of the application from a genesis file (i.e. token balances of genesis accounts). It is called when the application receives the `InitChain` message from the CometBFT engine, which happens when the node is started at `appBlockHeight == 0` (i.e. on genesis). The application must set the `InitChainer` in its [constructor](#constructor-function) via the [`SetInitChainer`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetInitChainer) method. + +In general, the `InitChainer` is mostly composed of the [`InitGenesis`](/../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. This is done by calling the `InitGenesis` function of the module manager, which in turn calls the `InitGenesis` function of each of the modules it contains. Note that the order in which the modules' `InitGenesis` functions must be called has to be set in the module manager using the [module manager's](/../build/building-modules/01-module-manager.md) `SetOrderInitGenesis` method. This is done in the [application's constructor](#constructor-function), and the `SetOrderInitGenesis` has to be called before the `SetInitChainer`. + +See an example of an `InitChainer` from `simapp`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L765-L773 +``` + +### PreBlocker + +There are two semantics around the new lifecycle method: + +* It runs before the `BeginBlocker` of all modules +* It can modify consensus parameters in storage, and signal the caller through the return value. + +When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameter in the finalize context: + +```go +app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) +``` + +The new ctx must be passed to all the other lifecycle methods. + +### BeginBlocker and EndBlocker + +The Cosmos SDK offers developers the possibility to implement automatic execution of code as part of their application. This is implemented through two functions called `BeginBlocker` and `EndBlocker`. They are called when the application receives the `FinalizeBlock` messages from the CometBFT consensus engine, which happens respectively at the beginning and at the end of each block. The application must set the `BeginBlocker` and `EndBlocker` in its [constructor](#constructor-function) via the [`SetBeginBlocker`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetBeginBlocker) and [`SetEndBlocker`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetEndBlocker) methods. + +In general, the `BeginBlocker` and `EndBlocker` functions are mostly composed of the [`BeginBlock` and `EndBlock`](/../build/building-modules/06-beginblock-endblock.md) functions of each of the application's modules. This is done by calling the `BeginBlock` and `EndBlock` functions of the module manager, which in turn calls the `BeginBlock` and `EndBlock` functions of each of the modules it contains. Note that the order in which the modules' `BeginBlock` and `EndBlock` functions must be called has to be set in the module manager using the `SetOrderBeginBlockers` and `SetOrderEndBlockers` methods, respectively. This is done via the [module manager](/../build/building-modules/01-module-manager.md) in the [application's constructor](#application-constructor), and the `SetOrderBeginBlockers` and `SetOrderEndBlockers` methods have to be called before the `SetBeginBlocker` and `SetEndBlocker` functions. + +As a sidenote, it is important to remember that application-specific blockchains are deterministic. Developers must be careful not to introduce non-determinism in `BeginBlocker` or `EndBlocker`, and must also be careful not to make them too computationally expensive, as [gas](04-gas-fees.md) does not constrain the cost of `BeginBlocker` and `EndBlocker` execution. + +See an example of `BeginBlocker` and `EndBlocker` functions from `simapp`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L752-L759 +``` + +### Register Codec + +The `EncodingConfig` structure is the last important part of the `app.go` file. The goal of this structure is to define the codecs that will be used throughout the app. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/params/encoding.go#L9-L16 +``` + +Here are descriptions of what each of the four fields means: + +* `InterfaceRegistry`: The `InterfaceRegistry` is used by the Protobuf codec to handle interfaces that are encoded and decoded (we also say "unpacked") using [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto). `Any` could be thought as a struct that contains a `type_url` (name of a concrete type implementing the interface) and a `value` (its encoded bytes). `InterfaceRegistry` provides a mechanism for registering interfaces and implementations that can be safely unpacked from `Any`. Each application module implements the `RegisterInterfaces` method that can be used to register the module's own interfaces and implementations. + * You can read more about `Any` in [ADR-019](/../build/architecture/adr-019-protobuf-state-encoding.md). + * To go more into details, the Cosmos SDK uses an implementation of the Protobuf specification called [`gogoprotobuf`](https://github.com/cosmos/gogoproto). By default, the [gogo protobuf implementation of `Any`](https://pkg.go.dev/github.com/cosmos/gogoproto/types) uses [global type registration](https://github.com/cosmos/gogoproto/blob/master/proto/properties.go#L540) to decode values packed in `Any` into concrete Go types. This introduces a vulnerability where any malicious module in the dependency tree could register a type with the global protobuf registry and cause it to be loaded and unmarshaled by a transaction that referenced it in the `type_url` field. For more information, please refer to [ADR-019](/../build/architecture/adr-019-protobuf-state-encoding.md). +* `Codec`: The default codec used throughout the Cosmos SDK. It is composed of a `BinaryCodec` used to encode and decode state, and a `JSONCodec` used to output data to the users (for example, in the [CLI](#cli)). By default, the SDK uses Protobuf as `Codec`. +* `TxConfig`: `TxConfig` defines an interface a client can utilize to generate an application-defined concrete transaction type. Currently, the SDK handles two transaction types: `SIGN_MODE_DIRECT` (which uses Protobuf binary as over-the-wire encoding) and `SIGN_MODE_LEGACY_AMINO_JSON` (which depends on Amino). Read more about transactions [here](/advanced/01-transactions.md). +* `Amino`: Some legacy parts of the Cosmos SDK still use Amino for backwards-compatibility. Each module exposes a `RegisterLegacyAmino` method to register the module's specific types within Amino. This `Amino` codec should not be used by app developers anymore, and will be removed in future releases. + +An application should create its own encoding config. +See an example of a `simappparams.EncodingConfig` from `simapp`: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/params/encoding.go#L11-L16 +``` + +## Modules + +[Modules](/../build/building-modules/00-intro.md) are the heart and soul of Cosmos SDK applications. They can be considered as state-machines nested within the state-machine. When a transaction is relayed from the underlying CometBFT engine via the ABCI to the application, it is routed by [`baseapp`](/advanced/00-baseapp.md) to the appropriate module in order to be processed. This paradigm enables developers to easily build complex state-machines, as most of the modules they need often already exist. **For developers, most of the work involved in building a Cosmos SDK application revolves around building custom modules required by their application that do not exist yet, and integrating them with modules that do already exist into one coherent application**. In the application directory, the standard practice is to store modules in the `x/` folder (not to be confused with the Cosmos SDK's `x/` folder, which contains already-built modules). + +### Application Module Interface + +Modules must implement [interfaces](/../build/building-modules/01-module-manager.md#application-module-interfaces) defined in the Cosmos SDK, [`AppModuleBasic`](/../build/building-modules/01-module-manager.md#appmodulebasic) and [`AppModule`](/../build/building-modules/01-module-manager.md#appmodule). The former implements basic non-dependent elements of the module, such as the `codec`, while the latter handles the bulk of the module methods (including methods that require references to other modules' `keeper`s). Both the `AppModule` and `AppModuleBasic` types are, by convention, defined in a file called `module.go`. + +`AppModule` exposes a collection of useful methods on the module that facilitates the composition of modules into a coherent application. These methods are called from the [`module manager`](/../build/building-modules/01-module-manager.md#manager), which manages the application's collection of modules. + +### `Msg` Services + +Each application module defines two [Protobuf services](https://developers.google.com/protocol-buffers/docs/sdk/next/proto#services): one `Msg` service to handle messages, and one gRPC `Query` service to handle queries. If we consider the module as a state-machine, then a `Msg` service is a set of state transition RPC methods. +Each Protobuf `Msg` service method is 1:1 related to a Protobuf request type, which must implement `sdk.Msg` interface. +Note that `sdk.Msg`s are bundled in [transactions](/advanced/01-transactions.md), and each transaction contains one or multiple messages. + +When a valid block of transactions is received by the full-node, CometBFT relays each one to the application via [`DeliverTx`](https://docs.cometbft.com/v0.37/spec/abci/abci++_app_requirements#specifics-of-responsedelivertx). Then, the application handles the transaction: + +1. Upon receiving the transaction, the application first unmarshals it from `[]byte`. +2. Then, it verifies a few things about the transaction like [fee payment and signatures](04-gas-fees.md#antehandler) before extracting the `Msg`(s) contained in the transaction. +3. `sdk.Msg`s are encoded using Protobuf [`Any`s](#register-codec). By analyzing each `Any`'s `type_url`, baseapp's `msgServiceRouter` routes the `sdk.Msg` to the corresponding module's `Msg` service. +4. If the message is successfully processed, the state is updated. + +For more details, see [transaction lifecycle](01-tx-lifecycle.md). + +Module developers create custom `Msg` services when they build their own module. The general practice is to define the `Msg` Protobuf service in a `tx.proto` file. For example, the `x/bank` module defines a service with two methods to transfer tokens: + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/bank/v1beta1/tx.proto#L13-L36 +``` + +Service methods use `keeper` in order to update the module state. + +Each module should also implement the `RegisterServices` method as part of the [`AppModule` interface](#application-module-interface). This method should call the `RegisterMsgServer` function provided by the generated Protobuf code. + +### gRPC `Query` Services + +gRPC `Query` services allow users to query the state using [gRPC](https://grpc.io). They are enabled by default, and can be configured under the `grpc.enable` and `grpc.address` fields inside [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). + +gRPC `Query` services are defined in the module's Protobuf definition files, specifically inside `query.proto`. The `query.proto` definition file exposes a single `Query` [Protobuf service](https://developers.google.com/protocol-buffers/docs/sdk/next/proto#services). Each gRPC query endpoint corresponds to a service method, starting with the `rpc` keyword, inside the `Query` service. + +Protobuf generates a `QueryServer` interface for each module, containing all the service methods. A module's [`keeper`](#keeper) then needs to implement this `QueryServer` interface, by providing the concrete implementation of each service method. This concrete implementation is the handler of the corresponding gRPC query endpoint. + +Finally, each module should also implement the `RegisterServices` method as part of the [`AppModule` interface](#application-module-interface). This method should call the `RegisterQueryServer` function provided by the generated Protobuf code. + +### Keeper + +[`Keepers`](/../build/building-modules/06-keeper.md) are the gatekeepers of their module's store(s). To read or write in a module's store, it is mandatory to go through one of its `keeper`'s methods. This is ensured by the [object-capabilities](/advanced/10-ocap.md) model of the Cosmos SDK. Only objects that hold the key to a store can access it, and only the module's `keeper` should hold the key(s) to the module's store(s). + +`Keepers` are generally defined in a file called `keeper.go`. It contains the `keeper`'s type definition and methods. + +The `keeper` type definition generally consists of the following: + +* **Key(s)** to the module's store(s) in the multistore. +* Reference to **other module's `keepers`**. Only needed if the `keeper` needs to access other module's store(s) (either to read or write from them). +* A reference to the application's **codec**. The `keeper` needs it to marshal structs before storing them, or to unmarshal them when it retrieves them, because stores only accept `[]bytes` as value. + +Along with the type definition, the next important component of the `keeper.go` file is the `keeper`'s constructor function, `NewKeeper`. This function instantiates a new `keeper` of the type defined above with a `codec`, stores `keys` and potentially references other modules' `keeper`s as parameters. The `NewKeeper` function is called from the [application's constructor](#constructor-function). The rest of the file defines the `keeper`'s methods, which are primarily getters and setters. + +### Command-Line, gRPC Services and REST Interfaces + +Each module defines command-line commands, gRPC services, and REST routes to be exposed to the end-user via the [application's interfaces](#application-interfaces). This enables end-users to create messages of the types defined in the module, or to query the subset of the state managed by the module. + +#### CLI + +Generally, the [commands related to a module](/../build/building-modules/09-module-interfaces.md#cli) are defined in a folder called `client/cli` in the module's folder. The CLI divides commands into two categories, transactions and queries, defined in `client/cli/tx.go` and `client/cli/query.go`, respectively. Both commands are built on top of the [Cobra Library](https://github.com/spf13/cobra): + +* Transactions commands let users generate new transactions so that they can be included in a block and eventually update the state. One command should be created for each [message type](#message-types) defined in the module. The command calls the constructor of the message with the parameters provided by the end-user, and wraps it into a transaction. The Cosmos SDK handles signing and the addition of other transaction metadata. +* Queries let users query the subset of the state defined by the module. Query commands forward queries to the [application's query router](/advanced/00-baseapp.md#query-routing), which routes them to the appropriate [querier](#querier) the `queryRoute` parameter supplied. + +#### gRPC + +[gRPC](https://grpc.io) is a modern open-source high performance RPC framework that has support in multiple languages. It is the recommended way for external clients (such as wallets, browsers and other backend services) to interact with a node. + +Each module can expose gRPC endpoints called [service methods](https://grpc.io/docs/sdk/next/what-is-grpc/core-concepts/#service-definition), which are defined in the [module's Protobuf `query.proto` file](#grpc-query-services). A service method is defined by its name, input arguments, and output response. The module then needs to perform the following actions: + +* Define a `RegisterGRPCGatewayRoutes` method on `AppModuleBasic` to wire the client gRPC requests to the correct handler inside the module. +* For each service method, define a corresponding handler. The handler implements the core logic necessary to serve the gRPC request, and is located in the `keeper/grpc_query.go` file. + +#### gRPC-gateway REST Endpoints + +Some external clients may not wish to use gRPC. In this case, the Cosmos SDK provides a gRPC gateway service, which exposes each gRPC service as a corresponding REST endpoint. Please refer to the [grpc-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) documentation to learn more. + +The REST endpoints are defined in the Protobuf files, along with the gRPC services, using Protobuf annotations. Modules that want to expose REST queries should add `google.api.http` annotations to their `rpc` methods. By default, all REST endpoints defined in the SDK have a URL starting with the `/cosmos/` prefix. + +The Cosmos SDK also provides a development endpoint to generate [Swagger](https://swagger.io/) definition files for these REST endpoints. This endpoint can be enabled inside the [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) config file, under the `api.swagger` key. + +## Application Interface + +[Interfaces](#command-line-grpc-services-and-rest-interfaces) let end-users interact with full-node clients. This means querying data from the full-node or creating and sending new transactions to be relayed by the full-node and eventually included in a block. + +The main interface is the [Command-Line Interface](/advanced/07-cli.md). The CLI of a Cosmos SDK application is built by aggregating [CLI commands](#cli) defined in each of the modules used by the application. The CLI of an application is the same as the daemon (e.g. `appd`), and is defined in a file called `appd/main.go`. The file contains the following: + +* **A `main()` function**, which is executed to build the `appd` interface client. This function prepares each command and adds them to the `rootCmd` before building them. At the root of `appd`, the function adds generic commands like `status`, `keys`, and `config`, query commands, tx commands, and `rest-server`. +* **Query commands**, which are added by calling the `queryCmd` function. This function returns a Cobra command that contains the query commands defined in each of the application's modules (passed as an array of `sdk.ModuleClients` from the `main()` function), as well as some other lower level query commands such as block or validator queries. Query command are called by using the command `appd query [query]` of the CLI. +* **Transaction commands**, which are added by calling the `txCmd` function. Similar to `queryCmd`, the function returns a Cobra command that contains the tx commands defined in each of the application's modules, as well as lower level tx commands like transaction signing or broadcasting. Tx commands are called by using the command `appd tx [tx]` of the CLI. + +See an example of an application's main command-line file from the [Cosmos Hub](https://github.com/cosmos/gaia). + +```go +https://github.com/cosmos/gaia/blob/26ae7c2/cmd/gaiad/cmd/root.go#L39-L80 +``` + +## Dependencies and Makefile + +This section is optional, as developers are free to choose their dependency manager and project building method. That said, the current most used framework for versioning control is [`go.mod`](https://github.com/golang/go/wiki/Modules). It ensures each of the libraries used throughout the application are imported with the correct version. + +The following is the `go.mod` of the [Cosmos Hub](https://github.com/cosmos/gaia), provided as an example. + +```go +https://github.com/cosmos/gaia/blob/26ae7c2/go.mod#L1-L28 +``` + +For building the application, a [Makefile](https://en.wikipedia.org/wiki/Makefile) is generally used. The Makefile primarily ensures that the `go.mod` is run before building the two entrypoints to the application, [`Node Client`](#node-client) and [`Application Interface`](#application-interface). + +Here is an example of the [Cosmos Hub Makefile](https://github.com/cosmos/gaia/blob/main/Makefile). diff --git a/docs/sdk/next/learn/beginner/gas-fees.mdx b/docs/sdk/next/learn/beginner/gas-fees.mdx new file mode 100644 index 00000000..6f34f3c0 --- /dev/null +++ b/docs/sdk/next/learn/beginner/gas-fees.mdx @@ -0,0 +1,101 @@ +--- +title: Gas and Fees +--- + +**Synopsis** +This document describes the default strategies to handle gas and fees within a Cosmos SDK application. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](00-app-anatomy.md) + + + +## Introduction to `Gas` and `Fees` + +In the Cosmos SDK, `gas` is a special unit that is used to track the consumption of resources during execution. `gas` is typically consumed whenever read and writes are made to the store, but it can also be consumed if expensive computation needs to be done. It serves two main purposes: + +* Make sure blocks are not consuming too many resources and are finalized. This is implemented by default in the Cosmos SDK via the [block gas meter](#block-gas-meter). +* Prevent spam and abuse from end-user. To this end, `gas` consumed during [`message`](/../build/building-modules/02-messages-and-queries.md#messages) execution is typically priced, resulting in a `fee` (`fees = gas * gas-prices`). `fees` generally have to be paid by the sender of the `message`. Note that the Cosmos SDK does not enforce `gas` pricing by default, as there may be other ways to prevent spam (e.g. bandwidth schemes). Still, most applications implement `fee` mechanisms to prevent spam by using the [`AnteHandler`](#antehandler). + +## Gas Meter + +In the Cosmos SDK, `gas` is a simple alias for `uint64`, and is managed by an object called a *gas meter*. Gas meters implement the `GasMeter` interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/store/types/gas.go#L40-L51 +``` + +where: + +* `GasConsumed()` returns the amount of gas that was consumed by the gas meter instance. +* `GasConsumedToLimit()` returns the amount of gas that was consumed by the gas meter instance, or the limit if it is reached. +* `GasRemaining()` returns the gas left in the GasMeter. +* `Limit()` returns the limit of the gas meter instance. `0` if the gas meter is infinite. +* `ConsumeGas(amount Gas, descriptor string)` consumes the amount of `gas` provided. If the `gas` overflows, it panics with the `descriptor` message. If the gas meter is not infinite, it panics if `gas` consumed goes above the limit. +* `RefundGas()` deducts the given amount from the gas consumed. This functionality enables refunding gas to the transaction or block gas pools so that EVM-compatible chains can fully support the go-ethereum StateDB interface. +* `IsPastLimit()` returns `true` if the amount of gas consumed by the gas meter instance is strictly above the limit, `false` otherwise. +* `IsOutOfGas()` returns `true` if the amount of gas consumed by the gas meter instance is above or equal to the limit, `false` otherwise. + +The gas meter is generally held in [`ctx`](/advanced/02-context.md), and consuming gas is done with the following pattern: + +```go +ctx.GasMeter().ConsumeGas(amount, "description") +``` + +By default, the Cosmos SDK makes use of two different gas meters, the [main gas meter](#main-gas-meter) and the [block gas meter](#block-gas-meter). + +### Main Gas Meter + +`ctx.GasMeter()` is the main gas meter of the application. The main gas meter is initialized in `FinalizeBlock` via `setFinalizeBlockState`, and then tracks gas consumption during execution sequences that lead to state-transitions, i.e. those originally triggered by [`FinalizeBlock`](/advanced/00-baseapp.md#finalizeblock). At the beginning of each transaction execution, the main gas meter **must be set to 0** in the [`AnteHandler`](#antehandler), so that it can track gas consumption per-transaction. + +Gas consumption can be done manually, generally by the module developer in the [`BeginBlocker`, `EndBlocker`](/../build/building-modules/06-beginblock-endblock.md) or [`Msg` service](/../build/building-modules/03-msg-services.md), but most of the time it is done automatically whenever there is a read or write to the store. This automatic gas consumption logic is implemented in a special store called [`GasKv`](/advanced/04-store.md#gaskv-store). + +### Block Gas Meter + +`ctx.BlockGasMeter()` is the gas meter used to track gas consumption per block and make sure it does not go above a certain limit. + +During the genesis phase, gas consumption is unlimited to accommodate initialization transactions. + +```go +app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(storetypes.NewInfiniteGasMeter())) +``` + +Following the genesis block, the block gas meter is set to a finite value by the SDK. This transition is facilitated by the consensus engine (e.g., CometBFT) calling the `RequestFinalizeBlock` function, which in turn triggers the SDK's `FinalizeBlock` method. Within `FinalizeBlock`, `internalFinalizeBlock` is executed, performing necessary state updates and function executions. The block gas meter, initialized each with a finite limit, is then incorporated into the context for transaction execution, ensuring gas consumption does not exceed the block's gas limit and is reset at the end of each block. + +Modules within the Cosmos SDK can consume block gas at any point during their execution by utilizing the `ctx`. This gas consumption primarily occurs during state read/write operations and transaction processing. The block gas meter, accessible via `ctx.BlockGasMeter()`, monitors the total gas usage within a block, enforcing the gas limit to prevent excessive computation. This ensures that gas limits are adhered to on a per-block basis, starting from the first block post-genesis. + +```go +gasMeter := app.getBlockGasMeter(app.finalizeBlockState.Context()) + +app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(gasMeter)) +``` + +The above shows the general mechanism for setting the block gas meter with a finite limit based on the block's consensus parameters. + +## AnteHandler + +The `AnteHandler` is run for every transaction during `CheckTx` and `FinalizeBlock`, before a Protobuf `Msg` service method for each `sdk.Msg` in the transaction. + +The anteHandler is not implemented in the core Cosmos SDK but in a module. That said, most applications today use the default implementation defined in the [`auth` module](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth). Here is what the `anteHandler` is intended to do in a normal Cosmos SDK application: + +* Verify that the transactions are of the correct type. Transaction types are defined in the module that implements the `anteHandler`, and they follow the transaction interface: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/tx_msg.go#L53-L58 +``` + +This enables developers to play with various types for the transaction of their application. In the default `auth` module, the default transaction type is `Tx`: + +```protobuf +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/proto/cosmos/tx/v1beta1/tx.proto#L15-L28 +``` + +* Verify signatures for each [`message`](/../build/building-modules/02-messages-and-queries.md#messages) contained in the transaction. Each `message` should be signed by one or multiple sender(s), and these signatures must be verified in the `anteHandler`. +* During `CheckTx`, verify that the gas prices provided with the transaction are greater than the local `min-gas-prices` (as a reminder, gas-prices can be deducted from the following equation: `fees = gas * gas-prices`). `min-gas-prices` is a parameter local to each full-node and used during `CheckTx` to discard transactions that do not provide a minimum amount of fees. This ensures that the mempool cannot be spammed with garbage transactions. +* Verify that the sender of the transaction has enough funds to cover for the `fees`. When the end-user generates a transaction, they must indicate 2 of the 3 following parameters (the third one being implicit): `fees`, `gas` and `gas-prices`. This signals how much they are willing to pay for nodes to execute their transaction. The provided `gas` value is stored in a parameter called `GasWanted` for later use. +* Set `newCtx.GasMeter` to 0, with a limit of `GasWanted`. **This step is crucial**, as it not only makes sure the transaction cannot consume infinite gas, but also that `ctx.GasMeter` is reset in-between each transaction (`ctx` is set to `newCtx` after `anteHandler` is run, and the `anteHandler` is run each time a transaction executes). + +As explained above, the `anteHandler` returns a maximum limit of `gas` the transaction can consume during execution called `GasWanted`. The actual amount consumed in the end is denominated `GasUsed`, and we must therefore have `GasUsed =< GasWanted`. Both `GasWanted` and `GasUsed` are relayed to the underlying consensus engine when [`FinalizeBlock`](/advanced/00-baseapp.md#finalizeblock) returns. diff --git a/docs/sdk/next/learn/beginner/query-lifecycle.mdx b/docs/sdk/next/learn/beginner/query-lifecycle.mdx new file mode 100644 index 00000000..18aafb5a --- /dev/null +++ b/docs/sdk/next/learn/beginner/query-lifecycle.mdx @@ -0,0 +1,146 @@ +--- +title: Query Lifecycle +--- + +**Synopsis** +This document describes the lifecycle of a query in a Cosmos SDK application, from the user interface to application stores and back. The query is referred to as `MyQuery`. + + + +**Pre-requisite Readings** + +* [Transaction Lifecycle](01-tx-lifecycle.md) + + +## Query Creation + +A [**query**](/../build/building-modules/02-messages-and-queries.md#queries) is a request for information made by end-users of applications through an interface and processed by a full-node. Users can query information about the network, the application itself, and application state directly from the application's stores or modules. Note that queries are different from [transactions](/advanced/01-transactions.md) (view the lifecycle [here](01-tx-lifecycle.md)), particularly in that they do not require consensus to be processed (as they do not trigger state-transitions); they can be fully handled by one full-node. + +For the purpose of explaining the query lifecycle, let's say the query, `MyQuery`, is requesting a list of delegations made by a certain delegator address in the application called `simapp`. As is to be expected, the [`staking`](/../../../x/staking/README.md) module handles this query. But first, there are a few ways `MyQuery` can be created by users. + +### CLI + +The main interface for an application is the command-line interface. Users connect to a full-node and run the CLI directly from their machines - the CLI interacts directly with the full-node. To create `MyQuery` from their terminal, users type the following command: + +```bash +simd query staking delegations +``` + +This query command was defined by the [`staking`](/../../../x/staking/README.md) module developer and added to the list of subcommands by the application developer when creating the CLI. + +Note that the general format is as follows: + +```bash +simd query [moduleName] [command] --flag +``` + +To provide values such as `--node` (the full-node the CLI connects to), the user can use the [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) config file to set them or provide them as flags. + +The CLI understands a specific set of commands, defined in a hierarchical structure by the application developer: from the [root command](/advanced/07-cli.md#root-command) (`simd`), the type of command (`Myquery`), the module that contains the command (`staking`), and command itself (`delegations`). Thus, the CLI knows exactly which module handles this command and directly passes the call there. + +### gRPC + +Another interface through which users can make queries is [gRPC](https://grpc.io) requests to a [gRPC server](/advanced/06-grpc_rest.md#grpc-server). The endpoints are defined as [Protocol Buffers](https://developers.google.com/protocol-buffers) service methods inside `.proto` files, written in Protobuf's own language-agnostic interface definition language (IDL). The Protobuf ecosystem developed tools for code-generation from `*.proto` files into various languages. These tools allow to build gRPC clients easily. + +One such tool is [grpcurl](https://github.com/fullstorydev/grpcurl), and a gRPC request for `MyQuery` using this client looks like: + +```bash +grpcurl \ + -plaintext # We want results in plain text + -import-path ./proto \ # Import these .proto files + -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service + -d '{"address":"$MY_DELEGATOR"}' \ # Query arguments + localhost:9090 \ # gRPC server endpoint + cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name +``` + +### REST + +Another interface through which users can make queries is through HTTP Requests to a [REST server](/advanced/06-grpc_rest.md#rest-server). The REST server is fully auto-generated from Protobuf services, using [gRPC-gateway](https://github.com/grpc-ecosystem/grpc-gateway). + +An example HTTP request for `MyQuery` looks like: + +```bash +GET http://localhost:1317/cosmos/staking/v1beta1/delegators/{delegatorAddr}/delegations +``` + +## How Queries are Handled by the CLI + +The preceding examples show how an external user can interact with a node by querying its state. To understand in more detail the exact lifecycle of a query, let's dig into how the CLI prepares the query, and how the node handles it. The interactions from the users' perspective are a bit different, but the underlying functions are almost identical because they are implementations of the same command defined by the module developer. This step of processing happens within the CLI, gRPC, or REST server, and heavily involves a `client.Context`. + +### Context + +The first thing that is created in the execution of a CLI command is a `client.Context`. A `client.Context` is an object that stores all the data needed to process a request on the user side. In particular, a `client.Context` stores the following: + +* **Codec**: The [encoder/decoder](/advanced/05-encoding.md) used by the application, used to marshal the parameters and query before making the CometBFT RPC request and unmarshal the returned response into a JSON object. The default codec used by the CLI is Protobuf. +* **Account Decoder**: The account decoder from the [`auth`](/../../../x/auth/README.md) module, which translates `[]byte`s into accounts. +* **RPC Client**: The CometBFT RPC Client, or node, to which requests are relayed. +* **Keyring**: A [Key Manager](/beginner/03-accounts.md#keyring) used to sign transactions and handle other operations with keys. +* **Output Writer**: A [Writer](https://pkg.go.dev/io/#Writer) used to output the response. +* **Configurations**: The flags configured by the user for this command, including `--height`, specifying the height of the blockchain to query, and `--indent`, which indicates to add an indent to the JSON response. + +The `client.Context` also contains various functions such as `Query()`, which retrieves the RPC Client and makes an ABCI call to relay a query to a full-node. + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/context.go#L27-70 +``` + +The `client.Context`'s primary role is to store data used during interactions with the end-user and provide methods to interact with this data - it is used before and after the query is processed by the full-node. Specifically, in handling `MyQuery`, the `client.Context` is utilized to encode the query parameters, retrieve the full-node, and write the output. Prior to being relayed to a full-node, the query needs to be encoded into a `[]byte` form, as full-nodes are application-agnostic and do not understand specific types. The full-node (RPC Client) itself is retrieved using the `client.Context`, which knows which node the user CLI is connected to. The query is relayed to this full-node to be processed. Finally, the `client.Context` contains a `Writer` to write output when the response is returned. These steps are further described in later sections. + +### Arguments and Route Creation + +At this point in the lifecycle, the user has created a CLI command with all of the data they wish to include in their query. A `client.Context` exists to assist in the rest of the `MyQuery`'s journey. Now, the next step is to parse the command or request, extract the arguments, and encode everything. These steps all happen on the user side within the interface they are interacting with. + +#### Encoding + +In our case (querying an address's delegations), `MyQuery` contains an [address](03-accounts.md#addresses) `delegatorAddress` as its only argument. However, the request can only contain `[]byte`s, as it is ultimately relayed to a consensus engine (e.g. CometBFT) of a full-node that has no inherent knowledge of the application types. Thus, the `codec` of `client.Context` is used to marshal the address. + +Here is what the code looks like for the CLI command: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/staking/client/cli/query.go#L315-L318 +``` + +#### gRPC Query Client Creation + +The Cosmos SDK leverages code generated from Protobuf services to make queries. The `staking` module's `MyQuery` service generates a `queryClient`, which the CLI uses to make queries. Here is the relevant code: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/staking/client/cli/query.go#L308-L343 +``` + +Under the hood, the `client.Context` has a `Query()` function used to retrieve the pre-configured node and relay a query to it; the function takes the query fully-qualified service method name as path (in our case: `/cosmos.staking.v1beta1.Query/Delegations`), and arguments as parameters. It first retrieves the RPC Client (called the [**node**](/advanced/03-node.md)) configured by the user to relay this query to, and creates the `ABCIQueryOptions` (parameters formatted for the ABCI call). The node is then used to make the ABCI call, `ABCIQueryWithOptions()`. + +Here is what the code looks like: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/query.go#L79-L113 +``` + +## RPC + +With a call to `ABCIQueryWithOptions()`, `MyQuery` is received by a [full-node](/advanced/05-encoding.md) which then processes the request. Note that, while the RPC is made to the consensus engine (e.g. CometBFT) of a full-node, queries are not part of consensus and so are not broadcasted to the rest of the network, as they do not require anything the network needs to agree upon. + +Read more about ABCI Clients and CometBFT RPC in the [CometBFT documentation](https://docs.cometbft.com/v0.37/spec/rpc/). + +## Application Query Handling + +When a query is received by the full-node after it has been relayed from the underlying consensus engine, it is at that point being handled within an environment that understands application-specific types and has a copy of the state. [`baseapp`](/advanced/00-baseapp.md) implements the ABCI [`Query()`](/advanced/00-baseapp.md#query) function and handles gRPC queries. The query route is parsed, and it matches the fully-qualified service method name of an existing service method (most likely in one of the modules), then `baseapp` relays the request to the relevant module. + +Since `MyQuery` has a Protobuf fully-qualified service method name from the `staking` module (recall `/cosmos.staking.v1beta1.Query/Delegations`), `baseapp` first parses the path, then uses its own internal `GRPCQueryRouter` to retrieve the corresponding gRPC handler, and routes the query to the module. The gRPC handler is responsible for recognizing this query, retrieving the appropriate values from the application's stores, and returning a response. Read more about query services [here](/../build/building-modules/04-query-services.md). + +Once a result is received from the querier, `baseapp` begins the process of returning a response to the user. + +## Response + +Since `Query()` is an ABCI function, `baseapp` returns the response as an [`abci.QueryResponse`](https://docs.cometbft.com/main/spec/abci/abci++_methods#query) type. The `client.Context` `Query()` routine receives the response and processes it. + +### CLI Response + +The application [`codec`](/advanced/05-encoding.md) is used to unmarshal the response to a JSON and the `client.Context` prints the output to the command line, applying any configurations such as the output type (text, JSON or YAML). + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/context.go#L350-L357 +``` + +And that's a wrap! The result of the query is outputted to the console by the CLI. diff --git a/docs/sdk/next/learn/beginner/tx-lifecycle.mdx b/docs/sdk/next/learn/beginner/tx-lifecycle.mdx new file mode 100644 index 00000000..3364fc5a --- /dev/null +++ b/docs/sdk/next/learn/beginner/tx-lifecycle.mdx @@ -0,0 +1,283 @@ +--- +title: Transaction Lifecycle +--- + +**Synopsis** +This document describes the lifecycle of a transaction from creation to committed state changes. Transaction definition is described in a [different doc](/advanced/01-transactions.md). The transaction is referred to as `Tx`. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](00-app-anatomy.md) + + +## Creation + +### Transaction Creation + +One of the main application interfaces is the command-line interface. The transaction `Tx` can be created by the user inputting a command in the following format from the [command-line](/advanced/07-cli.md), providing the type of transaction in `[command]`, arguments in `[args]`, and configurations such as gas prices in `[flags]`: + +```bash +[appname] tx [command] [args] [flags] +``` + +This command automatically **creates** the transaction, **signs** it using the account's private key, and **broadcasts** it to the specified peer node. + +There are several required and optional flags for transaction creation. The `--from` flag specifies which [account](03-accounts.md) the transaction is originating from. For example, if the transaction is sending coins, the funds are drawn from the specified `from` address. + +#### Gas and Fees + +Additionally, there are several [flags](/advanced/07-cli.md) users can use to indicate how much they are willing to pay in [fees](04-gas-fees.md): + +* `--gas` refers to how much [gas](04-gas-fees.md), which represents computational resources, `Tx` consumes. Gas is dependent on the transaction and is not precisely calculated until execution, but can be estimated by providing `auto` as the value for `--gas`. +* `--gas-adjustment` (optional) can be used to scale `gas` up in order to avoid underestimating. For example, users can specify their gas adjustment as 1.5 to use 1.5 times the estimated gas. +* `--gas-prices` specifies how much the user is willing to pay per unit of gas, which can be one or multiple denominations of tokens. For example, `--gas-prices=0.025uatom, 0.025upho` means the user is willing to pay 0.025uatom AND 0.025upho per unit of gas. +* `--fees` specifies how much in fees the user is willing to pay in total. +* `--timeout-height` specifies a block timeout height to prevent the tx from being committed past a certain height. + +The ultimate value of the fees paid is equal to the gas multiplied by the gas prices. In other words, `fees = ceil(gas * gasPrices)`. Thus, since fees can be calculated using gas prices and vice versa, the users specify only one of the two. + +Later, validators decide whether to include the transaction in their block by comparing the given or calculated `gas-prices` to their local `min-gas-prices`. `Tx` is rejected if its `gas-prices` is not high enough, so users are incentivized to pay more. + +#### Unordered Transactions + +With Cosmos SDK v0.53.0, users may send unordered transactions to chains that have this feature enabled. +The following flags allow a user to build an unordered transaction from the CLI. + +* `--unordered` specifies that this transaction should be unordered. (transaction sequence must be unset) +* `--timeout-duration` specifies the amount of time the unordered transaction should be valid in the mempool. The transaction's unordered nonce will be set to the time of transaction creation + timeout duration. + + + +Unordered transactions MUST leave sequence values unset. When a transaction is both unordered and contains a non-zero sequence value, +the transaction will be rejected. External services that operate on prior assumptions about transaction sequence values should be updated to handle unordered transactions. +Services should be aware that when the transaction is unordered, the transaction sequence will always be zero. + + + +#### CLI Example + +Users of the application `app` can enter the following command into their CLI to generate a transaction to send 1000uatom from a `senderAddress` to a `recipientAddress`. The command specifies how much gas they are willing to pay: an automatic estimate scaled up by 1.5 times, with a gas price of 0.025uatom per unit gas. + +```bash +appd tx send 1000uatom --from --gas auto --gas-adjustment 1.5 --gas-prices 0.025uatom +``` + +#### Other Transaction Creation Methods + +The command-line is an easy way to interact with an application, but `Tx` can also be created using a [gRPC or REST interface](/advanced/06-grpc_rest.md) or some other entry point defined by the application developer. From the user's perspective, the interaction depends on the web interface or wallet they are using (e.g. creating `Tx` using [Lunie.io](https://lunie.io/#/) and signing it with a Ledger Nano S). + +## Addition to Mempool + +Each full-node (running CometBFT) that receives a `Tx` sends an [ABCI message](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/), +`CheckTx`, to the application layer to check for validity, and receives an `abci.CheckTxResponse`. If the `Tx` passes the checks, it is held in the node's +[**Mempool**](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/mempool), an in-memory pool of transactions unique to each node, pending inclusion in a block - honest nodes discard a `Tx` if it is found to be invalid. Prior to consensus, nodes continuously check incoming transactions and gossip them to their peers. + +### Types of Checks + +The full-nodes perform stateless, then stateful checks on `Tx` during `CheckTx`, with the goal to +identify and reject an invalid transaction as early on as possible to avoid wasted computation. + +***Stateless*** checks do not require nodes to access state - light clients or offline nodes can do +them - and are thus less computationally expensive. Stateless checks include making sure addresses +are not empty, enforcing nonnegative numbers, and other logic specified in the definitions. + +***Stateful*** checks validate transactions and messages based on a committed state. Examples +include checking that the relevant values exist and can be transacted with, the address +has sufficient funds, and the sender is authorized or has the correct ownership to transact. +At any given moment, full-nodes typically have [multiple versions](/advanced/00-baseapp.md#state-updates) +of the application's internal state for different purposes. For example, nodes execute state +changes while in the process of verifying transactions, but still need a copy of the last committed +state in order to answer queries - they should not respond using state with uncommitted changes. + +In order to verify a `Tx`, full-nodes call `CheckTx`, which includes both *stateless* and *stateful* +checks. Further validation happens later in the [`DeliverTx`](#delivertx) stage. `CheckTx` goes +through several steps, beginning with decoding `Tx`. + +### Decoding + +When `Tx` is received by the application from the underlying consensus engine (e.g. CometBFT), it is still in its [encoded](/advanced/05-encoding.md) `[]byte` form and needs to be unmarshaled in order to be processed. Then, the [`runTx`](/advanced/00-baseapp.md#runtx-antehandler-runmsgs-posthandler) function is called to run in `runTxModeCheck` mode, meaning the function runs all checks but exits before executing messages and writing state changes. + +### ValidateBasic (deprecated) + +Messages ([`sdk.Msg`](/advanced/01-transactions.md#messages)) are extracted from transactions (`Tx`). The `ValidateBasic` method of the `sdk.Msg` interface implemented by the module developer is run for each transaction. +To discard obviously invalid messages, the `BaseApp` type calls the `ValidateBasic` method very early in the processing of the message in the [`CheckTx`](/advanced/00-baseapp.md#checktx) and [`DeliverTx`](/advanced/00-baseapp.md#delivertx) transactions. +`ValidateBasic` can include only **stateless** checks (the checks that do not require access to the state). + + +The `ValidateBasic` method on messages has been deprecated in favor of validating messages directly in their respective [`Msg` services](/../build/building-modules/03-msg-services.md#Validation). + +Read [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) for more details. + + + +`BaseApp` still calls `ValidateBasic` on messages that implement that method for backwards compatibility. + + +#### Guideline + +`ValidateBasic` should not be used anymore. Message validation should be performed in the `Msg` service when [handling a message](/../build/building-modules/msg-services#Validation) in a module Msg Server. + +### AnteHandler + +`AnteHandler`s even though optional, are in practice very often used to perform signature verification, gas calculation, fee deduction, and other core operations related to blockchain transactions. + +A copy of the cached context is provided to the `AnteHandler`, which performs limited checks specified for the transaction type. Using a copy allows the `AnteHandler` to do stateful checks for `Tx` without modifying the last committed state, and revert back to the original if the execution fails. + +For example, the [`auth`](https://github.com/cosmos/cosmos-sdk/blob/main/x/auth/README.md) module `AnteHandler` checks and increments sequence numbers, checks signatures and account numbers, and deducts fees from the first signer of the transaction - all state changes are made using the `checkState`. + + +Ante handlers only run on a transaction. If a transaction embeds multiple messages (like some x/authz, x/gov transactions for instance), the ante handlers only have awareness of the outer message. Inner messages are mostly directly routed to the [message router](https://docs.cosmos.network/main/learn/advanced/baseapp#msg-service-router) and will skip the chain of ante handlers. Keep that in mind when designing your own ante handler. + + +### Gas + +The [`Context`](/advanced/02-context.md), which keeps a `GasMeter` that tracks how much gas is used during the execution of `Tx`, is initialized. The user-provided amount of gas for `Tx` is known as `GasWanted`. If `GasConsumed`, the amount of gas consumed during execution, ever exceeds `GasWanted`, the execution stops and the changes made to the cached copy of the state are not committed. Otherwise, `CheckTx` sets `GasUsed` equal to `GasConsumed` and returns it in the result. After calculating the gas and fee values, validator-nodes check that the user-specified `gas-prices` is greater than their locally defined `min-gas-prices`. + +### Discard or Addition to Mempool + +If at any point during `CheckTx` the `Tx` fails, it is discarded and the transaction lifecycle ends +there. Otherwise, if it passes `CheckTx` successfully, the default protocol is to relay it to peer +nodes and add it to the Mempool so that the `Tx` becomes a candidate to be included in the next block. + +The **mempool** serves the purpose of keeping track of transactions seen by all full-nodes. +Full-nodes keep a **mempool cache** of the last `mempool.cache_size` transactions they have seen, as a first line of +defense to prevent replay attacks. Ideally, `mempool.cache_size` is large enough to encompass all +of the transactions in the full mempool. If the mempool cache is too small to keep track of all +the transactions, `CheckTx` is responsible for identifying and rejecting replayed transactions. + +Currently existing preventative measures include fees and a `sequence` (nonce) counter to distinguish +replayed transactions from identical but valid ones. If an attacker tries to spam nodes with many +copies of a `Tx`, full-nodes keeping a mempool cache reject all identical copies instead of running +`CheckTx` on them. Even if the copies have incremented `sequence` numbers, attackers are +disincentivized by the need to pay fees. + +Validator nodes keep a mempool to prevent replay attacks, just as full-nodes do, but also use it as +a pool of unconfirmed transactions in preparation of block inclusion. Note that even if a `Tx` +passes all checks at this stage, it is still possible to be found invalid later on, because +`CheckTx` does not fully validate the transaction (that is, it does not actually execute the messages). + +## Inclusion in a Block + +Consensus, the process through which validator nodes come to agreement on which transactions to +accept, happens in **rounds**. Each round begins with a proposer creating a block of the most +recent transactions and ends with **validators**, special full-nodes with voting power responsible +for consensus, agreeing to accept the block or go with a `nil` block instead. Validator nodes +execute the consensus algorithm, such as [CometBFT](https://docs.cometbft.com/v0.37/spec/consensus/), +confirming the transactions using ABCI requests to the application, in order to come to this agreement. + +The first step of consensus is the **block proposal**. One proposer amongst the validators is chosen +by the consensus algorithm to create and propose a block - in order for a `Tx` to be included, it +must be in this proposer's mempool. + +## State Changes + +The next step of consensus is to execute the transactions to fully validate them. All full-nodes +that receive a block proposal from the correct proposer execute the transactions by calling the ABCI function `FinalizeBlock`. +As mentioned throughout the documentation `BeginBlock`, `ExecuteTx` and `EndBlock` are called within FinalizeBlock. +Although every full-node operates individually and locally, the outcome is always consistent and unequivocal. This is because the state changes brought about by the messages are predictable, and the transactions are specifically sequenced in the proposed block. + +```text expandable + -------------------------- + | Receive Block Proposal | + -------------------------- + | + v + ------------------------- + | FinalizeBlock | + ------------------------- + | + v + ------------------- + | BeginBlock | + ------------------- + | + v + -------------------- + | ExecuteTx(tx0) | + | ExecuteTx(tx1) | + | ExecuteTx(tx2) | + | ExecuteTx(tx3) | + | . | + | . | + | . | + ------------------- + | + v + -------------------- + | EndBlock | + -------------------- + | + v + ------------------------- + | Consensus | + ------------------------- + | + v + ------------------------- + | Commit | + ------------------------- +``` + +### Transaction Execution + +The `FinalizeBlock` ABCI function defined in [`BaseApp`](/advanced/00-baseapp.md) does the bulk of the +state transitions: it is run for each transaction in the block in sequential order as committed +to during consensus. Under the hood, transaction execution is almost identical to `CheckTx` but calls the +[`runTx`](/advanced/00-baseapp.md#runtx) function in deliver mode instead of check mode. +Instead of using their `checkState`, full-nodes use `finalizeblock`: + +* **Decoding:** Since `FinalizeBlock` is an ABCI call, `Tx` is received in the encoded `[]byte` form. + Nodes first unmarshal the transaction, using the [`TxConfig`](00-app-anatomy.md#register-codec) defined in the app, then call `runTx` in `execModeFinalize`, which is very similar to `CheckTx` but also executes and writes state changes. + +* **Checks and `AnteHandler`:** Full-nodes call `validateBasicMsgs` and `AnteHandler` again. This second check + happens because they may not have seen the same transactions during the addition to Mempool stage + and a malicious proposer may have included invalid ones. One difference here is that the + `AnteHandler` does not compare `gas-prices` to the node's `min-gas-prices` since that value is local + to each node - differing values across nodes yield nondeterministic results. + +* **`MsgServiceRouter`:** After `CheckTx` exits, `FinalizeBlock` continues to run + [`runMsgs`](/advanced/00-baseapp.md#runtx-antehandler-runmsgs-posthandler) to fully execute each `Msg` within the transaction. + Since the transaction may have messages from different modules, `BaseApp` needs to know which module + to find the appropriate handler. This is achieved using `BaseApp`'s `MsgServiceRouter` so that it can be processed by the module's Protobuf [`Msg` service](/../build/building-modules/03-msg-services.md). + For `LegacyMsg` routing, the `Route` function is called via the [module manager](/../build/building-modules/01-module-manager.md) to retrieve the route name and find the legacy [`Handler`](/../build/building-modules/03-msg-services.md#handler-type) within the module. + +* **`Msg` service:** Protobuf `Msg` service is responsible for executing each message in the `Tx` and causes state transitions to persist in `finalizeBlockState`. + +* **PostHandlers:** [`PostHandler`](/advanced/00-baseapp.md#posthandler)s run after the execution of the message. If they fail, the state change of `runMsgs`, as well of `PostHandlers`, are both reverted. + +* **Gas:** While a `Tx` is being delivered, a `GasMeter` is used to keep track of how much + gas is being used; if execution completes, `GasUsed` is set and returned in the + `abci.ExecTxResult`. If execution halts because `BlockGasMeter` or `GasMeter` has run out or something else goes + wrong, a deferred function at the end appropriately errors or panics. + +If there are any failed state changes resulting from a `Tx` being invalid or `GasMeter` running out, +the transaction processing terminates and any state changes are reverted. Invalid transactions in a +block proposal cause validator nodes to reject the block and vote for a `nil` block instead. + +### Commit + +The final step is for nodes to commit the block and state changes. Validator nodes +perform the previous step of executing state transitions in order to validate the transactions, +then sign the block to confirm it. Full nodes that are not validators do not +participate in consensus - i.e. they cannot vote - but listen for votes to understand whether or +not they should commit the state changes. + +When they receive enough validator votes (2/3+ *precommits* weighted by voting power), full nodes commit to a new block to be added to the blockchain and +finalize the state transitions in the application layer. A new state root is generated to serve as +a merkle proof for the state transitions. Applications use the [`Commit`](/advanced/00-baseapp.md#commit) +ABCI method inherited from [Baseapp](/advanced/00-baseapp.md); it syncs all the state transitions by +writing the `deliverState` into the application's internal state. As soon as the state changes are +committed, `checkState` starts afresh from the most recently committed state and `deliverState` +resets to `nil` in order to be consistent and reflect the changes. + +Note that not all blocks have the same number of transactions and it is possible for consensus to +result in a `nil` block or one with none at all. In a public blockchain network, it is also possible +for validators to be **byzantine**, or malicious, which may prevent a `Tx` from being committed in +the blockchain. Possible malicious behaviors include the proposer deciding to censor a `Tx` by +excluding it from the block or a validator voting against the block. + +At this point, the transaction lifecycle of a `Tx` is over: nodes have verified its validity, +delivered it by executing its state changes, and committed those changes. The `Tx` itself, +in `[]byte` form, is stored in a block and appended to the blockchain. diff --git a/docs/sdk/next/learn/intro/overview.mdx b/docs/sdk/next/learn/intro/overview.mdx new file mode 100644 index 00000000..04f9615a --- /dev/null +++ b/docs/sdk/next/learn/intro/overview.mdx @@ -0,0 +1,40 @@ +--- +title: What is the Cosmos SDK +--- +The [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is an open-source toolkit for building multi-asset public Proof-of-Stake (PoS) blockchains, like the Cosmos Hub, as well as permissioned Proof-of-Authority (PoA) blockchains. Blockchains built with the Cosmos SDK are generally referred to as **application-specific blockchains**. + +The goal of the Cosmos SDK is to allow developers to easily create custom blockchains from scratch that can natively interoperate with other blockchains. +We further this modular approach by allowing developers to plug and play with different consensus engines this can range from the [CometBFT](https://github.com/cometbft/cometbft) or [Rollkit](https://rollkit.dev/). + +SDK-based blockchains have the choice to use the predefined modules or to build their own modules. What this means is that developers can build a blockchain that is tailored to their specific use case, without having to worry about the low-level details of building a blockchain from scratch. Predefined modules include staking, governance, and token issuance, among others. + +What's more, the Cosmos SDK is a capabilities-based system that allows developers to better reason about the security of interactions between modules. For a deeper look at capabilities, jump to [Object-Capability Model](/advanced/10-ocap.md). + +How you can look at this is if we imagine that the SDK is like a lego kit. You can choose to build the basic house from the instructions or you can choose to modify your house and add more floors, more doors, more windows. The choice is yours. + +## What are Application-Specific Blockchains + +One development paradigm in the blockchain world today is that of virtual-machine blockchains like Ethereum, where development generally revolves around building decentralized applications on top of an existing blockchain as a set of smart contracts. While smart contracts can be very good for some use cases like single-use applications (e.g. ICOs), they often fall short for building complex decentralized platforms. More generally, smart contracts can be limiting in terms of flexibility, sovereignty and performance. + +Application-specific blockchains offer a radically different development paradigm than virtual-machine blockchains. An application-specific blockchain is a blockchain customized to operate a single application: developers have all the freedom to make the design decisions required for the application to run optimally. They can also provide better sovereignty, security and performance. + +Learn more about [application-specific blockchains](01-why-app-specific.md). + +## What is Modularity + +Today there is a lot of talk around modularity and discussions between monolithic and modular. Originally the Cosmos SDK was built with a vision of modularity in mind. Modularity is derived from splitting a blockchain into customizable layers of execution, consensus, settlement and data availability, which is what the Cosmos SDK enables. This means that developers can plug and play, making their blockchain customisable by using different software for different layers. For example you can choose to build a vanilla chain and use the Cosmos SDK with CometBFT. CometBFT will be your consensus layer and the chain itself would be the settlement and execution layer. Another route could be to use the SDK with Rollkit and Celestia as your consensus and data availability layer. The benefit of modularity is that you can customize your chain to your specific use case. + +## Why the Cosmos SDK + +The Cosmos SDK is the most advanced framework for building custom modular application-specific blockchains today. Here are a few reasons why you might want to consider building your decentralized application with the Cosmos SDK: + +* It allows you to plug and play and customize your consensus layer. As above you can use Rollkit and Celestia as your consensus and data availability layer. This offers a lot of flexibility and customisation. +* Previously the default consensus engine available within the Cosmos SDK is [CometBFT](https://github.com/cometbft/cometbft). CometBFT is the most mature BFT consensus engine in existence. It is widely used across the industry and is considered the gold standard consensus engine for building Proof-of-Stake systems. +* The Cosmos SDK is open-source and designed to make it easy to build blockchains out of composable [modules](/../build/modules). As the ecosystem of open-source Cosmos SDK modules grows, it will become increasingly easier to build complex decentralized platforms with it. +* The Cosmos SDK is inspired by capabilities-based security, and informed by years of wrestling with blockchain state-machines. This makes the Cosmos SDK a very secure environment to build blockchains. +* Most importantly, the Cosmos SDK has already been used to build many application-specific blockchains that are already in production. Among others, we can cite [Cosmos Hub](https://hub.cosmos.network), [IRIS Hub](https://irisnet.org), [Binance Chain](https://docs.binance.org/), [Terra](https://terra.money/) or [Kava](https://www.kava.io/). [Many more](https://cosmos.network/ecosystem) are building on the Cosmos SDK. + +## Getting started with the Cosmos SDK + +* Learn more about the [architecture of a Cosmos SDK application](02-sdk-app-architecture.md) +* Learn how to build an application-specific blockchain from scratch with the [Cosmos SDK Tutorial](https://cosmos.network/docs/sdk/next/tutorial) diff --git a/docs/sdk/next/learn/intro/sdk-app-architecture.mdx b/docs/sdk/next/learn/intro/sdk-app-architecture.mdx new file mode 100644 index 00000000..29805872 --- /dev/null +++ b/docs/sdk/next/learn/intro/sdk-app-architecture.mdx @@ -0,0 +1,91 @@ +--- +title: Blockchain Architecture +description: 'At its core, a blockchain is a replicated deterministic state machine.' +--- +## State machine + +At its core, a blockchain is a [replicated deterministic state machine](https://en.wikipedia.org/wiki/State_machine_replication). + +A state machine is a computer science concept whereby a machine can have multiple states, but only one at any given time. There is a `state`, which describes the current state of the system, and `transactions`, that trigger state transitions. + +Given a state S and a transaction T, the state machine will return a new state S'. + +```text ++--------+ +--------+ +| | | | +| S +---------------->+ S' | +| | apply(T) | | ++--------+ +--------+ +``` + +In practice, the transactions are bundled in blocks to make the process more efficient. Given a state S and a block of transactions B, the state machine will return a new state S'. + +```text ++--------+ +--------+ +| | | | +| S +----------------------------> | S' | +| | For each T in B: apply(T) | | ++--------+ +--------+ +``` + +In a blockchain context, the state machine is deterministic. This means that if a node is started at a given state and replays the same sequence of transactions, it will always end up with the same final state. + +The Cosmos SDK gives developers maximum flexibility to define the state of their application, transaction types and state transition functions. The process of building state-machines with the Cosmos SDK will be described more in depth in the following sections. But first, let us see how the state-machine is replicated using **CometBFT**. + +## CometBFT + +Thanks to the Cosmos SDK, developers just have to define the state machine, and [*CometBFT*](https://docs.cometbft.com/v0.37/introduction/what-is-cometbft) will handle replication over the network for them. + +```text expandable + ^ +-------------------------------+ ^ + | | | | Built with Cosmos SDK + | | State-machine = Application | | + | | | v + | +-------------------------------+ + | | | ^ +Blockchain node | | Consensus | | + | | | | + | +-------------------------------+ | CometBFT + | | | | + | | Networking | | + | | | | + v +-------------------------------+ v +``` + +[CometBFT](https://docs.cometbft.com/v0.37/introduction/what-is-cometbft) is an application-agnostic engine that is responsible for handling the *networking* and *consensus* layers of a blockchain. In practice, this means that CometBFT is responsible for propagating and ordering transaction bytes. CometBFT relies on an eponymous Byzantine-Fault-Tolerant (BFT) algorithm to reach consensus on the order of transactions. + +The CometBFT [consensus algorithm](https://docs.cometbft.com/v0.37/introduction/what-is-cometbft#consensus-overview) works with a set of special nodes called *Validators*. Validators are responsible for adding blocks of transactions to the blockchain. At any given block, there is a validator set V. A validator in V is chosen by the algorithm to be the proposer of the next block. This block is considered valid if more than two thirds of V signed a `prevote` and a `precommit` on it, and if all the transactions that it contains are valid. The validator set can be changed by rules written in the state-machine. + +## ABCI + +CometBFT passes transactions to the application through an interface called the [ABCI](https://docs.cometbft.com/v0.37/spec/abci/), which the application must implement. + +```text expandable + +---------------------+ + | | + | Application | + | | + +--------+---+--------+ + ^ | + | | ABCI + | v + +--------+---+--------+ + | | + | | + | CometBFT | + | | + | | + +---------------------+ +``` + +Note that **CometBFT only handles transaction bytes**. It has no knowledge of what these bytes mean. All CometBFT does is order these transaction bytes deterministically. CometBFT passes the bytes to the application via the ABCI, and expects a return code to inform it if the messages contained in the transactions were successfully processed or not. + +Here are the most important messages of the ABCI: + +* `CheckTx`: When a transaction is received by CometBFT, it is passed to the application to check if a few basic requirements are met. `CheckTx` is used to protect the mempool of full-nodes against spam transactions. A special handler called the [`AnteHandler`](/beginner/04-gas-fees.md#antehandler) is used to execute a series of validation steps such as checking for sufficient fees and validating the signatures. If the checks are valid, the transaction is added to the [mempool](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/mempool) and relayed to peer nodes. Note that transactions are not processed (i.e. no modification of the state occurs) with `CheckTx` since they have not been included in a block yet. +* `DeliverTx`: When a [valid block](https://docs.cometbft.com/v0.37/spec/core/data_structures#block) is received by CometBFT, each transaction in the block is passed to the application via `DeliverTx` in order to be processed. It is during this stage that the state transitions occur. The `AnteHandler` executes again, along with the actual [`Msg` service](/../build/building-modules/03-msg-services.md) RPC for each message in the transaction. +* `BeginBlock`/`EndBlock`: These messages are executed at the beginning and the end of each block, whether the block contains transactions or not. It is useful to trigger automatic execution of logic. Proceed with caution though, as computationally expensive loops could slow down your blockchain, or even freeze it if the loop is infinite. + +Find a more detailed view of the ABCI methods from the [CometBFT docs](https://docs.cometbft.com/v0.37/spec/abci/). + +Any application built on CometBFT needs to implement the ABCI interface in order to communicate with the underlying local CometBFT engine. Fortunately, you do not have to implement the ABCI interface. The Cosmos SDK provides a boilerplate implementation of it in the form of [baseapp](03-sdk-design.md#baseapp). diff --git a/docs/sdk/next/learn/intro/sdk-design.mdx b/docs/sdk/next/learn/intro/sdk-design.mdx new file mode 100644 index 00000000..5370ffba --- /dev/null +++ b/docs/sdk/next/learn/intro/sdk-design.mdx @@ -0,0 +1,61 @@ +--- +title: Main Components of the Cosmos SDK +--- +The Cosmos SDK is a framework that facilitates the development of secure state-machines on top of CometBFT. At its core, the Cosmos SDK is a boilerplate implementation of the [ABCI](02-sdk-app-architecture.md#abci) in Golang. It comes with a [`multistore`](/advanced/04-store.md#multistore) to persist data and a [`router`](/advanced/00-baseapp.md#routing) to handle transactions. + +Here is a simplified view of how transactions are handled by an application built on top of the Cosmos SDK when transferred from CometBFT via `DeliverTx`: + +1. Decode `transactions` received from the CometBFT consensus engine (remember that CometBFT only deals with `[]bytes`). +2. Extract `messages` from `transactions` and do basic sanity checks. +3. Route each message to the appropriate module so that it can be processed. +4. Commit state changes. + +## `baseapp` + +`baseapp` is the boilerplate implementation of a Cosmos SDK application. It comes with an implementation of the ABCI to handle the connection with the underlying consensus engine. Typically, a Cosmos SDK application extends `baseapp` by embedding it in [`app.go`](/beginner/00-app-anatomy.md#core-application-file). + +Here is an example of this from `simapp`, the Cosmos SDK demonstration app: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L137-L180 +``` + +The goal of `baseapp` is to provide a secure interface between the store and the extensible state machine while defining as little about the state machine as possible (staying true to the ABCI). + +For more on `baseapp`, please click [here](/advanced/00-baseapp.md). + +## Multistore + +The Cosmos SDK provides a [`multistore`](/advanced/04-store.md#multistore) for persisting state. The multistore allows developers to declare any number of [`KVStores`](/advanced/04-store.md#base-layer-kvstores). These `KVStores` only accept the `[]byte` type as value and therefore any custom structure needs to be marshalled using [a codec](/advanced/05-encoding.md) before being stored. + +The multistore abstraction is used to divide the state in distinct compartments, each managed by its own module. For more on the multistore, click [here](/advanced/04-store.md#multistore) + +## Modules + +The power of the Cosmos SDK lies in its modularity. Cosmos SDK applications are built by aggregating a collection of interoperable modules. Each module defines a subset of the state and contains its own message/transaction processor, while the Cosmos SDK is responsible for routing each message to its respective module. + +Here is a simplified view of how a transaction is processed by the application of each full-node when it is received in a valid block: + +```mermaid expandable + flowchart TD + A[Transaction relayed from the full-node's CometBFT engine to the node's application via DeliverTx] --> B[APPLICATION] + B -->|"Using baseapp's methods: Decode the Tx, extract and route the message(s)"| C[Message routed to the correct module to be processed] + C --> D1[AUTH MODULE] + C --> D2[BANK MODULE] + C --> D3[STAKING MODULE] + C --> D4[GOV MODULE] + D1 -->|Handle message, Update state| E["Return result to CometBFT (0=Ok, 1=Err)"] + D2 -->|Handle message, Update state| E["Return result to CometBFT (0=Ok, 1=Err)"] + D3 -->|Handle message, Update state| E["Return result to CometBFT (0=Ok, 1=Err)"] + D4 -->|Handle message, Update state| E["Return result to CometBFT (0=Ok, 1=Err)"] +``` + +Each module can be seen as a little state-machine. Developers need to define the subset of the state handled by the module, as well as custom message types that modify the state (*Note:* `messages` are extracted from `transactions` by `baseapp`). In general, each module declares its own `KVStore` in the `multistore` to persist the subset of the state it defines. Most developers will need to access other 3rd party modules when building their own modules. Given that the Cosmos SDK is an open framework, some of the modules may be malicious, which means there is a need for security principles to reason about inter-module interactions. These principles are based on [object-capabilities](/advanced/10-ocap.md). In practice, this means that instead of having each module keep an access control list for other modules, each module implements special objects called `keepers` that can be passed to other modules to grant a pre-defined set of capabilities. + +Cosmos SDK modules are defined in the `x/` folder of the Cosmos SDK. Some core modules include: + +* `x/auth`: Used to manage accounts and signatures. +* `x/bank`: Used to enable tokens and token transfers. +* `x/staking` + `x/slashing`: Used to build Proof-of-Stake blockchains. + +In addition to the already existing modules in `x/`, which anyone can use in their app, the Cosmos SDK lets you build your own custom modules. You can check an [example of that in the tutorial](https://tutorials.cosmos.network/). diff --git a/docs/sdk/next/learn/intro/why-app-specific.mdx b/docs/sdk/next/learn/intro/why-app-specific.mdx new file mode 100644 index 00000000..b2779218 --- /dev/null +++ b/docs/sdk/next/learn/intro/why-app-specific.mdx @@ -0,0 +1,81 @@ +--- +title: Application-Specific Blockchains +--- + +**Synopsis** +This document explains what application-specific blockchains are, and why developers would want to build one as opposed to writing Smart Contracts. + + +## What are application-specific blockchains + +Application-specific blockchains are blockchains customized to operate a single application. Instead of building a decentralized application on top of an underlying blockchain like Ethereum, developers build their own blockchain from the ground up. This means building a full-node client, a light-client, and all the necessary interfaces (CLI, REST, ...) to interact with the nodes. + +```text expandable + ^ +-------------------------------+ ^ + | | | | Built with Cosmos SDK + | | State-machine = Application | | + | | | v + | +-------------------------------+ + | | | ^ +Blockchain node | | Consensus | | + | | | | + | +-------------------------------+ | CometBFT + | | | | + | | Networking | | + | | | | + v +-------------------------------+ v +``` + +## What are the shortcomings of Smart Contracts + +Virtual-machine blockchains like Ethereum addressed the demand for more programmability back in 2014. At the time, the options available for building decentralized applications were quite limited. Most developers would build on top of the complex and limited Bitcoin scripting language, or fork the Bitcoin codebase which was hard to work with and customize. + +Virtual-machine blockchains came in with a new value proposition. Their state-machine incorporates a virtual-machine that is able to interpret turing-complete programs called Smart Contracts. These Smart Contracts are very good for use cases like one-time events (e.g. ICOs), but they can fall short for building complex decentralized platforms. Here is why: + +* Smart Contracts are generally developed with specific programming languages that can be interpreted by the underlying virtual-machine. These programming languages are often immature and inherently limited by the constraints of the virtual-machine itself. For example, the Ethereum Virtual Machine does not allow developers to implement automatic execution of code. Developers are also limited to the account-based system of the EVM, and they can only choose from a limited set of functions for their cryptographic operations. These are examples, but they hint at the lack of **flexibility** that a smart contract environment often entails. +* Smart Contracts are all run by the same virtual machine. This means that they compete for resources, which can severely restrain **performance**. And even if the state-machine were to be split in multiple subsets (e.g. via sharding), Smart Contracts would still need to be interpreted by a virtual machine, which would limit performance compared to a native application implemented at state-machine level (our benchmarks show an improvement on the order of 10x in performance when the virtual-machine is removed). +* Another issue with the fact that Smart Contracts share the same underlying environment is the resulting limitation in **sovereignty**. A decentralized application is an ecosystem that involves multiple players. If the application is built on a general-purpose virtual-machine blockchain, stakeholders have very limited sovereignty over their application, and are ultimately superseded by the governance of the underlying blockchain. If there is a bug in the application, very little can be done about it. + +Application-Specific Blockchains are designed to address these shortcomings. + +## Application-Specific Blockchains Benefits + +### Flexibility + +Application-specific blockchains give maximum flexibility to developers: + +* In Cosmos blockchains, the state-machine is typically connected to the underlying consensus engine via an interface called the [ABCI](https://docs.cometbft.com/v0.37/spec/abci/). This interface can be wrapped in any programming language, meaning developers can build their state-machine in the programming language of their choice. + +* Developers can choose among multiple frameworks to build their state-machine. The most widely used today is the Cosmos SDK, but others exist (e.g. [Lotion](https://github.com/nomic-io/lotion), [Weave](https://github.com/iov-one/weave), ...). Typically the choice will be made based on the programming language they want to use (Cosmos SDK and Weave are in Golang, Lotion is in Javascript, ...). + +* The ABCI also allows developers to swap the consensus engine of their application-specific blockchain. Today, only CometBFT is production-ready, but in the future other consensus engines are expected to emerge. + +* Even when they settle for a framework and consensus engine, developers still have the freedom to tweak them if they don't perfectly match their requirements in their pristine forms. + +* Developers are free to explore the full spectrum of tradeoffs (e.g. number of validators vs transaction throughput, safety vs availability in asynchrony, ...) and design choices (DB or IAVL tree for storage, UTXO or account model, ...). + +* Developers can implement automatic execution of code. In the Cosmos SDK, logic can be automatically triggered at the beginning and the end of each block. They are also free to choose the cryptographic library used in their application, as opposed to being constrained by what is made available by the underlying environment in the case of virtual-machine blockchains. + +The list above contains a few examples that show how much flexibility application-specific blockchains give to developers. The goal of Cosmos and the Cosmos SDK is to make developer tooling as generic and composable as possible, so that each part of the stack can be forked, tweaked and improved without losing compatibility. As the community grows, more alternatives for each of the core building blocks will emerge, giving more options to developers. + +### Performance + +Decentralized applications built with Smart Contracts are inherently capped in performance by the underlying environment. For a decentralized application to optimise performance, it needs to be built as an application-specific blockchain. Next are some of the benefits an application-specific blockchain brings in terms of performance: + +* Developers of application-specific blockchains can choose to operate with a novel consensus engine such as CometBFT. Compared to Proof-of-Work (used by most virtual-machine blockchains today), it offers significant gains in throughput. +* An application-specific blockchain only operates a single application, so that the application does not compete with others for computation and storage. This is the opposite of most non-sharded virtual-machine blockchains today, where smart contracts all compete for computation and storage. +* Even if a virtual-machine blockchain offered application-based sharding coupled with an efficient consensus algorithm, performance would still be limited by the virtual-machine itself. The real throughput bottleneck is the state-machine, and requiring transactions to be interpreted by a virtual-machine significantly increases the computational complexity of processing them. + +### Security + +Security is hard to quantify, and greatly varies from platform to platform. That said here are some important benefits an application-specific blockchain can bring in terms of security: + +* Developers can choose proven programming languages like Go when building their application-specific blockchains, as opposed to smart contract programming languages that are often more immature. +* Developers are not constrained by the cryptographic functions made available by the underlying virtual-machines. They can use their own custom cryptography, and rely on well-audited crypto libraries. +* Developers do not have to worry about potential bugs or exploitable mechanisms in the underlying virtual-machine, making it easier to reason about the security of the application. + +### Sovereignty + +One of the major benefits of application-specific blockchains is sovereignty. A decentralized application is an ecosystem that involves many actors: users, developers, third-party services, and more. When developers build on a virtual-machine blockchain where many decentralized applications coexist, the community of the application is different than the community of the underlying blockchain, and the latter supersedes the former in the governance process. If there is a bug or if a new feature is needed, stakeholders of the application have very little leeway to upgrade the code. If the community of the underlying blockchain refuses to act, nothing can happen. + +The fundamental issue here is that the governance of the application and the governance of the network are not aligned. This issue is solved by application-specific blockchains. Because application-specific blockchains specialize to operate a single application, stakeholders of the application have full control over the entire chain. This ensures that the community will not be stuck if a bug is discovered, and that it has the freedom to choose how it is going to evolve. diff --git a/docs/sdk/next/learn/learn.mdx b/docs/sdk/next/learn/learn.mdx new file mode 100644 index 00000000..b0190b34 --- /dev/null +++ b/docs/sdk/next/learn/learn.mdx @@ -0,0 +1,9 @@ +--- +title: Learn +--- +* [Introduction](intro/00-overview.md) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, + laying the groundwork for understanding blockchain development. In this section we provide a High-Level Overview of the SDK, then dive deeper into Core concepts such as Application-Specific Blockchains, Blockchain Architecture, and finally we begin to explore the main components of the SDK. +* [Beginner](beginner/00-app-anatomy.md) - Start your journey with beginner-friendly resources in the Cosmos SDK's "Learn" + section, providing a gentle entry point for newcomers to blockchain development. Here we focus on a little more detail, covering the Anatomy of a Cosmos SDK Application, Transaction Lifecycles, Accounts and lastly, Gas and Fees. +* [Advanced](advanced/00-baseapp.md) - Level up your Cosmos SDK expertise with advanced topics, tailored for experienced + developers diving into intricate blockchain application development. We cover the Cosmos SDK on a lower level as we dive into the core of the SDK with BaseApp, Transactions, Context, Node Client (Daemon), Store, Encoding, gRPC, REST, and CometBFT Endpoints, CLI, Events, Telemetry, Object-Capability Model, RunTx recovery middleware, Cosmos Blockchain Simulator, Protobuf Documentation, In-Place Store Migrations, Configuration and AutoCLI. diff --git a/docs/sdk/next/overview.mdx b/docs/sdk/next/overview.mdx new file mode 100644 index 00000000..31a1b578 --- /dev/null +++ b/docs/sdk/next/overview.mdx @@ -0,0 +1,44 @@ +--- +title: "Website" +description: "Version: latest" +--- + +This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. + +### Installation + +``` +$ yarn +``` + +### Local Development + +``` +$ yarn start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +### Build + +``` +$ yarn build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +### Deployment + +Using SSH: + +``` +$ USE_SSH=true yarn deploy +``` + +Not using SSH: + +``` +$ GIT_USER= yarn deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. \ No newline at end of file diff --git a/docs/sdk/next/tutorials/transactions/building-a-transaction.mdx b/docs/sdk/next/tutorials/transactions/building-a-transaction.mdx new file mode 100644 index 00000000..601b8f5a --- /dev/null +++ b/docs/sdk/next/tutorials/transactions/building-a-transaction.mdx @@ -0,0 +1,192 @@ +--- +title: Building a Transaction +description: >- + These are the steps to build, sign and broadcast a transaction using v2 + semantics. +--- +These are the steps to build, sign and broadcast a transaction using v2 semantics. + +1. Correctly set up imports + +```go expandable +import ( + + "context" + "fmt" + "log" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + apisigning "cosmossdk.io/api/cosmos/tx/signing/v1beta1" + "cosmossdk.io/client/v2/broadcast/comet" + "cosmossdk.io/client/v2/tx" + "cosmossdk.io/core/transaction" + "cosmossdk.io/math" + banktypes "cosmossdk.io/x/bank/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/codec" + addrcodec "github.com/cosmos/cosmos-sdk/codec/address" + sdk "github.com/cosmos/cosmos-sdk/types" +) +``` + +2. Create a gRPC connection + +```go +clientConn, err := grpc.NewClient("127.0.0.1:9090", grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + log.Fatal(err) +} +``` + +3. Setup codec and interface registry + +```go +// Setup interface registry and register necessary interfaces + interfaceRegistry := codectypes.NewInterfaceRegistry() + +banktypes.RegisterInterfaces(interfaceRegistry) + +authtypes.RegisterInterfaces(interfaceRegistry) + +cryptocodec.RegisterInterfaces(interfaceRegistry) + + // Create a ProtoCodec for encoding/decoding + protoCodec := codec.NewProtoCodec(interfaceRegistry) +``` + +4. Initialize keyring + +```go expandable +ckr, err := keyring.New("autoclikeyring", "test", home, nil, protoCodec) + if err != nil { + log.Fatal("error creating keyring", err) +} + +kr, err := keyring.NewAutoCLIKeyring(ckr, addrcodec.NewBech32Codec("cosmos")) + if err != nil { + log.Fatal("error creating auto cli keyring", err) +} +``` + +5. Setup transaction parameters + +```go expandable +// Setup transaction parameters + txParams := tx.TxParameters{ + ChainID: "simapp-v2-chain", + SignMode: apisigning.SignMode_SIGN_MODE_DIRECT, + AccountConfig: tx.AccountConfig{ + FromAddress: "cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", + FromName: "alice", +}, +} + + // Configure gas settings + gasConfig, err := tx.NewGasConfig(100, 100, "0stake") + if err != nil { + log.Fatal("error creating gas config: ", err) +} + +txParams.GasConfig = gasConfig + + // Create auth query client + authClient := authtypes.NewQueryClient(clientConn) + + // Retrieve account information for the sender + fromAccount, err := getAccount("cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", authClient, protoCodec) + if err != nil { + log.Fatal("error getting from account: ", err) +} + + // Update txParams with the correct account number and sequence + txParams.AccountConfig.AccountNumber = fromAccount.GetAccountNumber() + +txParams.AccountConfig.Sequence = fromAccount.GetSequence() + + // Retrieve account information for the recipient + toAccount, err := getAccount("cosmos1e2wanzh89mlwct7cs7eumxf7mrh5m3ykpsh66m", authClient, protoCodec) + if err != nil { + log.Fatal("error getting to account: ", err) +} + + // Configure transaction settings + txConf, _ := tx.NewTxConfig(tx.ConfigOptions{ + AddressCodec: addrcodec.NewBech32Codec("cosmos"), + Cdc: protoCodec, + ValidatorAddressCodec: addrcodec.NewBech32Codec("cosmosval"), + EnabledSignModes: []apisigning.SignMode{ + apisigning.SignMode_SIGN_MODE_DIRECT +}, +}) +``` + +6. Build the transaction + +```go expandable +// Create a transaction factory + f, err := tx.NewFactory(kr, codec.NewProtoCodec(codectypes.NewInterfaceRegistry()), nil, txConf, addrcodec.NewBech32Codec("cosmos"), clientConn, txParams) + if err != nil { + log.Fatal("error creating factory", err) +} + + // Define the transaction message + msgs := []transaction.Msg{ + &banktypes.MsgSend{ + FromAddress: fromAccount.GetAddress().String(), + ToAddress: toAccount.GetAddress().String(), + Amount: sdk.Coins{ + sdk.NewCoin("stake", math.NewInt(1000000)), +}, +}, +} + + // Build and sign the transaction + tx, err := f.BuildsSignedTx(context.Background(), msgs...) + if err != nil { + log.Fatal("error building signed tx", err) +} +``` + +7. Broadcast the transaction + +```go expandable +// Create a broadcaster for the transaction + c, err := comet.NewCometBFTBroadcaster("http://127.0.0.1:26657", comet.BroadcastSync, protoCodec) + if err != nil { + log.Fatal("error creating comet broadcaster", err) +} + + // Broadcast the transaction + res, err := c.Broadcast(context.Background(), tx.Bytes()) + if err != nil { + log.Fatal("error broadcasting tx", err) +} +``` + +8. Helpers + +```go expandable +// getAccount retrieves account information using the provided address +func getAccount(address string, authClient authtypes.QueryClient, codec codec.Codec) (sdk.AccountI, error) { + // Query account info + accountQuery, err := authClient.Account(context.Background(), &authtypes.QueryAccountRequest{ + Address: string(address), +}) + if err != nil { + return nil, fmt.Errorf("error getting account: %w", err) +} + + // Unpack the account information + var account sdk.AccountI + err = codec.InterfaceRegistry().UnpackAny(accountQuery.Account, &account) + if err != nil { + return nil, fmt.Errorf("error unpacking account: %w", err) +} + +return account, nil +} +``` diff --git a/docs/sdk/v0.53/tutorials.mdx.bak b/docs/sdk/next/tutorials/tutorials.mdx similarity index 88% rename from docs/sdk/v0.53/tutorials.mdx.bak rename to docs/sdk/next/tutorials/tutorials.mdx index 2474f604..70f5d656 100644 --- a/docs/sdk/v0.53/tutorials.mdx.bak +++ b/docs/sdk/next/tutorials/tutorials.mdx @@ -1,9 +1,7 @@ --- -title: "Tutorials" -description: "Version: v0.53" +title: Tutorials --- - -## Advanced Tutorials[​](#advanced-tutorials "Direct link to Advanced Tutorials") +## Advanced Tutorials This section provides a concise overview of tutorials focused on implementing vote extensions in the Cosmos SDK. Vote extensions are a powerful feature for enhancing the security and fairness of blockchain applications, particularly in scenarios like implementing oracles and mitigating auction front-running. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx similarity index 54% rename from docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx rename to docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx index 19c61bdf..62dfa25a 100644 --- a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx @@ -1,65 +1,105 @@ --- -title: "Demo of Mitigating Front-Running with Vote Extensions" -description: "Version: v0.53" +title: Demo of Mitigating Front-Running with Vote Extensions --- - The purpose of this demo is to test the implementation of the `VoteExtensionHandler` and `PrepareProposalHandler` that we have just added to the codebase. These handlers are designed to mitigate front-running by ensuring that all validators have a consistent view of the mempool when preparing proposals. In this demo, we are using a 3 validator network. The Beacon validator is special because it has a custom transaction provider enabled. This means that it can potentially manipulate the order of transactions in a proposal to its advantage (i.e., front-running). 1. Bootstrap the validator network: This sets up a network with 3 validators. The script \`./scripts/configure.sh is used to configure the network and the validators. -``` -cd scriptsconfigure.sh +```shell +cd scripts +configure.sh ``` If this doesn't work please ensure you have run `make build` in the `tutorials/nameservice/base` directory. -2. Have alice attempt to reserve `bob.cosmos`: This is a normal transaction that alice wants to execute. The script \``./scripts/reserve.sh "bob.cosmos"` is used to send this transaction. +{/\* nolint:all \*/} +2\. Have alice attempt to reserve `bob.cosmos`: This is a normal transaction that alice wants to execute. The script \`\`./scripts/reserve.sh "bob.cosmos"\` is used to send this transaction. -``` +```shell reserve.sh "bob.cosmos" ``` -3. Query to verify the name has been reserved: This is to check the result of the transaction. The script `./scripts/whois.sh "bob.cosmos"` is used to query the state of the blockchain. +{/\* //nolint:all \*/} +3\. Query to verify the name has been reserved: This is to check the result of the transaction. The script `./scripts/whois.sh "bob.cosmos"` is used to query the state of the blockchain. -``` +```shell whois.sh "bob.cosmos" ``` It should return: -``` - "name": { "name": "bob.cosmos", "owner": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", "resolve_address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", "amount": [ { "denom": "uatom", "amount": "1000" } ] }} +```{ expandable + "name": { + "name": "bob.cosmos", + "owner": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", + "resolve_address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", + "amount": [ + { + "denom": "uatom", + "amount": "1000" + } + ] + } +} ``` To detect front-running attempts by the beacon, scrutinise the logs during the `ProcessProposal` stage. Open the logs for each validator, including the beacon, `val1`, and `val2`, to observe the following behavior. Open the log file of the validator node. The location of this file can vary depending on your setup, but it's typically located in a directory like `$HOME/cosmos/nodes/#{validator}/logs`. The directory in this case will be under the validator so, `beacon` `val1` or `val2`. Run the following to tail the logs of the validator or beacon: -``` +```shell tail -f $HOME/cosmos/nodes/#{validator}/logs ``` -``` -2:47PM ERR ❌️:: Detected invalid proposal bid :: name:"bob.cosmos" resolveAddress:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" owner:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" amount: module=server2:47PM ERR ❌️:: Unable to validate bids in Process Proposal :: module=server2:47PM ERR prevote step: state machine rejected a proposed block; this should not happen:the proposer may be misbehaving; prevoting nil err=null height=142 module=consensus round=0 +```shell +2:47PM ERR ❌️:: Detected invalid proposal bid :: name:"bob.cosmos" resolveAddress:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" owner:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" amount: module=server +2:47PM ERR ❌️:: Unable to validate bids in Process Proposal :: module=server +2:47PM ERR prevote step: state machine rejected a proposed block; this should not happen:the proposer may be misbehaving; prevoting nil err=null height=142 module=consensus round=0 ``` -4. List the Beacon's keys: This is to verify the addresses of the validators. The script `./scripts/list-beacon-keys.sh` is used to list the keys. +{/\* //nolint:all \*/} +4\. List the Beacon's keys: This is to verify the addresses of the validators. The script `./scripts/list-beacon-keys.sh` is used to list the keys. -``` +```shell list-beacon-keys.sh ``` We should receive something similar to the following: -``` -[ { "name": "alice", "type": "local", "address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A32cvBUkNJz+h2vld4A5BxvU5Rd+HyqpR3aGtvEhlm4C\"}" }, { "name": "barbara", "type": "local", "address": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"Ag9PFsNyTQPoJdbyCWia5rZH9CrvSrjMsk7Oz4L3rXQ5\"}" }, { "name": "beacon-key", "type": "local", "address": "cosmos1ez9a6x7lz4gvn27zr368muw8jeyas7sv84lfup", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"AlzJZMWyN7lass710TnAhyuFKAFIaANJyw5ad5P2kpcH\"}" }, { "name": "cindy", "type": "local", "address": "cosmos1m5j6za9w4qc2c5ljzxmm2v7a63mhjeag34pa3g", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A6F1/3yot5OpyXoSkBbkyl+3rqBkxzRVSJfvSpm/AvW5\"}" }] +```shell expandable +[ + { + "name": "alice", + "type": "local", + "address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", + "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A32cvBUkNJz+h2vld4A5BxvU5Rd+HyqpR3aGtvEhlm4C\"}" + }, + { + "name": "barbara", + "type": "local", + "address": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", + "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"Ag9PFsNyTQPoJdbyCWia5rZH9CrvSrjMsk7Oz4L3rXQ5\"}" + }, + { + "name": "beacon-key", + "type": "local", + "address": "cosmos1ez9a6x7lz4gvn27zr368muw8jeyas7sv84lfup", + "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"AlzJZMWyN7lass710TnAhyuFKAFIaANJyw5ad5P2kpcH\"}" + }, + { + "name": "cindy", + "type": "local", + "address": "cosmos1m5j6za9w4qc2c5ljzxmm2v7a63mhjeag34pa3g", + "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A6F1/3yot5OpyXoSkBbkyl+3rqBkxzRVSJfvSpm/AvW5\"}" + } +] ``` This allows us to match up the addresses and see that the bid was not front run by the beacon due as the resolve address is Alice's address and not the beacons address. By running this demo, we can verify that the `VoteExtensionHandler` and `PrepareProposalHandler` are working as expected and that they are able to prevent front-running. -## Conclusion[​](#conclusion "Direct link to Conclusion") +## Conclusion In this tutorial, we've tackled front-running and MEV, focusing on nameservice auctions' vulnerability to these issues. We've explored vote extensions, a key feature of ABCI 2.0, and integrated them into a Cosmos SDK application. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx similarity index 64% rename from docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx rename to docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx index 511b1469..01108221 100644 --- a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx @@ -1,18 +1,19 @@ --- -title: "Getting Started" -description: "Version: v0.53" +title: Getting Started +description: >- + - Getting Started - Understanding Front-Running - Mitigating Front-running + with Vote Extensions - Demo of Mitigating Front-Running --- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") +## Table of Contents * [Getting Started](#overview-of-the-project) -* [Understanding Front-Running](/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) -* [Mitigating Front-running with Vote Extensions](/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions) -* [Demo of Mitigating Front-Running](/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running) +* [Understanding Front-Running](01-understanding-frontrunning.md) +* [Mitigating Front-running with Vote Extensions](02-mitigating-front-running-with-vote-extesions.md) +* [Demo of Mitigating Front-Running](03-demo-of-mitigating-front-running.md) -## Getting Started[​](#getting-started-1 "Direct link to Getting Started") +## Getting Started -### Overview of the Project[​](#overview-of-the-project "Direct link to Overview of the Project") +### Overview of the Project This tutorial outlines the development of a module designed to mitigate front-running in nameservice auctions. The following functions are central to this module: @@ -20,22 +21,22 @@ This tutorial outlines the development of a module designed to mitigate front-ru * `PrepareProposal`: Processes the vote extensions from the previous block, creating a special transaction that encapsulates bids to be included in the current proposal. * `ProcessProposal`: Validates that the first transaction in the proposal is the special transaction containing the vote extensions and ensures the integrity of the bids. -In this advanced tutorial, we will be working with an example application that facilitates the auctioning of nameservices. To see what frontrunning and nameservices are [here](/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) This application provides a practical use case to explore the prevention of auction front-running, also known as "bid sniping", where a validator takes advantage of seeing a bid in the mempool to place their own higher bid before the original bid is processed. +In this advanced tutorial, we will be working with an example application that facilitates the auctioning of nameservices. To see what frontrunning and nameservices are [here](01-understanding-frontrunning.md) This application provides a practical use case to explore the prevention of auction front-running, also known as "bid sniping", where a validator takes advantage of seeing a bid in the mempool to place their own higher bid before the original bid is processed. The tutorial will guide you through using the Cosmos SDK to mitigate front-running using vote extensions. The module will be built on top of the base blockchain provided in the `tutorials/base` directory and will use the `auction` module as a foundation. By the end of this tutorial, you will have a better understanding of how to prevent front-running in blockchain auctions, specifically in the context of nameservice auctioning. -## What are Vote extensions?[​](#what-are-vote-extensions "Direct link to What are Vote extensions?") +## What are Vote extensions? Vote extensions is arbitrary information which can be inserted into a block. This feature is part of ABCI 2.0, which is available for use in the SDK 0.50 release and part of the 0.38 CometBFT release. More information about vote extensions can be seen [here](https://docs.cosmos.network/main/build/abci/vote-extensions). -## Requirements and Setup[​](#requirements-and-setup "Direct link to Requirements and Setup") +## Requirements and Setup Before diving into the advanced tutorial on auction front-running simulation, ensure you meet the following requirements: * [Golang >1.21.5](https://golang.org/doc/install) installed -* Familiarity with the concepts of front-running and MEV, as detailed in [Understanding Front-Running](/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) +* Familiarity with the concepts of front-running and MEV, as detailed in [Understanding Front-Running](01-understanding-frontrunning.md) * Understanding of Vote Extensions as described [here](https://docs.cosmos.network/main/build/abci/vote-extensions) You will also need a foundational blockchain to build upon coupled with your own module. The `tutorials/base` directory has the necessary blockchain code to start your custom project with the Cosmos SDK. For the module, you can use the `auction` module provided in the `tutorials/auction/x/auction` directory as a reference but please be aware that all of the code needed to implement vote extensions is already implemented in this module. diff --git a/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx new file mode 100644 index 00000000..a6d667f2 --- /dev/null +++ b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx @@ -0,0 +1,379 @@ +--- +title: Mitigating Front-running with Vote Extensions +description: >- + Prerequisites Implementing Structs for Vote Extensions Implementing Handlers + and Configuring Handlers +--- +## Table of Contents + +* [Prerequisites](#prerequisites) +* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) +* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) + +## Prerequisites + +Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. + +In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. + +### Implementing Structs for Vote Extensions + +First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: + +```go expandable +package abci + +import ( + + //import the necessary files +) + +type PrepareProposalHandler struct { + logger log.Logger + txConfig client.TxConfig + cdc codec.Codec + mempool *mempool.ThresholdMempool + txProvider provider.TxProvider + keyname string + runProvider bool +} +``` + +The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. + +```go +type ProcessProposalHandler struct { + TxConfig client.TxConfig + Codec codec.Codec + Logger log.Logger +} +``` + +After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. + +```go +type VoteExtHandler struct { + logger log.Logger + currentBlock int64 + mempool *mempool.ThresholdMempool + cdc codec.Codec +} +``` + +This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. + +```go +type InjectedVoteExt struct { + VoteExtSigner []byte + Bids [][]byte +} + +type InjectedVotes struct { + Votes []InjectedVoteExt +} +``` + +These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. + +```go +type AppVoteExtension struct { + Height int64 + Bids [][]byte +} +``` + +This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. + +```go +type SpecialTransaction struct { + Height int + Bids [][]byte +} +``` + +This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. + +### Implementing Handlers and Configuring Handlers + +To establish the `VoteExtensionHandler`, follow these steps: + +1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. + +2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. + +```go +func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { + return &VoteExtHandler{ + logger: lg, + mempool: mp, + cdc: cdc, +} +} +``` + +3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. + +```go expandable +func (h *VoteExtHandler) + +ExtendVoteHandler() + +sdk.ExtendVoteHandler { + return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) + voteExtBids := [][]byte{ +} + + // Get mempool txs + itr := h.mempool.SelectPending(context.Background(), nil) + for itr != nil { + tmptx := itr.Tx() + sdkMsgs := tmptx.GetMsgs() + + // Iterate through msgs, check for any bids + for _, msg := range sdkMsgs { + switch msg := msg.(type) { + case *nstypes.MsgBid: + // Marshal sdk bids to []byte + bz, err := h.cdc.Marshal(msg) + if err != nil { + h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) + +break +} + +voteExtBids = append(voteExtBids, bz) + +default: +} + +} + + // Move tx to ready pool + err := h.mempool.Update(context.Background(), tmptx) + + // Remove tx from app side mempool + if err != nil { + h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) +} + +itr = itr.Next() +} + + // Create vote extension + voteExt := AppVoteExtension{ + Height: req.Height, + Bids: voteExtBids, +} + + // Encode Vote Extension + bz, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("Error marshalling VE: %w", err) +} + +return &abci.ResponseExtendVote{ + VoteExtension: bz +}, nil +} +``` + +4. Configure the handler in `app/app.go` as shown below + +```go +bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...) + voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec) + +bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) +``` + +To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. + +To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: + +```go +if req.Height > 2 { + voteExt := req.GetLocalLastCommit() + +h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) +} +``` + +This is how the whole function should look: + +```go expandable +func (h *PrepareProposalHandler) + +PrepareProposalHandler() + +sdk.PrepareProposalHandler { + return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { + h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) + +var proposalTxs [][]byte + + var txs []sdk.Tx + + // Get Vote Extensions + if req.Height > 2 { + voteExt := req.GetLocalLastCommit() + +h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) +} + itr := h.mempool.Select(context.Background(), nil) + for itr != nil { + tmptx := itr.Tx() + +txs = append(txs, tmptx) + +itr = itr.Next() +} + +h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) + if h.runProvider { + tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) + if err != nil { + h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) +} + +txs = tmpMsgs +} + for _, sdkTxs := range txs { + txBytes, err := h.txConfig.TxEncoder()(sdkTxs) + if err != nil { + h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) +} + +proposalTxs = append(proposalTxs, txBytes) +} + +h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) + +return &abci.ResponsePrepareProposal{ + Txs: proposalTxs +}, nil +} +} +``` + +As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. + +5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. + +```go expandable +func (h *ProcessProposalHandler) + +ProcessProposalHandler() + +sdk.ProcessProposalHandler { + return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { + h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) + + // The first transaction will always be the Special Transaction + numTxs := len(req.Txs) + +h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) + if numTxs >= 1 { + var st SpecialTransaction + err = json.Unmarshal(req.Txs[0], &st) + if err != nil { + h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) +} + if len(st.Bids) > 0 { + h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) + +var bids []nstypes.MsgBid + for i, b := range st.Bids { + var bid nstypes.MsgBid + h.Codec.Unmarshal(b, &bid) + +h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) + +bids = append(bids, bid) +} + // Validate Bids in Tx + txs := req.Txs[1:] + ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) + if err != nil { + h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + if !ok { + h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + +h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") +} + +} + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_ACCEPT +}, nil +} +} +``` + +6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. + +```go expandable +func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { + log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) + + // Create empty response + st := SpecialTransaction{ + 0, + [][]byte{ +}, +} + + // Get Vote Ext for H-1 from Req + voteExt := req.GetLocalLastCommit() + votes := voteExt.Votes + + // Iterate through votes + var ve AppVoteExtension + for _, vote := range votes { + // Unmarshal to AppExt + err := json.Unmarshal(vote.VoteExtension, &ve) + if err != nil { + log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) +} + +st.Height = int(ve.Height) + + // If Bids in VE, append to Special Transaction + if len(ve.Bids) > 0 { + log.Info("🛠️ :: Bids in VE") + for _, b := range ve.Bids { + st.Bids = append(st.Bids, b) +} + +} + +} + +return st, nil +} +``` + +7. Configure the `ProcessProposalHandler()` in app/app.go: + +```go +processPropHandler := abci2.ProcessProposalHandler{ + app.txConfig, appCodec, logger +} + +bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) +``` + +This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. + +To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx new file mode 100644 index 00000000..65e96f0b --- /dev/null +++ b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx @@ -0,0 +1,379 @@ +--- +title: Mitigating Front-running with Vote Extensions +description: >- + - Prerequisites - Implementing Structs for Vote Extensions - Implementing + Handlers and Configuring Handlers +--- +## Table of Contents + +* [Prerequisites](#prerequisites) +* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) +* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) + +## Prerequisites + +Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. + +In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. + +### Implementing Structs for Vote Extensions + +First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: + +```go expandable +package abci + +import ( + + //import the necessary files +) + +type PrepareProposalHandler struct { + logger log.Logger + txConfig client.TxConfig + cdc codec.Codec + mempool *mempool.ThresholdMempool + txProvider provider.TxProvider + keyname string + runProvider bool +} +``` + +The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. + +```go +type ProcessProposalHandler struct { + TxConfig client.TxConfig + Codec codec.Codec + Logger log.Logger +} +``` + +After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. + +```go +type VoteExtHandler struct { + logger log.Logger + currentBlock int64 + mempool *mempool.ThresholdMempool + cdc codec.Codec +} +``` + +This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. + +```go +type InjectedVoteExt struct { + VoteExtSigner []byte + Bids [][]byte +} + +type InjectedVotes struct { + Votes []InjectedVoteExt +} +``` + +These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. + +```go +type AppVoteExtension struct { + Height int64 + Bids [][]byte +} +``` + +This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. + +```go +type SpecialTransaction struct { + Height int + Bids [][]byte +} +``` + +This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. + +### Implementing Handlers and Configuring Handlers + +To establish the `VoteExtensionHandler`, follow these steps: + +1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. + +2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. + +```go +func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { + return &VoteExtHandler{ + logger: lg, + mempool: mp, + cdc: cdc, +} +} +``` + +3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. + +```go expandable +func (h *VoteExtHandler) + +ExtendVoteHandler() + +sdk.ExtendVoteHandler { + return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) + voteExtBids := [][]byte{ +} + + // Get mempool txs + itr := h.mempool.SelectPending(context.Background(), nil) + for itr != nil { + tmptx := itr.Tx() + sdkMsgs := tmptx.GetMsgs() + + // Iterate through msgs, check for any bids + for _, msg := range sdkMsgs { + switch msg := msg.(type) { + case *nstypes.MsgBid: + // Marshal sdk bids to []byte + bz, err := h.cdc.Marshal(msg) + if err != nil { + h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) + +break +} + +voteExtBids = append(voteExtBids, bz) + +default: +} + +} + + // Move tx to ready pool + err := h.mempool.Update(context.Background(), tmptx) + + // Remove tx from app side mempool + if err != nil { + h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) +} + +itr = itr.Next() +} + + // Create vote extension + voteExt := AppVoteExtension{ + Height: req.Height, + Bids: voteExtBids, +} + + // Encode Vote Extension + bz, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("Error marshalling VE: %w", err) +} + +return &abci.ResponseExtendVote{ + VoteExtension: bz +}, nil +} +``` + +4. Configure the handler in `app/app.go` as shown below + +```go +bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...) + voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec) + +bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) +``` + +To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. + +To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: + +```go +if req.Height > 2 { + voteExt := req.GetLocalLastCommit() + +h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) +} +``` + +This is how the whole function should look: + +```go expandable +func (h *PrepareProposalHandler) + +PrepareProposalHandler() + +sdk.PrepareProposalHandler { + return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { + h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) + +var proposalTxs [][]byte + + var txs []sdk.Tx + + // Get Vote Extensions + if req.Height > 2 { + voteExt := req.GetLocalLastCommit() + +h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) +} + itr := h.mempool.Select(context.Background(), nil) + for itr != nil { + tmptx := itr.Tx() + +txs = append(txs, tmptx) + +itr = itr.Next() +} + +h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) + if h.runProvider { + tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) + if err != nil { + h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) +} + +txs = tmpMsgs +} + for _, sdkTxs := range txs { + txBytes, err := h.txConfig.TxEncoder()(sdkTxs) + if err != nil { + h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) +} + +proposalTxs = append(proposalTxs, txBytes) +} + +h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) + +return &abci.ResponsePrepareProposal{ + Txs: proposalTxs +}, nil +} +} +``` + +As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. + +5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. + +```go expandable +func (h *ProcessProposalHandler) + +ProcessProposalHandler() + +sdk.ProcessProposalHandler { + return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { + h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) + + // The first transaction will always be the Special Transaction + numTxs := len(req.Txs) + +h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) + if numTxs >= 1 { + var st SpecialTransaction + err = json.Unmarshal(req.Txs[0], &st) + if err != nil { + h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) +} + if len(st.Bids) > 0 { + h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) + +var bids []nstypes.MsgBid + for i, b := range st.Bids { + var bid nstypes.MsgBid + h.Codec.Unmarshal(b, &bid) + +h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) + +bids = append(bids, bid) +} + // Validate Bids in Tx + txs := req.Txs[1:] + ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) + if err != nil { + h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + if !ok { + h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + +h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") +} + +} + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_ACCEPT +}, nil +} +} +``` + +6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. + +```go expandable +func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { + log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) + + // Create empty response + st := SpecialTransaction{ + 0, + [][]byte{ +}, +} + + // Get Vote Ext for H-1 from Req + voteExt := req.GetLocalLastCommit() + votes := voteExt.Votes + + // Iterate through votes + var ve AppVoteExtension + for _, vote := range votes { + // Unmarshal to AppExt + err := json.Unmarshal(vote.VoteExtension, &ve) + if err != nil { + log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) +} + +st.Height = int(ve.Height) + + // If Bids in VE, append to Special Transaction + if len(ve.Bids) > 0 { + log.Info("🛠️ :: Bids in VE") + for _, b := range ve.Bids { + st.Bids = append(st.Bids, b) +} + +} + +} + +return st, nil +} +``` + +7. Configure the `ProcessProposalHandler()` in app/app.go: + +```go +processPropHandler := abci2.ProcessProposalHandler{ + app.txConfig, appCodec, logger +} + +bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) +``` + +This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. + +To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx similarity index 76% rename from docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx rename to docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx index 910615bf..67618ad2 100644 --- a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx @@ -1,27 +1,30 @@ --- -title: "Understanding Front-Running and more" -description: "Version: v0.53" +title: Understanding Front-Running and more +description: >- + Blockchain technology is vulnerable to practices that can affect the fairness + and security of the network. Two such practices are front-running and Maximal + Extractable Value (MEV), which are important for blockchain participants to + understand. --- - -## Introduction[​](#introduction "Direct link to Introduction") +## Introduction Blockchain technology is vulnerable to practices that can affect the fairness and security of the network. Two such practices are front-running and Maximal Extractable Value (MEV), which are important for blockchain participants to understand. -## What is Front-Running?[​](#what-is-front-running "Direct link to What is Front-Running?") +## What is Front-Running? Front-running is when someone, such as a validator, uses their ability to see pending transactions to execute their own transactions first, benefiting from the knowledge of upcoming transactions. In nameservice auctions, a front-runner might place a higher bid before the original bid is confirmed, unfairly winning the auction. -## Nameservices and Nameservice Auctions[​](#nameservices-and-nameservice-auctions "Direct link to Nameservices and Nameservice Auctions") +## Nameservices and Nameservice Auctions Nameservices are human-readable identifiers on a blockchain, akin to internet domain names, that correspond to specific addresses or resources. They simplify interactions with typically long and complex blockchain addresses, allowing users to have a memorable and unique identifier for their blockchain address or smart contract. Nameservice auctions are the process by which these identifiers are bid on and acquired. To combat front-running—where someone might use knowledge of pending bids to place a higher bid first—mechanisms such as commit-reveal schemes, auction extensions, and fair sequencing are implemented. These strategies ensure a transparent and fair bidding process, reducing the potential for Maximal Extractable Value (MEV) exploitation. -## What is Maximal Extractable Value (MEV)?[​](#what-is-maximal-extractable-value-mev "Direct link to What is Maximal Extractable Value (MEV)?") +## What is Maximal Extractable Value (MEV)? MEV is the highest value that can be extracted by manipulating the order of transactions within a block, beyond the standard block rewards and fees. This has become more prominent with the growth of decentralised finance (DeFi), where transaction order can greatly affect profits. -## Implications of MEV[​](#implications-of-mev "Direct link to Implications of MEV") +## Implications of MEV MEV can lead to: @@ -29,7 +32,7 @@ MEV can lead to: * **Market Fairness**: An uneven playing field where only a few can gain at the expense of the majority. * **User Experience**: Higher fees and network congestion due to the competition for MEV. -## Mitigating MEV and Front-Running[​](#mitigating-mev-and-front-running "Direct link to Mitigating MEV and Front-Running") +## Mitigating MEV and Front-Running Some solutions being developed to mitigate MEV and front-running, including: @@ -39,6 +42,6 @@ Some solutions being developed to mitigate MEV and front-running, including: For this tutorial, we will be exploring the last solution, fair sequencing services, in the context of nameservice auctions. -## Conclusion[​](#conclusion "Direct link to Conclusion") +## Conclusion MEV and front-running are challenges to blockchain integrity and fairness. Ongoing innovation and implementation of mitigation strategies are crucial for the ecosystem's health and success. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/getting-started.mdx b/docs/sdk/next/tutorials/vote-extensions/oracle/getting-started.mdx similarity index 64% rename from docs/sdk/v0.50/tutorials/vote-extensions/oracle/getting-started.mdx rename to docs/sdk/next/tutorials/vote-extensions/oracle/getting-started.mdx index 199b67e6..b65d4980 100644 --- a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/getting-started.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/oracle/getting-started.mdx @@ -1,30 +1,29 @@ --- -title: "Getting Started" -description: "Version: v0.50" +title: Getting Started +description: What is an Oracle? Implementing Vote Extensions Testing the Oracle Module --- +## Table of Contents -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") +* [What is an Oracle?](01-what-is-an-oracle.md) +* [Implementing Vote Extensions](02-implementing-vote-extensions.md) +* [Testing the Oracle Module](03-testing-oracle.md) -* [What is an Oracle?](/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle) -* [Implementing Vote Extensions](/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions) -* [Testing the Oracle Module](/v0.50/tutorials/vote-extensions/oracle/testing-oracle) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") +## Prerequisites Before you start with this tutorial, make sure you have: * A working chain project. This tutorial won't cover the steps of creating a new chain/module. * Familiarity with the Cosmos SDK. If you're not, we suggest you start with [Cosmos SDK Tutorials](https://tutorials.cosmos.network), as ABCI++ is considered an advanced topic. -* Read and understood [What is an Oracle?](/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle). This provides necessary background information for understanding the Oracle module. +* Read and understood [What is an Oracle?](01-what-is-an-oracle.md). This provides necessary background information for understanding the Oracle module. * Basic understanding of Go programming language. -## What are Vote extensions?[​](#what-are-vote-extensions "Direct link to What are Vote extensions?") +## What are Vote extensions? Vote extensions is arbitrary information which can be inserted into a block. This feature is part of ABCI 2.0, which is available for use in the SDK 0.50 release and part of the 0.38 CometBFT release. More information about vote extensions can be seen [here](https://docs.cosmos.network/main/build/abci/vote-extensions). -## Overview of the project[​](#overview-of-the-project "Direct link to Overview of the project") +## Overview of the project We’ll go through the creation of a simple price oracle module focusing on the vote extensions implementation, ignoring the details inside the price oracle itself. diff --git a/docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx b/docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx new file mode 100644 index 00000000..78986d10 --- /dev/null +++ b/docs/sdk/next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx @@ -0,0 +1,253 @@ +--- +title: Implementing Vote Extensions +description: >- + First we’ll create the OracleVoteExtension struct, this is the object that + will be marshaled as bytes and signed by the validator. +--- +## Implement ExtendVote + +First we’ll create the `OracleVoteExtension` struct, this is the object that will be marshaled as bytes and signed by the validator. + +In our example we’ll use JSON to marshal the vote extension for simplicity but we recommend to find an encoding that produces a smaller output, given that large vote extensions could impact CometBFT’s performance. Custom encodings and compressed bytes can be used out of the box. + +```go +// OracleVoteExtension defines the canonical vote extension structure. +type OracleVoteExtension struct { + Height int64 + Prices map[string]math.LegacyDec +} +``` + +Then we’ll create a `VoteExtensionsHandler` struct that contains everything we need to query for prices. + +```go +type VoteExtHandler struct { + logger log.Logger + currentBlock int64 // current block height + lastPriceSyncTS time.Time // last time we synced prices + providerTimeout time.Duration // timeout for fetching prices from providers + providers map[string]Provider // mapping of provider name to provider (e.g. Binance -> BinanceProvider) + +providerPairs map[string][]keeper.CurrencyPair // mapping of provider name to supported pairs (e.g. Binance -> [ATOM/USD]) + +Keeper keeper.Keeper // keeper of our oracle module +} +``` + +Finally, a function that returns `sdk.ExtendVoteHandler` is needed too, and this is where our vote extension logic will live. + +```go expandable +func (h *VoteExtHandler) + +ExtendVoteHandler() + +sdk.ExtendVoteHandler { + return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { + // here we'd have a helper function that gets all the prices and does a weighted average using the volume of each market + prices := h.getAllVolumeWeightedPrices() + voteExt := OracleVoteExtension{ + Height: req.Height, + Prices: prices, +} + +bz, err := json.Marshal(voteExt) + if err != nil { + return nil, fmt.Errorf("failed to marshal vote extension: %w", err) +} + +return &abci.ResponseExtendVote{ + VoteExtension: bz +}, nil +} +} +``` + +As you can see above, the creation of a vote extension is pretty simple and we just have to return bytes. CometBFT will handle the signing of these bytes for us. We ignored the process of getting the prices but you can see a more complete example [here:](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle/abci/vote_extensions.go) + +Here we’ll do some simple checks like: + +* Is the vote extension unmarshaled correctly? +* Is the vote extension for the right height? +* Some other validation, for example, are the prices from this extension too deviated from my own prices? Or maybe checks that can detect malicious behavior. + +```go expandable +func (h *VoteExtHandler) + +VerifyVoteExtensionHandler() + +sdk.VerifyVoteExtensionHandler { + return func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { + var voteExt OracleVoteExtension + err := json.Unmarshal(req.VoteExtension, &voteExt) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal vote extension: %w", err) +} + if voteExt.Height != req.Height { + return nil, fmt.Errorf("vote extension height does not match request height; expected: %d, got: %d", req.Height, voteExt.Height) +} + + // Verify incoming prices from a validator are valid. Note, verification during + // VerifyVoteExtensionHandler MUST be deterministic. For brevity and demo + // purposes, we omit implementation. + if err := h.verifyOraclePrices(ctx, voteExt.Prices); err != nil { + return nil, fmt.Errorf("failed to verify oracle prices from validator %X: %w", req.ValidatorAddress, err) +} + +return &abci.ResponseVerifyVoteExtension{ + Status: abci.ResponseVerifyVoteExtension_ACCEPT +}, nil +} +} +``` + +## Implement PrepareProposal + +```go +type ProposalHandler struct { + logger log.Logger + keeper keeper.Keeper // our oracle module keeper + valStore baseapp.ValidatorStore // to get the current validators' pubkeys +} +``` + +And we create the struct for our “special tx”, that will contain the prices and the votes so validators can later re-check in ProcessPRoposal that they get the same result than the block’s proposer. With this we could also check if all the votes have been used by comparing the votes received in ProcessProposal. + +```go +type StakeWeightedPrices struct { + StakeWeightedPrices map[string]math.LegacyDec + ExtendedCommitInfo abci.ExtendedCommitInfo +} +``` + +Now we create the `PrepareProposalHandler`. In this step we’ll first check if the vote extensions’ signatures are correct using a helper function called ValidateVoteExtensions from the baseapp package. + +```go +func (h *ProposalHandler) + +PrepareProposal() + +sdk.PrepareProposalHandler { + return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { + err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), req.LocalLastCommit) + if err != nil { + return nil, err +} +... +``` + +Then we proceed to make the calculations only if the current height if higher than the height at which vote extensions have been enabled. Remember that vote extensions are made available to the block proposer on the next block at which they are produced/enabled. + +```go expandable +... + proposalTxs := req.Txs + if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { + stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, req.LocalLastCommit) + if err != nil { + return nil, errors.New("failed to compute stake-weighted oracle prices") +} + injectedVoteExtTx := StakeWeightedPrices{ + StakeWeightedPrices: stakeWeightedPrices, + ExtendedCommitInfo: req.LocalLastCommit, +} +... +``` + +Finally we inject the result as a transaction at a specific location, usually at the beginning of the block: + +## Implement ProcessProposal + +Now we can implement the method that all validators will execute to ensure the proposer is doing his work correctly. + +Here, if vote extensions are enabled, we’ll check if the tx at index 0 is an injected vote extension + +```go +func (h *ProposalHandler) + +ProcessProposal() + +sdk.ProcessProposalHandler { + return func(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { + if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { + var injectedVoteExtTx StakeWeightedPrices + if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { + h.logger.Error("failed to decode injected vote extension tx", "err", err) + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} +... +``` + +Then we re-validate the vote extensions signatures using +baseapp.ValidateVoteExtensions, re-calculate the results (just like in PrepareProposal) and compare them with the results we got from the injected tx. + +```go expandable +err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), injectedVoteExtTx.ExtendedCommitInfo) + if err != nil { + return nil, err +} + + // Verify the proposer's stake-weighted oracle prices by computing the same + // calculation and comparing the results. We omit verification for brevity + // and demo purposes. + stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, injectedVoteExtTx.ExtendedCommitInfo) + if err != nil { + return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + if err := compareOraclePrices(injectedVoteExtTx.StakeWeightedPrices, stakeWeightedPrices); err != nil { + return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_REJECT +}, nil +} + +} + +return &abci.ResponseProcessProposal{ + Status: abci.ResponseProcessProposal_ACCEPT +}, nil +} +} +``` + +Important: In this example we avoided using the mempool and other basics, please refer to the DefaultProposalHandler for a complete implementation: [Link](https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/abci_utils.go) + +## Implement PreBlocker + +Now validators are extending their vote, verifying other votes and including the result in the block. But how do we actually make use of this result? This is done in the PreBlocker which is code that is run before any other code during FinalizeBlock so we make sure we make this information available to the chain and its modules during the entire block execution (from BeginBlock). + +At this step we know that the injected tx is well-formatted and has been verified by the validators participating in consensus, so making use of it is straightforward. Just check if vote extensions are enabled, pick up the first transaction and use a method in your module’s keeper to set the result. + +```go expandable +func (h *ProposalHandler) + +PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { + res := &sdk.ResponsePreBlock{ +} + if len(req.Txs) == 0 { + return res, nil +} + if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { + var injectedVoteExtTx StakeWeightedPrices + if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { + h.logger.Error("failed to decode injected vote extension tx", "err", err) + +return nil, err +} + + // set oracle prices using the passed in context, which will make these prices available in the current block + if err := h.keeper.SetOraclePrices(ctx, injectedVoteExtTx.StakeWeightedPrices); err != nil { + return nil, err +} + +} + +return res, nil +} +``` + +## Conclusion + +In this tutorial, we've created a simple price oracle module that incorporates vote extensions. We've seen how to implement `ExtendVote`, `VerifyVoteExtension`, `PrepareProposal`, `ProcessProposal`, and `PreBlocker` to handle the voting and verification process of vote extensions, as well as how to make use of the results during the block execution. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/testing-oracle.mdx b/docs/sdk/next/tutorials/vote-extensions/oracle/testing-oracle.mdx similarity index 78% rename from docs/sdk/v0.50/tutorials/vote-extensions/oracle/testing-oracle.mdx rename to docs/sdk/next/tutorials/vote-extensions/oracle/testing-oracle.mdx index a13af96e..e143a577 100644 --- a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/testing-oracle.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/oracle/testing-oracle.mdx @@ -1,57 +1,60 @@ --- -title: "Testing the Oracle Module" -description: "Version: v0.50" +title: Testing the Oracle Module +description: >- + We will guide you through the process of testing the Oracle module in your + application. The Oracle module uses vote extensions to provide current price + data. If you would like to see the complete working oracle module please see + here. --- - We will guide you through the process of testing the Oracle module in your application. The Oracle module uses vote extensions to provide current price data. If you would like to see the complete working oracle module please see [here](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle). -## Step 1: Compile and Install the Application[​](#step-1-compile-and-install-the-application "Direct link to Step 1: Compile and Install the Application") +## Step 1: Compile and Install the Application First, we need to compile and install the application. Please ensure you are in the `tutorials/oracle/base` directory. Run the following command in your terminal: -``` +```shell make install ``` This command compiles the application and moves the resulting binary to a location in your system's PATH. -## Step 2: Initialise the Application[​](#step-2-initialise-the-application "Direct link to Step 2: Initialise the Application") +## Step 2: Initialise the Application Next, we need to initialise the application. Run the following command in your terminal: -``` +```shell make init ``` This command runs the script `tutorials/oracle/base/scripts/init.sh`, which sets up the necessary configuration for your application to run. This includes creating the `app.toml` configuration file and initialising the blockchain with a genesis block. -## Step 3: Start the Application[​](#step-3-start-the-application "Direct link to Step 3: Start the Application") +## Step 3: Start the Application Now, we can start the application. Run the following command in your terminal: -``` +```shell exampled start ``` This command starts your application, begins the blockchain node, and starts processing transactions. -## Step 4: Query the Oracle Prices[​](#step-4-query-the-oracle-prices "Direct link to Step 4: Query the Oracle Prices") +## Step 4: Query the Oracle Prices Finally, we can query the current prices from the Oracle module. Run the following command in your terminal: -``` +```shell exampled q oracle prices ``` This command queries the current prices from the Oracle module. The expected output shows that the vote extensions were successfully included in the block and the Oracle module was able to retrieve the price data. -## Understanding Vote Extensions in Oracle[​](#understanding-vote-extensions-in-oracle "Direct link to Understanding Vote Extensions in Oracle") +## Understanding Vote Extensions in Oracle In the Oracle module, the `ExtendVoteHandler` function is responsible for creating the vote extensions. This function fetches the current prices from the provider, creates a `OracleVoteExtension` struct with these prices, and then marshals this struct into bytes. These bytes are then set as the vote extension. In the context of testing, the Oracle module uses a mock provider to simulate the behavior of a real price provider. This mock provider is defined in the mockprovider package and is used to return predefined prices for specific currency pairs. -## Conclusion[​](#conclusion "Direct link to Conclusion") +## Conclusion In this tutorial, we've delved into the concept of Oracle's in blockchain technology, focusing on their role in providing external data to a blockchain network. We've explored vote extensions, a powerful feature of ABCI++, and integrated them into a Cosmos SDK application to create a price oracle module. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx b/docs/sdk/next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx similarity index 82% rename from docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx rename to docs/sdk/next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx index cfca8c4d..492bc8c3 100644 --- a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx +++ b/docs/sdk/next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx @@ -1,16 +1,14 @@ --- -title: "What is an Oracle?" -description: "Version: v0.50" +title: What is an Oracle? --- - An oracle in blockchain technology is a system that provides external data to a blockchain network. It acts as a source of information that is not natively accessible within the blockchain's closed environment. This can range from financial market prices to real-world event, making it crucial for decentralised applications. -## Oracle in the Cosmos SDK[​](#oracle-in-the-cosmos-sdk "Direct link to Oracle in the Cosmos SDK") +## Oracle in the Cosmos SDK In the Cosmos SDK, an oracle module can be implemented to provide external data to the blockchain. This module can use features like vote extensions to submit additional data during the consensus process, which can then be used by the blockchain to update its state with information from the outside world. For instance, a price oracle module in the Cosmos SDK could supply timely and accurate asset price information, which is vital for various financial operations within the blockchain ecosystem. -## Conclusion[​](#conclusion "Direct link to Conclusion") +## Conclusion Oracles are essential for blockchains to interact with external data, enabling them to respond to real-world information and events. Their implementation is key to the reliability and robustness of blockchain networks. diff --git a/docs/sdk/next/user/run-node/interact-node.mdx b/docs/sdk/next/user/run-node/interact-node.mdx new file mode 100644 index 00000000..2142c593 --- /dev/null +++ b/docs/sdk/next/user/run-node/interact-node.mdx @@ -0,0 +1,298 @@ +--- +title: Interacting with the Node +--- + +**Synopsis** +There are multiple ways to interact with a node: using the CLI, using gRPC or using the REST endpoints. + + + +**Pre-requisite Readings** + +* [gRPC, REST and CometBFT Endpoints](/../learn/advanced/06-grpc_rest.md) +* [Running a Node](01-run-node.md) + + + +## Using the CLI + +Now that your chain is running, it is time to try sending tokens from the first account you created to a second account. In a new terminal window, start by running the following query command: + +```bash +simd query bank balances $MY_VALIDATOR_ADDRESS +``` + +You should see the current balance of the account you created, equal to the original balance of `stake` you granted it minus the amount you delegated via the `gentx`. Now, create a second account: + +```bash +simd keys add recipient --keyring-backend test + +# Put the generated address in a variable for later use. +RECIPIENT=$(simd keys show recipient -a --keyring-backend test) +``` + +The command above creates a local key-pair that is not yet registered on the chain. An account is created the first time it receives tokens from another account. Now, run the following command to send tokens to the `recipient` account: + +```bash +simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000000stake --chain-id my-test-chain --keyring-backend test + +# Check that the recipient account did receive the tokens. +simd query bank balances $RECIPIENT +``` + +Finally, delegate some of the stake tokens sent to the `recipient` account to the validator: + +```bash +simd tx staking delegate $(simd keys show my_validator --bech val -a --keyring-backend test) 500stake --from recipient --chain-id my-test-chain --keyring-backend test + +# Query the total delegations to `validator`. +simd query staking delegations-to $(simd keys show my_validator --bech val -a --keyring-backend test) +``` + +You should see two delegations, the first one made from the `gentx`, and the second one you just performed from the `recipient` account. + +## Using gRPC + +The Protobuf ecosystem developed tools for different use cases, including code-generation from `*.proto` files into various languages. These tools allow the building of clients easily. Often, the client connection (i.e. the transport) can be plugged and replaced very easily. Let's explore one of the most popular transports: [gRPC](/../learn/advanced/06-grpc_rest.md). + +Since the code generation library largely depends on your own tech stack, we will only present three alternatives: + +* `grpcurl` for generic debugging and testing, +* programmatically via Go, +* CosmJS for JavaScript/TypeScript developers. + +### grpcurl + +[grpcurl](https://github.com/fullstorydev/grpcurl) is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it. + +Assuming you have a local node running (either a localnet, or connected to a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml)): + +```bash +grpcurl -plaintext localhost:9090 list +``` + +You should see a list of gRPC services, like `cosmos.bank.v1beta1.Query`. This is called reflection, which is a Protobuf endpoint returning a description of all available endpoints. Each of these represents a different Protobuf service, and each service exposes multiple RPC methods you can query against. + +In order to get a description of the service you can run the following command: + +```bash +grpcurl -plaintext \ + localhost:9090 \ + describe cosmos.bank.v1beta1.Query # Service we want to inspect +``` + +It's also possible to execute an RPC call to query the node for information: + +```bash +grpcurl \ + -plaintext \ + -d "{\"address\":\"$MY_VALIDATOR_ADDRESS\"}" \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/AllBalances +``` + +The list of all available gRPC query endpoints is [coming soon](https://github.com/cosmos/cosmos-sdk/issues/7786). + +#### Query for historical state using grpcurl + +You may also query for historical data by passing some [gRPC metadata](https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md) to the query: the `x-cosmos-block-height` metadata should contain the block to query. Using grpcurl as above, the command looks like: + +```bash +grpcurl \ + -plaintext \ + -H "x-cosmos-block-height: 123" \ + -d "{\"address\":\"$MY_VALIDATOR_ADDRESS\"}" \ + localhost:9090 \ + cosmos.bank.v1beta1.Query/AllBalances +``` + +Assuming the state at that block has not yet been pruned by the node, this query should return a non-empty response. + +### Programmatically via Go + +The following snippet shows how to query the state using gRPC inside a Go program. The idea is to create a gRPC connection, and use the Protobuf-generated client code to query the gRPC server. + +#### Install Cosmos SDK + +```bash +go get github.com/cosmos/cosmos-sdk@main +``` + +```go expandable +package main + +import ( + + "context" + "fmt" + "google.golang.org/grpc" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +func queryState() + +error { + myAddress, err := sdk.AccAddressFromBech32("cosmos1...") // the my_validator or recipient address. + if err != nil { + return err +} + + // Create a connection to the gRPC server. + grpcConn, err := grpc.Dial( + "127.0.0.1:9090", // your gRPC server address. + grpc.WithInsecure(), // The Cosmos SDK doesn't support any transport security mechanism. + // This instantiates a general gRPC codec which handles proto bytes. We pass in a nil interface registry + // if the request/response types contain interface instead of 'nil' you should pass the application specific codec. + grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(nil).GRPCCodec())), + ) + if err != nil { + return err +} + +defer grpcConn.Close() + + // This creates a gRPC client to query the x/bank service. + bankClient := banktypes.NewQueryClient(grpcConn) + +bankRes, err := bankClient.Balance( + context.Background(), + &banktypes.QueryBalanceRequest{ + Address: myAddress.String(), + Denom: "stake" +}, + ) + if err != nil { + return err +} + +fmt.Println(bankRes.GetBalance()) // Prints the account balance + + return nil +} + +func main() { + if err := queryState(); err != nil { + panic(err) +} +} +``` + +You can replace the query client (here we are using `x/bank`'s) with one generated from any other Protobuf service. The list of all available gRPC query endpoints is [coming soon](https://github.com/cosmos/cosmos-sdk/issues/7786). + +#### Query for historical state using Go + +Querying for historical blocks is done by adding the block height metadata in the gRPC request. + +```go expandable +package main + +import ( + + "context" + "fmt" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +func queryState() + +error { + myAddress, err := sdk.AccAddressFromBech32("cosmos1yerherx4d43gj5wa3zl5vflj9d4pln42n7kuzu") // the my_validator or recipient address. + if err != nil { + return err +} + + // Create a connection to the gRPC server. + grpcConn, err := grpc.Dial( + "127.0.0.1:9090", // your gRPC server address. + grpc.WithInsecure(), // The Cosmos SDK doesn't support any transport security mechanism. + // This instantiates a general gRPC codec which handles proto bytes. We pass in a nil interface registry + // if the request/response types contain interface instead of 'nil' you should pass the application specific codec. + grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(nil).GRPCCodec())), + ) + if err != nil { + return err +} + +defer grpcConn.Close() + + // This creates a gRPC client to query the x/bank service. + bankClient := banktypes.NewQueryClient(grpcConn) + +var header metadata.MD + _, err = bankClient.Balance( + metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, "12"), // Add metadata to request + &banktypes.QueryBalanceRequest{ + Address: myAddress.String(), + Denom: "stake" +}, + grpc.Header(&header), // Retrieve header from response + ) + if err != nil { + return err +} + blockHeight := header.Get(grpctypes.GRPCBlockHeightHeader) + +fmt.Println(blockHeight) // Prints the block height (12) + +return nil +} + +func main() { + if err := queryState(); err != nil { + panic(err) +} +} +``` + +### CosmJS + +CosmJS documentation can be found at [Link](https://cosmos.github.io/cosmjs). As of January 2021, CosmJS documentation is still a work in progress. + +## Using the REST Endpoints + +As described in the [gRPC guide](/../learn/advanced/06-grpc_rest.md), all gRPC services on the Cosmos SDK are made available for more convenient REST-based queries through gRPC-gateway. The format of the URL path is based on the Protobuf service method's full-qualified name, but may contain small customizations so that final URLs look more idiomatic. For example, the REST endpoint for the `cosmos.bank.v1beta1.Query/AllBalances` method is `GET /cosmos/bank/v1beta1/balances/{address}`. Request arguments are passed as query parameters. + +Note that the REST endpoints are not enabled by default. To enable them, edit the `api` section of your `~/.simapp/config/app.toml` file: + +```toml +# Enable defines if the API server should be enabled. +enable = true +``` + +As a concrete example, the `curl` command to make balances request is: + +```bash +curl \ + -X GET \ + -H "Content-Type: application/json" \ + http://localhost:1317/cosmos/bank/v1beta1/balances/$MY_VALIDATOR_ADDRESS +``` + +Make sure to replace `localhost:1317` with the REST endpoint of your node, configured under the `api.address` field. + +The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) file. + +### Query for historical state using REST + +Querying for historical state is done using the HTTP header `x-cosmos-block-height`. For example, a curl command would look like: + +```bash +curl \ + -X GET \ + -H "Content-Type: application/json" \ + -H "x-cosmos-block-height: 123" \ + http://localhost:1317/cosmos/bank/v1beta1/balances/$MY_VALIDATOR_ADDRESS +``` + +Assuming the state at that block has not yet been pruned by the node, this query should return a non-empty response. + +### Cross-Origin Resource Sharing (CORS) + +[CORS policies](https://developer.mozilla.org/en-US/docs/sdk/next/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `enabled-unsafe-cors` field inside [`app.toml`](/../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). diff --git a/docs/sdk/next/user/run-node/keyring.mdx b/docs/sdk/next/user/run-node/keyring.mdx new file mode 100644 index 00000000..af3b321d --- /dev/null +++ b/docs/sdk/next/user/run-node/keyring.mdx @@ -0,0 +1,143 @@ +--- +title: Setting up the keyring +--- + +**Synopsis** +This document describes how to configure and use the keyring and its various backends for an [**application**](/../learn/beginner/00-app-anatomy.md). + + +The keyring holds the private/public key pairs used to interact with a node. For instance, a validator key needs to be set up before running the blockchain node, so that blocks can be correctly signed. The private key can be stored in different locations, called "backends," such as a file or the operating system's own key storage. + +## Available backends for the keyring + +Starting with the v0.38.0 release, Cosmos SDK comes with a new keyring implementation +that provides a set of commands to manage cryptographic keys in a secure fashion. The +new keyring supports multiple storage backends, some of which may not be available on +all operating systems. + +### The `os` backend + +The `os` backend relies on operating system-specific defaults to handle key storage +securely. Typically, an operating system's credential subsystem handles password prompts, +private keys storage, and user sessions according to the user's password policies. Here +is a list of the most popular operating systems and their respective password managers: + +* macOS: [Keychain](https://support.apple.com/en-gb/guide/keychain-access/welcome/mac) +* Windows: [Credentials Management API](https://docs.microsoft.com/en-us/windows/win32/secauthn/credentials-management) +* GNU/Linux: + * [libsecret](https://gitlab.gnome.org/GNOME/libsecret) + * [kwallet](https://api.kde.org/frameworks/kwallet/html/index.html) + * [keyctl](https://www.kernel.org/doc/html/latest/security/keys/core.html) + +GNU/Linux distributions that use GNOME as the default desktop environment typically come with +[Seahorse](https://wiki.gnome.org/Apps/Seahorse). Users of KDE based distributions are +commonly provided with [KDE Wallet Manager](https://userbase.kde.org/KDE_Wallet_Manager). +Whilst the former is in fact a `libsecret` convenient frontend, the latter is a `kwallet` +client. `keyctl` is a secure backend that leverages the Linux kernel security key management system +to store cryptographic keys securely in memory. + +`os` is the default option since operating system's default credentials managers are +designed to meet users' most common needs and provide them with a comfortable +experience without compromising on security. + +The recommended backends for headless environments are `file` and `pass`. + +### The `file` backend + +The `file` backend more closely resembles the keybase implementation used prior to +v0.38.1. It stores the keyring encrypted within the app's configuration directory. This +keyring will request a password each time it is accessed, which may occur multiple +times in a single command resulting in repeated password prompts. If using bash scripts +to execute commands using the `file` option you may want to utilize the following format +for multiple prompts: + +```shell +# assuming that KEYPASSWD is set in the environment +$ gaiacli config keyring-backend file # use file backend +$ (echo $KEYPASSWD; echo $KEYPASSWD) | gaiacli keys add me # multiple prompts +$ echo $KEYPASSWD | gaiacli keys show me # single prompt +``` + + +The first time you add a key to an empty keyring, you will be prompted to type the password twice. + + +### The `pass` backend + +The `pass` backend uses the [pass](https://www.passwordstore.org/) utility to manage on-disk +encryption of keys' sensitive data and metadata. Keys are stored inside `gpg` encrypted files +within app-specific directories. `pass` is available for the most popular UNIX +operating systems as well as GNU/Linux distributions. Please refer to its manual page for +information on how to download and install it. + + +**pass** uses [GnuPG](https://gnupg.org/) for encryption. `gpg` automatically invokes the `gpg-agent` +daemon upon execution, which handles the caching of GnuPG credentials. Please refer to `gpg-agent` +man page for more information on how to configure cache parameters such as credentials TTL and +passphrase expiration. + + +The password store must be set up prior to first use: + +```shell +pass init +``` + +Replace `` with your GPG key ID. You can use your personal GPG key or an alternative +one you may want to use specifically to encrypt the password store. + +### The `kwallet` backend + +The `kwallet` backend uses `KDE Wallet Manager`, which comes installed by default on the +GNU/Linux distributions that ship KDE as the default desktop environment. Please refer to +[KWallet API documentation](https://api.kde.org/frameworks/kwallet/html/index.html) for more +information. + +### The `keyctl` backend + +The *Kernel Key Retention Service* is a security facility that +has been added to the Linux kernel relatively recently. It allows sensitive +cryptographic data such as passwords, private key, authentication tokens, etc +to be stored securely in memory. + +The `keyctl` backend is available on Linux platforms only. + +### The `test` backend + +The `test` backend is a password-less variation of the `file` backend. Keys are stored +unencrypted on disk. + +**Provided for testing purposes only. The `test` backend is not recommended for use in production environments**. + +### The `memory` backend + +The `memory` backend stores keys in memory. The keys are immediately deleted after the program has exited. + +**Provided for testing purposes only. The `memory` backend is not recommended for use in production environments**. + +### Setting backend using an env variable + +You can set the keyring-backend using env variable: `BINNAME_KEYRING_BACKEND`. For example, if your binary name is `gaia-v5` then set: `export GAIA_V5_KEYRING_BACKEND=pass` + +## Adding keys to the keyring + + +Make sure you can build your own binary, and replace `simd` with the name of your binary in the snippets. + + +Applications developed using the Cosmos SDK come with the `keys` subcommand. For the purpose of this tutorial, we're running the `simd` CLI, which is an application built using the Cosmos SDK for testing and educational purposes. For more information, see [`simapp`](https://github.com/cosmos/cosmos-sdk/tree/main/simapp). + +You can use `simd keys` for help about the keys command and `simd keys [command] --help` for more information about a particular subcommand. + +To create a new key in the keyring, run the `add` subcommand with a `` argument. For the purpose of this tutorial, we will solely use the `test` backend, and call our new key `my_validator`. This key will be used in the next section. + +```bash +$ simd keys add my_validator --keyring-backend test + +# Put the generated address in a variable for later use. +MY_VALIDATOR_ADDRESS=$(simd keys show my_validator -a --keyring-backend test) +``` + +This command generates a new 24-word mnemonic phrase, persists it to the relevant backend, and outputs information about the keypair. If this keypair will be used to hold value-bearing tokens, be sure to write down the mnemonic phrase somewhere safe! + +By default, the keyring generates a `secp256k1` keypair. The keyring also supports `ed25519` keys, which may be created by passing the `--algo ed25519` flag. A keyring can of course hold both types of keys simultaneously, and the Cosmos SDK's `x/auth` module supports natively these two public key algorithms. diff --git a/docs/sdk/next/user/run-node/rosetta.mdx b/docs/sdk/next/user/run-node/rosetta.mdx new file mode 100644 index 00000000..c7267537 --- /dev/null +++ b/docs/sdk/next/user/run-node/rosetta.mdx @@ -0,0 +1,154 @@ +--- +title: Rosetta +description: >- + The rosetta project implements Coinbase's Rosetta API. This document provides + instructions on how to use the Rosetta API integration. For information about + the motivation and design choices, refer to ADR 035. +--- +The `rosetta` project implements Coinbase's [Rosetta API](https://www.rosetta-api.org). This document provides instructions on how to use the Rosetta API integration. For information about the motivation and design choices, refer to [ADR 035](https://docs.cosmos.network/main/architecture/adr-035-rosetta-api-support). + +## Installing Rosetta + +The Rosetta API server is a stand-alone server that connects to a node of a chain developed with Cosmos SDK. + +Rosetta can be added to any cosmos chain node. standalone or natively. + +### Standalone + +Rosetta can be executed as a standalone service, it connects to the node endpoints and expose the required endpoints. + +Install Rosetta standalone server with the following command: + +```bash +go install github.com/cosmos/rosetta +``` + +Alternatively, for building from source, simply run `make build`. The binary will be located in the root folder. + +### Native - As a node command + +To enable Native Rosetta API support, it's required to add the `RosettaCommand` to your application's root command file (e.g. `simd/cmd/root.go`). + +Import the `rosettaCmd` package: + +```go +import "github.com/cosmos/rosetta/cmd" +``` + +Find the following line: + +```go +initRootCmd(rootCmd, encodingConfig) +``` + +After that line, add the following: + +```go +rootCmd.AddCommand( + rosettaCmd.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Codec) +) +``` + +The `RosettaCommand` function builds the `rosetta` root command and is defined in the `rosettaCmd` package (`github.com/cosmos/rosetta/cmd`). + +Since we’ve updated the Cosmos SDK to work with the Rosetta API, updating the application's root command file is all you need to do. + +An implementation example can be found in `simapp` package. + +## Use Rosetta Command + +To run Rosetta in your application CLI, use the following command: + +> **Note:** if using the native approach, add your node name before any rosetta command. + +```shell +rosetta --help +``` + +To test and run Rosetta API endpoints for applications that are running and exposed, use the following command: + +```shell +rosetta + --blockchain "your application name (ex: gaia)" + --network "your chain identifier (ex: testnet-1)" + --tendermint "tendermint endpoint (ex: localhost:26657)" + --grpc "gRPC endpoint (ex: localhost:9090)" + --addr "rosetta binding address (ex: :8080)" + --grpc-types-server (optional) "gRPC endpoint for message descriptor types" +``` + +## Plugins - Multi chain connections + +Rosetta will try to reflect the node types trough reflection over the node gRPC endpoints, there may be cases were this approach is not enough. It is possible to extend or implement the required types easily through plugins. + +To use Rosetta over any chain, it is required to set up prefixes and registering zone specific interfaces through plugins. + +Each plugin is a minimalist implementation of `InitZone` and `RegisterInterfaces` which allow Rosetta to parse chain specific data. There is an example for cosmos-hub chain under `plugins/cosmos-hun/` folder + +* **InitZone**: An empty method that is executed first and defines prefixes, parameters and other settings. +* **RegisterInterfaces**: This method receives an interface registry which is were the zone specific types and interfaces will be loaded + +In order to add a new plugin: + +1. Create a folder over `plugins` folder with the name of the desired zone +2. Add a `main.go` file with the mentioned methods above. +3. Build the code binary through `go build -buildmode=plugin -o main.so main.go` + +The plugin folder is selected through the cli `--plugin` flag and loaded into the Rosetta server. + +## Extensions + +There are two ways in which you can customize and extend the implementation with your custom settings. + +### Message extension + +In order to make an `sdk.Msg` understandable by rosetta the only thing which is required is adding the methods to your messages that satisfy the `rosetta.Msg` interface. Examples on how to do so can be found in the staking types such as `MsgDelegate`, or in bank types such as `MsgSend`. + +### Client interface override + +In case more customization is required, it's possible to embed the Client type and override the methods which require customizations. + +Example: + +```go expandable +package custom_client +import ( + + +"context" + "github.com/coinbase/rosetta-sdk-go/types" + "github.com/cosmos/rosetta/lib" +) + +// CustomClient embeds the standard cosmos client +// which means that it implements the cosmos-rosetta-gateway Client +// interface while at the same time allowing to customize certain methods +type CustomClient struct { + *rosetta.Client +} + +func (c *CustomClient) + +ConstructionPayload(_ context.Context, request *types.ConstructionPayloadsRequest) (resp *types.ConstructionPayloadsResponse, err error) { + // provide custom signature bytes + panic("implement me") +} +``` + +NOTE: when using a customized client, the command cannot be used as the constructors required **may** differ, so it's required to create a new one. We intend to provide a way to init a customized client without writing extra code in the future. + +### Error extension + +Since rosetta requires to provide 'returned' errors to network options. In order to declare a new rosetta error, we use the `errors` package in cosmos-rosetta-gateway. + +Example: + +```go +package custom_errors +import crgerrs "github.com/cosmos/rosetta/lib/errors" + +var customErrRetriable = true +var CustomError = crgerrs.RegisterError(100, "custom message", customErrRetriable, "description") +``` + +Note: errors must be registered before cosmos-rosetta-gateway's `Server`.`Start` method is called. Otherwise the registration will be ignored. Errors with same code will be ignored too. diff --git a/docs/sdk/next/user/run-node/run-node.mdx b/docs/sdk/next/user/run-node/run-node.mdx new file mode 100644 index 00000000..c6f1ca18 --- /dev/null +++ b/docs/sdk/next/user/run-node/run-node.mdx @@ -0,0 +1,217 @@ +--- +title: Running a Node +--- + +**Synopsis** +Now that the application is ready and the keyring populated, it's time to see how to run the blockchain node. In this section, the application we are running is called [`simapp`](https://github.com/cosmos/cosmos-sdk/tree/main/simapp), and its corresponding CLI binary `simd`. + + + +**Pre-requisite Readings** + +* [Anatomy of a Cosmos SDK Application](/../learn/beginner/00-app-anatomy.md) +* [Setting up the keyring](00-keyring.md) + + + +## Initialize the Chain + + +Make sure you can build your own binary, and replace `simd` with the name of your binary in the snippets. + + +Before actually running the node, we need to initialize the chain, and most importantly, its genesis file. This is done with the `init` subcommand: + +```bash +# The argument is the custom username of your node, it should be human-readable. +simd init --chain-id my-test-chain +``` + +The command above creates all the configuration files needed for your node to run, as well as a default genesis file, which defines the initial state of the network. + + +All these configuration files are in `~/.simapp` by default, but you can overwrite the location of this folder by passing the `--home` flag to each command, +or set an `$APPD_HOME` environment variable (where `APPD` is the name of the binary). + + +The `~/.simapp` folder has the following structure: + +```bash +. # ~/.simapp + |- data # Contains the databases used by the node. + |- config/ + |- app.toml # Application-related configuration file. + |- config.toml # CometBFT-related configuration file. + |- genesis.json # The genesis file. + |- node_key.json # Private key to use for node authentication in the p2p protocol. + |- priv_validator_key.json # Private key to use as a validator in the consensus protocol. +``` + +## Updating Some Default Settings + +If you want to change any field values in configuration files (for ex: genesis.json) you can use `jq` ([installation](https://stedolan.github.io/jq/download/) & [docs](https://stedolan.github.io/jq/manual/#Assignment)) & `sed` commands to do that. A few examples are listed here. + +```bash expandable +# to change the chain-id +jq '.chain_id = "testing"' genesis.json > temp.json && mv temp.json genesis.json + +# to enable the api server +sed -i '/\[api\]/,+3 s/enable = false/enable = true/' app.toml + +# to change the voting_period +jq '.app_state.gov.voting_params.voting_period = "600s"' genesis.json > temp.json && mv temp.json genesis.json + +# to change the inflation +jq '.app_state.mint.minter.inflation = "0.300000000000000000"' genesis.json > temp.json && mv temp.json genesis.json +``` + +### Client Interaction + +When instantiating a node, GRPC and REST are defaulted to localhost to avoid unknown exposure of your node to the public. It is recommended not to expose these endpoints without a proxy that can handle load balancing or authentication set up between your node and the public. + + +A commonly used tool for this is [nginx](https://nginx.org). + + +## Adding Genesis Accounts + +Before starting the chain, you need to populate the state with at least one account. To do so, first [create a new account in the keyring](00-keyring.md#adding-keys-to-the-keyring) named `my_validator` under the `test` keyring backend (feel free to choose another name and another backend). + +Now that you have created a local account, go ahead and grant it some `stake` tokens in your chain's genesis file. Doing so will also make sure your chain is aware of this account's existence: + +```bash +simd genesis add-genesis-account $MY_VALIDATOR_ADDRESS 100000000000stake +``` + +Recall that `$MY_VALIDATOR_ADDRESS` is a variable that holds the address of the `my_validator` key in the [keyring](00-keyring.md#adding-keys-to-the-keyring). Also note that the tokens in the Cosmos SDK have the `{amount}{denom}` format: `amount` is an 18-digit-precision decimal number, and `denom` is the unique token identifier with its denomination key (e.g. `atom` or `uatom`). Here, we are granting `stake` tokens, as `stake` is the token identifier used for staking in [`simapp`](https://github.com/cosmos/cosmos-sdk/tree/main/simapp). For your own chain with its own staking denom, that token identifier should be used instead. + +Now that your account has some tokens, you need to add a validator to your chain. Validators are special full-nodes that participate in the consensus process (implemented in the [underlying consensus engine](/../learn/intro/02-sdk-app-architecture.md#cometbft)) in order to add new blocks to the chain. Any account can declare its intention to become a validator operator, but only those with sufficient delegation get to enter the active set (for example, only the top 125 validator candidates with the most delegation get to be validators in the Cosmos Hub). For this guide, you will add your local node (created via the `init` command above) as a validator of your chain. Validators can be declared before a chain is first started via a special transaction included in the genesis file called a `gentx`: + +```bash +# Create a gentx. +simd genesis gentx my_validator 100000000stake --chain-id my-test-chain --keyring-backend test + +# Add the gentx to the genesis file. +simd genesis collect-gentxs +``` + +A `gentx` does three things: + +1. Registers the `validator` account you created as a validator operator account (i.e., the account that controls the validator). +2. Self-delegates the provided `amount` of staking tokens. +3. Link the operator account with a CometBFT node pubkey that will be used for signing blocks. If no `--pubkey` flag is provided, it defaults to the local node pubkey created via the `simd init` command above. + +For more information on `gentx`, use the following command: + +```bash +simd genesis gentx --help +``` + +## Configuring the Node Using `app.toml` and `config.toml` + +The Cosmos SDK automatically generates two configuration files inside `~/.simapp/config`: + +* `config.toml`: used to configure the CometBFT, learn more on [CometBFT's documentation](https://docs.cometbft.com/v0.37/core/configuration), +* `app.toml`: generated by the Cosmos SDK, and used to configure your app, such as state pruning strategies, telemetry, gRPC and REST servers configuration, state sync... + +Both files are heavily commented, please refer to them directly to tweak your node. + +One example config to tweak is the `minimum-gas-prices` field inside `app.toml`, which defines the minimum gas prices the validator node is willing to accept for processing a transaction. Depending on the chain, it might be an empty string or not. If it's empty, make sure to edit the field with some value, for example `10token`, or else the node will halt on startup. For the purpose of this tutorial, let's set the minimum gas price to 0: + +```toml + # The minimum gas prices a validator is willing to accept for processing a + # transaction. A transaction's fees must meet the minimum of any denomination + # specified in this config (e.g. 0.25token1;0.0001token2). + minimum-gas-prices = "0stake" +``` + + +When running a node (not a validator!) and not wanting to run the application mempool, set the `max-txs` field to `-1`. + +```toml +[mempool] +# Setting max-txs to 0 will allow for an unbounded amount of transactions in the mempool. +# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool. +# Setting max_txs to a positive number (> 0) will limit the number of transactions in the mempool, by the specified amount. +# +# Note, this configuration only applies to SDK built-in app-side mempool +# implementations. +max-txs = "-1" +``` + + + +## Run a Localnet + +Now that everything is set up, you can finally start your node: + +```bash +simd start +``` + +You should see blocks come in. + +The previous command allows you to run a single node. This is enough for the next section on interacting with this node, but you may wish to run multiple nodes at the same time, and see how consensus happens between them. + +The naive way would be to run the same commands again in separate terminal windows. This is possible, however, in the Cosmos SDK, we leverage the power of [Docker Compose](https://docs.docker.com/compose/) to run a localnet. If you need inspiration on how to set up your own localnet with Docker Compose, you can have a look at the Cosmos SDK's [`docker-compose.yml`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/docker-compose.yml). + +### Standalone App/CometBFT + +By default, the Cosmos SDK runs CometBFT in-process with the application +If you want to run the application and CometBFT in separate processes, +start the application with the `--with-comet=false` flag +and set `rpc.laddr` in `config.toml` to the CometBFT node's RPC address. + +## Logging + +Logging provides a way to see what is going on with a node. The default logging level is info. This is a global level and all info logs will be outputted to the terminal. If you would like to filter specific logs to the terminal instead of all, then setting `module:log_level` is how this can work. + +Example: + +In config.toml: + +```toml +log_level: "state:info,p2p:info,consensus:info,x/staking:info,x/ibc:info,*error" +``` + +## State Sync + +State sync is the act in which a node syncs the latest or close to the latest state of a blockchain. This is useful for users who don't want to sync all the blocks in history. Read more in [CometBFT documentation](https://docs.cometbft.com/v0.37/core/state-sync). + +State sync works thanks to snapshots. Read how the SDK handles snapshots [here](https://github.com/cosmos/cosmos-sdk/blob/825245d/store/snapshots/README.md). + +### Local State Sync + +Local state sync works similar to normal state sync except that it works off a local snapshot of state instead of one provided via the p2p network. The steps to start local state sync are similar to normal state sync with a few different designs. + +1. As mentioned in https://docs.cometbft.com/v0.37/core/state-sync, one must set a height and hash in the config.toml along with a few rpc servers (the aforementioned link has instructions on how to do this). +2. Run ` ` to restore a local snapshot (note: first load it from a file with the *load* command). +3. Bootstrapping Comet state to start the node after the snapshot has been ingested. This can be done with the bootstrap command ` comet bootstrap-state` + +### Snapshots Commands + +The Cosmos SDK provides commands for managing snapshots. +These commands can be added in an app with the following snippet in `cmd//root.go`: + +```go +import ( + + "github.com/cosmos/cosmos-sdk/client/snapshot" +) + +func initRootCmd(/* ... */) { + // ... + rootCmd.AddCommand( + snapshot.Cmd(appCreator), + ) +} +``` + +Then the following commands are available at ` snapshots [command]`: + +* **list**: list local snapshots +* **load**: Load a snapshot archive file into snapshot store +* **restore**: Restore app state from local snapshot +* **export**: Export app state to snapshot store +* **dump**: Dump the snapshot as portable archive format +* **delete**: Delete a local snapshot diff --git a/docs/sdk/next/user/run-node/run-production.mdx b/docs/sdk/next/user/run-node/run-production.mdx new file mode 100644 index 00000000..6e62182c --- /dev/null +++ b/docs/sdk/next/user/run-node/run-production.mdx @@ -0,0 +1,267 @@ +--- +title: Running in Production +--- + +**Synopsis** +This section describes how to securely run a node in a public setting and/or on a mainnet on one of the many Cosmos SDK public blockchains. + + +When operating a node, full node or validator, in production it is important to set your server up securely. + + +There are many different ways to secure a server and your node, the described steps here is one way. To see another way of setting up a server see the [run in production tutorial](https://tutorials.cosmos.network/hands-on-exercise/4-run-in-prod). + + + +This walkthrough assumes the underlying operating system is Ubuntu. + + +## Server Setup + +### User + +When creating a server most times it is created as user `root`. This user has heightened privileges on the server. When operating a node, it is recommended to not run your node as the root user. + +1. Create a new user + +```bash +sudo adduser change_me +``` + +2. We want to allow this user to perform sudo tasks + +```bash +sudo usermod -aG sudo change_me +``` + +Now when logging into the server, the non `root` user can be used. + +### Go + +1. Install the [Go](https://go.dev/doc/install) version preconized by the application. + + +In the past, validators [have had issues](https://github.com/cosmos/cosmos-sdk/issues/13976) when using different versions of Go. It is recommended that the whole validator set uses the version of Go that is preconized by the application. + + +### Firewall + +Nodes should not have all ports open to the public, this is a simple way to get DDOS'd. Secondly it is recommended by [CometBFT](https://github.com/cometbft/cometbft) to never expose ports that are not required to operate a node. + +When setting up a firewall there are a few ports that can be open when operating a Cosmos SDK node. There is the CometBFT json-RPC, prometheus, p2p, remote signer and Cosmos SDK GRPC and REST. If the node is being operated as a node that does not offer endpoints to be used for submission or querying then a max of three endpoints are needed. + +Most, if not all servers come equipped with [ufw](https://help.ubuntu.com/community/UFW). Ufw will be used in this tutorial. + +1. Reset UFW to disallow all incoming connections and allow outgoing + +```bash +sudo ufw default deny incoming +sudo ufw default allow outgoing +``` + +2. Lets make sure that port 22 (ssh) stays open. + +```bash +sudo ufw allow ssh +``` + +or + +```bash +sudo ufw allow 22 +``` + +Both of the above commands are the same. + +3. Allow Port 26656 (cometbft p2p port). If the node has a modified p2p port then that port must be used here. + +```bash +sudo ufw allow 26656/tcp +``` + +4. Allow port 26660 (cometbft [prometheus](https://prometheus.io)). This acts as the applications monitoring port as well. + +```bash +sudo ufw allow 26660/tcp +``` + +5. IF the node which is being setup would like to expose CometBFTs jsonRPC and Cosmos SDK GRPC and REST then follow this step. (Optional) + +##### CometBFT JsonRPC + +```bash +sudo ufw allow 26657/tcp +``` + +##### Cosmos SDK GRPC + +```bash +sudo ufw allow 9090/tcp +``` + +##### Cosmos SDK REST + +```bash +sudo ufw allow 1317/tcp +``` + +6. Lastly, enable ufw + +```bash +sudo ufw enable +``` + +### Signing + +If the node that is being started is a validator there are multiple ways a validator could sign blocks. + +#### File + +File based signing is the simplest and default approach. This approach works by storing the consensus key, generated on initialization, to sign blocks. This approach is only as safe as your server setup as if the server is compromised so is your key. This key is located in the `config/priv_val_key.json` directory generated on initialization. + +A second file exists that user must be aware of, the file is located in the data directory `data/priv_val_state.json`. This file protects your node from double signing. It keeps track of the consensus keys last sign height, round and latest signature. If the node crashes and needs to be recovered this file must be kept in order to ensure that the consensus key will not be used for signing a block that was previously signed. + +#### Remote Signer + +A remote signer is a secondary server that is separate from the running node that signs blocks with the consensus key. This means that the consensus key does not live on the node itself. This increases security because your full node which is connected to the remote signer can be swapped without missing blocks. + +The two most used remote signers are [tmkms](https://github.com/iqlusioninc/tmkms) from [Iqlusion](https://www.iqlusion.io) and [horcrux](https://github.com/strangelove-ventures/horcrux) from [Strangelove](https://strange.love). + +##### TMKMS + +###### Dependencies + +1. Update server dependencies and install extras needed. + +```sh +sudo apt update -y && sudo apt install build-essential curl jq -y +``` + +2. Install Rust: + +```sh +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +``` + +3. Install Libusb: + +```sh +sudo apt install libusb-1.0-0-dev +``` + +###### Setup + +There are two ways to install tmkms, from source or `cargo install`. In the examples we will cover downloading or building from source and using softsign. Softsign stands for software signing, but you could use a [yubihsm](https://www.yubico.com/products/hardware-security-module/) as your signing key if you wish. + +1. Build: + +From source: + +```bash +cd $HOME +git clone https://github.com/iqlusioninc/tmkms.git +cd $HOME/tmkms +cargo install tmkms --features=softsign +tmkms init config +tmkms softsign keygen ./config/secrets/secret_connection_key +``` + +or + +Cargo install: + +```bash +cargo install tmkms --features=softsign +tmkms init config +tmkms softsign keygen ./config/secrets/secret_connection_key +``` + + +To use tmkms with a yubikey install the binary with `--features=yubihsm`. + + +2. Migrate the validator key from the full node to the new tmkms instance. + +```bash +scp user@123.456.32.123:~/.simd/config/priv_validator_key.json ~/tmkms/config/secrets +``` + +3. Import the validator key into tmkms. + +```bash +tmkms softsign import $HOME/tmkms/config/secrets/priv_validator_key.json $HOME/tmkms/config/secrets/priv_validator_key +``` + +At this point, it is necessary to delete the `priv_validator_key.json` from the validator node and the tmkms node. Since the key has been imported into tmkms (above) it is no longer necessary on the nodes. The key can be safely stored offline. + +4. Modify the `tmkms.toml`. + +```bash +vim $HOME/tmkms/config/tmkms.toml +``` + +This example shows a configuration that could be used for soft signing. The example has an IP of `123.456.12.345` with a port of `26659` a chain\_id of `test-chain-waSDSe`. These are items that must be modified for the usecase of tmkms and the network. + +```toml expandable +# CometBFT KMS configuration file + +## Chain Configuration + +[[chain]] +id = "osmosis-1" +key_format = { type = "bech32", account_key_prefix = "cosmospub", consensus_key_prefix = "cosmosvalconspub" } +state_file = "/root/tmkms/config/state/priv_validator_state.json" + +## Signing Provider Configuration + +### Software-based Signer Configuration + +[[providers.softsign]] +chain_ids = ["test-chain-waSDSe"] +key_type = "consensus" +path = "/root/tmkms/config/secrets/priv_validator_key" + +## Validator Configuration + +[[validator]] +chain_id = "test-chain-waSDSe" +addr = "tcp://123.456.12.345:26659" +secret_key = "/root/tmkms/config/secrets/secret_connection_key" +protocol_version = "v0.34" +reconnect = true +``` + +5. Set the address of the tmkms instance. + +```bash +vim $HOME/.simd/config/config.toml + +priv_validator_laddr = "tcp://0.0.0.0:26659" +``` + + +The above address it set to `0.0.0.0` but it is recommended to set the tmkms server to secure the startup + + + +It is recommended to comment or delete the lines that specify the path of the validator key and validator: + +```toml +# Path to the JSON file containing the private key to use as a validator in the consensus protocol +# priv_validator_key_file = "config/priv_validator_key.json" + +# Path to the JSON file containing the last sign state of a validator +# priv_validator_state_file = "data/priv_validator_state.json" +``` + + + +6. Start the two processes. + +```bash +tmkms start -c $HOME/tmkms/config/tmkms.toml +``` + +```bash +simd start +``` diff --git a/docs/sdk/next/user/run-node/run-testnet.mdx b/docs/sdk/next/user/run-node/run-testnet.mdx new file mode 100644 index 00000000..3922b631 --- /dev/null +++ b/docs/sdk/next/user/run-node/run-testnet.mdx @@ -0,0 +1,97 @@ +--- +title: Running a Testnet +--- + +**Synopsis** +The `simd testnet` subcommand makes it easy to initialize and start a simulated test network for testing purposes. + + +In addition to the commands for [running a node](01-run-node.md), the `simd` binary also includes a `testnet` command that allows you to start a simulated test network in-process or to initialize files for a simulated test network that runs in a separate process. + +## Initialize Files + +First, let's take a look at the `init-files` subcommand. + +This is similar to the `init` command when initializing a single node, but in this case we are initializing multiple nodes, generating the genesis transactions for each node, and then collecting those transactions. + +The `init-files` subcommand initializes the necessary files to run a test network in a separate process (i.e. using a Docker container). Running this command is not a prerequisite for the `start` subcommand ([see below](#start-testnet)). + +In order to initialize the files for a test network, run the following command: + +```bash +simd testnet init-files +``` + +You should see the following output in your terminal: + +```bash +Successfully initialized 4 node directories +``` + +The default output directory is a relative `.testnets` directory. Let's take a look at the files created within the `.testnets` directory. + +### gentxs + +The `gentxs` directory includes a genesis transaction for each validator node. Each file includes a JSON encoded genesis transaction used to register a validator node at the time of genesis. The genesis transactions are added to the `genesis.json` file within each node directory during the initialization process. + +### nodes + +A node directory is created for each validator node. Within each node directory is a `simd` directory. The `simd` directory is the home directory for each node, which includes the configuration and data files for that node (i.e. the same files included in the default `~/.simapp` directory when running a single node). + +## Start Testnet + +Now, let's take a look at the `start` subcommand. + +The `start` subcommand both initializes and starts an in-process test network. This is the fastest way to spin up a local test network for testing purposes. + +You can start the local test network by running the following command: + +```bash +simd testnet start +``` + +You should see something similar to the following: + +```bash expandable +acquiring test network lock +preparing test network with chain-id "chain-mtoD9v" + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++ THIS MNEMONIC IS FOR TESTING PURPOSES ONLY ++ +++ DO NOT USE IN PRODUCTION ++ +++ ++ +++ sustain know debris minute gate hybrid stereo custom ++ +++ divorce cross spoon machine latin vibrant term oblige ++ +++ moment beauty laundry repeat grab game bronze truly ++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +starting test network... +started test network +press the Enter Key to terminate +``` + +The first validator node is now running in-process, which means the test network will terminate once you either close the terminal window or you press the Enter key. In the output, the mnemonic phrase for the first validator node is provided for testing purposes. The validator node is using the same default addresses being used when initializing and starting a single node (no need to provide a `--node` flag). + +Check the status of the first validator node: + +```shell +simd status +``` + +Import the key from the provided mnemonic: + +```shell +simd keys add test --recover --keyring-backend test +``` + +Check the balance of the account address: + +```shell +simd q bank balances [address] +``` + +Use this test account to manually test against the test network. + +## Testnet Options + +You can customize the configuration of the test network with flags. In order to see all flag options, append the `--help` flag to each command. diff --git a/docs/sdk/next/user/run-node/txs.mdx b/docs/sdk/next/user/run-node/txs.mdx new file mode 100644 index 00000000..47537f2e --- /dev/null +++ b/docs/sdk/next/user/run-node/txs.mdx @@ -0,0 +1,461 @@ +--- +title: 'Generating, Signing and Broadcasting Transactions' +--- + +**Synopsis** +This document describes how to generate an (unsigned) transaction, signing it (with one or multiple keys), and broadcasting it to the network. + + +## Using the CLI + +The easiest way to send transactions is using the CLI, as we have seen in the previous page when [interacting with a node](02-interact-node.md#using-the-cli). For example, running the following command + +```bash +simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain --keyring-backend test +``` + +will run the following steps: + +* generate a transaction with one `Msg` (`x/bank`'s `MsgSend`), and print the generated transaction to the console. +* ask the user for confirmation to send the transaction from the `$MY_VALIDATOR_ADDRESS` account. +* fetch `$MY_VALIDATOR_ADDRESS` from the keyring. This is possible because we have [set up the CLI's keyring](00-keyring.md) in a previous step. +* sign the generated transaction with the keyring's account. +* broadcast the signed transaction to the network. This is possible because the CLI connects to the node's CometBFT RPC endpoint. + +The CLI bundles all the necessary steps into a simple-to-use user experience. However, it's possible to run all the steps individually too. + +### Generating a Transaction + +Generating a transaction can simply be done by appending the `--generate-only` flag on any `tx` command, e.g.: + +```bash +simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain --generate-only +``` + +This will output the unsigned transaction as JSON in the console. We can also save the unsigned transaction to a file (to be passed around between signers more easily) by appending `> unsigned_tx.json` to the above command. + +### Signing a Transaction + +Signing a transaction using the CLI requires the unsigned transaction to be saved in a file. Let's assume the unsigned transaction is in a file called `unsigned_tx.json` in the current directory (see previous paragraph on how to do that). Then, simply run the following command: + +```bash +simd tx sign unsigned_tx.json --chain-id my-test-chain --keyring-backend test --from $MY_VALIDATOR_ADDRESS +``` + +This command will decode the unsigned transaction and sign it with `SIGN_MODE_DIRECT` with `$MY_VALIDATOR_ADDRESS`'s key, which we already set up in the keyring. The signed transaction will be output as JSON to the console, and, as above, we can save it to a file by appending `--output-document signed_tx.json`. + +Some useful flags to consider in the `tx sign` command: + +* `--sign-mode`: you may use `amino-json` to sign the transaction using `SIGN_MODE_LEGACY_AMINO_JSON`, +* `--offline`: sign in offline mode. This means that the `tx sign` command doesn't connect to the node to retrieve the signer's account number and sequence, both needed for signing. In this case, you must manually supply the `--account-number` and `--sequence` flags. This is useful for offline signing, i.e. signing in a secure environment which doesn't have access to the internet. + +#### Signing with Multiple Signers + + +Please note that signing a transaction with multiple signers or with a multisig account, where at least one signer uses `SIGN_MODE_DIRECT`, is not yet possible. You may follow [this Github issue](https://github.com/cosmos/cosmos-sdk/issues/8141) for more info. + + +Signing with multiple signers is done with the `tx multisign` command. This command assumes that all signers use `SIGN_MODE_LEGACY_AMINO_JSON`. The flow is similar to the `tx sign` command flow, but instead of signing an unsigned transaction file, each signer signs the file signed by previous signer(s). The `tx multisign` command will append signatures to the existing transactions. It is important that signers sign the transaction **in the same order** as given by the transaction, which is retrievable using the `GetSigners()` method. + +For example, starting with the `unsigned_tx.json`, and assuming the transaction has 4 signers, we would run: + +```bash +# Let signer1 sign the unsigned tx. +simd tx multisign unsigned_tx.json signer_key_1 --chain-id my-test-chain --keyring-backend test > partial_tx_1.json +# Now signer1 will send the partial_tx_1.json to the signer2. +# Signer2 appends their signature: +simd tx multisign partial_tx_1.json signer_key_2 --chain-id my-test-chain --keyring-backend test > partial_tx_2.json +# Signer2 sends the partial_tx_2.json file to signer3, and signer3 can append his signature: +simd tx multisign partial_tx_2.json signer_key_3 --chain-id my-test-chain --keyring-backend test > partial_tx_3.json +``` + +### Broadcasting a Transaction + +Broadcasting a transaction is done using the following command: + +```bash +simd tx broadcast tx_signed.json +``` + +You may optionally pass the `--broadcast-mode` flag to specify which response to receive from the node: + +* `sync`: the CLI waits for a CheckTx execution response only. +* `async`: the CLI returns immediately (transaction might fail). + +### Encoding a Transaction + +In order to broadcast a transaction using the gRPC or REST endpoints, the transaction will need to be encoded first. This can be done using the CLI. + +Encoding a transaction is done using the following command: + +```bash +simd tx encode tx_signed.json +``` + +This will read the transaction from the file, serialize it using Protobuf, and output the transaction bytes as base64 in the console. + +### Decoding a Transaction + +The CLI can also be used to decode transaction bytes. + +Decoding a transaction is done using the following command: + +```bash +simd tx decode [protobuf-byte-string] +``` + +This will decode the transaction bytes and output the transaction as JSON in the console. You can also save the transaction to a file by appending `> tx.json` to the above command. + +## Programmatically with Go + +It is possible to manipulate transactions programmatically via Go using the Cosmos SDK's `TxBuilder` interface. + +### Generating a Transaction + +Before generating a transaction, a new instance of a `TxBuilder` needs to be created. Since the Cosmos SDK supports both Amino and Protobuf transactions, the first step would be to decide which encoding scheme to use. All the subsequent steps remain unchanged, whether you're using Amino or Protobuf, as `TxBuilder` abstracts the encoding mechanisms. In the following snippet, we will use Protobuf. + +```go expandable +import ( + + "github.com/cosmos/cosmos-sdk/simapp" +) + +func sendTx() + +error { + // Choose your codec: Amino or Protobuf. Here, we use Protobuf, given by the following function. + app := simapp.NewSimApp(...) + + // Create a new TxBuilder. + txBuilder := app.TxConfig().NewTxBuilder() + + // --snip-- +} +``` + +We can also set up some keys and addresses that will send and receive the transactions. Here, for the purpose of the tutorial, we will be using some dummy data to create keys. + +```go +import ( + + "github.com/cosmos/cosmos-sdk/testutil/testdata" +) + +priv1, _, addr1 := testdata.KeyTestPubAddr() + +priv2, _, addr2 := testdata.KeyTestPubAddr() + +priv3, _, addr3 := testdata.KeyTestPubAddr() +``` + +Populating the `TxBuilder` can be done via its methods: + +```go +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/client/tx_config.go#L39-L57 +``` + +```go expandable +import ( + + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +func sendTx() + +error { + // --snip-- + + // Define two x/bank MsgSend messages: + // - from addr1 to addr3, + // - from addr2 to addr3. + // This means that the transaction needs two signers: addr1 and addr2. + msg1 := banktypes.NewMsgSend(addr1, addr3, types.NewCoins(types.NewInt64Coin("atom", 12))) + +msg2 := banktypes.NewMsgSend(addr2, addr3, types.NewCoins(types.NewInt64Coin("atom", 34))) + err := txBuilder.SetMsgs(msg1, msg2) + if err != nil { + return err +} + +txBuilder.SetGasLimit(...) + +txBuilder.SetFeeAmount(...) + +txBuilder.SetMemo(...) + +txBuilder.SetTimeoutHeight(...) +} +``` + +At this point, `TxBuilder`'s underlying transaction is ready to be signed. + +#### Generating an Unordered Transaction + +Starting with Cosmos SDK v0.53.0, users may send unordered transactions to chains that have the feature enabled. + + + +Unordered transactions MUST leave sequence values unset. When a transaction is both unordered and contains a non-zero sequence value, +the transaction will be rejected. External services that operate on prior assumptions about transaction sequence values should be updated to handle unordered transactions. +Services should be aware that when the transaction is unordered, the transaction sequence will always be zero. + + + +Using the example above, we can set the required fields to mark a transaction as unordered. +By default, unordered transactions charge an extra 2240 units of gas to offset the additional storage overhead that supports their functionality. +The extra units of gas are customizable and therefore vary by chain, so be sure to check the chain's ante handler for the gas value set, if any. + +```go +func sendTx() + +error { + // --snip-- + expiration := 5 * time.Minute + txBuilder.SetUnordered(true) + +txBuilder.SetTimeoutTimestamp(time.Now().Add(expiration + (1 * time.Nanosecond))) +} +``` + +Unordered transactions from the same account must use a unique timeout timestamp value. The difference between each timeout timestamp value may be as small as a nanosecond, however. + +```go expandable +import ( + + "github.com/cosmos/cosmos-sdk/client" +) + +func sendMessages(txBuilders []client.TxBuilder) + +error { + // --snip-- + expiration := 5 * time.Minute + for _, txb := range txBuilders { + txb.SetUnordered(true) + +txb.SetTimeoutTimestamp(time.Now().Add(expiration + (1 * time.Nanosecond))) +} +} +``` + +### Signing a Transaction + +We set encoding config to use Protobuf, which will use `SIGN_MODE_DIRECT` by default. As per [ADR-020](https://github.com/cosmos/cosmos-sdk/blob/main/docs/sdk/next/architecture/adr-020-protobuf-transaction-encoding.md), each signer needs to sign the `SignerInfo`s of all other signers. This means that we need to perform two steps sequentially: + +* for each signer, populate the signer's `SignerInfo` inside `TxBuilder`, +* once all `SignerInfo`s are populated, for each signer, sign the `SignDoc` (the payload to be signed). + +In the current `TxBuilder`'s API, both steps are done using the same method: `SetSignatures()`. The current API requires us to first perform a round of `SetSignatures()` *with empty signatures*, only to populate `SignerInfo`s, and a second round of `SetSignatures()` to actually sign the correct payload. + +```go expandable +import ( + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" +) + +func sendTx() + +error { + // --snip-- + privs := []cryptotypes.PrivKey{ + priv1, priv2 +} + accNums:= []uint64{..., ... +} // The accounts' account numbers + accSeqs:= []uint64{..., ... +} // The accounts' sequence numbers + + // First round: we gather all the signer infos. We use the "set empty + // signature" hack to do that. + var sigsV2 []signing.SignatureV2 + for i, priv := range privs { + sigV2 := signing.SignatureV2{ + PubKey: priv.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: encCfg.TxConfig.SignModeHandler().DefaultMode(), + Signature: nil, +}, + Sequence: accSeqs[i], +} + +sigsV2 = append(sigsV2, sigV2) +} + err := txBuilder.SetSignatures(sigsV2...) + if err != nil { + return err +} + + // Second round: all signer infos are set, so each signer can sign. + sigsV2 = []signing.SignatureV2{ +} + for i, priv := range privs { + signerData := xauthsigning.SignerData{ + ChainID: chainID, + AccountNumber: accNums[i], + Sequence: accSeqs[i], +} + +sigV2, err := tx.SignWithPrivKey( + encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData, + txBuilder, priv, encCfg.TxConfig, accSeqs[i]) + if err != nil { + return nil, err +} + +sigsV2 = append(sigsV2, sigV2) +} + +err = txBuilder.SetSignatures(sigsV2...) + if err != nil { + return err +} +} +``` + +The `TxBuilder` is now correctly populated. To print it, you can use the `TxConfig` interface from the initial encoding config `encCfg`: + +```go expandable +func sendTx() + +error { + // --snip-- + + // Generated Protobuf-encoded bytes. + txBytes, err := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx()) + if err != nil { + return err +} + + // Generate a JSON string. + txJSONBytes, err := encCfg.TxConfig.TxJSONEncoder()(txBuilder.GetTx()) + if err != nil { + return err +} + txJSON := string(txJSONBytes) +} +``` + +### Broadcasting a Transaction + +The preferred way to broadcast a transaction is to use gRPC, though using REST (via `gRPC-gateway`) or the CometBFT RPC is also possible. An overview of the differences between these methods is exposed [here](/../learn/advanced/06-grpc_rest.md). For this tutorial, we will only describe the gRPC method. + +```go expandable +import ( + + "context" + "fmt" + "google.golang.org/grpc" + "github.com/cosmos/cosmos-sdk/types/tx" +) + +func sendTx(ctx context.Context) + +error { + // --snip-- + + // Create a connection to the gRPC server. + grpcConn := grpc.Dial( + "127.0.0.1:9090", // Or your gRPC server address. + grpc.WithInsecure(), // The Cosmos SDK doesn't support any transport security mechanism. + ) + +defer grpcConn.Close() + + // Broadcast the tx via gRPC. We create a new client for the Protobuf Tx + // service. + txClient := tx.NewServiceClient(grpcConn) + // We then call the BroadcastTx method on this client. + grpcRes, err := txClient.BroadcastTx( + ctx, + &tx.BroadcastTxRequest{ + Mode: tx.BroadcastMode_BROADCAST_MODE_SYNC, + TxBytes: txBytes, // Proto-binary of the signed transaction, see previous step. +}, + ) + if err != nil { + return err +} + +fmt.Println(grpcRes.TxResponse.Code) // Should be `0` if the tx is successful + + return nil +} +``` + +#### Simulating a Transaction + +Before broadcasting a transaction, we sometimes may want to dry-run the transaction, to estimate some information about the transaction without actually committing it. This is called simulating a transaction, and can be done as follows: + +```go expandable +import ( + + "context" + "fmt" + "testing" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/types/tx" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" +) + +func simulateTx() + +error { + // --snip-- + + // Simulate the tx via gRPC. We create a new client for the Protobuf Tx + // service. + txClient := tx.NewServiceClient(grpcConn) + txBytes := /* Fill in with your signed transaction bytes. */ + + // We then call the Simulate method on this client. + grpcRes, err := txClient.Simulate( + context.Background(), + &tx.SimulateRequest{ + TxBytes: txBytes, +}, + ) + if err != nil { + return err +} + +fmt.Println(grpcRes.GasInfo) // Prints estimated gas used. + + return nil +} +``` + +## Using gRPC + +It is not possible to generate or sign a transaction using gRPC, only to broadcast one. In order to broadcast a transaction using gRPC, you will need to generate, sign, and encode the transaction using either the CLI or programmatically with Go. + +### Broadcasting a Transaction + +Broadcasting a transaction using the gRPC endpoint can be done by sending a `BroadcastTx` request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: + +```bash +grpcurl -plaintext \ + -d '{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ + localhost:9090 \ + cosmos.tx.v1beta1.Service/BroadcastTx +``` + +## Using REST + +It is not possible to generate or sign a transaction using REST, only to broadcast one. In order to broadcast a transaction using REST, you will need to generate, sign, and encode the transaction using either the CLI or programmatically with Go. + +### Broadcasting a Transaction + +Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) can be done by sending a POST request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -d' {"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ + localhost:1317/cosmos/tx/v1beta1/txs +``` + +## Using CosmJS (JavaScript & TypeScript) + +CosmJS aims to build client libraries in JavaScript that can be embedded in web applications. Please see [Link](https://cosmos.github.io/cosmjs) for more information. As of January 2021, CosmJS documentation is still a work in progress. diff --git a/docs/sdk/next/user/user.mdx b/docs/sdk/next/user/user.mdx new file mode 100644 index 00000000..100e226a --- /dev/null +++ b/docs/sdk/next/user/user.mdx @@ -0,0 +1,12 @@ +--- +title: User Guides +description: >- + This section is designed for developers who are using the Cosmos SDK to build + applications. It provides essential guides and references to effectively use + the SDK's features. +--- +This section is designed for developers who are using the Cosmos SDK to build applications. It provides essential guides and references to effectively use the SDK's features. + +* [Setting up keys](run-node/00-keyring.md) - Learn how to set up secure key management using the Cosmos SDK's keyring feature. This guide provides a streamlined approach to cryptographic key handling, which is crucial for securing your application. +* [Running a node](run-node/01-run-node.md) - This guide provides step-by-step instructions to deploy and manage a node in the Cosmos network. It ensures a smooth and reliable operation of your blockchain application by covering all the necessary setup and maintenance steps. +* [CLI](run-node/02-interact-node.md) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. diff --git a/docs/sdk/proposed-nav-next.json b/docs/sdk/proposed-nav-next.json deleted file mode 100644 index f1fa84cf..00000000 --- a/docs/sdk/proposed-nav-next.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "version": "next", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { "group": "Transactions & Fees", "pages": [] }, - { "group": "Messaging & Queries", "pages": [ - "docs/sdk/next/build/building-modules/messaging-and-queries" - ]}, - { "group": "Integration", "groups": [ - { "group": "App Wiring & Runtime", "pages": [] }, - { "group": "Module Wiring", "pages": [] }, - { "group": "Upgrades & Migrations", "pages": [] }, - { "group": "Messaging Integration", "pages": [] }, - { "group": "Vote Extensions (End-to-End)", "pages": [] } - ]}, - { "group": "Module Anatomy & Keepers", "pages": [] }, - { "group": "Runtime & ABCI", "pages": [ - "docs/sdk/next/build/abci/index" - ]}, - { "group": "State & Store", "pages": [] }, - { "group": "Encoding & Protobuf", "pages": [] }, - { "group": "Testing & Simulation", "pages": [] }, - { "group": "Core Concepts", "pages": [ - "docs/sdk/next/index" - ]}, - { "group": "Node Operations", "pages": [] }, - { "group": "Tooling", "pages": [] } - ] - }, - { "tab": "Module Reference", "groups": [] }, - { "tab": "API Reference", "pages": [] }, - { "tab": "Release Notes", "pages": [] } - ] -} - diff --git a/docs/sdk/proposed-nav-v0.47.json b/docs/sdk/proposed-nav-v0.47.json deleted file mode 100644 index d811b8a7..00000000 --- a/docs/sdk/proposed-nav-v0.47.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "version": "v0.47", - "tabs": [ - { "tab": "API Reference", "pages": [] }, - { "tab": "Release Notes", "pages": [] } - ] -} - diff --git a/docs/sdk/proposed-nav-v0.50.json b/docs/sdk/proposed-nav-v0.50.json deleted file mode 100644 index d47d6173..00000000 --- a/docs/sdk/proposed-nav-v0.50.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "version": "v0.50", - "tabs": [ - { "tab": "API Reference", "pages": [] }, - { "tab": "Release Notes", "pages": [] } - ] -} - diff --git a/docs/sdk/proposed-nav-v0.53.json b/docs/sdk/proposed-nav-v0.53.json deleted file mode 100644 index 1b118103..00000000 --- a/docs/sdk/proposed-nav-v0.53.json +++ /dev/null @@ -1,224 +0,0 @@ -{ - "version": "v0.53", - "tabs": [ - { - "tab": "Documentation", - "groups": [ - { - "group": "Runtime & ABCI", - "pages": [ - "docs/sdk/v0.53/build/abci/introduction", - "docs/sdk/v0.53/build/abci/prepare-proposal", - "docs/sdk/v0.53/build/abci/process-proposal", - "docs/sdk/v0.53/build/abci/checktx" - ] - }, - { - "group": "Transactions & Fees", - "pages": [ - "docs/sdk/v0.53/learn/beginner/tx-lifecycle", - "docs/sdk/v0.53/learn/advanced/transactions", - "docs/sdk/v0.53/learn/beginner/gas-fees" - ] - }, - { - "group": "Integration", - "groups": [ - { - "group": "App Wiring & Runtime", - "pages": [ - "docs/sdk/v0.53/build/building-apps/app-go", - "docs/sdk/v0.53/build/building-apps/runtime", - "docs/sdk/v0.53/build/building-apps/app-go-di", - "docs/sdk/v0.53/build/building-apps/app-mempool", - "docs/sdk/v0.53/build/building-apps/app-upgrade", - "docs/sdk/v0.53/build/building-apps/app-testnet" - ] - }, - { - "group": "Module Wiring", - "pages": [ - "docs/sdk/v0.53/build/building-modules/module-manager", - "docs/sdk/v0.53/build/building-modules/module-interfaces", - "docs/sdk/v0.53/build/building-modules/structure", - "docs/sdk/v0.53/build/building-modules/keeper", - "docs/sdk/v0.53/build/building-modules/genesis", - "docs/sdk/v0.53/build/building-modules/invariants", - "docs/sdk/v0.53/build/building-modules/errors", - "docs/sdk/v0.53/build/building-modules/preblock", - "docs/sdk/v0.53/build/building-modules/depinject" - ] - }, - { - "group": "Messaging Integration", - "pages": [ - "docs/sdk/v0.53/build/building-modules/messages-and-queries", - "docs/sdk/v0.53/build/building-modules/msg-services", - "docs/sdk/v0.53/build/building-modules/query-services" - ] - }, - { - "group": "Upgrades & Migrations", - "pages": [ - "docs/sdk/v0.53/build/building-apps/app-upgrade", - "docs/sdk/v0.53/build/building-modules/upgrade", - "docs/sdk/v0.53/learn/advanced/upgrade" - ] - }, - { - "group": "Vote Extensions (End-to-End)", - "pages": [ - "docs/sdk/v0.53/build/abci/vote-extensions", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/getting-started", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions", - "docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle" - ] - } - ] - }, - { - "group": "State & Store", - "pages": [ - "docs/sdk/v0.53/learn/advanced/store" - ] - }, - { - "group": "Encoding & Protobuf", - "pages": [ - "docs/sdk/v0.53/learn/advanced/encoding", - "docs/sdk/v0.53/build/building-modules/protobuf-annotations" - ] - }, - { - "group": "Testing & Simulation", - "pages": [ - "docs/sdk/v0.53/build/building-modules/testing", - "docs/sdk/v0.53/build/building-modules/simulator" - ] - }, - { - "group": "Tooling", - "pages": [ - "docs/sdk/v0.53/learn/advanced/cli" - ] - }, - { - "group": "Core Concepts", - "pages": [ - "docs/sdk/v0.53/learn/intro/overview", - "docs/sdk/v0.53/learn/intro/why-app-specific", - "docs/sdk/v0.53/learn/intro/sdk-app-architecture", - "docs/sdk/v0.53/learn/intro/sdk-design", - "docs/sdk/v0.53/learn/beginner/accounts", - "docs/sdk/v0.53/learn/advanced/context", - "docs/sdk/v0.53/learn/advanced/node", - "docs/sdk/v0.53/learn/advanced/events", - "docs/sdk/v0.53/learn/advanced/telemetry", - "docs/sdk/v0.53/learn/advanced/ocap", - "docs/sdk/v0.53/learn/advanced/config", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle" - ] - }, - { - "group": "Node Operations", - "pages": [ - "docs/sdk/v0.53/user", - "docs/sdk/v0.53/user/run-node/interact-node", - "docs/sdk/v0.53/user/run-node/run-testnet", - "docs/sdk/v0.53/user/run-node/run-node", - "docs/sdk/v0.53/user/run-node/txs", - "docs/sdk/v0.53/user/run-node/keyring", - "docs/sdk/v0.53/user/run-node/run-production" - ] - } - ] - }, - { - "tab": "Module Reference", - "groups": [ - { - "group": "x/auth", - "pages": [ - "docs/sdk/v0.53/build/modules/auth", - "docs/sdk/v0.53/build/modules/auth/vesting", - "docs/sdk/v0.53/build/modules/auth/tx" - ] - }, - { - "group": "x/authz & feegrant", - "pages": [ - "docs/sdk/v0.53/build/modules/authz", - "docs/sdk/v0.53/build/modules/feegrant" - ] - }, - { - "group": "x/bank & mint", - "pages": [ - "docs/sdk/v0.53/build/modules/bank", - "docs/sdk/v0.53/build/modules/mint" - ] - }, - { - "group": "x/gov & group", - "pages": [ - "docs/sdk/v0.53/build/modules/gov", - "docs/sdk/v0.53/build/modules/group" - ] - }, - { - "group": "x/staking suite", - "pages": [ - "docs/sdk/v0.53/build/modules/staking", - "docs/sdk/v0.53/build/modules/slashing", - "docs/sdk/v0.53/build/modules/distribution" - ] - }, - { - "group": "x/consensus & evidence", - "pages": [ - "docs/sdk/v0.53/build/modules/consensus", - "docs/sdk/v0.53/build/modules/evidence" - ] - }, - { - "group": "x/params & upgrade", - "pages": [ - "docs/sdk/v0.53/build/modules/params", - "docs/sdk/v0.53/build/modules/upgrade" - ] - }, - { - "group": "x/protocolpool", - "pages": [ - "docs/sdk/v0.53/build/modules/protocolpool" - ] - }, - { - "group": "x/nft & epochs", - "pages": [ - "docs/sdk/v0.53/build/modules/nft", - "docs/sdk/v0.53/build/modules/epochs" - ] - } - ] - }, - { - "tab": "API Reference", - "pages": [ - "docs/sdk/v0.53/learn/advanced/grpc_rest", - "docs/sdk/v0.53/learn/advanced/proto-docs" - ] - }, - { - "tab": "Release Notes", - "pages": [ - "docs/sdk/v0.53/changelog/release-notes" - ] - } - ] -} diff --git a/docs/sdk/sdk-categorization.json b/docs/sdk/sdk-categorization.json deleted file mode 100644 index d1109aff..00000000 --- a/docs/sdk/sdk-categorization.json +++ /dev/null @@ -1,210 +0,0 @@ -{ - "v0.53": { - "Runtime & ABCI": [ - "docs/sdk/v0.53/build/abci/introduction", - "docs/sdk/v0.53/build/abci/prepare-proposal", - "docs/sdk/v0.53/build/abci/process-proposal", - "docs/sdk/v0.53/build/abci/checktx" - ], - "Transactions & Fees": [ - "docs/sdk/v0.53/learn/beginner/tx-lifecycle", - "docs/sdk/v0.53/learn/advanced/transactions", - "docs/sdk/v0.53/learn/beginner/gas-fees" - ], - "Messaging & Queries": [ - "docs/sdk/v0.53/build/building-modules/messages-and-queries", - "docs/sdk/v0.53/build/building-modules/msg-services", - "docs/sdk/v0.53/build/building-modules/query-services" - ], - "Module Anatomy & Keepers": [ - "docs/sdk/v0.53/build/building-modules/module-manager", - "docs/sdk/v0.53/build/building-modules/module-interfaces", - "docs/sdk/v0.53/build/building-modules/structure", - "docs/sdk/v0.53/build/building-modules/keeper", - "docs/sdk/v0.53/build/building-modules/genesis", - "docs/sdk/v0.53/build/building-modules/invariants", - "docs/sdk/v0.53/build/building-modules/errors", - "docs/sdk/v0.53/build/building-modules/preblock" - ], - "App Wiring & Runtime": [ - "docs/sdk/v0.53/build/building-apps/app-go", - "docs/sdk/v0.53/build/building-apps/runtime", - "docs/sdk/v0.53/build/building-apps/app-go-di", - "docs/sdk/v0.53/build/building-apps/app-mempool", - "docs/sdk/v0.53/build/building-apps/app-upgrade", - "docs/sdk/v0.53/build/building-apps/vote-extensions" - ], - "State & Store": [ - "docs/sdk/v0.53/learn/advanced/store" - ], - "Encoding & Protobuf": [ - "docs/sdk/v0.53/learn/advanced/encoding", - "docs/sdk/v0.53/learn/advanced/proto-docs", - "docs/sdk/v0.53/build/building-modules/protobuf-annotations" - ], - "Upgrades & Migrations": [ - "docs/sdk/v0.53/build/building-apps/app-upgrade", - "docs/sdk/v0.53/build/building-modules/upgrade", - "docs/sdk/v0.53/learn/advanced/upgrade" - ], - "Testing & Simulation": [ - "docs/sdk/v0.53/build/building-modules/testing", - "docs/sdk/v0.53/build/building-modules/simulator" - ], - "APIs & Clients": [ - "docs/sdk/v0.53/learn/advanced/cli", - "docs/sdk/v0.53/learn/advanced/grpc_rest" - ], - "Core Concepts": [ - "docs/sdk/v0.53/learn/intro/overview", - "docs/sdk/v0.53/learn/intro/why-app-specific", - "docs/sdk/v0.53/learn/intro/sdk-app-architecture", - "docs/sdk/v0.53/learn/intro/sdk-design", - "docs/sdk/v0.53/learn/beginner/accounts", - "docs/sdk/v0.53/learn/advanced/context", - "docs/sdk/v0.53/learn/advanced/node", - "docs/sdk/v0.53/learn/advanced/events", - "docs/sdk/v0.53/learn/advanced/telemetry", - "docs/sdk/v0.53/learn/advanced/ocap", - "docs/sdk/v0.53/learn/advanced/config", - "docs/sdk/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle" - ], - "Node Operations": [ - "docs/sdk/v0.53/user", - "docs/sdk/v0.53/user/run-node/interact-node", - "docs/sdk/v0.53/user/run-node/run-testnet", - "docs/sdk/v0.53/user/run-node/run-node", - "docs/sdk/v0.53/user/run-node/txs", - "docs/sdk/v0.53/user/run-node/keyring", - "docs/sdk/v0.53/user/run-node/run-production" - ], - "Module Reference (x/*)": [ - "docs/sdk/v0.53/build/modules/auth", - "docs/sdk/v0.53/build/modules/auth/vesting", - "docs/sdk/v0.53/build/modules/auth/tx", - "docs/sdk/v0.53/build/modules/authz", - "docs/sdk/v0.53/build/modules/feegrant", - "docs/sdk/v0.53/build/modules/bank", - "docs/sdk/v0.53/build/modules/mint", - "docs/sdk/v0.53/build/modules/gov", - "docs/sdk/v0.53/build/modules/group", - "docs/sdk/v0.53/build/modules/staking", - "docs/sdk/v0.53/build/modules/slashing", - "docs/sdk/v0.53/build/modules/distribution", - "docs/sdk/v0.53/build/modules/consensus", - "docs/sdk/v0.53/build/modules/evidence", - "docs/sdk/v0.53/build/modules/params", - "docs/sdk/v0.53/build/modules/upgrade", - "docs/sdk/v0.53/build/modules/protocolpool", - "docs/sdk/v0.53/build/modules/nft", - "docs/sdk/v0.53/build/modules/epochs" - ] - }, - "v0.50": { - "Runtime & ABCI": [], - "Transactions & Fees": [ - "docs/sdk/v0.50/learn/beginner/tx-lifecycle", - "docs/sdk/v0.50/learn/advanced/transactions", - "docs/sdk/v0.50/learn/beginner/gas-fees" - ], - "Messaging & Queries": [ - "docs/sdk/v0.50/learn/advanced/baseapp" - ], - "Module Anatomy & Keepers": [], - "App Wiring & Runtime": [], - "State & Store": [ - "docs/sdk/v0.50/learn/advanced/store" - ], - "Encoding & Protobuf": [ - "docs/sdk/v0.50/learn/advanced/encoding", - "docs/sdk/v0.50/learn/advanced/proto-docs" - ], - "Upgrades & Migrations": [ - "docs/sdk/v0.50/learn/advanced/upgrade" - ], - "Testing & Simulation": [ - "docs/sdk/v0.50/learn/advanced/simulation" - ], - "APIs & Clients": [ - "docs/sdk/v0.50/learn/advanced/cli", - "docs/sdk/v0.50/learn/advanced/grpc_rest" - ], - "Core Concepts": [ - "docs/sdk/v0.50/learn/intro/overview", - "docs/sdk/v0.50/learn/intro/why-app-specific", - "docs/sdk/v0.50/learn/intro/sdk-app-architecture", - "docs/sdk/v0.50/learn/intro/sdk-design", - "docs/sdk/v0.50/learn/beginner/accounts", - "docs/sdk/v0.50/learn/advanced/events", - "docs/sdk/v0.50/learn/advanced/ocap", - "docs/sdk/v0.50/learn/advanced/config", - "docs/sdk/v0.50/tutorials/vote-extensions/oracle/what-is-an-oracle" - ], - "Node Operations": [ - "docs/sdk/v0.50/user", - "docs/sdk/v0.50/user/run-node/interact-node", - "docs/sdk/v0.50/user/run-node/run-testnet", - "docs/sdk/v0.50/user/run-node/run-node", - "docs/sdk/v0.50/user/run-node/txs", - "docs/sdk/v0.50/user/run-node/keyring", - "docs/sdk/v0.50/user/run-node/rosetta", - "docs/sdk/v0.50/user/run-node/run-production" - ] - }, - "v0.47": { - "Runtime & ABCI": [], - "Transactions & Fees": [ - "docs/sdk/v0.47/learn/beginner/tx-lifecycle", - "docs/sdk/v0.47/learn/advanced/transactions", - "docs/sdk/v0.47/learn/beginner/gas-fees" - ], - "Messaging & Queries": [ - "docs/sdk/v0.47/learn/advanced/baseapp" - ], - "Module Anatomy & Keepers": [], - "App Wiring & Runtime": [], - "State & Store": [ - "docs/sdk/v0.47/learn/advanced/store", - "docs/sdk/v0.47/learn/advanced/interblock-cache" - ], - "Encoding & Protobuf": [ - "docs/sdk/v0.47/learn/advanced/encoding", - "docs/sdk/v0.47/learn/advanced/proto-docs" - ], - "Upgrades & Migrations": [ - "docs/sdk/v0.47/learn/advanced/upgrade" - ], - "Testing & Simulation": [ - "docs/sdk/v0.47/learn/advanced/simulation" - ], - "APIs & Clients": [ - "docs/sdk/v0.47/learn/advanced/cli", - "docs/sdk/v0.47/learn/advanced/grpc_rest" - ], - "Core Concepts": [ - "docs/sdk/v0.47/learn/intro/overview", - "docs/sdk/v0.47/learn/intro/why-app-specific", - "docs/sdk/v0.47/learn/intro/sdk-app-architecture", - "docs/sdk/v0.47/learn/intro/sdk-design", - "docs/sdk/v0.47/learn/beginner/accounts", - "docs/sdk/v0.47/learn/advanced/context", - "docs/sdk/v0.47/learn/advanced/node", - "docs/sdk/v0.47/learn/advanced/events", - "docs/sdk/v0.47/learn/advanced/telemetry", - "docs/sdk/v0.47/learn/advanced/ocap", - "docs/sdk/v0.47/learn/advanced/config" - ], - "Node Operations": [ - "docs/sdk/v0.47/user", - "docs/sdk/v0.47/user/run-node/interact-node", - "docs/sdk/v0.47/user/run-node/multisig-guide", - "docs/sdk/v0.47/user/run-node/run-testnet", - "docs/sdk/v0.47/user/run-node/run-node", - "docs/sdk/v0.47/user/run-node/rosetta", - "docs/sdk/v0.47/user/run-node/txs", - "docs/sdk/v0.47/user/run-node/keyring", - "docs/sdk/v0.47/user/run-node/run-production" - ] - } -} - diff --git a/docs/sdk/v0.47/build.mdx b/docs/sdk/v0.47/build.mdx index efda570a..77bd4f86 100644 --- a/docs/sdk/v0.47/build.mdx +++ b/docs/sdk/v0.47/build.mdx @@ -3,13 +3,13 @@ title: "Build" description: "Version: v0.47" --- -* [Architecture](/v0.47/build/architecture) - Overview and detailed explanation of the system architecture. -* [Building Apps](/v0.47/build/building-apps/app-go) - The documentation in this section will guide you through the process of developing your dApp using the Cosmos SDK framework. -* [Modules](/v0.47/build/modules) - Information about the various modules available in the Cosmos SDK: Auth, Authz, Bank, Crisis, Distribution, Evidence, Feegrant, Governance, Mint, Params, Slashing, Staking, Upgrade, NFT, Consensus, Circuit, Genutil. -* [Migrations](/v0.47/build/migrations/intro) - See what has been updated in each release the process of the transition between versions. -* [Packages](/v0.47/build/packages) - Explore a curated collection of pre-built modules and functionalities, streamlining the development process. -* [Tooling](/v0.47/build/tooling) - A suite of utilities designed to enhance the development workflow, optimizing the efficiency of Cosmos SDK-based projects. -* [ADR's](/v0.47/build/architecture) - Provides a structured repository of key decisions made during the development process, which have been documented and offers rationale behind key decisions being made. -* [RFC](/v0.47/build/rfc) - A Request for Comments (RFC) is a record of discussion on an open-ended topic related to the design and implementation of the Cosmos SDK, for which no immediate decision is required. -* [Specifications](/v0.47/build/spec/SPEC_STANDARD) - A detailed reference for the specifications of various components and features. -* [REST API](https://docs.cosmos.network/api) - A comprehensive reference for the application programming interfaces (APIs) provided by the SDK. +- [Architecture](/docs/sdk/v0.47/architecture/README) - Overview and detailed explanation of the system architecture. +- [Building Apps](/docs/sdk/v0.47/building-apps/00-app-go) - The documentation in this section will guide you through the process of developing your dApp using the Cosmos SDK framework. +- [Modules](/docs/sdk/v0.47/modules/README) - Information about the various modules available in the Cosmos SDK: Auth, Authz, Bank, Crisis, Distribution, Evidence, Feegrant, Governance, Mint, Params, Slashing, Staking, Upgrade, NFT, Consensus, Circuit, Genutil. +- [Migrations](/docs/sdk/v0.47/migrations/01-intro) - See what has been updated in each release the process of the transition between versions. +- [Packages](/docs/sdk/v0.47/packages/README) - Explore a curated collection of pre-built modules and functionalities, streamlining the development process. +- [Tooling](/docs/sdk/v0.47/tooling/README) - A suite of utilities designed to enhance the development workflow, optimizing the efficiency of Cosmos SDK-based projects. +- [ADR's](/docs/sdk/v0.47/architecture/README) - Provides a structured repository of key decisions made during the development process, which have been documented and offers rationale behind key decisions being made. +- [RFC](/docs/sdk/v0.47/rfc/README) - A Request for Comments (RFC) is a record of discussion on an open-ended topic related to the design and implementation of the Cosmos SDK, for which no immediate decision is required. +- [Specifications](/docs/sdk/build/spec/SPEC_STANDARD) - A detailed reference for the specifications of various components and features. +- [REST API](https://docs.cosmos.network/api) - A comprehensive reference for the application programming interfaces (APIs) provided by the SDK. diff --git a/docs/sdk/v0.47/changelog/release-notes.mdx b/docs/sdk/v0.47/changelog/release-notes.mdx index 2f92c210..1c4b08c5 100644 --- a/docs/sdk/v0.47/changelog/release-notes.mdx +++ b/docs/sdk/v0.47/changelog/release-notes.mdx @@ -1,407 +1,6 @@ --- title: "Release Notes" description: "Cosmos SDK release notes and changelog" -mode: "custom" --- - - - {/* - - Guiding Principles: - - Changelogs are for humans, not machines. - - There should be an entry for every single version. - - The same types of changes should be grouped. - - Versions and sections should be linkable. - - The latest version comes first. - - The release date of each version is displayed. - - Mention whether you follow Semantic Versioning. - - Usage: - - Change log entries are to be added to the Unreleased section under the - - appropriate stanza (see below). Each entry should ideally include a tag and - - the Github issue reference in the following format: - - * () \# message - - The issue numbers will later be link-ified during the release process so you do - - not have to worry about including a link manually, but you can if you wish. - - Types of changes (Stanzas): - - "Features" for new features. - - "Improvements" for changes in existing functionality. - - "Deprecated" for soon-to-be removed features. - - "Bug Fixes" for any bug fixes. - - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. - - "CLI Breaking" for breaking CLI commands. - - "API Breaking" for breaking exported APIs used by developers building on SDK. - - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. - - Ref: https://keepachangelog.com/en/1.0.0/ - - */} - - # Changelog - - ## [Unreleased] - - ## [v0.47.17](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.17) - 2025-02-12 - - ### Bug Fixes - - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker - - ## [v0.47.16](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.16) - 2025-02-20 - - ### Bug Fixes - - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal - - ## [v0.47.15](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.15) - 2024-12-16 - - ### Bug Fixes - - * Bump `cosmossdk.io/math` to v1.4. - - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any - - ## [v0.47.14](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.14) - 2024-09-20 - - ### Improvements - - * [#21295](https://github.com/cosmos/cosmos-sdk/pull/21295) Bump to gogoproto v1.7.0. - - * [#21295](https://github.com/cosmos/cosmos-sdk/pull/21295) Remove usage of `slices.SortFunc` due to API break in used versions. - - ## [v0.47.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.13) - 2024-07-15 - - ### Bug Fixes - - * (client) [#20912](https://github.com/cosmos/cosmos-sdk/pull/20912) Fix `math.LegacyDec` type deserialization in GRPC queries. - - * (x/group) [#20750](https://github.com/cosmos/cosmos-sdk/pull/20750) x/group shouldn't claim "orm" error codespace. This prevents any chain Cosmos SDK `v0.47` chain to use the ORM module. - - ## [v0.47.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.12) - 2024-06-10 - - ## Improvements - - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. - - ### Bug Fixes - - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. - - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. - - ## [v0.47.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.11) - 2024-04-22 - - ### Bug Fixes - - * (x/feegrant,x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m). The same issue was found in `x/feegrant` and `x/authz` modules. - - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. - - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from `proposal.FinalTallyResult` in the gprc query. - - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19746) Throw an error when signing with incorrect Ledger. - - ## [v0.47.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.10) - 2024-02-27 - - ### Bug Fixes - - * (x/staking) Fix a possible bypass of delagator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) - - * (server) [#19573](https://github.com/cosmos/cosmos-sdk/pull/19573) Use proper `db_backend` type when reading chain-id - - ## [v0.47.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.9) - 2024-02-19 - - ### Bug Fixes - - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. - - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. - - ## [v0.47.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.8) - 2024-01-22 - - ### Improvements - - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. - - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1. - - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 - - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. - - ### Bug Fixes - - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. - - * (server) [#18920](https://github.com/cosmos/cosmos-sdk/pull/18920) Fixes consensus failure while restart node with wrong `chainId` in genesis. - - ## [v0.47.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.7) - 2023-12-20 - - ### Improvements - - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. - - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. - - ### Bug Fixes - - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after BeginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. - - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. - - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. - - ## [v0.47.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.6) - 2023-11-14 - - ### Features - - * (server) [#18110](https://github.com/cosmos/cosmos-sdk/pull/18110) Start gRPC & API server in standalone mode. - - ### Improvements - - * (baseapp) [#17954](https://github.com/cosmos/cosmos-sdk/issues/17954) Add `Mempool()` method on `BaseApp` to allow access to the mempool. - - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. - - ### Bug Fixes - - * (server) [#18254](https://github.com/cosmos/cosmos-sdk/pull/18254) Don't hardcode gRPC address to localhost. - - * (server) [#18251](https://github.com/cosmos/cosmos-sdk/pull/18251) Call `baseapp.Close()` when app started as grpc only. - - * (baseapp) [#17769](https://github.com/cosmos/cosmos-sdk/pull/17769) Ensure we respect block size constraints in the `DefaultProposalHandler`'s `PrepareProposal` handler when a nil or no-op mempool is used. We provide a `TxSelector` type to assist in making transaction selection generalized. We also fix a comparison bug in tx selection when `req.maxTxBytes` is reached. - - * (config) [#17649](https://github.com/cosmos/cosmos-sdk/pull/17649) Fix `mempool.max-txs` configuration is invalid in `app.config`. - - * (mempool) [#17668](https://github.com/cosmos/cosmos-sdk/pull/17668) Fix `PriorityNonceIterator.Next()` nil pointer ref for min priority at the end of iteration. - - * (x/auth) [#17902](https://github.com/cosmos/cosmos-sdk/pull/17902) Remove tip posthandler. - - * (x/bank) [#18107](https://github.com/cosmos/cosmos-sdk/pull/18107) Add missing keypair of SendEnabled to restore legacy param set before migration. - - ### Client Breaking Changes - - * (x/gov) [#17910](https://github.com/cosmos/cosmos-sdk/pull/17910) Remove telemetry for counting votes and proposals. It was incorrectly counting votes. Use alternatives, such as state streaming. - - ## [v0.47.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.5) - 2023-09-01 - - ### Features - - * (client/rpc) [#17274](https://github.com/cosmos/cosmos-sdk/pull/17274) Add `QueryEventForTxCmd` cmd to subscribe and wait event for transaction by hash. - - * (keyring) [#17424](https://github.com/cosmos/cosmos-sdk/pull/17424) Allows to import private keys encoded in hex. - - ### Improvements - - * (x/gov) [#17387](https://github.com/cosmos/cosmos-sdk/pull/17387) Add `MsgSubmitProposal` `SetMsgs` method. - - * (x/gov) [#17354](https://github.com/cosmos/cosmos-sdk/issues/17354) Emit `VoterAddr` in `proposal_vote` event. - - * (x/group, x/gov) [#17220](https://github.com/cosmos/cosmos-sdk/pull/17220) Add `--skip-metadata` flag in `draft-proposal` to skip metadata prompt. - - * (x/genutil) [#17296](https://github.com/cosmos/cosmos-sdk/pull/17296) Add `MigrateHandler` to allow reuse migrate genesis related function. - - * In v0.46, v0.47 this function is additive to the `genesis migrate` command. However in v0.50+, adding custom migrations to the `genesis migrate` command is directly possible. - - ### Bug Fixes - - * (server) [#17181](https://github.com/cosmos/cosmos-sdk/pull/17181) Fix `db_backend` lookup fallback from `config.toml`. - - * (runtime) [#17284](https://github.com/cosmos/cosmos-sdk/pull/17284) Properly allow to combine depinject-enabled modules and non-depinject-enabled modules in app v2. - - * (baseapp) [#17159](https://github.com/cosmos/cosmos-sdk/pull/17159) Validators can propose blocks that exceed the gas limit. - - * (baseapp) [#16547](https://github.com/cosmos/cosmos-sdk/pull/16547) Ensure a transaction's gas limit cannot exceed the block gas limit. - - * (x/gov,x/group) [#17220](https://github.com/cosmos/cosmos-sdk/pull/17220) Do not try validate `msgURL` as web URL in `draft-proposal` command. - - * (cli) [#17188](https://github.com/cosmos/cosmos-sdk/pull/17188) Fix `--output-document` flag in `tx multi-sign`. - - * (x/auth) [#17209](https://github.com/cosmos/cosmos-sdk/pull/17209) Internal error on AccountInfo when account's public key is not set. - - ## [v0.47.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.4) - 2023-07-17 - - ### Features - - * (sims) [#16656](https://github.com/cosmos/cosmos-sdk/pull/16656) Add custom max gas for block for sim config with unlimited as default. - - ### Improvements - - * (cli) [#16856](https://github.com/cosmos/cosmos-sdk/pull/16856) Improve `simd prune` UX by using the app default home directory and set pruning method as first variable argument (defaults to default). `pruning.PruningCmd` rest unchanged for API compability, use `pruning.Cmd` instead. - - * (testutil) [#16704](https://github.com/cosmos/cosmos-sdk/pull/16704) Make app config configurator for testing configurable with external modules. - - * (deps) [#16565](https://github.com/cosmos/cosmos-sdk/pull/16565) Bump CometBFT to [v0.37.2](https://github.com/cometbft/cometbft/blob/v0.37.2/CHANGELOG.md). - - ### Bug Fixes - - * (x/auth) [#16994](https://github.com/cosmos/cosmos-sdk/pull/16994) Fix regression where querying transactions events with `<=` or `>=` would not work. - - * (server) [#16827](https://github.com/cosmos/cosmos-sdk/pull/16827) Properly use `--trace` flag (before it was setting the trace level instead of displaying the stacktraces). - - * (x/auth) [#16554](https://github.com/cosmos/cosmos-sdk/pull/16554) `ModuleAccount.Validate` now reports a nil `.BaseAccount` instead of panicking. - - * [#16588](https://github.com/cosmos/cosmos-sdk/pull/16588) Propogate snapshotter failures to the caller, (it would create an empty snapshot silently before). - - * (x/slashing) [#16784](https://github.com/cosmos/cosmos-sdk/pull/16784) Emit event with the correct reason in `SlashWithInfractionReason`. - - ## [v0.47.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.3) - 2023-06-08 - - ### Features - - * (baseapp) [#16290](https://github.com/cosmos/cosmos-sdk/pull/16290) Add circuit breaker setter in baseapp. - - * (x/group) [#16191](https://github.com/cosmos/cosmos-sdk/pull/16191) Add EventProposalPruned event to group module whenever a proposal is pruned. - - * (tx) [#15992](https://github.com/cosmos/cosmos-sdk/pull/15992) Add `WithExtensionOptions` in tx Factory to allow `SetExtensionOptions` with given extension options. - - ### Improvements - - * (baseapp) [#16407](https://github.com/cosmos/cosmos-sdk/pull/16407) Make `DefaultProposalHandler.ProcessProposalHandler` return a ProcessProposal NoOp when using none or a NoOp mempool. - - * (deps) [#16083](https://github.com/cosmos/cosmos-sdk/pull/16083) Bumps `proto-builder` image to 0.13.0. - - * (client) [#16075](https://github.com/cosmos/cosmos-sdk/pull/16075) Partly revert [#15953](https://github.com/cosmos/cosmos-sdk/issues/15953) and `factory.Prepare` now does nothing in offline mode. - - * (server) [#15984](https://github.com/cosmos/cosmos-sdk/pull/15984) Use `cosmossdk.io/log` package for logging instead of CometBFT logger. NOTE: v0.45 and v0.46 were not using CometBFT logger either. This keeps the same underlying logger (zerolog) as in v0.45.x+ and v0.46.x+ but now properly supporting filtered logging. - - * (gov) [#15979](https://github.com/cosmos/cosmos-sdk/pull/15979) Improve gov error message when failing to convert v1 proposal to v1beta1. - - * (store) [#16067](https://github.com/cosmos/cosmos-sdk/pull/16067) Add local snapshots management commands. - - * (server) [#16061](https://github.com/cosmos/cosmos-sdk/pull/16061) Add Comet bootstrap command. - - * (snapshots) [#16060](https://github.com/cosmos/cosmos-sdk/pull/16060) Support saving and restoring snapshot locally. - - * (x/staking) [#16068](https://github.com/cosmos/cosmos-sdk/pull/16068) Update simulation to allow non-EOA accounts to stake. - - * (server) [#16142](https://github.com/cosmos/cosmos-sdk/pull/16142) Remove JSON Indentation from the GRPC to REST gateway's responses. (Saving bandwidth) - - * (types) [#16145](https://github.com/cosmos/cosmos-sdk/pull/16145) Rename interface `ExtensionOptionI` back to `TxExtensionOptionI` to avoid breaking change. - - * (baseapp) [#16193](https://github.com/cosmos/cosmos-sdk/pull/16193) Add `Close` method to `BaseApp` for custom app to cleanup resource in graceful shutdown. - - ### Bug Fixes - - * Fix [barberry](https://forum.cosmos.network/t/cosmos-sdk-security-advisory-barberry/10825) security vulnerability. - - * (server) [#16395](https://github.com/cosmos/cosmos-sdk/pull/16395) Do not override some Comet config is purposely set differently in `InterceptConfigsPreRunHandler`. - - * (store) [#16449](https://github.com/cosmos/cosmos-sdk/pull/16449) Fix StateSync Restore by excluding memory store. - - * (cli) [#16312](https://github.com/cosmos/cosmos-sdk/pull/16312) Allow any addresses in `client.ValidatePromptAddress`. - - * (x/group) [#16017](https://github.com/cosmos/cosmos-sdk/pull/16017) Correctly apply account number in group v2 migration. - - ### API Breaking Changes - - * (testutil) [#14991](https://github.com/cosmos/cosmos-sdk/pull/14991) The `testutil/testdata_pulsar` package has moved to `testutil/testdata/testpb`. Chains will not notice this breaking change as this package contains testing utilities only used by the SDK internally. - - ## [v0.47.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.2) - 2023-04-27 - - ### Improvements - - * (x/evidence) [#15908](https://github.com/cosmos/cosmos-sdk/pull/15908) Update the equivocation handler to work with ICS by removing a pubkey check that was performing a no-op for consumer chains. - - * (x/slashing) [#15908](https://github.com/cosmos/cosmos-sdk/pull/15908) Remove the validators' pubkey check in the signature handler in order to work with ICS. - - * (deps) [#15957](https://github.com/cosmos/cosmos-sdk/pull/15957) Bump CometBFT to [v0.37.1](https://github.com/cometbft/cometbft/blob/v0.37.1/CHANGELOG.md#v0371). - - * (store) [#15683](https://github.com/cosmos/cosmos-sdk/pull/15683) `rootmulti.Store.CacheMultiStoreWithVersion` now can handle loading archival states that don't persist any of the module stores the current state has. - - * [#15448](https://github.com/cosmos/cosmos-sdk/pull/15448) Automatically populate the block timestamp for historical queries. In contexts where the block timestamp is needed for previous states, the timestamp will now be set. Note, when querying against a node it must be re-synced in order to be able to automatically populate the block timestamp. Otherwise, the block timestamp will be populated for heights going forward once upgraded. - - * [#14019](https://github.com/cosmos/cosmos-sdk/issues/14019) Remove the interface casting to allow other implementations of a `CommitMultiStore`. - - * (simtestutil) [#15903](https://github.com/cosmos/cosmos-sdk/pull/15903) Add `AppStateFnWithExtendedCbs` with moduleStateCb callback function to allow access moduleState. - - ### Bug Fixes - - * (baseapp) [#15789](https://github.com/cosmos/cosmos-sdk/pull/15789) Ensure `PrepareProposal` and `ProcessProposal` respect `InitialHeight` set by CometBFT when set to a value greater than 1. - - * (types) [#15433](https://github.com/cosmos/cosmos-sdk/pull/15433) Allow disabling of account address caches (for printing bech32 account addresses). - - * (client/keys) [#15876](https://github.com/cosmos/cosmos-sdk/pull/15876) Fix the JSON output ` keys list --output json` when there are no keys. - - ## [v0.47.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.1) - 2023-03-23 - - ### Features - - * (x/bank) [#15265](https://github.com/cosmos/cosmos-sdk/pull/15265) Update keeper interface to include `GetAllDenomMetaData`. - - * (x/groups) [#14879](https://github.com/cosmos/cosmos-sdk/pull/14879) Add `Query/Groups` query to get all the groups. - - * (x/gov,cli) [#14718](https://github.com/cosmos/cosmos-sdk/pull/14718) Added `AddGovPropFlagsToCmd` and `ReadGovPropFlags` functions. - - * (cli) [#14655](https://github.com/cosmos/cosmos-sdk/pull/14655) Add a new command to list supported algos. - - * (x/genutil,cli) [#15147](https://github.com/cosmos/cosmos-sdk/pull/15147) Add `--initial-height` flag to cli init cmd to provide `genesis.json` with user-defined initial block height. - - ### Improvements - - * (x/distribution) [#15462](https://github.com/cosmos/cosmos-sdk/pull/15462) Add delegator address to the event for withdrawing delegation rewards. - - * [#14609](https://github.com/cosmos/cosmos-sdk/pull/14609) Add `RetryForBlocks` method to use in tests that require waiting for a transaction to be included in a block. - - ### Bug Fixes - - * (baseapp) [#15487](https://github.com/cosmos/cosmos-sdk/pull/15487) Reset state before calling PrepareProposal and ProcessProposal. - - * (cli) [#15123](https://github.com/cosmos/cosmos-sdk/pull/15123) Fix the CLI `offline` mode behavior to be really offline. The API of `clienttx.NewFactoryCLI` is updated to return an error. - - ### Deprecated - - * (x/genutil) [#15316](https://github.com/cosmos/cosmos-sdk/pull/15316) Remove requirement on node & IP being included in a gentx. - - ## [v0.47.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.47.0) - 2023-03-14 - - ### Features - - * (x/gov) [#15151](https://github.com/cosmos/cosmos-sdk/pull/15151) Add `burn_vote_quorum`, `burn_proposal_deposit_prevote` and `burn_vote_veto` params to allow applications to decide if they would like to burn deposits - - * (client) [#14509](https://github.com/cosmos/cosmos-sdk/pull/#14509) Added `AddKeyringFlags` function. - - * (x/bank) [#14045](https://github.com/cosmos/cosmos-sdk/pull/14045) Add CLI command `spendable-balances`, which also accepts the flag `--denom`. - - * (x/slashing, x/staking) [#14363](https://github.com/cosmos/cosmos-sdk/pull/14363) Add the infraction a validator commited type as an argument to a `SlashWithInfractionReason` keeper method. - - * (client) [#14051](https://github.com/cosmos/cosmos-sdk/pull/14051) Add `--grpc` client option. - - * (x/genutil) [#14149](https://github.com/cosmos/cosmos-sdk/pull/14149) Add `genutilcli.GenesisCoreCommand` command, which contains all genesis-related sub-commands. - - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) Add new proto field `hash` of type `string` to `QueryEvidenceRequest` which helps to decode the hash properly while using query API. - - * (core) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add a `FormatCoins` function to in `core/coins` to format sdk Coins following the Value Renderers spec. - - * (math) [#13306](https://github.com/cosmos/cosmos-sdk/pull/13306) Add `FormatInt` and `FormatDec` functiosn in `math` to format integers and decimals following the Value Renderers spec. - - * (x/staking) [#13122](https://github.com/cosmos/cosmos-sdk/pull/13122) Add `UnbondingCanComplete` and `PutUnbondingOnHold` to `x/staking` module. - - * [#13437](https://github.com/cosmos/cosmos-sdk/pull/13437) Add new flag `--modules-to-export` in `simd export` command to export only selected modules. - - * [#13298](https://github.com/cosmos/cosmos-sdk/pull/13298) Add `AddGenesisAccount` helper func in x/auth module which helps adding accounts to genesis state. - - * (x/authz) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) Add an allow list, an optional list of addresses allowed to receive bank assets via authz MsgSend grant. - - * (sdk.Coins) [#12627](https://github.com/cosmos/cosmos-sdk/pull/12627) Make a Denoms method on sdk.Coins. - - * (testutil) [#12973](https://github.com/cosmos/cosmos-sdk/pull/12973) Add generic `testutil.RandSliceElem` function which selects a random element from the list. - - * (client) [#12936](https://github.com/cosmos/cosmos-sdk/pull/12936) Add capability to preprocess transactions before broadcasting from a higher level chain. - - * (cli) [#13064](https://github.com/cosmos/cosmos-sdk/pull/13064) Add `debug prefixes` to list supported HRP prefixes via . - - * (ledger) [#12935](https://github.com/cosmos/cosmos-sdk/pull/12935) Generalize Ledger integration to allow for different apps or keytypes that use SECP256k1. - - * (x/bank) [#11981](https://github.com/cosmos/cosmos-sdk/pull/11981) Create the `SetSendEnabled` endpoint for managing the bank's SendEnabled settings. - - * (x/auth) [#13210](https://github.com/cosmos/cosmos-sdk/pull/13210) Add `Query/AccountInfo` endpoint for simplified access to basic account info. - - * (x/consensus) [#12905](https://github.com/cosmos/cosmos-sdk/pull/12905) Create a new `x/consensus` module that is now responsible for maintaining Tendermint consensus parameters instead of `x/param`. Legacy types remain in order to facilitate parameter migration from the deprecated `x/params`. App developers should ensure that they execute `baseapp.MigrateParams` during their chain upgrade. These legacy types will be removed in a future release. - - * (client/tx) [#13670](https://github.com/cosmos/cosmos-sdk/pull/13670) Add validation in `BuildUnsignedTx` to prevent simple inclusion of valid mnemonics - - ### Improvements - - * [#14995](https://github.com/cosmos/cosmos-sdk/pull/14995) Allow unknown fields in `ParseTypedEvent`. - - * (store) [#14931](https://github.com/cosmos/cosmos-sdk/pull/14931) Exclude in-memory KVStores, i.e. `StoreTypeMemory`, from CommitInfo commitments. - - * (cli) [#14919](https://github.com/cosmos/cosmos-sdk/pull/14919) Fix never assigned error when write validators. - - * (x/group) [#14923](https://github.com/cosmos/cosmos-sdk/pull/14923) Fix error while using pagination in `x/group` from CLI. - - * (types/coin) [#14715](https://github.com/cosmos/cosmos-sdk/pull/14715) `sdk.Coins.Add` now returns an empty set of coins `sdk.Coins{}` if both coins set are empty. - - * This is a behavior change, as previously `sdk.Coins.Add` would return `nil` in this case. - - * (reflection) [#14838](https://github.com/cosmos/cosmos-sdk/pull/14838) We now require that all proto files' import path (i.e. the OS path) matches their fully-qualified package name. For example, proto files with package name `cosmos.my.pkg.v1` should live in the folder `cosmos/my/pkg/v1/*.proto` relatively to the protoc import root folder (usually the root `proto/` folder). - - * (baseapp) [#14505](https://github.com/cosmos/cosmos-sdk/pull/14505) PrepareProposal and ProcessProposal now use deliverState for the first block in order to access changes made in InitChain. - - * (x/group) [#14527](https://github.com/cosmos/cosmos-sdk/pull/14527) Fix wrong address set in `EventUpdateGroupPolicy`. - - * (cli) [#14509](https://github.com/cosmos/cosmos-sdk/pull/14509) Added missing options to keyring-backend flag usage. - - * (server) [#14441](https://github.com/cosmos/cosmos-sdk/pull/14441) Fix `--log_format` flag not working. - - * (ante) [#14448](https://github.com/cosmos/cosmos-sdk/pull/14448) Return anteEvents when postHandler fail. - - * (baseapp) [#13983](https://github.com/cosmos/cosmos-sdk/pull/13983) Don't emit duplicate ante-handler events when a post-handler is defined. - - * (x/staking) [#14064](https://github.com/cosmos/cosmos-sdk/pull/14064) Set all fields in `redelegation.String()`. - - * (x/upgrade) [#13936](https://github.com/cosmos/cosmos-sdk/pull/13936) Make downgrade verification work again. - - * (x/group) [#13742](https://github.com/cosmos/cosmos-sdk/pull/13742) Fix `validate-genesis` when group policy accounts exist. - - * (store) [#13516](https://github.com/cosmos/cosmos-sdk/pull/13516) Fix state listener that was observing writes at wrong time. - - * (simstestutil) [#15305](https://github.com/cosmos/cosmos-sdk/pull/15305) Add `AppStateFnWithExtendedCb` with callback function to extend rawState. - - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. - - * (cli) [#14953](https://github.com/cosmos/cosmos-sdk/pull/14953) Enable profiling block replay during abci handshake with `--cpu-profile`. - - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. - - * (store) [#14189](https://github.com/cosmos/cosmos-sdk/pull/14189) Add config `iavl-lazy-loading` to enable lazy loading of iavl store, to improve start up time of archive nodes, add method `SetLazyLoading` to `CommitMultiStore` interface. - - * (deps) [#14830](https://github.com/cosmos/cosmos-sdk/pull/14830) Bump to IAVL `v0.19.5-rc.1`. - - * (tools) [#14793](https://github.com/cosmos/cosmos-sdk/pull/14793) Dockerfile optimization. - - * (x/gov) [#13010](https://github.com/cosmos/cosmos-sdk/pull/13010) Partial cherry-pick of this issue for adding proposer migration. - - * [#14691](https://github.com/cosmos/cosmos-sdk/pull/14691) Change behavior of `sdk.StringifyEvents` to not flatten events attributes by events type. - - * This change only affects ABCI message logs, and not the events field. - - * [#14692](https://github.com/cosmos/cosmos-sdk/pull/14692) Improve RPC queries error message when app is at height 0. - - * [#14017](https://github.com/cosmos/cosmos-sdk/pull/14017) Simplify ADR-028 and `address.Module`. - - * This updates the [ADR-028](https://docs.cosmos.network/main/architecture/adr-028-public-key-addresses) and enhance the `address.Module` API to support module addresses and sub-module addresses in a backward compatible way. - - * (snapshots) [#14608](https://github.com/cosmos/cosmos-sdk/pull/14608/) Deprecate unused structs `SnapshotKVItem` and `SnapshotSchema`. - - * [#15243](https://github.com/cosmos/cosmos-sdk/pull/15243) `LatestBlockResponse` & `BlockByHeightResponse` types' field `sdk_block` was incorrectly cast `proposer_address` bytes to validator operator address, now to consensus address - - * (x/group, x/gov) [#14483](https://github.com/cosmos/cosmos-sdk/pull/14483) Add support for `[]string` and `[]int` in `draft-proposal` prompt. - - * (protobuf) [#14476](https://github.com/cosmos/cosmos-sdk/pull/14476) Clean up protobuf annotations `{accepts,implements}_interface`. - - * (x/gov, x/group) [#14472](https://github.com/cosmos/cosmos-sdk/pull/14472) The recommended metadata format for x/gov and x/group proposals now uses an array of strings (instead of a single string) for the `authors` field. - - * (crypto) [#14460](https://github.com/cosmos/cosmos-sdk/pull/14460) Check the signature returned by a ledger device against the public key in the keyring. - - * [#14356](https://github.com/cosmos/cosmos-sdk/pull/14356) Add `events.GetAttributes` and `event.GetAttribute` methods to simplify the retrieval of an attribute from event(s). - - * (types) [#14332](https://github.com/cosmos/cosmos-sdk/issues/14332) Reduce state export time by 50%. - - * (types) [#14163](https://github.com/cosmos/cosmos-sdk/pull/14163) Refactor `(coins Coins) Validate()` to avoid unnecessary map. - - * [#13881](https://github.com/cosmos/cosmos-sdk/pull/13881) Optimize iteration on nested cached KV stores and other operations in general. - - * (x/gov) [#14347](https://github.com/cosmos/cosmos-sdk/pull/14347) Support `v1.Proposal` message in `v1beta1.Proposal.Content`. - - * [#13882](https://github.com/cosmos/cosmos-sdk/pull/13882) Add tx `encode` and `decode` endpoints to amino tx service. - - > Note: These endpoints encodes and decodes only amino txs. - - * (config) [#13894](https://github.com/cosmos/cosmos-sdk/pull/13894) Support state streaming configuration in `app.toml` template and default configuration. - - * (x/nft) [#13836](https://github.com/cosmos/cosmos-sdk/pull/13836) Remove the validation for `classID` and `nftID` from the NFT module. - - * [#13789](https://github.com/cosmos/cosmos-sdk/pull/13789) Add tx `encode` and `decode` endpoints to tx service. - - > Note: These endpoints will only encode and decode proto messages, Amino encoding and decoding is not supported. - - * [#13619](https://github.com/cosmos/cosmos-sdk/pull/13619) Add new function called LogDeferred to report errors in defers. Use the function in x/bank files. - - * (deps) [#13397](https://github.com/cosmos/cosmos-sdk/pull/13397) Bump Go version minimum requirement to `1.19`. - - * [#13070](https://github.com/cosmos/cosmos-sdk/pull/13070) Migrate from `gogo/protobuf` to `cosmos/gogoproto`. - - * [#12995](https://github.com/cosmos/cosmos-sdk/pull/12995) Add `FormatTime` and `ParseTimeString` methods. - - * [#12952](https://github.com/cosmos/cosmos-sdk/pull/12952) Replace keyring module to Cosmos fork. - - * [#12352](https://github.com/cosmos/cosmos-sdk/pull/12352) Move the `RegisterSwaggerAPI` logic into a separate helper function in the server package. - - * [#12876](https://github.com/cosmos/cosmos-sdk/pull/12876) Remove proposer-based rewards. - - * [#12846](https://github.com/cosmos/cosmos-sdk/pull/12846) Remove `RandomizedParams` from the `AppModuleSimulation` interface which is no longer needed. - - * (ci) [#12854](https://github.com/cosmos/cosmos-sdk/pull/12854) Use ghcr.io to host the proto builder image. Update proto builder image to go 1.19 - - * (x/bank) [#12706](https://github.com/cosmos/cosmos-sdk/pull/12706) Added the `chain-id` flag to the `AddTxFlagsToCmd` API. There is no longer a need to explicitly register this flag on commands whens `AddTxFlagsToCmd` is already called. - - * [#12717](https://github.com/cosmos/cosmos-sdk/pull/12717) Use injected encoding params in simapp. - - * [#12634](https://github.com/cosmos/cosmos-sdk/pull/12634) Move `sdk.Dec` to math package. - - * [#12187](https://github.com/cosmos/cosmos-sdk/pull/12187) Add batch operation for x/nft module. - - * [#12455](https://github.com/cosmos/cosmos-sdk/pull/12455) Show attempts count in error for signing. - - * [#13101](https://github.com/cosmos/cosmos-sdk/pull/13101) Remove weights from `simapp/params` and `testutil/sims`. They are now in their respective modules. - - * [#12398](https://github.com/cosmos/cosmos-sdk/issues/12398) Refactor all `x` modules to unit-test via mocks and decouple `simapp`. - - * [#13144](https://github.com/cosmos/cosmos-sdk/pull/13144) Add validator distribution info grpc gateway get endpoint. - - * [#13168](https://github.com/cosmos/cosmos-sdk/pull/13168) Migrate tendermintdev/proto-builder to ghcr.io. New image `ghcr.io/cosmos/proto-builder:0.8` - - * [#13178](https://github.com/cosmos/cosmos-sdk/pull/13178) Add `cosmos.msg.v1.service` protobuf annotation to allow tooling to distinguish between Msg and Query services via reflection. - - * [#13236](https://github.com/cosmos/cosmos-sdk/pull/13236) Integrate Filter Logging - - * [#13528](https://github.com/cosmos/cosmos-sdk/pull/13528) Update `ValidateMemoDecorator` to only check memo against `MaxMemoCharacters` param when a memo is present. - - * [#13651](https://github.com/cosmos/cosmos-sdk/pull/13651) Update `server/config/config.GetConfig` function. - - * [#13781](https://github.com/cosmos/cosmos-sdk/pull/13781) Remove `client/keys.KeysCdc`. - - * [#13802](https://github.com/cosmos/cosmos-sdk/pull/13802) Add --output-document flag to the export CLI command to allow writing genesis state to a file. - - * [#13794](https://github.com/cosmos/cosmos-sdk/pull/13794) `types/module.Manager` now supports the - - `cosmossdk.io/core/appmodule.AppModule` API via the new `NewManagerFromMap` constructor. - - * [#14175](https://github.com/cosmos/cosmos-sdk/pull/14175) Add `server.DefaultBaseappOptions(appopts)` function to reduce boiler plate in root.go. - - ### State Machine Breaking - - * (baseapp, x/auth/posthandler) [#13940](https://github.com/cosmos/cosmos-sdk/pull/13940) Update `PostHandler` to receive the `runTx` success boolean. - - * (store) [#14378](https://github.com/cosmos/cosmos-sdk/pull/14378) The `CacheKV` store is thread-safe again, which includes improved iteration and deletion logic. Iteration is on a strictly isolated view now, which is breaking from previous behavior. - - * (x/bank) [#14538](https://github.com/cosmos/cosmos-sdk/pull/14538) Validate denom in bank balances GRPC queries. - - * (x/group) [#14465](https://github.com/cosmos/cosmos-sdk/pull/14465) Add title and summary to proposal struct. - - * (x/gov) [#14390](https://github.com/cosmos/cosmos-sdk/pull/14390) Add title, proposer and summary to proposal struct. - - * (x/group) [#14071](https://github.com/cosmos/cosmos-sdk/pull/14071) Don't re-tally proposal after voting period end if they have been marked as ACCEPTED or REJECTED. - - * (x/group) [#13742](https://github.com/cosmos/cosmos-sdk/pull/13742) Migrate group policy account from module accounts to base account. - - * (x/auth)[#13780](https://github.com/cosmos/cosmos-sdk/pull/13780) `id` (type of int64) in `AccountAddressByID` grpc query is now deprecated, update to account-id(type of uint64) to use `AccountAddressByID`. - - * (codec) [#13307](https://github.com/cosmos/cosmos-sdk/pull/13307) Register all modules' `Msg`s with group's ModuleCdc so that Amino sign bytes are correctly generated.* (x/gov) - - * (codec) [#13196](https://github.com/cosmos/cosmos-sdk/pull/13196) Register all modules' `Msg`s with gov's ModuleCdc so that Amino sign bytes are correctly generated. - - * (group) [#13592](https://github.com/cosmos/cosmos-sdk/pull/13592) Fix group types registration with Amino. - - * (x/distribution) [#12852](https://github.com/cosmos/cosmos-sdk/pull/12852) Deprecate `CommunityPoolSpendProposal`. Please execute a `MsgCommunityPoolSpend` message via the new v1 `x/gov` module instead. This message can be used to directly fund the `x/gov` module account. - - * (x/bank) [#12610](https://github.com/cosmos/cosmos-sdk/pull/12610) `MsgMultiSend` now allows only a single input. - - * (x/bank) [#12630](https://github.com/cosmos/cosmos-sdk/pull/12630) Migrate `x/bank` to self-managed parameters and deprecate its usage of `x/params`. - - * (x/auth) [#12475](https://github.com/cosmos/cosmos-sdk/pull/12475) Migrate `x/auth` to self-managed parameters and deprecate its usage of `x/params`. - - * (x/slashing) [#12399](https://github.com/cosmos/cosmos-sdk/pull/12399) Migrate `x/slashing` to self-managed parameters and deprecate its usage of `x/params`. - - * (x/mint) [#12363](https://github.com/cosmos/cosmos-sdk/pull/12363) Migrate `x/mint` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/distribution) [#12434](https://github.com/cosmos/cosmos-sdk/pull/12434) Migrate `x/distribution` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/crisis) [#12445](https://github.com/cosmos/cosmos-sdk/pull/12445) Migrate `x/crisis` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) Migrate `x/gov` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/staking) [#12409](https://github.com/cosmos/cosmos-sdk/pull/12409) Migrate `x/staking` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) Move the SendEnabled information out of the Params and into the state store directly. - - * (x/gov) [#12771](https://github.com/cosmos/cosmos-sdk/pull/12771) Initial deposit requirement for proposals at submission time. - - * (x/staking) [#12967](https://github.com/cosmos/cosmos-sdk/pull/12967) `unbond` now creates only one unbonding delegation entry when multiple unbondings exist at a single height (e.g. through multiple messages in a transaction). - - * (x/auth/vesting) [#13502](https://github.com/cosmos/cosmos-sdk/pull/13502) Add Amino Msg registration for `MsgCreatePeriodicVestingAccount`. - - ### API Breaking Changes - - * Migrate to CometBFT. Follow the migration instructions in the [upgrade guide](./UPGRADING.md#migration-to-cometbft-part-1). - - * (simulation) [#14728](https://github.com/cosmos/cosmos-sdk/pull/14728) Rename the `ParamChanges` field to `LegacyParamChange` and `Contents` to `LegacyProposalContents` in `simulation.SimulationState`. Additionally it adds a `ProposalMsgs` field to `simulation.SimulationState`. - - * (x/gov) [#14782](https://github.com/cosmos/cosmos-sdk/pull/14782) Move the `metadata` argument in `govv1.NewProposal` alongside `title` and `summary`. - - * (x/upgrade) [#14216](https://github.com/cosmos/cosmos-sdk/pull/14216) Change upgrade keeper receiver to upgrade keeper pointers. - - * (x/auth) [#13780](https://github.com/cosmos/cosmos-sdk/pull/13780) Querying with `id` (type of int64) in `AccountAddressByID` grpc query now throws error, use account-id(type of uint64) instead. - - * (store) [#13516](https://github.com/cosmos/cosmos-sdk/pull/13516) Update State Streaming APIs: - - * Add method `ListenCommit` to `ABCIListener` - - * Move `ListeningEnabled` and `AddListener` methods to `CommitMultiStore` - - * Remove `CacheWrapWithListeners` from `CacheWrap` and `CacheWrapper` interfaces - - * Remove listening APIs from the caching layer (it should only listen to the `rootmulti.Store`) - - * Add three new options to file streaming service constructor. - - * Modify `ABCIListener` such that any error from any method will always halt the app via `panic` - - * (x/auth) [#13877](https://github.com/cosmos/cosmos-sdk/pull/13877) Rename `AccountKeeper`'s `GetNextAccountNumber` to `NextAccountNumber`. - - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) The `NewQueryEvidenceRequest` function now takes `hash` as a HEX encoded `string`. - - * (server) [#13485](https://github.com/cosmos/cosmos-sdk/pull/13485) The `Application` service now requires the `RegisterNodeService` method to be implemented. - - * [#13437](https://github.com/cosmos/cosmos-sdk/pull/13437) Add a list of modules to export argument in `ExportAppStateAndValidators`. - - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move simulation flags to `x/simulation/client/cli`. - - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move simulation helpers functions (`SetupSimulation`, `SimulationOperations`, `CheckExportSimulation`, `PrintStats`, `GetSimulationLog`) to `testutil/sims`. - - * (simapp) [#13402](https://github.com/cosmos/cosmos-sdk/pull/13402) Move `testutil/rest` package to `testutil`. - - * (types) [#13380](https://github.com/cosmos/cosmos-sdk/pull/13380) Remove deprecated `sdk.NewLevelDB`. - - * (simapp) [#13378](https://github.com/cosmos/cosmos-sdk/pull/13378) Move `simapp.App` to `runtime.AppI`. - - * (tx) [#12659](https://github.com/cosmos/cosmos-sdk/pull/12659) Remove broadcast mode `block`. - - * (simapp) [#12747](https://github.com/cosmos/cosmos-sdk/pull/12747) Remove `simapp.MakeTestEncodingConfig`. Please use `moduletestutil.MakeTestEncodingConfig` (`types/module/testutil`) in tests instead. - - * (x/bank) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) `NewSendAuthorization` takes a new argument of an optional list of addresses allowed to receive bank assests via authz MsgSend grant. You can pass `nil` for the same behavior as before, i.e. any recipient is allowed. - - * (x/bank) [#12593](https://github.com/cosmos/cosmos-sdk/pull/12593) Add `SpendableCoin` method to `BaseViewKeeper` - - * (x/slashing) [#12581](https://github.com/cosmos/cosmos-sdk/pull/12581) Remove `x/slashing` legacy querier. - - * (types) [#12355](https://github.com/cosmos/cosmos-sdk/pull/12355) Remove the compile-time `types.DBbackend` variable. Removes usage of the same in server/util.go - - * (x/gov) [#12368](https://github.com/cosmos/cosmos-sdk/pull/12369) Gov keeper is now passed by reference instead of copy to make post-construction mutation of Hooks and Proposal Handlers possible at a framework level. - - * (simapp) [#12270](https://github.com/cosmos/cosmos-sdk/pull/12270) Remove `invCheckPeriod uint` attribute from `SimApp` struct as per migration of `x/crisis` to app wiring - - * (simapp) [#12334](https://github.com/cosmos/cosmos-sdk/pull/12334) Move `simapp.ConvertAddrsToValAddrs` and `simapp.CreateTestPubKeys ` to respectively `simtestutil.ConvertAddrsToValAddrs` and `simtestutil.CreateTestPubKeys` (`testutil/sims`) - - * (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Move `simapp.EmptyAppOptions` to `simtestutil.EmptyAppOptions` (`testutil/sims`) - - * (simapp) [#12312](https://github.com/cosmos/cosmos-sdk/pull/12312) Remove `skipUpgradeHeights map[int64]bool` and `homePath string` from `NewSimApp` constructor as per migration of `x/upgrade` to app-wiring. - - * (testutil) [#12278](https://github.com/cosmos/cosmos-sdk/pull/12278) Move all functions from `simapp/helpers` to `testutil/sims` - - * (testutil) [#12233](https://github.com/cosmos/cosmos-sdk/pull/12233) Move `simapp.TestAddr` to `simtestutil.TestAddr` (`testutil/sims`) - - * (x/staking) [#12102](https://github.com/cosmos/cosmos-sdk/pull/12102) Staking keeper now is passed by reference instead of copy. Keeper's SetHooks no longer returns keeper. It updates the keeper in place instead. - - * (linting) [#12141](https://github.com/cosmos/cosmos-sdk/pull/12141) Fix usability related linting for database. This means removing the infix Prefix from `prefix.NewPrefixWriter` and such so that it is `prefix.NewWriter` and making `db.DBConnection` and such into `db.Connection` - - * (x/distribution) [#12434](https://github.com/cosmos/cosmos-sdk/pull/12434) `x/distribution` module `SetParams` keeper method definition is now updated to return `error`. - - * (x/staking) [#12409](https://github.com/cosmos/cosmos-sdk/pull/12409) `x/staking` module `SetParams` keeper method definition is now updated to return `error`. - - * (x/crisis) [#12445](https://github.com/cosmos/cosmos-sdk/pull/12445) `x/crisis` module `SetConstantFee` keeper method definition is now updated to return `error`. - - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) `x/gov` module refactored to use `Params` as single struct instead of `DepositParams`, `TallyParams` & `VotingParams`. - - * (x/gov) [#12631](https://github.com/cosmos/cosmos-sdk/pull/12631) Migrate `x/gov` to self-managed parameters and deprecate it's usage of `x/params`. - - * (x/bank) [#12630](https://github.com/cosmos/cosmos-sdk/pull/12630) `x/bank` module `SetParams` keeper method definition is now updated to return `error`. - - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) Move the SendEnabled information out of the Params and into the state store directly. - - The information can now be accessed using the BankKeeper. - - Setting can be done using MsgSetSendEnabled as a governance proposal. - - A SendEnabled query has been added to both GRPC and CLI. - - * (appModule) Remove `Route`, `QuerierRoute` and `LegacyQuerierHandler` from AppModule Interface. - - * (x/modules) Remove all LegacyQueries and related code from modules - - * (store) [#11825](https://github.com/cosmos/cosmos-sdk/pull/11825) Make extension snapshotter interface safer to use, renamed the util function `WriteExtensionItem` to `WriteExtensionPayload`. - - * (x/genutil)[#12956](https://github.com/cosmos/cosmos-sdk/pull/12956) `genutil.AppModuleBasic` has a new attribute: genesis transaction validation function. The existing validation logic is implemented in `genutiltypes.DefaultMessageValidator`. Use `genutil.NewAppModuleBasic` to create a new genutil Module Basic. - - * (codec) [#12964](https://github.com/cosmos/cosmos-sdk/pull/12964) `ProtoCodec.MarshalInterface` now returns an error when serializing unregistered types and a subsequent `ProtoCodec.UnmarshalInterface` would fail. - - * (x/staking) [#12973](https://github.com/cosmos/cosmos-sdk/pull/12973) Removed `stakingkeeper.RandomValidator`. Use `testutil.RandSliceElem(r, sk.GetAllValidators(ctx))` instead. - - * (x/gov) [#13160](https://github.com/cosmos/cosmos-sdk/pull/13160) Remove custom marshaling of proposl and voteoption. - - * (types) [#13430](https://github.com/cosmos/cosmos-sdk/pull/13430) Remove unused code `ResponseCheckTx` and `ResponseDeliverTx` - - * (store) [#13529](https://github.com/cosmos/cosmos-sdk/pull/13529) Add method `LatestVersion` to `MultiStore` interface, add method `SetQueryMultiStore` to baesapp to support alternative `MultiStore` implementation for query service. - - * (pruning) [#13609](https://github.com/cosmos/cosmos-sdk/pull/13609) Move pruning package to be under store package - - * [#13794](https://github.com/cosmos/cosmos-sdk/pull/13794) Most methods on `types/module.AppModule` have been moved to - - extension interfaces. `module.Manager.Modules` is now of type `map[string]interface{}` to support in parallel the new - - `cosmossdk.io/core/appmodule.AppModule` API. - - ### CLI Breaking Changes - - * (genesis) [#14149](https://github.com/cosmos/cosmos-sdk/pull/14149) Add `simd genesis` command, which contains all genesis-related sub-commands. - - * (x/genutil) [#13535](https://github.com/cosmos/cosmos-sdk/pull/13535) Replace in `simd init`, the `--staking-bond-denom` flag with `--default-denom` which is used for all default denomination in the genesis, instead of only staking. - - ### Bug Fixes - - * (x/auth/vesting) [#15373](https://github.com/cosmos/cosmos-sdk/pull/15373) Add extra checks when creating a periodic vesting account. - - * (x/auth) [#13838](https://github.com/cosmos/cosmos-sdk/pull/13838) Fix calling `String()` and `MarshalYAML` panics when pubkey is set on a `BaseAccount``. - - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) Fix evidence query API to decode the hash properly. - - * (bank) [#13691](https://github.com/cosmos/cosmos-sdk/issues/13691) Fix unhandled error for vesting account transfers, when total vesting amount exceeds total balance. - - * [#13553](https://github.com/cosmos/cosmos-sdk/pull/13553) Ensure all parameter validation for decimal types handles nil decimal values. - - * [#13145](https://github.com/cosmos/cosmos-sdk/pull/13145) Fix panic when calling `String()` to a Record struct type. - - * [#13116](https://github.com/cosmos/cosmos-sdk/pull/13116) Fix a dead-lock in the `Group-TotalWeight` `x/group` invariant. - - * (types) [#12154](https://github.com/cosmos/cosmos-sdk/pull/12154) Add `baseAccountGetter` to avoid invalid account error when create vesting account. - - * (x/staking) [#12303](https://github.com/cosmos/cosmos-sdk/pull/12303) Use bytes instead of string comparison in delete validator queue - - * (store/rootmulti) [#12487](https://github.com/cosmos/cosmos-sdk/pull/12487) Fix non-deterministic map iteration. - - * (sdk/dec_coins) [#12903](https://github.com/cosmos/cosmos-sdk/pull/12903) Fix nil `DecCoin` creation when converting `Coins` to `DecCoins` - - * (store) [#12945](https://github.com/cosmos/cosmos-sdk/pull/12945) Fix nil end semantics in store/cachekv/iterator when iterating a dirty cache. - - * (x/gov) [#13051](https://github.com/cosmos/cosmos-sdk/pull/13051) In SubmitPropsal, when a legacy msg fails it's handler call, wrap the error as ErrInvalidProposalContent (instead of ErrNoProposalHandlerExists). - - * (snapshot) [#13400](https://github.com/cosmos/cosmos-sdk/pull/13400) Fix snapshot checksum issue in golang 1.19. - - * (server) [#13778](https://github.com/cosmos/cosmos-sdk/pull/13778) Set Cosmos SDK default endpoints to localhost to avoid unknown exposure of endpoints. - - * (x/auth) [#13877](https://github.com/cosmos/cosmos-sdk/pull/13877) Handle missing account numbers during `InitGenesis`. - - * (x/gov) [#13918](https://github.com/cosmos/cosmos-sdk/pull/13918) Propagate message errors when executing a proposal. - - ### Deprecated - - * (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) The `evidence_hash` field of `QueryEvidenceRequest` has been deprecated and now contains a new field `hash` with type `string`. - - * (x/bank) [#11859](https://github.com/cosmos/cosmos-sdk/pull/11859) The Params.SendEnabled field is deprecated and unusable. - - The information can now be accessed using the BankKeeper. - - Setting can be done using MsgSetSendEnabled as a governance proposal. - - A SendEnabled query has been added to both GRPC and CLI. - - ## Previous Versions - - [CHANGELOG of previous versions](https://github.com/cosmos/cosmos-sdk/blob/main/CHANGELOG.md#v0460---2022-07-26). - +{/* Release notes content will be added here soon */} \ No newline at end of file diff --git a/docs/sdk/v0.47/learn.mdx b/docs/sdk/v0.47/learn.mdx index d607d0fa..88cef5df 100644 --- a/docs/sdk/v0.47/learn.mdx +++ b/docs/sdk/v0.47/learn.mdx @@ -3,6 +3,9 @@ title: "Learn" description: "Version: v0.47" --- -* [Introduction](/v0.47/learn/intro/overview) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, laying the groundwork for understanding blockchain development. In this section we provide a High-Level Overview of the SDK, then dive deeper into Core concepts such as Application-Specific Blockchains, Blockchain Architecture, and finally we begin to explore what are the main components of the SDK. -* [Beginner](/v0.47/learn/beginner/overview-app) - Start your journey with beginner-friendly resources in the Cosmos SDK's "Learn" section, providing a gentle entry point for newcomers to blockchain development. Here we focus on a little more detail, covering the Anatomy of a Cosmos SDK Application, Transaction Lifecycles, Accounts and lastly, Gas and Fees. -* [Advanced](/v0.47/learn/advanced/baseapp) - Level up your Cosmos SDK expertise with advanced topics, tailored for experienced developers diving into intricate blockchain application development. We cover the Cosmos SDK on a lower level as we dive into the core of the SDK with BaseApp, Transactions, Context, Node Client (Daemon), Store, Encoding, gRPC, REST, and CometBFT Endpoints, CLI, Events, Telementry, Object-Capability Model, RunTx recovery middleware, Cosmos Blockchain Simulator, Protobuf Documentation, In-Place Store Migrations, Configuration and AutoCLI. +* [Introduction](/docs/sdk/v0.47/intro/00-overview) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, +laying the groundwork for understanding blockchain development. In this section we provide a High-Level Overview of the SDK, then dive deeper into Core concepts such as Application-Specific Blockchains, Blockchain Architecture, and finally we begin to explore the main components of the SDK. +* [Beginner](/docs/sdk/v0.47/beginner/00-app-anatomy) - Start your journey with beginner-friendly resources in the Cosmos SDK's "Learn" +section, providing a gentle entry point for newcomers to blockchain development. Here we focus on a little more detail, covering the Anatomy of a Cosmos SDK Application, Transaction Lifecycles, Accounts and lastly, Gas and Fees. +* [Advanced](/docs/sdk/v0.47/advanced/00-baseapp) - Level up your Cosmos SDK expertise with advanced topics, tailored for experienced +developers diving into intricate blockchain application development. We cover the Cosmos SDK on a lower level as we dive into the core of the SDK with BaseApp, Transactions, Context, Node Client (Daemon), Store, Encoding, gRPC, REST, and CometBFT Endpoints, CLI, Events, Telemetry, Object-Capability Model, RunTx recovery middleware, Cosmos Blockchain Simulator, Protobuf Documentation, In-Place Store Migrations, Configuration and AutoCLI. \ No newline at end of file diff --git a/docs/sdk/v0.47/learn/advanced/autocli.mdx b/docs/sdk/v0.47/learn/advanced/autocli.mdx new file mode 100644 index 00000000..aec581d2 --- /dev/null +++ b/docs/sdk/v0.47/learn/advanced/autocli.mdx @@ -0,0 +1,259 @@ +--- +title: "AutoCLI" +description: "Version: v0.47" +--- + + +**Synopsis** +This document details how to build CLI and REST interfaces for a module. Examples from various Cosmos SDK modules are included. + + + +**Pre-requisite Readings** + +* [CLI](https://docs.cosmos.network/main/core/cli) + + + +The `autocli` (also known as `client/v2`) package is a [Go library](https://pkg.go.dev/cosmossdk.io/client/v2/autocli) for generating CLI (command line interface) interfaces for Cosmos SDK-based applications. It provides a simple way to add CLI commands to your application by generating them automatically based on your gRPC service definitions. Autocli generates CLI commands and flags directly from your protobuf messages, including options, input parameters, and output parameters. This means that you can easily add a CLI interface to your application without having to manually create and manage commands. + +## Overview + +`autocli` generates CLI commands and flags for each method defined in your gRPC service. By default, it generates commands for each gRPC services. The commands are named based on the name of the service method. + +For example, given the following protobuf definition for a service: + +```protobuf +service MyService { + rpc MyMethod(MyRequest) returns (MyResponse) {} +} +``` + +For instance, `autocli` would generate a command named `my-method` for the `MyMethod` method. The command will have flags for each field in the `MyRequest` message. + +It is possible to customize the generation of transactions and queries by defining options for each service. + +## Application Wiring + +Here are the steps to use AutoCLI: + +1. Ensure your app's modules implements the `appmodule.AppModule` interface. +2. (optional) Configure how behave `autocli` command generation, by implementing the `func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions` method on the module. +3. Use the `autocli.AppOptions` struct to specify the modules you defined. If you are using `depinject`, it can automatically create an instance of `autocli.AppOptions` based on your app's configuration. +4. Use the `EnhanceRootCommand()` method provided by `autocli` to add the CLI commands for the specified modules to your root command. + + +AutoCLI is additive only, meaning _enhancing_ the root command will only add subcommands that are not already registered. This means that you can use AutoCLI alongside other custom commands within your app. + + +Here's an example of how to use `autocli` in your app: + +``` go +// Define your app's modules +testModules := map[string]appmodule.AppModule{ + "testModule": &TestModule{}, +} + +// Define the autocli AppOptions +autoCliOpts := autocli.AppOptions{ + Modules: testModules, +} + +// Create the root command +rootCmd := &cobra.Command{ + Use: "app", +} + +if err := appOptions.EnhanceRootCommand(rootCmd); err != nil { + return err +} + +// Run the root command +if err := rootCmd.Execute(); err != nil { + return err +} +``` + +### Keyring + +`autocli` uses a keyring for key name resolving names and signing transactions. + + +AutoCLI provides a better UX than normal CLI as it allows to resolve key names directly from the keyring in all transactions and commands. + +```sh + q bank balances alice + tx bank send alice bob 1000denom +``` + + + +The keyring used for resolving names and signing transactions is provided via the `client.Context`. +The keyring is then converted to the `client/v2/autocli/keyring` interface. +If no keyring is provided, the `autocli` generated command will not be able to sign transactions, but will still be able to query the chain. + + +The Cosmos SDK keyring implements the `client/v2/autocli/keyring` interface, thanks to the following wrapper: + +```go +keyring.NewAutoCLIKeyring(kb) +``` + + + +## Signing + +`autocli` supports signing transactions with the keyring. +The [`cosmos.msg.v1.signer` protobuf annotation](https://docs.cosmos.network/main/build/building-modules/protobuf-annotations) defines the signer field of the message. +This field is automatically filled when using the `--from` flag or defining the signer as a positional argument. + + +AutoCLI currently supports only one signer per transaction. + + +## Module wiring & Customization + +The `AutoCLIOptions()` method on your module allows to specify custom commands, sub-commands or flags for each service, as it was a `cobra.Command` instance, within the `RpcCommandOptions` struct. Defining such options will customize the behavior of the `autocli` command generation, which by default generates a command for each method in your gRPC service. + +```go +*autocliv1.RpcCommandOptions{ + RpcMethod: "Params", // The name of the gRPC service + Use: "params", // Command usage that is displayed in the help + Short: "Query the parameters of the governance process", // Short description of the command + Long: "Query the parameters of the governance process. Specify specific param types (voting|tallying|deposit) to filter results.", // Long description of the command + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "params_type", Optional: true}, // Transform a flag into a positional argument + }, +} +``` + + +AutoCLI can create a gov proposal of any tx by simply setting the `GovProposal` field to `true` in the `autocli.RpcCommandOptions` struct. +Users can however use the `--no-proposal` flag to disable the proposal creation (which is useful if the authority isn't the gov module on a chain). + + +### Specifying Subcommands + +By default, `autocli` generates a command for each method in your gRPC service. However, you can specify subcommands to group related commands together. To specify subcommands, use the `autocliv1.ServiceCommandDescriptor` struct. + +This example shows how to use the `autocliv1.ServiceCommandDescriptor` struct to group related commands together and specify subcommands in your gRPC service by defining an instance of `autocliv1.ModuleOptions` in your `autocli.go`. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/x/gov/autocli.go#L94-L97 +``` + +### Positional Arguments + +By default `autocli` generates a flag for each field in your protobuf message. However, you can choose to use positional arguments instead of flags for certain fields. + +To add positional arguments to a command, use the `autocliv1.PositionalArgDescriptor` struct, as seen in the example below. Specify the `ProtoField` parameter, which is the name of the protobuf field that should be used as the positional argument. In addition, if the parameter is a variable-length argument, you can specify the `Varargs` parameter as `true`. This can only be applied to the last positional parameter, and the `ProtoField` must be a repeated field. + +Here's an example of how to define a positional argument for the `Account` method of the `auth` service: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-beta.0/x/auth/autocli.go#L25-L30 +``` + +Then the command can be used as follows, instead of having to specify the `--address` flag: + +```bash + query auth account cosmos1abcd...xyz +``` + +#### Flattened Fields in Positional Arguments + +AutoCLI also supports flattening nested message fields as positional arguments. This means you can access nested fields +using dot notation in the `ProtoField` parameter. This is particularly useful when you want to directly set nested +message fields as positional arguments. + +For example, if you have a nested message structure like this: + +```protobuf +message Permissions { + string level = 1; + repeated string limit_type_urls = 2; +} + +message MsgAuthorizeCircuitBreaker { + string grantee = 1; + Permissions permissions = 2; +} +``` + +You can flatten the fields in your AutoCLI configuration: + +```go +{ + RpcMethod: "AuthorizeCircuitBreaker", + Use: "authorize ", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{ + {ProtoField: "grantee"}, + {ProtoField: "permissions.level"}, + {ProtoField: "permissions.limit_type_urls"}, + }, +} +``` + +This allows users to provide values for nested fields directly as positional arguments: + +```bash + tx circuit authorize cosmos1... super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend" +``` + +Instead of having to provide a complex JSON structure for nested fields, flattening makes the CLI more user-friendly by allowing direct access to nested fields. + +#### Customising Flag Names + +By default, `autocli` generates flag names based on the names of the fields in your protobuf message. However, you can customise the flag names by providing a `FlagOptions`. This parameter allows you to specify custom names for flags based on the names of the message fields. + +For example, if you have a message with the fields `test` and `test1`, you can use the following naming options to customise the flags: + +``` go +autocliv1.RpcCommandOptions{ + FlagOptions: map[string]*autocliv1.FlagOptions{ + "test": { Name: "custom_name", }, + "test1": { Name: "other_name", }, + }, +} +``` + +`FlagsOptions` is defined like sub commands in the `AutoCLIOptions()` method on your module. + +### Combining AutoCLI with Other Commands Within A Module + +AutoCLI can be used alongside other commands within a module. For example, the `gov` module uses AutoCLI to generate commands for the `query` subcommand, but also defines custom commands for the `proposer` subcommands. + +In order to enable this behavior, set in `AutoCLIOptions()` the `EnhanceCustomCommand` field to `true`, for the command type (queries and/or transactions) you want to enhance. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/fa4d87ef7e6d87aaccc94c337ffd2fe90fcb7a9d/x/gov/autocli.go#L98 +``` + +If not set to true, `AutoCLI` will not generate commands for the module if there are already commands registered for the module (when `GetTxCmd()` or `GetTxCmd()` are defined). + +### Skip a command + +AutoCLI automatically skips unsupported commands when [`cosmos_proto.method_added_in` protobuf annotation](https://docs.cosmos.network/main/build/building-modules/protobuf-annotations) is present. + +Additionally, a command can be manually skipped using the `autocliv1.RpcCommandOptions`: + +```go +*autocliv1.RpcCommandOptions{ + RpcMethod: "Params", // The name of the gRPC service + Skip: true, +} +``` + +### Use AutoCLI for non module commands + +It is possible to use `AutoCLI` for non module commands. The trick is still to implement the `appmodule.Module` interface and append it to the `appOptions.ModuleOptions` map. + +For example, here is how the SDK does it for `cometbft` gRPC commands: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/client/v2.0.0-beta.1/client/grpc/cmtservice/autocli.go#L52-L71 +``` + +## Summary + +`autocli` lets you generate CLI for your Cosmos SDK-based applications without any cobra boilerplate. It allows you to easily generate CLI commands and flags from your protobuf messages, and provides many options for customising the behavior of your CLI application. \ No newline at end of file diff --git a/docs/sdk/v0.47/learn/advanced/baseapp.mdx b/docs/sdk/v0.47/learn/advanced/baseapp.mdx index 4378fd07..cd0f7b16 100644 --- a/docs/sdk/v0.47/learn/advanced/baseapp.mdx +++ b/docs/sdk/v0.47/learn/advanced/baseapp.mdx @@ -379,9 +379,9 @@ The [`BeginBlock` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37. baseapp/baseapp.go - ``` +``` loading... - ``` +``` [See full example on GitHub](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/baseapp/baseapp.go#L406-L433) diff --git a/docs/sdk/v0.47/learn/advanced/cli.mdx b/docs/sdk/v0.47/learn/advanced/cli.mdx index b08b0d28..7a49ccd4 100644 --- a/docs/sdk/v0.47/learn/advanced/cli.mdx +++ b/docs/sdk/v0.47/learn/advanced/cli.mdx @@ -198,7 +198,7 @@ The `InterceptConfigsPreRunHandler` call creates a viper literal, default `serve When willing to configure which logger is used, do not to use `InterceptConfigsPreRunHandler`, which sets the default SDK logger, but instead use `InterceptConfigsAndCreateContext` and set the server context and the logger manually: - ``` +``` -return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig)+serverCtx, err := server.InterceptConfigsAndCreateContext(cmd, customAppTemplate, customAppConfig, customCMTConfig)+if err != nil {+ return err+}+// overwrite default server logger+logger, err := server.CreateSDKLogger(serverCtx, cmd.OutOrStdout())+if err != nil {+ return err+}+serverCtx.Logger = logger.With(log.ModuleKey, "server")+// set server context+return server.SetCmdServerContext(cmd, serverCtx) - ``` +``` diff --git a/docs/sdk/v0.47/learn/advanced/events.mdx b/docs/sdk/v0.47/learn/advanced/events.mdx index 04e9cf71..56fae5fb 100644 --- a/docs/sdk/v0.47/learn/advanced/events.mdx +++ b/docs/sdk/v0.47/learn/advanced/events.mdx @@ -16,7 +16,7 @@ description: "Version: v0.47" ## Events[​](#events-1 "Direct link to Events") -Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: `{eventType}.{attributeKey}={attributeValue}`. +Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: ``{eventType}.``{attributeKey}```={attributeValue}`. proto/tendermint/abci/types.proto @@ -38,7 +38,7 @@ An Event contains: *Typed Events* are Protobuf-defined [messages](/v0.47/build/architecture/adr-032-typed-events) used by the Cosmos SDK for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`. *Legacy Events* are defined on a **per-module basis** in the module's `/types/events.go` file. They are triggered from the module's Protobuf [`Msg` service](/v0.47/build/building-modules/msg-services) by using the [`EventManager`](#eventmanager). -In addition, each module documents its events under in the `Events` sections of its specs (x/\{moduleName}/`README.md`). +In addition, each module documents its events under in the `Events` sections of its specs (x/\`{moduleName}`/`README.md`). Lastly, Events are returned to the underlying consensus engine in the response of the following ABCI messages: diff --git a/docs/sdk/v0.47/learn/advanced/grpc_rest.mdx b/docs/sdk/v0.47/learn/advanced/grpc_rest.mdx index 6ab1f720..abcb5a79 100644 --- a/docs/sdk/v0.47/learn/advanced/grpc_rest.mdx +++ b/docs/sdk/v0.47/learn/advanced/grpc_rest.mdx @@ -62,7 +62,7 @@ All routes are configured under the following fields in `~/.simapp/config/app.to If, for various reasons, you cannot use gRPC (for example, you are building a web application, and browsers don't support HTTP2 on which gRPC is built), then the Cosmos SDK offers REST routes via gRPC-gateway. -[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway `"/cosmos/bank/v1beta1/balances/{address}"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: +[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway ``"/cosmos/bank/v1beta1/balances/``{address}```"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: proto/cosmos/bank/v1beta1/query.proto diff --git a/docs/sdk/v0.47/learn/beginner/app-anatomy.mdx b/docs/sdk/v0.47/learn/beginner/app-anatomy.mdx new file mode 100644 index 00000000..2e3f3ed3 --- /dev/null +++ b/docs/sdk/v0.47/learn/beginner/app-anatomy.mdx @@ -0,0 +1,279 @@ +--- +title: "Anatomy of a Cosmos SDK Application" +description: "Version: v0.47" +--- + + +**Synopsis** +This document describes the core parts of a Cosmos SDK application, represented throughout the document as a placeholder application named `app`. + + +## Node Client + +The Daemon, or [Full-Node Client](/docs/sdk/v0.47/learn/advanced/03-node), is the core process of a Cosmos SDK-based blockchain. Participants in the network run this process to initialize their state-machine, connect with other full-nodes, and update their state-machine as new blocks come in. + +```text + ^ +-------------------------------+ ^ + | | | | + | | State-machine = Application | | + | | | | Built with Cosmos SDK + | | ^ + | | + | +----------- | ABCI | ----------+ v + | | + v | ^ + | | | | +Blockchain Node | | Consensus | | + | | | | + | +-------------------------------+ | CometBFT + | | | | + | | Networking | | + | | | | + v +-------------------------------+ v +``` + +The blockchain full-node presents itself as a binary, generally suffixed by `-d` for "daemon" (e.g. `appd` for `app` or `gaiad` for `gaia`). This binary is built by running a simple [`main.go`](/docs/sdk/v0.47/learn/advanced/03-nodemain-function) function placed in `./cmd/appd/`. This operation usually happens through the [Makefile](#dependencies-and-makefile). + +Once the main binary is built, the node can be started by running the [`start` command](/docs/sdk/v0.47/learn/advanced/03-nodestart-command). This command function primarily does three things: + +1. Create an instance of the state-machine defined in [`app.go`](#core-application-file). +2. Initialize the state-machine with the latest known state, extracted from the `db` stored in the `~/.app/data` folder. At this point, the state-machine is at height `appBlockHeight`. +3. Create and start a new CometBFT instance. Among other things, the node performs a handshake with its peers. It gets the latest `blockHeight` from them and replays blocks to sync to this height if it is greater than the local `appBlockHeight`. The node starts from genesis and CometBFT sends an `InitChain` message via the ABCI to the `app`, which triggers the [`InitChainer`](#initchainer). + + +When starting a CometBFT instance, the genesis file is the `0` height and the state within the genesis file is committed at block height `1`. When querying the state of the node, querying block height 0 will return an error. + + +## Core Application File + +In general, the core of the state-machine is defined in a file called `app.go`. This file mainly contains the **type definition of the application** and functions to **create and initialize it**. + +### Type Definition of the Application + +The first thing defined in `app.go` is the `type` of the application. It is generally comprised of the following parts: + +* **Embedding [runtime.App](/docs/sdk/v0.47/build/building-apps/00-runtime)** The runtime package manages the application's core components and modules through dependency injection. It provides declarative configuration for module management, state storage, and ABCI handling. + * `Runtime` wraps `BaseApp`, meaning when a transaction is relayed by CometBFT to the application, `app` uses `runtime`'s methods to route them to the appropriate module. `BaseApp` implements all the [ABCI methods](https://docs.cometbft.com/v0.38/spec/abci/) and the [routing logic](/docs/sdk/v0.47/learn/advanced/00-baseappservice-routers). + * It automatically configures the **[module manager](/docs/sdk/v0.47/build/building-modules/01-module-managermanager)** based on the app wiring configuration. The module manager facilitates operations related to these modules, like registering their [`Msg` service](/docs/sdk/v0.47/build/building-modules/03-msg-services) and [gRPC `Query` service](#grpc-query-services), or setting the order of execution between modules for various functions like [`InitChainer`](#initchainer), [`PreBlocker`](#preblocker) and [`BeginBlocker` and `EndBlocker`](#beginblocker-and-endblocker). +* [**An App Wiring configuration file**](/docs/sdk/v0.47/build/building-apps/00-runtime) The app wiring configuration file contains the list of application's modules that `runtime` must instantiate. The instantiation of the modules is done using `depinject`. It also contains the order in which all modules' `InitGenesis` and `Pre/Begin/EndBlocker` methods should be executed. +* **A reference to an [`appCodec`](/docs/sdk/v0.47/learn/advanced/05-encoding).** The application's `appCodec` is used to serialize and deserialize data structures in order to store them, as stores can only persist `[]bytes`. The default codec is [Protocol Buffers](/docs/sdk/v0.47/learn/advanced/05-encoding). +* **A reference to a [`legacyAmino`](/docs/sdk/v0.47/learn/advanced/05-encoding) codec.** Some parts of the Cosmos SDK have not been migrated to use the `appCodec` above, and are still hardcoded to use Amino. Other parts explicitly use Amino for backwards compatibility. For these reasons, the application still holds a reference to the legacy Amino codec. Please note that the Amino codec will be removed from the SDK in the upcoming releases. + +See an example of application type definition from `simapp`, the Cosmos SDK's own app used for demo and testing purposes: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app_di.go#L57-L90 +``` + +### Constructor Function + +Also defined in `app.go` is the constructor function, which constructs a new application of the type defined in the preceding section. The function must fulfill the `AppCreator` signature in order to be used in the [`start` command](/docs/sdk/v0.47/learn/advanced/03-nodestart-command) of the application's daemon command. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/server/types/app.go#L67-L69 +``` + +Here are the main actions performed by this function: + +* Instantiate a new [`codec`](/docs/sdk/v0.47/learn/advanced/05-encoding) and initialize the `codec` of each of the application's modules using the [basic manager](/docs/sdk/v0.47/build/building-modules/01-module-managerbasicmanager). +* Instantiate a new application with a reference to a `baseapp` instance, a codec, and all the appropriate store keys. +* Instantiate all the [`keeper`](#keeper) objects defined in the application's `type` using the `NewKeeper` function of each of the application's modules. Note that keepers must be instantiated in the correct order, as the `NewKeeper` of one module might require a reference to another module's `keeper`. +* Instantiate the application's [module manager](/docs/sdk/v0.47/build/building-modules/01-module-managermanager) with the [`AppModule`](#application-module-interface) object of each of the application's modules. +* With the module manager, initialize the application's [`Msg` services](/docs/sdk/v0.47/learn/advanced/00-baseappmsg-services), [gRPC `Query` services](/docs/sdk/v0.47/learn/advanced/00-baseappgrpc-query-services), [legacy `Msg` routes](/docs/sdk/v0.47/learn/advanced/00-baseapprouting), and [legacy query routes](/docs/sdk/v0.47/learn/advanced/00-baseappquery-routing). When a transaction is relayed to the application by CometBFT via the ABCI, it is routed to the appropriate module's [`Msg` service](#msg-services) using the routes defined here. Likewise, when a gRPC query request is received by the application, it is routed to the appropriate module's [`gRPC query service`](#grpc-query-services) using the gRPC routes defined here. The Cosmos SDK still supports legacy `Msg`s and legacy CometBFT queries, which are routed using the legacy `Msg` routes and the legacy query routes, respectively. +* With the module manager, register the [application's modules' invariants](/docs/sdk/v0.47/build/building-modules/07-invariants). Invariants are variables (e.g. total supply of a token) that are evaluated at the end of each block. The process of checking invariants is done via a special module called the [`InvariantsRegistry`](/docs/sdk/v0.47/build/building-modules/07-invariantsinvariant-registry). The value of the invariant should be equal to a predicted value defined in the module. Should the value be different than the predicted one, special logic defined in the invariant registry is triggered (usually the chain is halted). This is useful to make sure that no critical bug goes unnoticed, producing long-lasting effects that are hard to fix. +* With the module manager, set the order of execution between the `InitGenesis`, `PreBlocker`, `BeginBlocker`, and `EndBlocker` functions of each of the [application's modules](#application-module-interface). Note that not all modules implement these functions. +* Set the remaining application parameters: + * [`InitChainer`](#initchainer): used to initialize the application when it is first started. + * [`PreBlocker`](#preblocker): called before BeginBlock. + * [`BeginBlocker`, `EndBlocker`](#beginblocker-and-endblocker): called at the beginning and at the end of every block. + * [`anteHandler`](/docs/sdk/v0.47/learn/advanced/00-baseappantehandler): used to handle fees and signature verification. +* Mount the stores. +* Return the application. + +Note that the constructor function only creates an instance of the app, while the actual state is either carried over from the `~/.app/data` folder if the node is restarted, or generated from the genesis file if the node is started for the first time. + +See an example of application constructor from `simapp`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L190-L708 +``` + +### InitChainer + +The `InitChainer` is a function that initializes the state of the application from a genesis file (i.e. token balances of genesis accounts). It is called when the application receives the `InitChain` message from the CometBFT engine, which happens when the node is started at `appBlockHeight == 0` (i.e. on genesis). The application must set the `InitChainer` in its [constructor](#constructor-function) via the [`SetInitChainer`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetInitChainer) method. + +In general, the `InitChainer` is mostly composed of the [`InitGenesis`](/docs/sdk/v0.47/build/building-modules/08-genesisinitgenesis) function of each of the application's modules. This is done by calling the `InitGenesis` function of the module manager, which in turn calls the `InitGenesis` function of each of the modules it contains. Note that the order in which the modules' `InitGenesis` functions must be called has to be set in the module manager using the [module manager's](/docs/sdk/v0.47/build/building-modules/01-module-manager) `SetOrderInitGenesis` method. This is done in the [application's constructor](#constructor-function), and the `SetOrderInitGenesis` has to be called before the `SetInitChainer`. + +See an example of an `InitChainer` from `simapp`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L765-L773 +``` + +### PreBlocker + +There are two semantics around the new lifecycle method: + +* It runs before the `BeginBlocker` of all modules +* It can modify consensus parameters in storage, and signal the caller through the return value. + +When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameter in the finalize context: + +```go +app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) +``` + +The new ctx must be passed to all the other lifecycle methods. + +### BeginBlocker and EndBlocker + +The Cosmos SDK offers developers the possibility to implement automatic execution of code as part of their application. This is implemented through two functions called `BeginBlocker` and `EndBlocker`. They are called when the application receives the `FinalizeBlock` messages from the CometBFT consensus engine, which happens respectively at the beginning and at the end of each block. The application must set the `BeginBlocker` and `EndBlocker` in its [constructor](#constructor-function) via the [`SetBeginBlocker`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetBeginBlocker) and [`SetEndBlocker`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetEndBlocker) methods. + +In general, the `BeginBlocker` and `EndBlocker` functions are mostly composed of the [`BeginBlock` and `EndBlock`](/docs/sdk/v0.47/build/building-modules/06-beginblock-endblock) functions of each of the application's modules. This is done by calling the `BeginBlock` and `EndBlock` functions of the module manager, which in turn calls the `BeginBlock` and `EndBlock` functions of each of the modules it contains. Note that the order in which the modules' `BeginBlock` and `EndBlock` functions must be called has to be set in the module manager using the `SetOrderBeginBlockers` and `SetOrderEndBlockers` methods, respectively. This is done via the [module manager](/docs/sdk/v0.47/build/building-modules/01-module-manager) in the [application's constructor](#application-constructor), and the `SetOrderBeginBlockers` and `SetOrderEndBlockers` methods have to be called before the `SetBeginBlocker` and `SetEndBlocker` functions. + +As a sidenote, it is important to remember that application-specific blockchains are deterministic. Developers must be careful not to introduce non-determinism in `BeginBlocker` or `EndBlocker`, and must also be careful not to make them too computationally expensive, as [gas](/docs/sdk/v0.47/learn/beginner/04-gas-fees) does not constrain the cost of `BeginBlocker` and `EndBlocker` execution. + +See an example of `BeginBlocker` and `EndBlocker` functions from `simapp`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L752-L759 +``` + +### Register Codec + +The `EncodingConfig` structure is the last important part of the `app.go` file. The goal of this structure is to define the codecs that will be used throughout the app. + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/params/encoding.go#L9-L16 +``` + +Here are descriptions of what each of the four fields means: + +* `InterfaceRegistry`: The `InterfaceRegistry` is used by the Protobuf codec to handle interfaces that are encoded and decoded (we also say "unpacked") using [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto). `Any` could be thought as a struct that contains a `type_url` (name of a concrete type implementing the interface) and a `value` (its encoded bytes). `InterfaceRegistry` provides a mechanism for registering interfaces and implementations that can be safely unpacked from `Any`. Each application module implements the `RegisterInterfaces` method that can be used to register the module's own interfaces and implementations. + * You can read more about `Any` in [ADR-019](/docs/sdk/v0.47/build/architecture/adr-019-protobuf-state-encoding). + * To go more into details, the Cosmos SDK uses an implementation of the Protobuf specification called [`gogoprotobuf`](https://github.com/cosmos/gogoproto). By default, the [gogo protobuf implementation of `Any`](https://pkg.go.dev/github.com/cosmos/gogoproto/types) uses [global type registration](https://github.com/cosmos/gogoproto/blob/master/proto/properties.go#L540) to decode values packed in `Any` into concrete Go types. This introduces a vulnerability where any malicious module in the dependency tree could register a type with the global protobuf registry and cause it to be loaded and unmarshaled by a transaction that referenced it in the `type_url` field. For more information, please refer to [ADR-019](/docs/sdk/v0.47/build/architecture/adr-019-protobuf-state-encoding). +* `Codec`: The default codec used throughout the Cosmos SDK. It is composed of a `BinaryCodec` used to encode and decode state, and a `JSONCodec` used to output data to the users (for example, in the [CLI](#cli)). By default, the SDK uses Protobuf as `Codec`. +* `TxConfig`: `TxConfig` defines an interface a client can utilize to generate an application-defined concrete transaction type. Currently, the SDK handles two transaction types: `SIGN_MODE_DIRECT` (which uses Protobuf binary as over-the-wire encoding) and `SIGN_MODE_LEGACY_AMINO_JSON` (which depends on Amino). Read more about transactions [here](/docs/sdk/v0.47/learn/advanced/01-transactions). +* `Amino`: Some legacy parts of the Cosmos SDK still use Amino for backwards-compatibility. Each module exposes a `RegisterLegacyAmino` method to register the module's specific types within Amino. This `Amino` codec should not be used by app developers anymore, and will be removed in future releases. + +An application should create its own encoding config. +See an example of a `simappparams.EncodingConfig` from `simapp`: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/params/encoding.go#L11-L16 +``` + +## Modules + +[Modules](/docs/sdk/v0.47/build/building-modules/00-intro) are the heart and soul of Cosmos SDK applications. They can be considered as state-machines nested within the state-machine. When a transaction is relayed from the underlying CometBFT engine via the ABCI to the application, it is routed by [`baseapp`](/docs/sdk/v0.47/learn/advanced/00-baseapp) to the appropriate module in order to be processed. This paradigm enables developers to easily build complex state-machines, as most of the modules they need often already exist. **For developers, most of the work involved in building a Cosmos SDK application revolves around building custom modules required by their application that do not exist yet, and integrating them with modules that do already exist into one coherent application**. In the application directory, the standard practice is to store modules in the `x/` folder (not to be confused with the Cosmos SDK's `x/` folder, which contains already-built modules). + +### Application Module Interface + +Modules must implement [interfaces](/docs/sdk/v0.47/build/building-modules/01-module-managerapplication-module-interfaces) defined in the Cosmos SDK, [`AppModuleBasic`](/docs/sdk/v0.47/build/building-modules/01-module-managerappmodulebasic) and [`AppModule`](/docs/sdk/v0.47/build/building-modules/01-module-managerappmodule). The former implements basic non-dependent elements of the module, such as the `codec`, while the latter handles the bulk of the module methods (including methods that require references to other modules' `keeper`s). Both the `AppModule` and `AppModuleBasic` types are, by convention, defined in a file called `module.go`. + +`AppModule` exposes a collection of useful methods on the module that facilitates the composition of modules into a coherent application. These methods are called from the [`module manager`](/docs/sdk/v0.47/build/building-modules/01-module-managermanager), which manages the application's collection of modules. + +### `Msg` Services + +Each application module defines two [Protobuf services](https://developers.google.com/protocol-buffers/docs/proto#services): one `Msg` service to handle messages, and one gRPC `Query` service to handle queries. If we consider the module as a state-machine, then a `Msg` service is a set of state transition RPC methods. +Each Protobuf `Msg` service method is 1:1 related to a Protobuf request type, which must implement `sdk.Msg` interface. +Note that `sdk.Msg`s are bundled in [transactions](/docs/sdk/v0.47/learn/advanced/01-transactions), and each transaction contains one or multiple messages. + +When a valid block of transactions is received by the full-node, CometBFT relays each one to the application via [`DeliverTx`](https://docs.cometbft.com/v0.37/spec/abci/abci++_app_requirements#specifics-of-responsedelivertx). Then, the application handles the transaction: + +1. Upon receiving the transaction, the application first unmarshals it from `[]byte`. +2. Then, it verifies a few things about the transaction like [fee payment and signatures](/docs/sdk/v0.47/learn/beginner/04-gas-feesantehandler) before extracting the `Msg`(s) contained in the transaction. +3. `sdk.Msg`s are encoded using Protobuf [`Any`s](#register-codec). By analyzing each `Any`'s `type_url`, baseapp's `msgServiceRouter` routes the `sdk.Msg` to the corresponding module's `Msg` service. +4. If the message is successfully processed, the state is updated. + +For more details, see [transaction lifecycle](/docs/sdk/v0.47/learn/beginner/01-tx-lifecycle). + +Module developers create custom `Msg` services when they build their own module. The general practice is to define the `Msg` Protobuf service in a `tx.proto` file. For example, the `x/bank` module defines a service with two methods to transfer tokens: + +```protobuf reference +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/bank/v1beta1/tx.proto#L13-L36 +``` + +Service methods use `keeper` in order to update the module state. + +Each module should also implement the `RegisterServices` method as part of the [`AppModule` interface](#application-module-interface). This method should call the `RegisterMsgServer` function provided by the generated Protobuf code. + +### gRPC `Query` Services + +gRPC `Query` services allow users to query the state using [gRPC](https://grpc.io). They are enabled by default, and can be configured under the `grpc.enable` and `grpc.address` fields inside [`app.toml`](/docs/sdk/v0.47/user/run-node/01-run-nodeconfiguring-the-node-using-apptoml-and-configtoml). + +gRPC `Query` services are defined in the module's Protobuf definition files, specifically inside `query.proto`. The `query.proto` definition file exposes a single `Query` [Protobuf service](https://developers.google.com/protocol-buffers/docs/proto#services). Each gRPC query endpoint corresponds to a service method, starting with the `rpc` keyword, inside the `Query` service. + +Protobuf generates a `QueryServer` interface for each module, containing all the service methods. A module's [`keeper`](#keeper) then needs to implement this `QueryServer` interface, by providing the concrete implementation of each service method. This concrete implementation is the handler of the corresponding gRPC query endpoint. + +Finally, each module should also implement the `RegisterServices` method as part of the [`AppModule` interface](#application-module-interface). This method should call the `RegisterQueryServer` function provided by the generated Protobuf code. + +### Keeper + +[`Keepers`](/docs/sdk/v0.47/build/building-modules/06-keeper) are the gatekeepers of their module's store(s). To read or write in a module's store, it is mandatory to go through one of its `keeper`'s methods. This is ensured by the [object-capabilities](/docs/sdk/v0.47/learn/advanced/10-ocap) model of the Cosmos SDK. Only objects that hold the key to a store can access it, and only the module's `keeper` should hold the key(s) to the module's store(s). + +`Keepers` are generally defined in a file called `keeper.go`. It contains the `keeper`'s type definition and methods. + +The `keeper` type definition generally consists of the following: + +* **Key(s)** to the module's store(s) in the multistore. +* Reference to **other module's `keepers`**. Only needed if the `keeper` needs to access other module's store(s) (either to read or write from them). +* A reference to the application's **codec**. The `keeper` needs it to marshal structs before storing them, or to unmarshal them when it retrieves them, because stores only accept `[]bytes` as value. + +Along with the type definition, the next important component of the `keeper.go` file is the `keeper`'s constructor function, `NewKeeper`. This function instantiates a new `keeper` of the type defined above with a `codec`, stores `keys` and potentially references other modules' `keeper`s as parameters. The `NewKeeper` function is called from the [application's constructor](#constructor-function). The rest of the file defines the `keeper`'s methods, which are primarily getters and setters. + +### Command-Line, gRPC Services and REST Interfaces + +Each module defines command-line commands, gRPC services, and REST routes to be exposed to the end-user via the [application's interfaces](#application-interfaces). This enables end-users to create messages of the types defined in the module, or to query the subset of the state managed by the module. + +#### CLI + +Generally, the [commands related to a module](/docs/sdk/v0.47/build/building-modules/09-module-interfacescli) are defined in a folder called `client/cli` in the module's folder. The CLI divides commands into two categories, transactions and queries, defined in `client/cli/tx.go` and `client/cli/query.go`, respectively. Both commands are built on top of the [Cobra Library](https://github.com/spf13/cobra): + +* Transactions commands let users generate new transactions so that they can be included in a block and eventually update the state. One command should be created for each [message type](#message-types) defined in the module. The command calls the constructor of the message with the parameters provided by the end-user, and wraps it into a transaction. The Cosmos SDK handles signing and the addition of other transaction metadata. +* Queries let users query the subset of the state defined by the module. Query commands forward queries to the [application's query router](/docs/sdk/v0.47/learn/advanced/00-baseappquery-routing), which routes them to the appropriate [querier](#querier) the `queryRoute` parameter supplied. + +#### gRPC + +[gRPC](https://grpc.io) is a modern open-source high performance RPC framework that has support in multiple languages. It is the recommended way for external clients (such as wallets, browsers and other backend services) to interact with a node. + +Each module can expose gRPC endpoints called [service methods](https://grpc.io/docs/what-is-grpc/core-concepts/#service-definition), which are defined in the [module's Protobuf `query.proto` file](#grpc-query-services). A service method is defined by its name, input arguments, and output response. The module then needs to perform the following actions: + +* Define a `RegisterGRPCGatewayRoutes` method on `AppModuleBasic` to wire the client gRPC requests to the correct handler inside the module. +* For each service method, define a corresponding handler. The handler implements the core logic necessary to serve the gRPC request, and is located in the `keeper/grpc_query.go` file. + +#### gRPC-gateway REST Endpoints + +Some external clients may not wish to use gRPC. In this case, the Cosmos SDK provides a gRPC gateway service, which exposes each gRPC service as a corresponding REST endpoint. Please refer to the [grpc-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) documentation to learn more. + +The REST endpoints are defined in the Protobuf files, along with the gRPC services, using Protobuf annotations. Modules that want to expose REST queries should add `google.api.http` annotations to their `rpc` methods. By default, all REST endpoints defined in the SDK have a URL starting with the `/cosmos/` prefix. + +The Cosmos SDK also provides a development endpoint to generate [Swagger](https://swagger.io/) definition files for these REST endpoints. This endpoint can be enabled inside the [`app.toml`](/docs/sdk/v0.47/user/run-node/01-run-nodeconfiguring-the-node-using-apptoml-and-configtoml) config file, under the `api.swagger` key. + +## Application Interface + +[Interfaces](#command-line-grpc-services-and-rest-interfaces) let end-users interact with full-node clients. This means querying data from the full-node or creating and sending new transactions to be relayed by the full-node and eventually included in a block. + +The main interface is the [Command-Line Interface](/docs/sdk/v0.47/learn/advanced/07-cli). The CLI of a Cosmos SDK application is built by aggregating [CLI commands](#cli) defined in each of the modules used by the application. The CLI of an application is the same as the daemon (e.g. `appd`), and is defined in a file called `appd/main.go`. The file contains the following: + +* **A `main()` function**, which is executed to build the `appd` interface client. This function prepares each command and adds them to the `rootCmd` before building them. At the root of `appd`, the function adds generic commands like `status`, `keys`, and `config`, query commands, tx commands, and `rest-server`. +* **Query commands**, which are added by calling the `queryCmd` function. This function returns a Cobra command that contains the query commands defined in each of the application's modules (passed as an array of `sdk.ModuleClients` from the `main()` function), as well as some other lower level query commands such as block or validator queries. Query command are called by using the command `appd query [query]` of the CLI. +* **Transaction commands**, which are added by calling the `txCmd` function. Similar to `queryCmd`, the function returns a Cobra command that contains the tx commands defined in each of the application's modules, as well as lower level tx commands like transaction signing or broadcasting. Tx commands are called by using the command `appd tx [tx]` of the CLI. + +See an example of an application's main command-line file from the [Cosmos Hub](https://github.com/cosmos/gaia). + +```go reference +https://github.com/cosmos/gaia/blob/26ae7c2/cmd/gaiad/cmd/root.go#L39-L80 +``` + +## Dependencies and Makefile + +This section is optional, as developers are free to choose their dependency manager and project building method. That said, the current most used framework for versioning control is [`go.mod`](https://github.com/golang/go/wiki/Modules). It ensures each of the libraries used throughout the application are imported with the correct version. + +The following is the `go.mod` of the [Cosmos Hub](https://github.com/cosmos/gaia), provided as an example. + +```go reference +https://github.com/cosmos/gaia/blob/26ae7c2/go.mod#L1-L28 +``` + +For building the application, a [Makefile](https://en.wikipedia.org/wiki/Makefile) is generally used. The Makefile primarily ensures that the `go.mod` is run before building the two entrypoints to the application, [`Node Client`](#node-client) and [`Application Interface`](#application-interface). + +Here is an example of the [Cosmos Hub Makefile](https://github.com/cosmos/gaia/blob/main/Makefile). \ No newline at end of file diff --git a/docs/sdk/v0.47/learn/beginner/query-lifecycle.mdx b/docs/sdk/v0.47/learn/beginner/query-lifecycle.mdx index e631ff0c..36f0b3e5 100644 --- a/docs/sdk/v0.47/learn/beginner/query-lifecycle.mdx +++ b/docs/sdk/v0.47/learn/beginner/query-lifecycle.mdx @@ -46,7 +46,7 @@ Another interface through which users can make queries is [gRPC](https://grpc.io One such tool is [grpcurl](https://github.com/fullstorydev/grpcurl), and a gRPC request for `MyQuery` using this client looks like: ``` -grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name +grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '\{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name ``` ### REST[​](#rest "Direct link to REST") @@ -56,7 +56,7 @@ Another interface through which users can make queries is through HTTP Requests An example HTTP request for `MyQuery` looks like: ``` -GET http://localhost:1317/cosmos/staking/v1beta1/delegators/{delegatorAddr}/delegations +GET http://localhost:1317/cosmos/staking/v1beta1/delegators/`{delegatorAddr}`/delegations ``` ## How Queries are Handled by the CLI[​](#how-queries-are-handled-by-the-cli "Direct link to How Queries are Handled by the CLI") diff --git a/docs/sdk/v0.47/overview.mdx b/docs/sdk/v0.47/overview.mdx new file mode 100644 index 00000000..721f9f25 --- /dev/null +++ b/docs/sdk/v0.47/overview.mdx @@ -0,0 +1,44 @@ +--- +title: "Website" +description: "Version: v0.47" +--- + +This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. + +### Installation + +``` +$ yarn +``` + +### Local Development + +``` +$ yarn start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +### Build + +``` +$ yarn build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +### Deployment + +Using SSH: + +``` +$ USE_SSH=true yarn deploy +``` + +Not using SSH: + +``` +$ GIT_USER= yarn deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. \ No newline at end of file diff --git a/docs/sdk/v0.47/tutorials.mdx b/docs/sdk/v0.47/tutorials.mdx new file mode 100644 index 00000000..46ccc281 --- /dev/null +++ b/docs/sdk/v0.47/tutorials.mdx @@ -0,0 +1,29 @@ +--- +title: Tutorials +--- + +# Cosmos SDK Tutorials + +The tutorials for Cosmos SDK are maintained in a single location and apply across all SDK versions. These hands-on guides will help you master key concepts and advanced features through practical examples. + +## Available Tutorials + +### Transaction Building +- **[Building a Transaction](../next/tutorials/transactions/building-a-transaction.mdx)** - Learn to construct, sign, and broadcast transactions + +### Vote Extensions +Advanced consensus features for building sophisticated applications: + +#### Oracle Implementation +- **[What is an Oracle?](../next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/oracle/getting-started.mdx)** +- **[Implementing Vote Extensions](../next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx)** +- **[Testing Oracle](../next/tutorials/vote-extensions/oracle/testing-oracle.mdx)** + +#### Mitigating Front-Running +- **[Understanding Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx)** +- **[Mitigating Front-Running with Vote Extensions](../next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx)** +- **[Demo of Mitigating Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx)** + +Visit the [full tutorials section](../next/tutorials/tutorials.mdx) for detailed guides and learning paths. \ No newline at end of file diff --git a/docs/sdk/v0.47/user.mdx b/docs/sdk/v0.47/user.mdx index 8bd7ed22..c3a4b911 100644 --- a/docs/sdk/v0.47/user.mdx +++ b/docs/sdk/v0.47/user.mdx @@ -5,6 +5,6 @@ description: "Version: v0.47" This section is designed for developers who are using the Cosmos SDK to build applications. It provides essential guides and references to effectively use the SDK's features. -* [Setting up keys](/v0.47/user/run-node/keyring) - Learn how to set up secure key management using the Cosmos SDK's keyring feature. This guide provides a streamlined approach to cryptographic key handling, which is crucial for securing your application. -* [Running a node](/v0.47/user/run-node/run-node) - This guide provides step-by-step instructions to deploy and manage a node in the Cosmos network. It ensures a smooth and reliable operation of your blockchain application by covering all the necessary setup and maintenance steps. -* [CLI](/v0.47/user/run-node/interact-node) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. +* [Setting up keys](/docs/sdk/v0.47/run-node/00-keyring) - Learn how to set up secure key management using the Cosmos SDK's keyring feature. This guide provides a streamlined approach to cryptographic key handling, which is crucial for securing your application. +* [Running a node](/docs/sdk/v0.47/run-node/01-run-node) - This guide provides step-by-step instructions to deploy and manage a node in the Cosmos network. It ensures a smooth and reliable operation of your blockchain application by covering all the necessary setup and maintenance steps. +* [CLI](/docs/sdk/v0.47/run-node/02-interact-node) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. \ No newline at end of file diff --git a/docs/sdk/v0.47/user/run-node/run-node.mdx b/docs/sdk/v0.47/user/run-node/run-node.mdx index 2456315e..3323c879 100644 --- a/docs/sdk/v0.47/user/run-node/run-node.mdx +++ b/docs/sdk/v0.47/user/run-node/run-node.mdx @@ -100,9 +100,9 @@ One example config to tweak is the `minimum-gas-prices` field inside `app.toml`, When running a node (not a validator!) and not wanting to run the application mempool, set the `max-txs` field to `-1`. - ``` +``` [mempool]# Setting max-txs to 0 will allow for a unbounded amount of transactions in the mempool.# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool.# Setting max_txs to a positive number (> 0) will limit the number of transactions in the mempool, by the specified amount.## Note, this configuration only applies to SDK built-in app-side mempool# implementations.max-txs = "-1" - ``` +``` ## Run a Localnet[​](#run-a-localnet "Direct link to Run a Localnet") diff --git a/docs/sdk/v0.47/user/run-node/run-production.mdx b/docs/sdk/v0.47/user/run-node/run-production.mdx index 5616c118..6e38b4d0 100644 --- a/docs/sdk/v0.47/user/run-node/run-production.mdx +++ b/docs/sdk/v0.47/user/run-node/run-production.mdx @@ -212,9 +212,9 @@ vim $HOME/.simd/config/config.tomlpriv_validator_laddr = "tcp://127.0.0.1:26659" It is recommended to comment or delete the lines that specify the path of the validator key and validator: - ``` +``` # Path to the JSON file containing the private key to use as a validator in the consensus protocol# priv_validator_key_file = "config/priv_validator_key.json"# Path to the JSON file containing the last sign state of a validator# priv_validator_state_file = "data/priv_validator_state.json" - ``` +``` 6. Start the two processes. diff --git a/docs/sdk/v0.47/user/run-node/txs.mdx b/docs/sdk/v0.47/user/run-node/txs.mdx index c98a80ed..5b12d729 100644 --- a/docs/sdk/v0.47/user/run-node/txs.mdx +++ b/docs/sdk/v0.47/user/run-node/txs.mdx @@ -179,7 +179,7 @@ It is not possible to generate or sign a transaction using gRPC, only to broadca Broadcasting a transaction using the gRPC endpoint can be done by sending a `BroadcastTx` request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -grpcurl -plaintext \ -d '{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx +grpcurl -plaintext \ -d '{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx ``` ## Using REST[​](#using-rest "Direct link to Using REST") @@ -191,7 +191,7 @@ It is not possible to generate or sign a transaction using REST, only to broadca Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) can be done by sending a POST request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs +curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs ``` ## Using CosmJS (JavaScript & TypeScript)[​](#using-cosmjs-javascript--typescript "Direct link to Using CosmJS (JavaScript & TypeScript)") diff --git a/docs/sdk/v0.50/changelog/release-notes.mdx b/docs/sdk/v0.50/changelog/release-notes.mdx index 6cf2ff60..1c4b08c5 100644 --- a/docs/sdk/v0.50/changelog/release-notes.mdx +++ b/docs/sdk/v0.50/changelog/release-notes.mdx @@ -1,508 +1,6 @@ --- title: "Release Notes" description: "Cosmos SDK release notes and changelog" -mode: "custom" --- - - - {/* - - Guiding Principles: - - Changelogs are for humans, not machines. - - There should be an entry for every single version. - - The same types of changes should be grouped. - - Versions and sections should be linkable. - - The latest version comes first. - - The release date of each version is displayed. - - Mention whether you follow Semantic Versioning. - - Usage: - - Change log entries are to be added to the Unreleased section under the - - appropriate stanza (see below). Each entry is required to include a tag and - - the Github issue reference in the following format: - - * () \# message - - The tag should consist of where the change is being made ex. (x/staking), (store) - - The issue numbers will later be link-ified during the release process so you do - - not have to worry about including a link manually, but you can if you wish. - - Types of changes (Stanzas): - - "Features" for new features. - - "Improvements" for changes in existing functionality. - - "Deprecated" for soon-to-be removed features. - - "Bug Fixes" for any bug fixes. - - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. - - "CLI Breaking" for breaking CLI commands. - - "API Breaking" for breaking exported APIs used by developers building on SDK. - - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. - - Ref: https://keepachangelog.com/en/1.0.0/ - - */} - - # Changelog - - ## [Unreleased] - - ### Improvements - - * (x/gov) [#24386](https://github.com/cosmos/cosmos-sdk/pull/24386) Improve helpers to easily create governance proposals from CLI. - - ### Bug Fixes - - * (baseapp) [#23879](https://github.com/cosmos/cosmos-sdk/pull/23879) Ensure finalize block response is not empty in the defer check of FinalizeBlock to avoid panic by nil pointer. - - * (query) [#23884](https://github.com/cosmos/cosmos-sdk/pull/23884) Fix NPE in query pagination. - - ## [v0.50.14](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.14) - 2025-07-08 - - ### Bug Fixes - - * [GHSA-p22h-3m2v-cmgh](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-p22h-3m2v-cmgh) Fix x/distribution can halt when historical rewards overflow. - - ## [v0.50.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.13) - 2025-03-12 - - ### Bug Fixes - - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker - - ## [v0.50.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.12) - 2025-02-20 - - ### Bug Fixes - - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal - - ## [v0.50.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.11) - 2024-12-16 - - ### Features - - * (crypto/keyring) [#21653](https://github.com/cosmos/cosmos-sdk/pull/21653) New Linux-only backend that adds Linux kernel's `keyctl` support. - - ### Improvements - - * (server) [#21941](https://github.com/cosmos/cosmos-sdk/pull/21941) Regenerate addrbook.json for in place testnet. - - ### Bug Fixes - - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any - - * (server) [#22564](https://github.com/cosmos/cosmos-sdk/pull/22564) Fix fallback genesis path in server - - * (x/group) [#22425](https://github.com/cosmos/cosmos-sdk/pull/22425) Proper address rendering in error - - * (sims) [#21906](https://github.com/cosmos/cosmos-sdk/pull/21906) Skip sims test when running dry on validators - - * (cli) [#21919](https://github.com/cosmos/cosmos-sdk/pull/21919) Query address-by-acc-num by account_id instead of id. - - * (x/group) [#22229](https://github.com/cosmos/cosmos-sdk/pull/22229) Accept `1` and `try` in CLI for group proposal exec. - - ## [v0.50.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.10) - 2024-09-20 - - ### Features - - * (cli) [#20779](https://github.com/cosmos/cosmos-sdk/pull/20779) Added `module-hash-by-height` command to query and retrieve module hashes at a specified blockchain height, enhancing debugging capabilities. - - * (cli) [#21372](https://github.com/cosmos/cosmos-sdk/pull/21372) Added a `bulk-add-genesis-account` genesis command to add many genesis accounts at once. - - * (types/collections) [#21724](https://github.com/cosmos/cosmos-sdk/pull/21724) Added `LegacyDec` collection value. - - ### Improvements - - * (x/bank) [#21460](https://github.com/cosmos/cosmos-sdk/pull/21460) Added `Sender` attribute in `MsgMultiSend` event. - - * (genutil) [#21701](https://github.com/cosmos/cosmos-sdk/pull/21701) Improved error messages for genesis validation. - - * (testutil/integration) [#21816](https://github.com/cosmos/cosmos-sdk/pull/21816) Allow to pass baseapp options in `NewIntegrationApp`. - - ### Bug Fixes - - * (runtime) [#21769](https://github.com/cosmos/cosmos-sdk/pull/21769) Fix baseapp options ordering to avoid overwriting options set by modules. - - * (x/consensus) [#21493](https://github.com/cosmos/cosmos-sdk/pull/21493) Fix regression that prevented to upgrade to > v0.50.7 without consensus version params. - - * (baseapp) [#21256](https://github.com/cosmos/cosmos-sdk/pull/21256) Halt height will not commit the block indicated, meaning that if halt-height is set to 10, only blocks until 9 (included) will be committed. This is to go back to the original behavior before a change was introduced in v0.50.0. - - * (baseapp) [#21444](https://github.com/cosmos/cosmos-sdk/pull/21444) Follow-up, Return PreBlocker events in FinalizeBlockResponse. - - * (baseapp) [#21413](https://github.com/cosmos/cosmos-sdk/pull/21413) Fix data race in sdk mempool. - - ## [v0.50.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.9) - 2024-08-07 - - ## Bug Fixes - - * (baseapp) [#21159](https://github.com/cosmos/cosmos-sdk/pull/21159) Return PreBlocker events in FinalizeBlockResponse. - - * [#20939](https://github.com/cosmos/cosmos-sdk/pull/20939) Fix collection reverse iterator to include `pagination.key` in the result. - - * (client/grpc) [#20969](https://github.com/cosmos/cosmos-sdk/pull/20969) Fix `node.NewQueryServer` method not setting `cfg`. - - * (testutil/integration) [#21006](https://github.com/cosmos/cosmos-sdk/pull/21006) Fix `NewIntegrationApp` method not writing default genesis to state. - - * (runtime) [#21080](https://github.com/cosmos/cosmos-sdk/pull/21080) Fix `app.yaml` / `app.json` incompatibility with `depinject v1.0.0`. - - ## [v0.50.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.8) - 2024-07-15 - - ## Features - - * (client) [#20690](https://github.com/cosmos/cosmos-sdk/pull/20690) Import mnemonic from file - - ## Improvements - - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. - - * [#20631](https://github.com/cosmos/cosmos-sdk/pull/20631) Fix json parsing in the wait-tx command. - - * (x/auth) [#20438](https://github.com/cosmos/cosmos-sdk/pull/20438) Add `--skip-signature-verification` flag to multisign command to allow nested multisigs. - - ## Bug Fixes - - * (simulation) [#17911](https://github.com/cosmos/cosmos-sdk/pull/17911) Fix all problems with executing command `make test-sim-custom-genesis-fast` for simulation test. - - * (simulation) [#18196](https://github.com/cosmos/cosmos-sdk/pull/18196) Fix the problem of `validator set is empty after InitGenesis` in simulation test. - - ## [v0.50.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.7) - 2024-06-04 - - ### Improvements - - * (debug) [#20328](https://github.com/cosmos/cosmos-sdk/pull/20328) Add consensus address for debug cmd. - - * (runtime) [#20264](https://github.com/cosmos/cosmos-sdk/pull/20264) Expose grpc query router via depinject. - - * (x/consensus) [#20381](https://github.com/cosmos/cosmos-sdk/pull/20381) Use Comet utility for consensus module consensus param updates. - - * (client) [#20356](https://github.com/cosmos/cosmos-sdk/pull/20356) Overwrite client context when available in `SetCmdClientContext`. - - ### Bug Fixes - - * (baseapp) [#20346](https://github.com/cosmos/cosmos-sdk/pull/20346) Correctly assign `execModeSimulate` to context for `simulateTx`. - - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. - - * (baseapp) [#20107](https://github.com/cosmos/cosmos-sdk/pull/20107) Avoid header height overwrite block height. - - * (cli) [#20020](https://github.com/cosmos/cosmos-sdk/pull/20020) Make bootstrap-state command support both new and legacy genesis format. - - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. - - ## [v0.50.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.6) - 2024-04-22 - - ### Features - - * (types) [#19759](https://github.com/cosmos/cosmos-sdk/pull/19759) Align SignerExtractionAdapter in PriorityNonceMempool Remove. - - * (client) [#19870](https://github.com/cosmos/cosmos-sdk/pull/19870) Add new query command `wait-tx`. Alias `event-query-tx-for` to `wait-tx` for backward compatibility. - - ### Improvements - - * (telemetry) [#19903](https://github.com/cosmos/cosmos-sdk/pull/19903) Conditionally emit metrics based on enablement. - - * **Introduction of `Now` Function**: Added a new function called `Now` to the telemetry package. It returns the current system time if telemetry is enabled, or a zero time if telemetry is not enabled. - - * **Atomic Global Variable**: Implemented an atomic global variable to manage the state of telemetry's enablement. This ensures thread safety for the telemetry state. - - * **Conditional Telemetry Emission**: All telemetry functions have been updated to emit metrics only when telemetry is enabled. They perform a check with `isTelemetryEnabled()` and return early if telemetry is disabled, minimizing unnecessary operations and overhead. - - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Upgrade prometheus version and fix API breaking change due to prometheus bump. - - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Bump `cosmossdk.io/store` to v1.1.0. - - * (server) [#19884](https://github.com/cosmos/cosmos-sdk/pull/19884) Add start customizability to start command options. - - * (x/gov) [#19853](https://github.com/cosmos/cosmos-sdk/pull/19853) Emit `depositor` in `EventTypeProposalDeposit`. - - * (x/gov) [#19844](https://github.com/cosmos/cosmos-sdk/pull/19844) Emit the proposer of governance proposals. - - * (baseapp) [#19616](https://github.com/cosmos/cosmos-sdk/pull/19616) Don't share gas meter in tx execution. - - ## Bug Fixes - - * (x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m) for `x/authz`. - - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19745) Fix tx sign doesn't throw an error when incorrect Ledger is used. - - * (baseapp) [#19970](https://github.com/cosmos/cosmos-sdk/pull/19970) Fix default config values to use no-op mempool as default. - - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. - - * (x/bank) [#20028](https://github.com/cosmos/cosmos-sdk/pull/20028) Align query with multi denoms for send-enabled. - - ## [v0.50.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.5) - 2024-03-12 - - ### Features - - * (baseapp) [#19626](https://github.com/cosmos/cosmos-sdk/pull/19626) Add `DisableBlockGasMeter` option to `BaseApp`, which removes the block gas meter during transaction execution. - - ### Improvements - - * (x/distribution) [#19707](https://github.com/cosmos/cosmos-sdk/pull/19707) Add autocli config for `DelegationTotalRewards` for CLI consistency with `q rewards` commands in previous versions. - - * (x/auth) [#19651](https://github.com/cosmos/cosmos-sdk/pull/19651) Allow empty public keys in `GetSignBytesAdapter`. - - ### Bug Fixes - - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from proposal.FinalTallyResult in the gprc query. - - * (types) [#19709](https://github.com/cosmos/cosmos-sdk/pull/19709) Fix skip staking genesis export when using `CoreAppModuleAdaptor` / `CoreAppModuleBasicAdaptor` for it. - - * (x/auth) [#19549](https://github.com/cosmos/cosmos-sdk/pull/19549) Accept custom get signers when injecting `x/auth/tx`. - - * (x/staking) Fix a possible bypass of delegator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) - - * (baseapp) Fix a bug in `baseapp.ValidateVoteExtensions` helper ([GHSA-95rx-m9m5-m94v](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-95rx-m9m5-m94v)). The helper has been fixed and for avoiding API breaking changes `currentHeight` and `chainID` arguments are ignored. Those arguments are removed from the helper in v0.51+. - - ## [v0.50.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.4) - 2024-02-19 - - ### Features - - * (server) [#19280](https://github.com/cosmos/cosmos-sdk/pull/19280) Adds in-place testnet CLI command. - - ### Improvements - - * (client) [#19393](https://github.com/cosmos/cosmos-sdk/pull/19393/) Add `ReadDefaultValuesFromDefaultClientConfig` to populate the default values from the default client config in client.Context without creating a app folder. - - ### Bug Fixes - - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. - - * (baseapp) [#19338](https://github.com/cosmos/cosmos-sdk/pull/19338) Set HeaderInfo in context when calling `setState`. - - * (baseapp): [#19200](https://github.com/cosmos/cosmos-sdk/pull/19200) Ensure that sdk side ve math matches cometbft. - - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. - - * (baseapp) [#19198](https://github.com/cosmos/cosmos-sdk/pull/19198) Remove usage of pointers in logs in all optimistic execution goroutines. - - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. - - * (crypto) [#19371](https://github.com/cosmos/cosmos-sdk/pull/19371) Avoid CLI redundant log in stdout, log to stderr instead. - - ## [v0.50.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.3) - 2024-01-15 - - ### Features - - * (types) [#18991](https://github.com/cosmos/cosmos-sdk/pull/18991) Add SignerExtractionAdapter to PriorityNonceMempool/Config and provide Default implementation matching existing behavior. - - * (gRPC) [#19043](https://github.com/cosmos/cosmos-sdk/pull/19043) Add `halt_height` to the gRPC `/cosmos/base/node/v1beta1/config` request. - - ### Improvements - - * (x/bank) [#18956](https://github.com/cosmos/cosmos-sdk/pull/18956) Introduced a new `DenomOwnersByQuery` query method for `DenomOwners`, which accepts the denom value as a query string parameter, resolving issues with denoms containing slashes. - - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. - - * (x/auth/tx) [#18772](https://github.com/cosmos/cosmos-sdk/pull/18772) Remove misleading gas wanted from tx simulation failure log. - - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. - - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 - - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 - - * (baseapp) [#18915](https://github.com/cosmos/cosmos-sdk/pull/18915) Add a new `ExecModeVerifyVoteExtension` exec mode and ensure it's populated in the `Context` during `VerifyVoteExtension` execution. - - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. - - ### Bug Fixes - - * (baseapp) [#19058](https://github.com/cosmos/cosmos-sdk/pull/19058) Fix baseapp posthandler branch would fail if the `runMsgs` had returned an error. - - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after module's beginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. - - * (baseapp) [#18895](https://github.com/cosmos/cosmos-sdk/pull/18895) Fix de-duplicating vote extensions during validation in ValidateVoteExtensions. - - ## [v0.50.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.2) - 2023-12-11 - - ### Features - - * (debug) [#18219](https://github.com/cosmos/cosmos-sdk/pull/18219) Add debug commands for application codec types. - - * (client/keys) [#17639](https://github.com/cosmos/cosmos-sdk/pull/17639) Allows using and saving public keys encoded as base64. - - * (server) [#17094](https://github.com/cosmos/cosmos-sdk/pull/17094) Add a `shutdown-grace` flag for waiting a given time before exit. - - ### Improvements - - * (telemetry) [#18646] (https://github.com/cosmos/cosmos-sdk/pull/18646) Enable statsd and dogstatsd telemetry sinks. - - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. - - * (x/gov) [#18025](https://github.com/cosmos/cosmos-sdk/pull/18025) Improve ` q gov proposer` by querying directly a proposal instead of tx events. It is an alias of `q gov proposal` as the proposer is a field of the proposal. - - * (version) [#18063](https://github.com/cosmos/cosmos-sdk/pull/18063) Allow to define extra info to be displayed in ` version --long` command. - - * (codec/unknownproto)[#18541](https://github.com/cosmos/cosmos-sdk/pull/18541) Remove the use of "protoc-gen-gogo/descriptor" in favour of using the official protobuf descriptorpb types inside unknownproto. - - ### Bug Fixes - - * (x/auth) [#18564](https://github.com/cosmos/cosmos-sdk/pull/18564) Fix total fees calculation when batch signing. - - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. - - * [#18531](https://github.com/cosmos/cosmos-sdk/pull/18531) Baseapp's `GetConsensusParams` returns an empty struct instead of panicking if no params are found. - - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. - - * (baseapp) [#18486](https://github.com/cosmos/cosmos-sdk/pull/18486) Fixed FinalizeBlock calls not being passed to ABCIListeners. - - * (baseapp) [#18627](https://github.com/cosmos/cosmos-sdk/pull/18627) Post handlers are run on non successful transaction executions too. - - * (baseapp) [#18654](https://github.com/cosmos/cosmos-sdk/pull/18654) Fixes an issue in which `gogoproto.Merge` does not work with gogoproto messages with custom types. - - ## [v0.50.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.1) - 2023-11-07 - - > v0.50.0 has been retracted due to a mistake in tagging the release. Please use v0.50.1 instead. - - ### Features - - * (baseapp) [#18071](https://github.com/cosmos/cosmos-sdk/pull/18071) Add hybrid handlers to `MsgServiceRouter`. - - * (server) [#18162](https://github.com/cosmos/cosmos-sdk/pull/18162) Start gRPC & API server in standalone mode. - - * (baseapp & types) [#17712](https://github.com/cosmos/cosmos-sdk/pull/17712) Introduce `PreBlock`, which runs before begin blocker other modules, and allows to modify consensus parameters, and the changes are visible to the following state machine logics. Additionally it can be used for vote extensions. - - * (genutil) [#17571](https://github.com/cosmos/cosmos-sdk/pull/17571) Allow creation of `AppGenesis` without a file lookup. - - * (codec) [#17042](https://github.com/cosmos/cosmos-sdk/pull/17042) Add `CollValueV2` which supports encoding of protov2 messages in collections. - - * (x/gov) [#16976](https://github.com/cosmos/cosmos-sdk/pull/16976) Add `failed_reason` field to `Proposal` under `x/gov` to indicate the reason for a failed proposal. Referenced from [#238](https://github.com/bnb-chain/greenfield-cosmos-sdk/pull/238) under `bnb-chain/greenfield-cosmos-sdk`. - - * (baseapp) [#16898](https://github.com/cosmos/cosmos-sdk/pull/16898) Add `preFinalizeBlockHook` to allow vote extensions persistence. - - * (cli) [#16887](https://github.com/cosmos/cosmos-sdk/pull/16887) Add two new CLI commands: ` tx simulate` for simulating a transaction; ` query block-results` for querying CometBFT RPC for block results. - - * (x/bank) [#16852](https://github.com/cosmos/cosmos-sdk/pull/16852) Add `DenomMetadataByQueryString` query in bank module to support metadata query by query string. - - * (baseapp) [#16581](https://github.com/cosmos/cosmos-sdk/pull/16581) Implement Optimistic Execution as an experimental feature (not enabled by default). - - * (types) [#16257](https://github.com/cosmos/cosmos-sdk/pull/16257) Allow setting the base denom in the denom registry. - - * (baseapp) [#16239](https://github.com/cosmos/cosmos-sdk/pull/16239) Add Gas Limits to allow node operators to resource bound queries. - - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Make `StartCmd` more customizable. - - * (types/simulation) [#16074](https://github.com/cosmos/cosmos-sdk/pull/16074) Add generic SimulationStoreDecoder for modules using collections. - - * (genutil) [#16046](https://github.com/cosmos/cosmos-sdk/pull/16046) Add "module-name" flag to genutil `add-genesis-account` to enable intializing module accounts at genesis.* [#15970](https://github.com/cosmos/cosmos-sdk/pull/15970) Enable SIGN_MODE_TEXTUAL. - - * (types) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Add `module.NewBasicManagerFromManager` for creating a basic module manager from a module manager. - - * (types/module) [#15829](https://github.com/cosmos/cosmos-sdk/pull/15829) Add new endblocker interface to handle valset updates. - - * (runtime) [#15818](https://github.com/cosmos/cosmos-sdk/pull/15818) Provide logger through `depinject` instead of appBuilder. - - * (types) [#15735](https://github.com/cosmos/cosmos-sdk/pull/15735) Make `ValidateBasic() error` method of `Msg` interface optional. Modules should validate messages directly in their message handlers ([RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation)). - - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) Allow applications to specify a custom genesis migration function for the `genesis migrate` command. - - * (telemetry) [#15657](https://github.com/cosmos/cosmos-sdk/pull/15657) Emit more data (go version, sdk version, upgrade height) in prom metrics. - - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) Add status endpoint for clients. - - * (testutil/integration) [#15556](https://github.com/cosmos/cosmos-sdk/pull/15556) Introduce `testutil/integration` package for module integration testing. - - * (runtime) [#15547](https://github.com/cosmos/cosmos-sdk/pull/15547) Allow runtime to pass event core api service to modules. - - * (client) [#15458](https://github.com/cosmos/cosmos-sdk/pull/15458) Add a `CmdContext` field to client.Context initialized to cobra command's context. - - * (x/genutil) [#15301](https://github.com/cosmos/cosmos-sdk/pull/15031) Add application genesis. The genesis is now entirely managed by the application and passed to CometBFT at note instantiation. Functions that were taking a `cmttypes.GenesisDoc{}` now takes a `genutiltypes.AppGenesis{}`. - - * (core) [#15133](https://github.com/cosmos/cosmos-sdk/pull/15133) Implement RegisterServices in the module manager. - - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Return a human readable denomination for IBC vouchers when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest` and `--resolve-denom` flag to `GetBalancesCmd()`. - - * (core) [#14860](https://github.com/cosmos/cosmos-sdk/pull/14860) Add `Precommit` and `PrepareCheckState` AppModule callbacks. - - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Upstream expedited proposals from Osmosis. - - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by events with queries directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. - - * (x/auth) [#14650](https://github.com/cosmos/cosmos-sdk/pull/14650) Add Textual SignModeHandler. Enable `SIGN_MODE_TEXTUAL` by following the [UPGRADING.md](./UPGRADING.md) instructions. - - * (x/crisis) [#14588](https://github.com/cosmos/cosmos-sdk/pull/14588) Use CacheContext() in AssertInvariants(). - - * (mempool) [#14484](https://github.com/cosmos/cosmos-sdk/pull/14484) Add priority nonce mempool option for transaction replacement. - - * (query) [#14468](https://github.com/cosmos/cosmos-sdk/pull/14468) Implement pagination for collections. - - * (x/gov) [#14373](https://github.com/cosmos/cosmos-sdk/pull/14373) Add new proto field `constitution` of type `string` to gov module genesis state, which allows chain builders to lay a strong foundation by specifying purpose. - - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) Add ` config` command is now a sub-command, for setting, getting and migrating Cosmos SDK configuration files. - - * (x/distribution) [#14322](https://github.com/cosmos/cosmos-sdk/pull/14322) Introduce a new gRPC message handler, `DepositValidatorRewardsPool`, that allows explicit funding of a validator's reward pool. - - * (x/bank) [#14224](https://github.com/cosmos/cosmos-sdk/pull/14224) Allow injection of restrictions on transfers using `AppendSendRestriction` or `PrependSendRestriction`. - - ### Improvements - - * (x/gov) [#18189](https://github.com/cosmos/cosmos-sdk/pull/18189) Limit the accepted deposit coins for a proposal to the minimum proposal deposit denoms. - - * (x/staking) [#18049](https://github.com/cosmos/cosmos-sdk/pull/18049) Return early if Slash encounters zero tokens to burn. - - * (x/staking) [#18035](https://github.com/cosmos/cosmos-sdk/pull/18035) Hoisted out of the redelegation loop, the non-changing validator and delegator addresses parsing. - - * (keyring) [#17913](https://github.com/cosmos/cosmos-sdk/pull/17913) Add `NewAutoCLIKeyring` for creating an AutoCLI keyring from a SDK keyring. - - * (x/consensus) [#18041](https://github.com/cosmos/cosmos-sdk/pull/18041) Let `ToProtoConsensusParams()` return an error. - - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. - - * (baseapp) [#17667](https://github.com/cosmos/cosmos-sdk/pull/17667) Close databases opened by SDK in `baseApp.Close()`. - - * (types/module) [#17554](https://github.com/cosmos/cosmos-sdk/pull/17554) Introduce `HasABCIGenesis` which is implemented by a module only when a validatorset update needs to be returned. - - * (cli) [#17389](https://github.com/cosmos/cosmos-sdk/pull/17389) gRPC CometBFT commands have been added under ` q consensus comet`. CometBFT commands placement in the SDK has been simplified. See the exhaustive list below. - - * `client/rpc.StatusCommand()` is now at `server.StatusCommand()` - - * (testutil) [#17216](https://github.com/cosmos/cosmos-sdk/issues/17216) Add `DefaultContextWithKeys` to `testutil` package. - - * (cli) [#17187](https://github.com/cosmos/cosmos-sdk/pull/17187) Do not use `ctx.PrintObjectLegacy` in commands anymore. - - * ` q gov proposer [proposal-id]` now returns a proposal id as int instead of string. - - * (x/staking) [#17164](https://github.com/cosmos/cosmos-sdk/pull/17164) Add `BondedTokensAndPubKeyByConsAddr` to the keeper to enable vote extension verification. - - * (x/group, x/gov) [#17109](https://github.com/cosmos/cosmos-sdk/pull/17109) Let proposal summary be 40x longer than metadata limit. - - * (version) [#17096](https://github.com/cosmos/cosmos-sdk/pull/17096) Improve `getSDKVersion()` to handle module replacements. - - * (types) [#16890](https://github.com/cosmos/cosmos-sdk/pull/16890) Remove `GetTxCmd() *cobra.Command` and `GetQueryCmd() *cobra.Command` from `module.AppModuleBasic` interface. - - * (x/authz) [#16869](https://github.com/cosmos/cosmos-sdk/pull/16869) Improve error message when grant not found. - - * (all) [#16497](https://github.com/cosmos/cosmos-sdk/pull/16497) Removed all exported vestiges of `sdk.MustSortJSON` and `sdk.SortJSON`. - - * (server) [#16238](https://github.com/cosmos/cosmos-sdk/pull/16238) Don't setup p2p node keys if starting a node in GRPC only mode. - - * (cli) [#16206](https://github.com/cosmos/cosmos-sdk/pull/16206) Make ABCI handshake profileable. - - * (types) [#16076](https://github.com/cosmos/cosmos-sdk/pull/16076) Optimize `ChainAnteDecorators`/`ChainPostDecorators` to instantiate the functions once instead of on every invocation of the returned `AnteHandler`/`PostHandler`. - - * (server) [#16071](https://github.com/cosmos/cosmos-sdk/pull/16071) When `mempool.max-txs` is set to a negative value, use a no-op mempool (effectively disable the app mempool). - - * (types/query) [#16041](https://github.com/cosmos/cosmos-sdk/pull/16041) Change pagination max limit to a variable in order to be modifed by application devs. - - * (simapp) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Refactor SimApp for removing the global basic manager. - - * (all modules) [#15901](https://github.com/cosmos/cosmos-sdk/issues/15901) All core Cosmos SDK modules query commands have migrated to [AutoCLI](https://docs.cosmos.network/main/core/autocli), ensuring parity between gRPC and CLI queries. - - * (x/auth) [#15867](https://github.com/cosmos/cosmos-sdk/pull/15867) Support better logging for signature verification failure. - - * (store/cachekv) [#15767](https://github.com/cosmos/cosmos-sdk/pull/15767) Reduce peak RAM usage during and after `InitGenesis`. - - * (x/bank) [#15764](https://github.com/cosmos/cosmos-sdk/pull/15764) Speedup x/bank `InitGenesis`. - - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) Refactor the validator's missed block signing window to be a chunked bitmap instead of a "logical" bitmap, significantly reducing the storage footprint. - - * (x/gov) [#15554](https://github.com/cosmos/cosmos-sdk/pull/15554) Add proposal result log in `active_proposal` event. When a proposal passes but fails to execute, the proposal result is logged in the `active_proposal` event. - - * (x/consensus) [#15553](https://github.com/cosmos/cosmos-sdk/pull/15553) Migrate consensus module to use collections. - - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Add `server.InterceptConfigsAndCreateContext` as alternative to `server.InterceptConfigsPreRunHandler` which does not set the server context and the default SDK logger. - - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) Improve the `PriorityNonceMempool`: - - * Support generic transaction prioritization, instead of `ctx.Priority()` - - * Improve construction through the use of a single `PriorityNonceMempoolConfig` instead of option functions - - * (x/authz) [#15164](https://github.com/cosmos/cosmos-sdk/pull/15164) Add `MsgCancelUnbondingDelegation` to staking authorization. - - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Remove unnecessary sleeps from gRPC and API server initiation. The servers will start and accept requests as soon as they're ready. - - * (baseapp) [#15023](https://github.com/cosmos/cosmos-sdk/pull/15023) & [#15213](https://github.com/cosmos/cosmos-sdk/pull/15213) Add `MessageRouter` interface to baseapp and pass it to authz, gov and groups instead of concrete type. - - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) Introduce `cosmossdk.io/log` package to provide a consistent logging interface through the SDK. CometBFT logger is now replaced by `cosmossdk.io/log.Logger`. - - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. - - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Allow transaction event queries to directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. - - * (x/evidence) [#14757](https://github.com/cosmos/cosmos-sdk/pull/14757) Evidence messages do not need to implement a `.Type()` anymore. - - * (x/auth/tx) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove `.Type()` and `Route()` methods from all msgs and `legacytx.LegacyMsg` interface. - - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by either height/hash ` q block --type=height|hash `. - - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) Return undelegate amount in MsgUndelegateResponse. - - * [#14529](https://github.com/cosmos/cosmos-sdk/pull/14529) Add new property `BondDenom` to `SimulationState` struct. - - * (store) [#14439](https://github.com/cosmos/cosmos-sdk/pull/14439) Remove global metric gatherer from store. - - * By default store has a no op metric gatherer, the application developer must set another metric gatherer or us the provided one in `store/metrics`. - - * (store) [#14438](https://github.com/cosmos/cosmos-sdk/pull/14438) Pass logger from baseapp to store. - - * (baseapp) [#14417](https://github.com/cosmos/cosmos-sdk/pull/14417) The store package no longer has a dependency on baseapp. - - * (module) [#14415](https://github.com/cosmos/cosmos-sdk/pull/14415) Loosen assertions in SetOrderBeginBlockers() and SetOrderEndBlockers(). - - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. - - * [#14406](https://github.com/cosmos/cosmos-sdk/issues/14406) Migrate usage of `types/store.go` to `store/types/..`. - - * (context)[#14384](https://github.com/cosmos/cosmos-sdk/pull/14384) Refactor(context): Pass EventManager to the context as an interface. - - * (types) [#14354](https://github.com/cosmos/cosmos-sdk/pull/14354) Improve performance on Context.KVStore and Context.TransientStore by 40%. - - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` - - * (signing) [#14087](https://github.com/cosmos/cosmos-sdk/pull/14087) Add SignModeHandlerWithContext interface with a new `GetSignBytesWithContext` to get the sign bytes using `context.Context` as an argument to access state. - - * (server) [#14062](https://github.com/cosmos/cosmos-sdk/pull/14062) Remove rosetta from server start. - - * (crypto) [#3129](https://github.com/cosmos/cosmos-sdk/pull/3129) New armor and keyring key derivation uses aead and encryption uses chacha20poly. - - ### State Machine Breaking - - * (x/gov) [#18146](https://github.com/cosmos/cosmos-sdk/pull/18146) Add denom check to reject denoms outside of those listed in `MinDeposit`. A new `MinDepositRatio` param is added (with a default value of `0.001`) and now deposits are required to be at least `MinDepositRatio*MinDeposit` to be accepted. - - * (x/group,x/gov) [#16235](https://github.com/cosmos/cosmos-sdk/pull/16235) A group and gov proposal is rejected if the proposal metadata title and summary do not match the proposal title and summary. - - * (baseapp) [#15930](https://github.com/cosmos/cosmos-sdk/pull/15930) change vote info provided by prepare and process proposal to the one in the block. - - * (x/staking) [#15731](https://github.com/cosmos/cosmos-sdk/pull/15731) Introducing a new index to retrieve the delegations by validator efficiently. - - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) The `HistoricalInfoKey` has been updated to use a binary format. - - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) The validator slashing window now stores "chunked" bitmap entries for each validator's signing window instead of a single boolean entry per signing window index. - - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. - - * (x/feegrant) [#14294](https://github.com/cosmos/cosmos-sdk/pull/14294) Moved the logic of rejecting duplicate grant from `msg_server` to `keeper` method. - - ### API Breaking Changes - - * (x/auth) [#17787](https://github.com/cosmos/cosmos-sdk/pull/17787) Remove Tip functionality. - - * (types) `module.EndBlockAppModule` has been replaced by Core API `appmodule.HasEndBlocker` or `module.HasABCIEndBlock` when needing validator updates. - - * (types) `module.BeginBlockAppModule` has been replaced by Core API `appmodule.HasBeginBlocker`. - - * (types) [#17358](https://github.com/cosmos/cosmos-sdk/pull/17358) Remove deprecated `sdk.Handler`, use `baseapp.MsgServiceHandler` instead. - - * (client) [#17197](https://github.com/cosmos/cosmos-sdk/pull/17197) `keys.Commands` does not take a home directory anymore. It is inferred from the root command. - - * (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. - - * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address - - * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. - - * `FromABCIEvidence` & `GetConsensusAddress(consAc address.Codec)` now take a consensus address codec to be able to decode the incoming address. - - * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function - - * (x/staking) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgCreateValidator`, `NewValidator`, `NewMsgCancelUnbondingDelegation`, `NewMsgUndelegate`, `NewMsgBeginRedelegate`, `NewMsgDelegate` and `NewMsgEditValidator` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`: - - * `NewRedelegation` and `NewUnbondingDelegation` takes a validatorAddressCodec and a delegatorAddressCodec in order to decode the addresses. - - * `NewRedelegationResponse` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. - - * `NewMsgCreateValidator.Validate()` takes an address codec in order to decode the address. - - * `BuildCreateValidatorMsg` takes a ValidatorAddressCodec in order to decode addresses. - - * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` - - * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses. - - * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. - - * (x/staking) [#16959](https://github.com/cosmos/cosmos-sdk/pull/16959) Add validator and consensus address codec as staking keeper arguments. - - * (x/staking) [#16958](https://github.com/cosmos/cosmos-sdk/pull/16958) DelegationI interface `GetDelegatorAddr` & `GetValidatorAddr` have been migrated to return string instead of sdk.AccAddress and sdk.ValAddress respectively. stakingtypes.NewDelegation takes a string instead of sdk.AccAddress and sdk.ValAddress. - - * (testutil) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) The *cli testutil* `QueryBalancesExec` has been removed. Use the gRPC or REST query instead. - - * (x/staking) [#16795](https://github.com/cosmos/cosmos-sdk/pull/16795) `DelegationToDelegationResponse`, `DelegationsToDelegationResponses`, `RedelegationsToRedelegationResponses` are no longer exported. - - * (x/auth/vesting) [#16741](https://github.com/cosmos/cosmos-sdk/pull/16741) Vesting account constructor now return an error with the result of their validate function. - - * (x/auth) [#16650](https://github.com/cosmos/cosmos-sdk/pull/16650) The *cli testutil* `QueryAccountExec` has been removed. Use the gRPC or REST query instead. - - * (x/auth) [#16621](https://github.com/cosmos/cosmos-sdk/pull/16621) Pass address codec to auth new keeper constructor. - - * (x/auth) [#16423](https://github.com/cosmos/cosmos-sdk/pull/16423) `helpers.AddGenesisAccount` has been moved to `x/genutil` to remove the cyclic dependency between `x/auth` and `x/genutil`. - - * (baseapp) [#16342](https://github.com/cosmos/cosmos-sdk/pull/16342) NewContext was renamed to NewContextLegacy. The replacement (NewContext) now does not take a header, instead you should set the header via `WithHeaderInfo` or `WithBlockHeight`. Note that `WithBlockHeight` will soon be depreacted and its recommneded to use `WithHeaderInfo`. - - * (x/mint) [#16329](https://github.com/cosmos/cosmos-sdk/pull/16329) Use collections for state management: - - * Removed: keeper `GetParams`, `SetParams`, `GetMinter`, `SetMinter`. - - * (x/crisis) [#16328](https://github.com/cosmos/cosmos-sdk/pull/16328) Use collections for state management: - - * Removed: keeper `GetConstantFee`, `SetConstantFee` - - * (x/staking) [#16324](https://github.com/cosmos/cosmos-sdk/pull/16324) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. Notable changes: - - * `Validator` method now returns `types.ErrNoValidatorFound` instead of `nil` when not found. - - * (x/distribution) [#16302](https://github.com/cosmos/cosmos-sdk/pull/16302) Use collections for FeePool state management. - - * Removed: keeper `GetFeePool`, `SetFeePool`, `GetFeePoolCommunityCoins` - - * (types) [#16272](https://github.com/cosmos/cosmos-sdk/pull/16272) `FeeGranter` in the `FeeTx` interface returns `[]byte` instead of `string`. - - * (x/gov) [#16268](https://github.com/cosmos/cosmos-sdk/pull/16268) Use collections for proposal state management (part 2): - - * this finalizes the gov collections migration - - * Removed: types all the key related functions - - * Removed: keeper `InsertActiveProposalsQueue`, `RemoveActiveProposalsQueue`, `InsertInactiveProposalsQueue`, `RemoveInactiveProposalsQueue`, `IterateInactiveProposalsQueue`, `IterateActiveProposalsQueue`, `ActiveProposalsQueueIterator`, `InactiveProposalsQueueIterator` - - * (x/slashing) [#16246](https://github.com/cosmos/cosmos-sdk/issues/16246) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. `GetValidatorSigningInfo` now returns an error instead of a `found bool`, the error can be `nil` (found), `ErrNoSigningInfoFound` (not found) and any other error. - - * (module) [#16227](https://github.com/cosmos/cosmos-sdk/issues/16227) `manager.RunMigrations()` now take a `context.Context` instead of a `sdk.Context`. - - * (x/crisis) [#16216](https://github.com/cosmos/cosmos-sdk/issues/16216) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` instead of panicking. - - * (x/distribution) [#16211](https://github.com/cosmos/cosmos-sdk/pull/16211) Use collections for params state management. - - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Add API `StartCmdWithOptions` to create customized start command. - - * (x/mint) [#16179](https://github.com/cosmos/cosmos-sdk/issues/16179) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. - - * (x/gov) [#16171](https://github.com/cosmos/cosmos-sdk/pull/16171) Use collections for proposal state management (part 1): - - * Removed: keeper: `GetProposal`, `UnmarshalProposal`, `MarshalProposal`, `IterateProposal`, `GetProposal`, `GetProposalFiltered`, `GetProposals`, `GetProposalID`, `SetProposalID` - - * Removed: errors unused errors - - * (x/gov) [#16164](https://github.com/cosmos/cosmos-sdk/pull/16164) Use collections for vote state management: - - * Removed: types `VoteKey`, `VoteKeys` - - * Removed: keeper `IterateVotes`, `IterateAllVotes`, `GetVotes`, `GetVote`, `SetVote` - - * (sims) [#16155](https://github.com/cosmos/cosmos-sdk/pull/16155) - - * `simulation.NewOperationMsg` now marshals the operation msg as proto bytes instead of legacy amino JSON bytes. - - * `simulation.NewOperationMsg` is now 2-arity instead of 3-arity with the obsolete argument `codec.ProtoCodec` removed. - - * The field `OperationMsg.Msg` is now of type `[]byte` instead of `json.RawMessage`. - - * (x/gov) [#16127](https://github.com/cosmos/cosmos-sdk/pull/16127) Use collections for deposit state management: - - * The following methods are removed from the gov keeper: `GetDeposit`, `GetAllDeposits`, `IterateAllDeposits`. - - * The following functions are removed from the gov types: `DepositKey`, `DepositsKey`. - - * (x/gov) [#16118](https://github.com/cosmos/cosmos-sdk/pull/16118/) Use collections for constituion and params state management. - - * (x/gov) [#16106](https://github.com/cosmos/cosmos-sdk/pull/16106) Remove gRPC query methods from gov keeper. - - * (x/*all*) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetSignBytes` implementations on messages and global legacy amino codec definitions have been removed from all modules. - - * (sims) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetOrGenerate` no longer requires a codec argument is now 4-arity instead of 5-arity. - - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16798) Remove aliases in `types/math.go` (part 2). - - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16040) Remove aliases in `types/math.go` (part 1). - - * (x/auth) [#16016](https://github.com/cosmos/cosmos-sdk/pull/16016) Use collections for accounts state management: - - * removed: keeper `HasAccountByID`, `AccountAddressByID`, `SetParams - - * (x/genutil) [#15999](https://github.com/cosmos/cosmos-sdk/pull/15999) Genutil now takes the `GenesisTxHanlder` interface instead of deliverTx. The interface is implemented on baseapp - - * (x/gov) [#15988](https://github.com/cosmos/cosmos-sdk/issues/15988) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` (instead of panicking or returning a `found bool`). Iterators callback functions now return an error instead of a `bool`. - - * (x/auth) [#15985](https://github.com/cosmos/cosmos-sdk/pull/15985) The `AccountKeeper` does not expose the `QueryServer` and `MsgServer` APIs anymore. - - * (x/authz) [#15962](https://github.com/cosmos/cosmos-sdk/issues/15962) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. The `Authorization` interface's `Accept` method now takes a `context.Context` instead of a `sdk.Context`. - - * (x/distribution) [#15948](https://github.com/cosmos/cosmos-sdk/issues/15948) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Keeper methods also now return an `error`. - - * (x/bank) [#15891](https://github.com/cosmos/cosmos-sdk/issues/15891) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Also `FundAccount` and `FundModuleAccount` from the `testutil` package accept a `context.Context` instead of a `sdk.Context`, and it's position was moved to the first place. - - * (x/slashing) [#15875](https://github.com/cosmos/cosmos-sdk/pull/15875) `x/slashing.NewAppModule` now requires an `InterfaceRegistry` parameter. - - * (x/crisis) [#15852](https://github.com/cosmos/cosmos-sdk/pull/15852) Crisis keeper now takes a instance of the address codec to be able to decode user addresses - - * (x/auth) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The type of struct field `ante.HandlerOptions.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. - - * (client) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The return type of the interface method `TxConfig.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. - - * The signature of `VerifySignature` has been changed to accept a `x/tx/signing.HandlerMap` and other structs from `x/tx` as arguments. - - * The signature of `NewTxConfigWithTextual` has been deprecated and its signature changed to accept a `SignModeOptions`. - - * The signature of `NewSigVerificationDecorator` has been changed to accept a `x/tx/signing.HandlerMap`. - - * (x/bank) [#15818](https://github.com/cosmos/cosmos-sdk/issues/15818) `BaseViewKeeper`'s `Logger` method now doesn't require a context. `NewBaseKeeper`, `NewBaseSendKeeper` and `NewBaseViewKeeper` now also require a `log.Logger` to be passed in. - - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) `MigrateGenesisCmd` now takes a `MigrationMap` instead of having the SDK genesis migration hardcoded. - - * (client) [#15673](https://github.com/cosmos/cosmos-sdk/pull/15673) Move `client/keys.OutputFormatJSON` and `client/keys.OutputFormatText` to `client/flags` package. - - * (x/*all*) [#15648](https://github.com/cosmos/cosmos-sdk/issues/15648) Make `SetParams` consistent across all modules and validate the params at the message handling instead of `SetParams` method. - - * (codec) [#15600](https://github.com/cosmos/cosmos-sdk/pull/15600) [#15873](https://github.com/cosmos/cosmos-sdk/pull/15873) add support for getting signers to `codec.Codec` and `InterfaceRegistry`: - - * `InterfaceRegistry` is has unexported methods and implements `protodesc.Resolver` plus the `RangeFiles` and `SigningContext` methods. All implementations of `InterfaceRegistry` by other users must now embed the official implementation. - - * `Codec` has new methods `InterfaceRegistry`, `GetMsgAnySigners`, `GetMsgV1Signers`, and `GetMsgV2Signers` as well as unexported methods. All implementations of `Codec` by other users must now embed an official implementation from the `codec` package. - - * `AminoCodec` is marked as deprecated and no longer implements `Codec. - - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) `RegisterNodeService` now requires a config parameter. - - * (x/nft) [#15588](https://github.com/cosmos/cosmos-sdk/pull/15588) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. - - * (baseapp) [#15568](https://github.com/cosmos/cosmos-sdk/pull/15568) `SetIAVLLazyLoading` is removed from baseapp. - - * (x/genutil) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `CollectGenTxsCmd` & `GenTxCmd` takes a address.Codec to be able to decode addresses. - - * (x/bank) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `GenesisBalance.GetAddress` now returns a string instead of `sdk.AccAddress` - - * `MsgSendExec` test helper function now takes a address.Codec - - * (x/auth) [#15520](https://github.com/cosmos/cosmos-sdk/pull/15520) `NewAccountKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) `runTxMode`s were renamed to `execMode`. `ModeDeliver` as changed to `ModeFinalize` and a new `ModeVoteExtension` was added for vote extensions. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Writing of state to the multistore was moved to `FinalizeBlock`. `Commit` still handles the committing values to disk. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Calls to BeginBlock and EndBlock have been replaced with core api beginblock & endblock. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock and EndBlock are now internal to baseapp. For testing, user must call `FinalizeBlock`. BeginBlock and EndBlock calls are internal to Baseapp. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) All calls to ABCI methods now accept a pointer of the abci request and response types - - * (x/consensus) [#15517](https://github.com/cosmos/cosmos-sdk/pull/15517) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`. - - * (x/bank) [#15477](https://github.com/cosmos/cosmos-sdk/pull/15477) `banktypes.NewMsgMultiSend` and `keeper.InputOutputCoins` only accept one input. - - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Remove `server.ErrorCode` that was not used anywhere. - - * (x/capability) [#15344](https://github.com/cosmos/cosmos-sdk/pull/15344) Capability module was removed and is now housed in [IBC-GO](https://github.com/cosmos/ibc-go). - - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) The `PriorityNonceMempool` is now generic over type `C comparable` and takes a single `PriorityNonceMempoolConfig[C]` argument. See `DefaultPriorityNonceMempoolConfig` for how to construct the configuration and a `TxPriority` type. - - * [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `StdTx` transaction and signing APIs. No SDK version has actually supported `StdTx` since before Stargate. - - * [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) - - * (x/gov) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. - - * (x/authx) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. - - * `types/tx.Tx` no longer implements `sdk.Tx`. - - * `sdk.Tx` now requires a new method `GetMsgsV2()`. - - * `sdk.Msg.GetSigners` was deprecated and is no longer supported. Use the `cosmos.msg.v1.signer` protobuf annotation instead. - - * `TxConfig` has a new method `SigningContext() *signing.Context`. - - * `SigVerifiableTx.GetSigners()` now returns `([][]byte, error)` instead of `[]sdk.AccAddress`. - - * `AccountKeeper` now has an `AddressCodec() address.Codec` method and the expected `AccountKeeper` for `x/auth/ante` expects this method. - - * [#15211](https://github.com/cosmos/cosmos-sdk/pull/15211) Remove usage of `github.com/cometbft/cometbft/libs/bytes.HexBytes` in favor of `[]byte` thorough the SDK. - - * (crypto) [#15070](https://github.com/cosmos/cosmos-sdk/pull/15070) `GenerateFromPassword` and `Cost` from `bcrypt.go` now take a `uint32` instead of a `int` type. - - * (types) [#15067](https://github.com/cosmos/cosmos-sdk/pull/15067) Remove deprecated alias from `types/errors`. Use `cosmossdk.io/errors` instead. - - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Refactor how gRPC and API servers are started to remove unnecessary sleeps: - - * `api.Server#Start` now accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the API server can gracefully exit. The caller does not need to stop the server. - - * To start the gRPC server you must first create the server via `NewGRPCServer`, after which you can start the gRPC server via `StartGRPCServer` which accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the gRPC server can gracefully exit. The caller does not need to stop the server. - - * Rename `WaitForQuitSignals` to `ListenForQuitSignals`. Note, this function is no longer blocking. Thus the caller is expected to provide a `context.CancelFunc` which indicates that when a signal is caught, that any spawned processes can gracefully exit. - - * Remove `ServerStartTime` constant. - - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) All functions that were taking a CometBFT logger, now take `cosmossdk.io/log.Logger` instead. - - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. - - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Allow a human readable denomination for coins when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest`. - - * [#14847](https://github.com/cosmos/cosmos-sdk/pull/14847) App and ModuleManager methods `InitGenesis`, `ExportGenesis`, `BeginBlock` and `EndBlock` now also return an error. - - * (x/upgrade) [#14764](https://github.com/cosmos/cosmos-sdk/pull/14764) The `x/upgrade` module is extracted to have a separate go.mod file which allows it to be a standalone module. - - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Refactor transaction searching: - - * Refactor `QueryTxsByEvents` to accept a `query` of type `string` instead of `events` of type `[]string` - - * Refactor CLI methods to accept `--query` flag instead of `--events` - - * Pass `prove=false` to Tendermint's `TxSearch` RPC method - - * (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct. - - * (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`. - - * (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`. - - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Add an expedited field in the gov v1 proposal and `MsgNewMsgProposal`. - - * (x/feegrant) [#14649](https://github.com/cosmos/cosmos-sdk/pull/14649) Extract Feegrant in its own go.mod and rename the package to `cosmossdk.io/x/feegrant`. - - * (tx) [#14634](https://github.com/cosmos/cosmos-sdk/pull/14634) Move the `tx` go module to `x/tx`. - - * (store/streaming)[#14603](https://github.com/cosmos/cosmos-sdk/pull/14603) `StoreDecoderRegistry` moved from store to `types/simulations` this breaks the `AppModuleSimulation` interface. - - * (snapshots) [#14597](https://github.com/cosmos/cosmos-sdk/pull/14597) Move `snapshots` to `store/snapshots`, rename and bump proto package to v1. - - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. - - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` - - * (baseapp) [#14050](https://github.com/cosmos/cosmos-sdk/pull/14050) Refactor `ABCIListener` interface to accept Go contexts. - - * (x/auth) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850/) Remove `MarshalYAML` methods from module (`x/...`) types. - - * (modules) [#13850](https://github.com/cosmos/cosmos-sdk/pull/13850) and [#14046](https://github.com/cosmos/cosmos-sdk/pull/14046) Remove gogoproto stringer annotations. This removes the custom `String()` methods on all types that were using the annotations. - - * (x/evidence) [14724](https://github.com/cosmos/cosmos-sdk/pull/14724) Extract Evidence in its own go.mod and rename the package to `cosmossdk.io/x/evidence`. - - * (crypto/keyring) [#13734](https://github.com/cosmos/cosmos-sdk/pull/13834) The keyring's `Sign` method now takes a new `signMode` argument. It is only used if the signing key is a Ledger hardware device. You can set it to 0 in all other cases. - - * (snapshots) [14048](https://github.com/cosmos/cosmos-sdk/pull/14048) Move the Snapshot package to the store package. This is done in an effort group all storage related logic under one package. - - * (signing) [#13701](https://github.com/cosmos/cosmos-sdk/pull/) Add `context.Context` as an argument `x/auth/signing.VerifySignature`. - - * (store) [#11825](https://github.com/cosmos/cosmos-sdk/pull/11825) Make extension snapshotter interface safer to use, renamed the util function `WriteExtensionItem` to `WriteExtensionPayload`. - - ### Client Breaking Changes - - * (x/gov) [#17910](https://github.com/cosmos/cosmos-sdk/pull/17910) Remove telemetry for counting votes and proposals. It was incorrectly counting votes. Use alternatives, such as state streaming. - - * (abci) [#15845](https://github.com/cosmos/cosmos-sdk/pull/15845) Remove duplicating events in `logs`. - - * (abci) [#15845](https://github.com/cosmos/cosmos-sdk/pull/15845) Add `msg_index` to all event attributes to associate events and messages. - - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) `HistoricalInfoKey` now has a binary format. - - * (store/streaming) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) State Streaming removed emitting of beginblock, endblock and delivertx in favour of emitting FinalizeBlock. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock & EndBlock events have begin or endblock in the events in order to identify which stage they are emitted from since they are returned to comet as FinalizeBlock events. - - * (grpc-web) [#14652](https://github.com/cosmos/cosmos-sdk/pull/14652) Use same port for gRPC-Web and the API server. - - ### CLI Breaking Changes - - * (all) The migration of modules to [AutoCLI](https://docs.cosmos.network/main/core/autocli) led to no changes in UX but a [small change in CLI outputs](https://github.com/cosmos/cosmos-sdk/issues/16651) where results can be nested. - - * (all) Query pagination flags have been renamed with the migration to AutoCLI: - - * `--reverse` -> `--page-reverse` - - * `--offset` -> `--page-offset` - - * `--limit` -> `--page-limit` - - * `--count-total` -> `--page-count-total` - - * (cli) [#17184](https://github.com/cosmos/cosmos-sdk/pull/17184) All json keys returned by the `status` command are now snake case instead of pascal case. - - * (server) [#17177](https://github.com/cosmos/cosmos-sdk/pull/17177) Remove `iavl-lazy-loading` configuration. - - * (x/gov) [#16987](https://github.com/cosmos/cosmos-sdk/pull/16987) In ` query gov proposals` the proposal status flag have renamed from `--status` to `--proposal-status`. Additionally, that flags now uses the ENUM values: `PROPOSAL_STATUS_DEPOSIT_PERIOD`, `PROPOSAL_STATUS_VOTING_PERIOD`, `PROPOSAL_STATUS_PASSED`, `PROPOSAL_STATUS_REJECTED`, `PROPOSAL_STATUS_FAILED`. - - * (x/bank) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) With the migration to AutoCLI some bank commands have been split in two: - - * Use `total-supply` (or `total`) for querying the total supply and `total-supply-of` for querying the supply of a specific denom. - - * Use `denoms-metadata` for querying all denom metadata and `denom-metadata` for querying a specific denom metadata. - - * (rosetta) [#16276](https://github.com/cosmos/cosmos-sdk/issues/16276) Rosetta migration to standalone repo. - - * (cli) [#15826](https://github.com/cosmos/cosmos-sdk/pull/15826) Remove ` q account` command. Use ` q auth account` instead. - - * (cli) [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `--amino` flag from `sign` and `multi-sign` commands. Amino `StdTx` has been deprecated for a while. Amino JSON signing still works as expected. - - * (x/gov) [#14880](https://github.com/cosmos/cosmos-sdk/pull/14880) Remove ` tx gov submit-legacy-proposal cancel-software-upgrade` and `software-upgrade` commands. These commands are now in the `x/upgrade` module and using gov v1. Use `tx upgrade software-upgrade` instead. - - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. - - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) ` q block ` is removed as it just output json. The new command allows either height/hash and is ` q block --type=height|hash `. - - * (grpc-web) [#14652](https://github.com/cosmos/cosmos-sdk/pull/14652) Remove `grpc-web.address` flag. - - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) ` config` command is now a sub-command using Confix. Use ` config --help` to learn more. - - ### Bug Fixes - - * (server) [#18254](https://github.com/cosmos/cosmos-sdk/pull/18254) Don't hardcode gRPC address to localhost. - - * (x/gov) [#18173](https://github.com/cosmos/cosmos-sdk/pull/18173) Gov hooks now return an error and are *blocking* when they fail. Expect for `AfterProposalFailedMinDeposit` and `AfterProposalVotingPeriodEnded` which log the error and continue. - - * (x/gov) [#17873](https://github.com/cosmos/cosmos-sdk/pull/17873) Fail any inactive and active proposals that cannot be decoded. - - * (x/slashing) [#18016](https://github.com/cosmos/cosmos-sdk/pull/18016) Fixed builder function for missed blocks key (`validatorMissedBlockBitArrayPrefixKey`) in slashing/migration/v4. - - * (x/bank) [#18107](https://github.com/cosmos/cosmos-sdk/pull/18107) Add missing keypair of SendEnabled to restore legacy param set before migration. - - * (baseapp) [#17769](https://github.com/cosmos/cosmos-sdk/pull/17769) Ensure we respect block size constraints in the `DefaultProposalHandler`'s `PrepareProposal` handler when a nil or no-op mempool is used. We provide a `TxSelector` type to assist in making transaction selection generalized. We also fix a comparison bug in tx selection when `req.maxTxBytes` is reached. - - * (mempool) [#17668](https://github.com/cosmos/cosmos-sdk/pull/17668) Fix `PriorityNonceIterator.Next()` nil pointer ref for min priority at the end of iteration. - - * (config) [#17649](https://github.com/cosmos/cosmos-sdk/pull/17649) Fix `mempool.max-txs` configuration is invalid in `app.config`. - - * (baseapp) [#17518](https://github.com/cosmos/cosmos-sdk/pull/17518) Utilizing voting power from vote extensions (CometBFT) instead of the current bonded tokens (x/staking) to determine if a set of vote extensions are valid. - - * (baseapp) [#17251](https://github.com/cosmos/cosmos-sdk/pull/17251) VerifyVoteExtensions and ExtendVote initialize their own contexts/states, allowing VerifyVoteExtensions being called without ExtendVote. - - * (x/distribution) [#17236](https://github.com/cosmos/cosmos-sdk/pull/17236) Using "validateCommunityTax" in "Params.ValidateBasic", preventing panic when field "CommunityTax" is nil. - - * (x/bank) [#17170](https://github.com/cosmos/cosmos-sdk/pull/17170) Avoid empty spendable error message on send coins. - - * (x/group) [#17146](https://github.com/cosmos/cosmos-sdk/pull/17146) Rename x/group legacy ORM package's error codespace from "orm" to "legacy_orm", preventing collisions with ORM's error codespace "orm". - - * (types/query) [#16905](https://github.com/cosmos/cosmos-sdk/pull/16905) Collections Pagination now applies proper count when filtering results. - - * (x/bank) [#16841](https://github.com/cosmos/cosmos-sdk/pull/16841) Correctly process legacy `DenomAddressIndex` values. - - * (x/auth/vesting) [#16733](https://github.com/cosmos/cosmos-sdk/pull/16733) Panic on overflowing and negative EndTimes when creating a PeriodicVestingAccount. - - * (x/consensus) [#16713](https://github.com/cosmos/cosmos-sdk/pull/16713) Add missing ABCI param in `MsgUpdateParams`. - - * (baseapp) [#16700](https://github.com/cosmos/cosmos-sdk/pull/16700) Fix consensus failure in returning no response to malformed transactions. - - * [#16639](https://github.com/cosmos/cosmos-sdk/pull/16639) Make sure we don't execute blocks beyond the halt height. - - * (baseapp) [#16613](https://github.com/cosmos/cosmos-sdk/pull/16613) Ensure each message in a transaction has a registered handler, otherwise `CheckTx` will fail. - - * (baseapp) [#16596](https://github.com/cosmos/cosmos-sdk/pull/16596) Return error during `ExtendVote` and `VerifyVoteExtension` if the request height is earlier than `VoteExtensionsEnableHeight`. - - * (baseapp) [#16259](https://github.com/cosmos/cosmos-sdk/pull/16259) Ensure the `Context` block height is correct after `InitChain` and prior to the second block. - - * (x/gov) [#16231](https://github.com/cosmos/cosmos-sdk/pull/16231) Fix Rawlog JSON formatting of proposal_vote option field.* (cli) [#16138](https://github.com/cosmos/cosmos-sdk/pull/16138) Fix snapshot commands panic if snapshot don't exists. - - * (x/staking) [#16043](https://github.com/cosmos/cosmos-sdk/pull/16043) Call `AfterUnbondingInitiated` hook for new unbonding entries only and fix `UnbondingDelegation` entries handling. This is a behavior change compared to Cosmos SDK v0.47.x, now the hook is called only for new unbonding entries. - - * (types) [#16010](https://github.com/cosmos/cosmos-sdk/pull/16010) Let `module.CoreAppModuleBasicAdaptor` fallback to legacy genesis handling. - +{/* Release notes content will be added here soon */} \ No newline at end of file diff --git a/docs/sdk/v0.50/learn/advanced/autocli.mdx b/docs/sdk/v0.50/learn/advanced/autocli.mdx index ef1b82d7..9e683bbb 100644 --- a/docs/sdk/v0.50/learn/advanced/autocli.mdx +++ b/docs/sdk/v0.50/learn/advanced/autocli.mdx @@ -53,9 +53,9 @@ Here's an example of how to use `autocli` in your app: AutoCLI provides a better UX than normal CLI as it allows to resolve key names directly from the keyring in all transactions and commands. - ``` +``` q bank balances alice tx bank send alice bob 1000denom - ``` +``` The keyring used for resolving names and signing transactions is provided via the `client.Context`. The keyring is then converted to the `client/v2/autocli/keyring` interface. If no keyring is provided, the `autocli` generated command will not be able to sign transactions, but will still be able to query the chain. @@ -63,9 +63,9 @@ The keyring used for resolving names and signing transactions is provided via th The Cosmos SDK keyring and Hubl keyring both implement the `client/v2/autocli/keyring` interface, thanks to the following wrapper: - ``` +``` keyring.NewAutoCLIKeyring(kb) - ``` +``` ## Signing[​](#signing "Direct link to Signing") diff --git a/docs/sdk/v0.50/learn/advanced/baseapp.mdx b/docs/sdk/v0.50/learn/advanced/baseapp.mdx index 523094fb..2d12b3e9 100644 --- a/docs/sdk/v0.50/learn/advanced/baseapp.mdx +++ b/docs/sdk/v0.50/learn/advanced/baseapp.mdx @@ -355,9 +355,9 @@ loading... baseapp/baseapp.go - ``` +``` loading... - ``` +``` [See full example on GitHub](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/baseapp/baseapp.go#L682-L706) diff --git a/docs/sdk/v0.50/learn/advanced/cli.mdx b/docs/sdk/v0.50/learn/advanced/cli.mdx index 1c1f5ed2..60080735 100644 --- a/docs/sdk/v0.50/learn/advanced/cli.mdx +++ b/docs/sdk/v0.50/learn/advanced/cli.mdx @@ -210,7 +210,7 @@ The `InterceptConfigsPreRunHandler` call creates a viper literal, default `serve When willing to configure which logger is used, do not use `InterceptConfigsPreRunHandler`, which sets the default SDK logger, but instead use `InterceptConfigsAndCreateContext` and set the server context and the logger manually: - ``` +``` -return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig)+serverCtx, err := server.InterceptConfigsAndCreateContext(cmd, customAppTemplate, customAppConfig, customCMTConfig)+if err != nil {+ return err+}+// overwrite default server logger+logger, err := server.CreateSDKLogger(serverCtx, cmd.OutOrStdout())+if err != nil {+ return err+}+serverCtx.Logger = logger.With(log.ModuleKey, "server")+// set server context+return server.SetCmdServerContext(cmd, serverCtx) - ``` +``` diff --git a/docs/sdk/v0.50/learn/advanced/events.mdx b/docs/sdk/v0.50/learn/advanced/events.mdx index e22bc01a..939bed3b 100644 --- a/docs/sdk/v0.50/learn/advanced/events.mdx +++ b/docs/sdk/v0.50/learn/advanced/events.mdx @@ -14,7 +14,7 @@ description: "Version: v0.50" ## Events[​](#events-1 "Direct link to Events") -Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: `{eventType}.{attributeKey}={attributeValue}`. +Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: ``{eventType}.``{attributeKey}```={attributeValue}`. proto/tendermint/abci/types.proto @@ -36,7 +36,7 @@ An Event contains: *Typed Events* are Protobuf-defined [messages](/v0.50/build/architecture/adr-032-typed-events) used by the Cosmos SDK for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`. *Legacy Events* are defined on a **per-module basis** in the module's `/types/events.go` file. They are triggered from the module's Protobuf [`Msg` service](/v0.50/build/building-modules/msg-services) by using the [`EventManager`](#eventmanager). -In addition, each module documents its events under in the `Events` sections of its specs (x/\{moduleName}/`README.md`). +In addition, each module documents its events under in the `Events` sections of its specs (x/\`{moduleName}`/`README.md`). Lastly, Events are returned to the underlying consensus engine in the response of the following ABCI messages: diff --git a/docs/sdk/v0.50/learn/advanced/grpc_rest.mdx b/docs/sdk/v0.50/learn/advanced/grpc_rest.mdx index 1b72521d..dc8841d2 100644 --- a/docs/sdk/v0.50/learn/advanced/grpc_rest.mdx +++ b/docs/sdk/v0.50/learn/advanced/grpc_rest.mdx @@ -66,7 +66,7 @@ All routes are configured under the following fields in `~/.simapp/config/app.to If, for various reasons, you cannot use gRPC (for example, you are building a web application, and browsers don't support HTTP2 on which gRPC is built), then the Cosmos SDK offers REST routes via gRPC-gateway. -[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway `"/cosmos/bank/v1beta1/balances/{address}"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: +[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway ``"/cosmos/bank/v1beta1/balances/``{address}```"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: proto/cosmos/bank/v1beta1/query.proto @@ -97,8 +97,8 @@ Some CometBFT RPC endpoints are directly related to the Cosmos SDK: * any Protobuf fully-qualified service method, such as `/cosmos.bank.v1beta1.Query/AllBalances`. The `data` field should then include the method's request parameter(s) encoded as bytes using Protobuf. * `/app/simulate`: this will simulate a transaction, and return some information such as gas used. * `/app/version`: this will return the application's version. - * `/store/{storeName}/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. - * `/store/{storeName}/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. + * ``/store/``{storeName}```/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. + * ``/store/``{storeName}```/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. * `/p2p/filter/addr/{port}`: this will return a filtered list of the node's P2P peers by address port. * `/p2p/filter/id/{id}`: this will return a filtered list of the node's P2P peers by ID. diff --git a/docs/sdk/v0.50/learn/beginner/query-lifecycle.mdx b/docs/sdk/v0.50/learn/beginner/query-lifecycle.mdx index caec069b..940d4c23 100644 --- a/docs/sdk/v0.50/learn/beginner/query-lifecycle.mdx +++ b/docs/sdk/v0.50/learn/beginner/query-lifecycle.mdx @@ -44,7 +44,7 @@ Another interface through which users can make queries is [gRPC](https://grpc.io One such tool is [grpcurl](https://github.com/fullstorydev/grpcurl), and a gRPC request for `MyQuery` using this client looks like: ``` -grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name +grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '\{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name ``` ### REST[​](#rest "Direct link to REST") @@ -54,7 +54,7 @@ Another interface through which users can make queries is through HTTP Requests An example HTTP request for `MyQuery` looks like: ``` -GET http://localhost:1317/cosmos/staking/v1beta1/delegators/{delegatorAddr}/delegations +GET http://localhost:1317/cosmos/staking/v1beta1/delegators/`{delegatorAddr}`/delegations ``` ## How Queries are Handled by the CLI[​](#how-queries-are-handled-by-the-cli "Direct link to How Queries are Handled by the CLI") diff --git a/docs/sdk/v0.50/overview.mdx b/docs/sdk/v0.50/overview.mdx new file mode 100644 index 00000000..a13496b3 --- /dev/null +++ b/docs/sdk/v0.50/overview.mdx @@ -0,0 +1,44 @@ +--- +title: "Website" +description: "Version: v0.50" +--- + +This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. + +### Installation + +``` +$ yarn +``` + +### Local Development + +``` +$ yarn start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +### Build + +``` +$ yarn build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +### Deployment + +Using SSH: + +``` +$ USE_SSH=true yarn deploy +``` + +Not using SSH: + +``` +$ GIT_USER= yarn deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. \ No newline at end of file diff --git a/docs/sdk/v0.50/tutorials.mdx b/docs/sdk/v0.50/tutorials.mdx index 92695160..46ccc281 100644 --- a/docs/sdk/v0.50/tutorials.mdx +++ b/docs/sdk/v0.50/tutorials.mdx @@ -1,12 +1,29 @@ --- -title: "Tutorials" -description: "Version: v0.50" +title: Tutorials --- -## Advanced Tutorials[​](#advanced-tutorials "Direct link to Advanced Tutorials") +# Cosmos SDK Tutorials -This section provides a concise overview of tutorials focused on implementing vote extensions in the Cosmos SDK. Vote extensions are a powerful feature for enhancing the security and fairness of blockchain applications, particularly in scenarios like implementing oracles and mitigating auction front-running. +The tutorials for Cosmos SDK are maintained in a single location and apply across all SDK versions. These hands-on guides will help you master key concepts and advanced features through practical examples. -* **Implementing Oracle with Vote Extensions** - This tutorial details how to use vote extensions for the implementation of a secure and reliable oracle within a blockchain application. It demonstrates the use of vote extensions to securely include oracle data submissions in blocks, ensuring the data's integrity and reliability for the blockchain. +## Available Tutorials -* **Mitigating Auction Front-Running with Vote Extensions** - Explore how to prevent auction front-running using vote extensions. This tutorial outlines the creation of a module aimed at mitigating front-running in nameservice auctions, emphasising the `ExtendVote`, `PrepareProposal`, and `ProcessProposal` functions to facilitate a fair auction process. +### Transaction Building +- **[Building a Transaction](../next/tutorials/transactions/building-a-transaction.mdx)** - Learn to construct, sign, and broadcast transactions + +### Vote Extensions +Advanced consensus features for building sophisticated applications: + +#### Oracle Implementation +- **[What is an Oracle?](../next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/oracle/getting-started.mdx)** +- **[Implementing Vote Extensions](../next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx)** +- **[Testing Oracle](../next/tutorials/vote-extensions/oracle/testing-oracle.mdx)** + +#### Mitigating Front-Running +- **[Understanding Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx)** +- **[Mitigating Front-Running with Vote Extensions](../next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx)** +- **[Demo of Mitigating Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx)** + +Visit the [full tutorials section](../next/tutorials/tutorials.mdx) for detailed guides and learning paths. \ No newline at end of file diff --git a/docs/sdk/v0.50/tutorials/transactions/building-a-transaction.mdx b/docs/sdk/v0.50/tutorials/transactions/building-a-transaction.mdx deleted file mode 100644 index 87e1cf26..00000000 --- a/docs/sdk/v0.50/tutorials/transactions/building-a-transaction.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: "Building a Transaction" -description: "Version: v0.50" ---- - -These are the steps to build, sign and broadcast a transaction using v2 semantics. - -1. Correctly set up imports - -``` -import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" apisigning "cosmossdk.io/api/cosmos/tx/signing/v1beta1" "cosmossdk.io/client/v2/broadcast/comet" "cosmossdk.io/client/v2/tx" "cosmossdk.io/core/transaction" "cosmossdk.io/math" banktypes "cosmossdk.io/x/bank/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/codec" addrcodec "github.com/cosmos/cosmos-sdk/codec/address" sdk "github.com/cosmos/cosmos-sdk/types") -``` - -2. Create a gRPC connection - -``` -clientConn, err := grpc.NewClient("127.0.0.1:9090", grpc.WithTransportCredentials(insecure.NewCredentials()))if err != nil { log.Fatal(err)} -``` - -3. Setup codec and interface registry - -``` - // Setup interface registry and register necessary interfaces interfaceRegistry := codectypes.NewInterfaceRegistry() banktypes.RegisterInterfaces(interfaceRegistry) authtypes.RegisterInterfaces(interfaceRegistry) cryptocodec.RegisterInterfaces(interfaceRegistry) // Create a ProtoCodec for encoding/decoding protoCodec := codec.NewProtoCodec(interfaceRegistry) -``` - -4. Initialize keyring - -``` - ckr, err := keyring.New("autoclikeyring", "test", home, nil, protoCodec) if err != nil { log.Fatal("error creating keyring", err) } kr, err := keyring.NewAutoCLIKeyring(ckr, addrcodec.NewBech32Codec("cosmos")) if err != nil { log.Fatal("error creating auto cli keyring", err) } -``` - -5. Setup transaction parameters - -``` - // Setup transaction parameters txParams := tx.TxParameters{ ChainID: "simapp-v2-chain", SignMode: apisigning.SignMode_SIGN_MODE_DIRECT, AccountConfig: tx.AccountConfig{ FromAddress: "cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", FromName: "alice", }, } // Configure gas settings gasConfig, err := tx.NewGasConfig(100, 100, "0stake") if err != nil { log.Fatal("error creating gas config: ", err) } txParams.GasConfig = gasConfig // Create auth query client authClient := authtypes.NewQueryClient(clientConn) // Retrieve account information for the sender fromAccount, err := getAccount("cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", authClient, protoCodec) if err != nil { log.Fatal("error getting from account: ", err) } // Update txParams with the correct account number and sequence txParams.AccountConfig.AccountNumber = fromAccount.GetAccountNumber() txParams.AccountConfig.Sequence = fromAccount.GetSequence() // Retrieve account information for the recipient toAccount, err := getAccount("cosmos1e2wanzh89mlwct7cs7eumxf7mrh5m3ykpsh66m", authClient, protoCodec) if err != nil { log.Fatal("error getting to account: ", err) } // Configure transaction settings txConf, _ := tx.NewTxConfig(tx.ConfigOptions{ AddressCodec: addrcodec.NewBech32Codec("cosmos"), Cdc: protoCodec, ValidatorAddressCodec: addrcodec.NewBech32Codec("cosmosval"), EnabledSignModes: []apisigning.SignMode{apisigning.SignMode_SIGN_MODE_DIRECT}, }) -``` - -6. Build the transaction - -``` -// Create a transaction factory f, err := tx.NewFactory(kr, codec.NewProtoCodec(codectypes.NewInterfaceRegistry()), nil, txConf, addrcodec.NewBech32Codec("cosmos"), clientConn, txParams) if err != nil { log.Fatal("error creating factory", err) } // Define the transaction message msgs := []transaction.Msg{ &banktypes.MsgSend{ FromAddress: fromAccount.GetAddress().String(), ToAddress: toAccount.GetAddress().String(), Amount: sdk.Coins{ sdk.NewCoin("stake", math.NewInt(1000000)), }, }, } // Build and sign the transaction tx, err := f.BuildsSignedTx(context.Background(), msgs...) if err != nil { log.Fatal("error building signed tx", err) } -``` - -7. Broadcast the transaction - -``` -// Create a broadcaster for the transaction c, err := comet.NewCometBFTBroadcaster("http://127.0.0.1:26657", comet.BroadcastSync, protoCodec) if err != nil { log.Fatal("error creating comet broadcaster", err) } // Broadcast the transaction res, err := c.Broadcast(context.Background(), tx.Bytes()) if err != nil { log.Fatal("error broadcasting tx", err) } -``` - -8. Helpers - -``` -// getAccount retrieves account information using the provided addressfunc getAccount(address string, authClient authtypes.QueryClient, codec codec.Codec) (sdk.AccountI, error) { // Query account info accountQuery, err := authClient.Account(context.Background(), &authtypes.QueryAccountRequest{ Address: string(address), }) if err != nil { return nil, fmt.Errorf("error getting account: %w", err) } // Unpack the account information var account sdk.AccountI err = codec.InterfaceRegistry().UnpackAny(accountQuery.Account, &account) if err != nil { return nil, fmt.Errorf("error unpacking account: %w", err) } return account, nil} -``` diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx deleted file mode 100644 index 0b6e0e7e..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: "Demo of Mitigating Front-Running with Vote Extensions" -description: "Version: v0.50" ---- - -The purpose of this demo is to test the implementation of the `VoteExtensionHandler` and `PrepareProposalHandler` that we have just added to the codebase. These handlers are designed to mitigate front-running by ensuring that all validators have a consistent view of the mempool when preparing proposals. - -In this demo, we are using a 3 validator network. The Beacon validator is special because it has a custom transaction provider enabled. This means that it can potentially manipulate the order of transactions in a proposal to its advantage (i.e., front-running). - -1. Bootstrap the validator network: This sets up a network with 3 validators. The script \`./scripts/configure.sh is used to configure the network and the validators. - -``` -cd scriptsconfigure.sh -``` - -If this doesn't work please ensure you have run `make build` in the `tutorials/nameservice/base` directory. - -2. Have alice attempt to reserve `bob.cosmos`: This is a normal transaction that alice wants to execute. The script \``./scripts/reserve.sh "bob.cosmos"` is used to send this transaction. - -``` -reserve.sh "bob.cosmos" -``` - -3. Query to verify the name has been reserved: This is to check the result of the transaction. The script `./scripts/whois.sh "bob.cosmos"` is used to query the state of the blockchain. - -``` -whois.sh "bob.cosmos" -``` - -It should return: - -``` - "name": { "name": "bob.cosmos", "owner": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", "resolve_address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", "amount": [ { "denom": "uatom", "amount": "1000" } ] }} -``` - -To detect front-running attempts by the beacon, scrutinise the logs during the `ProcessProposal` stage. Open the logs for each validator, including the beacon, `val1`, and `val2`, to observe the following behavior. Open the log file of the validator node. The location of this file can vary depending on your setup, but it's typically located in a directory like `$HOME/cosmos/nodes/#{validator}/logs`. The directory in this case will be under the validator so, `beacon` `val1` or `val2`. Run the following to tail the logs of the validator or beacon: - -``` -tail -f $HOME/cosmos/nodes/#{validator}/logs -``` - -``` -2:47PM ERR ❌️:: Detected invalid proposal bid :: name:"bob.cosmos" resolveAddress:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" owner:"cosmos1wmuwv38pdur63zw04t0c78r2a8dyt08hf9tpvd" amount: module=server2:47PM ERR ❌️:: Unable to validate bids in Process Proposal :: module=server2:47PM ERR prevote step: state machine rejected a proposed block; this should not happen:the proposer may be misbehaving; prevoting nil err=null height=142 module=consensus round=0 -``` - -4. List the Beacon's keys: This is to verify the addresses of the validators. The script `./scripts/list-beacon-keys.sh` is used to list the keys. - -``` -list-beacon-keys.sh -``` - -We should receive something similar to the following: - -``` -[ { "name": "alice", "type": "local", "address": "cosmos1h6zy2kn9efxtw5z22rc5k9qu7twl70z24kr3ht", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A32cvBUkNJz+h2vld4A5BxvU5Rd+HyqpR3aGtvEhlm4C\"}" }, { "name": "barbara", "type": "local", "address": "cosmos1nq9wuvuju4jdmpmzvxmg8zhhu2ma2y2l2pnu6w", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"Ag9PFsNyTQPoJdbyCWia5rZH9CrvSrjMsk7Oz4L3rXQ5\"}" }, { "name": "beacon-key", "type": "local", "address": "cosmos1ez9a6x7lz4gvn27zr368muw8jeyas7sv84lfup", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"AlzJZMWyN7lass710TnAhyuFKAFIaANJyw5ad5P2kpcH\"}" }, { "name": "cindy", "type": "local", "address": "cosmos1m5j6za9w4qc2c5ljzxmm2v7a63mhjeag34pa3g", "pubkey": "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"A6F1/3yot5OpyXoSkBbkyl+3rqBkxzRVSJfvSpm/AvW5\"}" }] -``` - -This allows us to match up the addresses and see that the bid was not front run by the beacon due as the resolve address is Alice's address and not the beacons address. - -By running this demo, we can verify that the `VoteExtensionHandler` and `PrepareProposalHandler` are working as expected and that they are able to prevent front-running. - -## Conclusion[​](#conclusion "Direct link to Conclusion") - -In this tutorial, we've tackled front-running and MEV, focusing on nameservice auctions' vulnerability to these issues. We've explored vote extensions, a key feature of ABCI 2.0, and integrated them into a Cosmos SDK application. - -Through practical exercises, you've implemented vote extensions, and tested their effectiveness in creating a fair auction system. You've gained practical insights by configuring a validator network and analysing blockchain logs. - -Keep experimenting with these concepts, engage with the community, and stay updated on new advancements. The knowledge you've acquired here is crucial for developing secure and fair blockchain applications. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx deleted file mode 100644 index 8ba26a67..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: "Getting Started" -description: "Version: v0.50" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [Getting Started](#overview-of-the-project) -* [Understanding Front-Running](/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) -* [Mitigating Front-running with Vote Extensions](/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions) -* [Demo of Mitigating Front-Running](/v0.50/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running) - -## Getting Started[​](#getting-started-1 "Direct link to Getting Started") - -### Overview of the Project[​](#overview-of-the-project "Direct link to Overview of the Project") - -This tutorial outlines the development of a module designed to mitigate front-running in nameservice auctions. The following functions are central to this module: - -* `ExtendVote`: Gathers bids from the mempool and includes them in the vote extension to ensure a fair and transparent auction process. -* `PrepareProposal`: Processes the vote extensions from the previous block, creating a special transaction that encapsulates bids to be included in the current proposal. -* `ProcessProposal`: Validates that the first transaction in the proposal is the special transaction containing the vote extensions and ensures the integrity of the bids. - -In this advanced tutorial, we will be working with an example application that facilitates the auctioning of nameservices. To see what frontrunning and nameservices are [here](/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) This application provides a practical use case to explore the prevention of auction front-running, also known as "bid sniping", where a validator takes advantage of seeing a bid in the mempool to place their own higher bid before the original bid is processed. - -The tutorial will guide you through using the Cosmos SDK to mitigate front-running using vote extensions. The module will be built on top of the base blockchain provided in the `tutorials/base` directory and will use the `auction` module as a foundation. By the end of this tutorial, you will have a better understanding of how to prevent front-running in blockchain auctions, specifically in the context of nameservice auctioning. - -## What are Vote extensions?[​](#what-are-vote-extensions "Direct link to What are Vote extensions?") - -Vote extensions is arbitrary information which can be inserted into a block. This feature is part of ABCI 2.0, which is available for use in the SDK 0.50 release and part of the 0.38 CometBFT release. - -More information about vote extensions can be seen [here](https://docs.cosmos.network/main/build/abci/vote-extensions). - -## Requirements and Setup[​](#requirements-and-setup "Direct link to Requirements and Setup") - -Before diving into the advanced tutorial on auction front-running simulation, ensure you meet the following requirements: - -* [Golang >1.21.5](https://golang.org/doc/install) installed -* Familiarity with the concepts of front-running and MEV, as detailed in [Understanding Front-Running](/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning) -* Understanding of Vote Extensions as described [here](https://docs.cosmos.network/main/build/abci/vote-extensions) - -You will also need a foundational blockchain to build upon coupled with your own module. The `tutorials/base` directory has the necessary blockchain code to start your custom project with the Cosmos SDK. For the module, you can use the `auction` module provided in the `tutorials/auction/x/auction` directory as a reference but please be aware that all of the code needed to implement vote extensions is already implemented in this module. - -This will set up a strong base for your blockchain, enabling the integration of advanced features such as auction front-running simulation. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx deleted file mode 100644 index 9d0f910b..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Mitigating Front-running with Vote Extensions" -description: "Version: v0.50" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [Prerequisites](#prerequisites) -* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) -* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") - -Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. - -In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. - -### Implementing Structs for Vote Extensions[​](#implementing-structs-for-vote-extensions "Direct link to Implementing Structs for Vote Extensions") - -First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: - -``` -package abciimport ( //import the necessary files)type PrepareProposalHandler struct { logger log.Logger txConfig client.TxConfig cdc codec.Codec mempool *mempool.ThresholdMempool txProvider provider.TxProvider keyname string runProvider bool} -``` - -The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. - -``` -type ProcessProposalHandler struct { TxConfig client.TxConfig Codec codec.Codec Logger log.Logger} -``` - -After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 mempool *mempool.ThresholdMempool cdc codec.Codec} -``` - -This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. - -``` -type InjectedVoteExt struct { VoteExtSigner []byte Bids [][]byte}type InjectedVotes struct { Votes []InjectedVoteExt} -``` - -These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. - -``` -type AppVoteExtension struct { Height int64 Bids [][]byte} -``` - -This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. - -``` -type SpecialTransaction struct { Height int Bids [][]byte} -``` - -This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. - -### Implementing Handlers and Configuring Handlers[​](#implementing-handlers-and-configuring-handlers "Direct link to Implementing Handlers and Configuring Handlers") - -To establish the `VoteExtensionHandler`, follow these steps: - -1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. - -2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. - -``` -func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { return &VoteExtHandler{ logger: lg, mempool: mp, cdc: cdc, } } -``` - -3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) voteExtBids := [][]byte{} // Get mempool txs itr := h.mempool.SelectPending(context.Background(), nil) for itr != nil { tmptx := itr.Tx() sdkMsgs := tmptx.GetMsgs() // Iterate through msgs, check for any bids for _, msg := range sdkMsgs { switch msg := msg.(type) { case *nstypes.MsgBid: // Marshal sdk bids to []byte bz, err := h.cdc.Marshal(msg) if err != nil { h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) break } voteExtBids = append(voteExtBids, bz) default: } } // Move tx to ready pool err := h.mempool.Update(context.Background(), tmptx) // Remove tx from app side mempool if err != nil { h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) } itr = itr.Next() } // Create vote extension voteExt := AppVoteExtension{ Height: req.Height, Bids: voteExtBids, } // Encode Vote Extension bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("Error marshalling VE: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil} -``` - -4. Configure the handler in `app/app.go` as shown below - -``` -bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...)voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec)bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) -``` - -To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. - -To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: - -``` -if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } -``` - -This is how the whole function should look: - -``` -func (h *PrepareProposalHandler) PrepareProposalHandler() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) var proposalTxs [][]byte var txs []sdk.Tx // Get Vote Extensions if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } itr := h.mempool.Select(context.Background(), nil) for itr != nil { tmptx := itr.Tx() txs = append(txs, tmptx) itr = itr.Next() } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) if h.runProvider { tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) if err != nil { h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) } txs = tmpMsgs } for _, sdkTxs := range txs { txBytes, err := h.txConfig.TxEncoder()(sdkTxs) if err != nil { h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) } proposalTxs = append(proposalTxs, txBytes) } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) return &abci.ResponsePrepareProposal{Txs: proposalTxs}, nil }} -``` - -As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. - -5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. - -``` -func (h *ProcessProposalHandler) ProcessProposalHandler() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) // The first transaction will always be the Special Transaction numTxs := len(req.Txs) h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) if numTxs >= 1 { var st SpecialTransaction err = json.Unmarshal(req.Txs[0], &st) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) } if len(st.Bids) > 0 { h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) var bids []nstypes.MsgBid for i, b := range st.Bids { var bid nstypes.MsgBid h.Codec.Unmarshal(b, &bid) h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) bids = append(bids, bid) } // Validate Bids in Tx txs := req.Txs[1:] ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if !ok { h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. - -``` -func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) // Create empty response st := SpecialTransaction{ 0, [][]byte{}, } // Get Vote Ext for H-1 from Req voteExt := req.GetLocalLastCommit() votes := voteExt.Votes // Iterate through votes var ve AppVoteExtension for _, vote := range votes { // Unmarshal to AppExt err := json.Unmarshal(vote.VoteExtension, &ve) if err != nil { log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) } st.Height = int(ve.Height) // If Bids in VE, append to Special Transaction if len(ve.Bids) > 0 { log.Info("🛠️ :: Bids in VE") for _, b := range ve.Bids { st.Bids = append(st.Bids, b) } } } return st, nil} -``` - -7. Configure the `ProcessProposalHandler()` in app/app.go: - -``` -processPropHandler := abci2.ProcessProposalHandler{app.txConfig, appCodec, logger}bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) -``` - -This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. - -To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx deleted file mode 100644 index 9d0f910b..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Mitigating Front-running with Vote Extensions" -description: "Version: v0.50" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [Prerequisites](#prerequisites) -* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) -* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") - -Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. - -In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. - -### Implementing Structs for Vote Extensions[​](#implementing-structs-for-vote-extensions "Direct link to Implementing Structs for Vote Extensions") - -First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: - -``` -package abciimport ( //import the necessary files)type PrepareProposalHandler struct { logger log.Logger txConfig client.TxConfig cdc codec.Codec mempool *mempool.ThresholdMempool txProvider provider.TxProvider keyname string runProvider bool} -``` - -The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. - -``` -type ProcessProposalHandler struct { TxConfig client.TxConfig Codec codec.Codec Logger log.Logger} -``` - -After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 mempool *mempool.ThresholdMempool cdc codec.Codec} -``` - -This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. - -``` -type InjectedVoteExt struct { VoteExtSigner []byte Bids [][]byte}type InjectedVotes struct { Votes []InjectedVoteExt} -``` - -These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. - -``` -type AppVoteExtension struct { Height int64 Bids [][]byte} -``` - -This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. - -``` -type SpecialTransaction struct { Height int Bids [][]byte} -``` - -This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. - -### Implementing Handlers and Configuring Handlers[​](#implementing-handlers-and-configuring-handlers "Direct link to Implementing Handlers and Configuring Handlers") - -To establish the `VoteExtensionHandler`, follow these steps: - -1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. - -2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. - -``` -func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { return &VoteExtHandler{ logger: lg, mempool: mp, cdc: cdc, } } -``` - -3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) voteExtBids := [][]byte{} // Get mempool txs itr := h.mempool.SelectPending(context.Background(), nil) for itr != nil { tmptx := itr.Tx() sdkMsgs := tmptx.GetMsgs() // Iterate through msgs, check for any bids for _, msg := range sdkMsgs { switch msg := msg.(type) { case *nstypes.MsgBid: // Marshal sdk bids to []byte bz, err := h.cdc.Marshal(msg) if err != nil { h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) break } voteExtBids = append(voteExtBids, bz) default: } } // Move tx to ready pool err := h.mempool.Update(context.Background(), tmptx) // Remove tx from app side mempool if err != nil { h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) } itr = itr.Next() } // Create vote extension voteExt := AppVoteExtension{ Height: req.Height, Bids: voteExtBids, } // Encode Vote Extension bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("Error marshalling VE: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil} -``` - -4. Configure the handler in `app/app.go` as shown below - -``` -bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...)voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec)bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) -``` - -To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. - -To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: - -``` -if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } -``` - -This is how the whole function should look: - -``` -func (h *PrepareProposalHandler) PrepareProposalHandler() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) var proposalTxs [][]byte var txs []sdk.Tx // Get Vote Extensions if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } itr := h.mempool.Select(context.Background(), nil) for itr != nil { tmptx := itr.Tx() txs = append(txs, tmptx) itr = itr.Next() } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) if h.runProvider { tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) if err != nil { h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) } txs = tmpMsgs } for _, sdkTxs := range txs { txBytes, err := h.txConfig.TxEncoder()(sdkTxs) if err != nil { h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) } proposalTxs = append(proposalTxs, txBytes) } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) return &abci.ResponsePrepareProposal{Txs: proposalTxs}, nil }} -``` - -As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. - -5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. - -``` -func (h *ProcessProposalHandler) ProcessProposalHandler() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) // The first transaction will always be the Special Transaction numTxs := len(req.Txs) h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) if numTxs >= 1 { var st SpecialTransaction err = json.Unmarshal(req.Txs[0], &st) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) } if len(st.Bids) > 0 { h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) var bids []nstypes.MsgBid for i, b := range st.Bids { var bid nstypes.MsgBid h.Codec.Unmarshal(b, &bid) h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) bids = append(bids, bid) } // Validate Bids in Tx txs := req.Txs[1:] ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if !ok { h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. - -``` -func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) // Create empty response st := SpecialTransaction{ 0, [][]byte{}, } // Get Vote Ext for H-1 from Req voteExt := req.GetLocalLastCommit() votes := voteExt.Votes // Iterate through votes var ve AppVoteExtension for _, vote := range votes { // Unmarshal to AppExt err := json.Unmarshal(vote.VoteExtension, &ve) if err != nil { log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) } st.Height = int(ve.Height) // If Bids in VE, append to Special Transaction if len(ve.Bids) > 0 { log.Info("🛠️ :: Bids in VE") for _, b := range ve.Bids { st.Bids = append(st.Bids, b) } } } return st, nil} -``` - -7. Configure the `ProcessProposalHandler()` in app/app.go: - -``` -processPropHandler := abci2.ProcessProposalHandler{app.txConfig, appCodec, logger}bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) -``` - -This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. - -To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx deleted file mode 100644 index c4f53e42..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: "Understanding Front-Running and more" -description: "Version: v0.50" ---- - -## Introduction[​](#introduction "Direct link to Introduction") - -Blockchain technology is vulnerable to practices that can affect the fairness and security of the network. Two such practices are front-running and Maximal Extractable Value (MEV), which are important for blockchain participants to understand. - -## What is Front-Running?[​](#what-is-front-running "Direct link to What is Front-Running?") - -Front-running is when someone, such as a validator, uses their ability to see pending transactions to execute their own transactions first, benefiting from the knowledge of upcoming transactions. In nameservice auctions, a front-runner might place a higher bid before the original bid is confirmed, unfairly winning the auction. - -## Nameservices and Nameservice Auctions[​](#nameservices-and-nameservice-auctions "Direct link to Nameservices and Nameservice Auctions") - -Nameservices are human-readable identifiers on a blockchain, akin to internet domain names, that correspond to specific addresses or resources. They simplify interactions with typically long and complex blockchain addresses, allowing users to have a memorable and unique identifier for their blockchain address or smart contract. - -Nameservice auctions are the process by which these identifiers are bid on and acquired. To combat front-running—where someone might use knowledge of pending bids to place a higher bid first—mechanisms such as commit-reveal schemes, auction extensions, and fair sequencing are implemented. These strategies ensure a transparent and fair bidding process, reducing the potential for Maximal Extractable Value (MEV) exploitation. - -## What is Maximal Extractable Value (MEV)?[​](#what-is-maximal-extractable-value-mev "Direct link to What is Maximal Extractable Value (MEV)?") - -MEV is the highest value that can be extracted by manipulating the order of transactions within a block, beyond the standard block rewards and fees. This has become more prominent with the growth of decentralised finance (DeFi), where transaction order can greatly affect profits. - -## Implications of MEV[​](#implications-of-mev "Direct link to Implications of MEV") - -MEV can lead to: - -* **Network Security**: Potential centralisation, as those with more computational power might dominate the process, increasing the risk of attacks. -* **Market Fairness**: An uneven playing field where only a few can gain at the expense of the majority. -* **User Experience**: Higher fees and network congestion due to the competition for MEV. - -## Mitigating MEV and Front-Running[​](#mitigating-mev-and-front-running "Direct link to Mitigating MEV and Front-Running") - -Some solutions being developed to mitigate MEV and front-running, including: - -* **Time-delayed Transactions**: Random delays to make transaction timing unpredictable. -* **Private Transaction Pools**: Concealing transactions until they are mined. -* **Fair Sequencing Services**: Processing transactions in the order they are received. - -For this tutorial, we will be exploring the last solution, fair sequencing services, in the context of nameservice auctions. - -## Conclusion[​](#conclusion "Direct link to Conclusion") - -MEV and front-running are challenges to blockchain integrity and fairness. Ongoing innovation and implementation of mitigation strategies are crucial for the ecosystem's health and success. diff --git a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx b/docs/sdk/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx deleted file mode 100644 index 0578a98c..00000000 --- a/docs/sdk/v0.50/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: "Implementing Vote Extensions" -description: "Version: v0.50" ---- - -## Implement ExtendVote[​](#implement-extendvote "Direct link to Implement ExtendVote") - -First we’ll create the `OracleVoteExtension` struct, this is the object that will be marshaled as bytes and signed by the validator. - -In our example we’ll use JSON to marshal the vote extension for simplicity but we recommend to find an encoding that produces a smaller output, given that large vote extensions could impact CometBFT’s performance. Custom encodings and compressed bytes can be used out of the box. - -``` -// OracleVoteExtension defines the canonical vote extension structure.type OracleVoteExtension struct { Height int64 Prices map[string]math.LegacyDec} -``` - -Then we’ll create a `VoteExtensionsHandler` struct that contains everything we need to query for prices. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 // current block height lastPriceSyncTS time.Time // last time we synced prices providerTimeout time.Duration // timeout for fetching prices from providers providers map[string]Provider // mapping of provider name to provider (e.g. Binance -> BinanceProvider) providerPairs map[string][]keeper.CurrencyPair // mapping of provider name to supported pairs (e.g. Binance -> [ATOM/USD]) Keeper keeper.Keeper // keeper of our oracle module} -``` - -Finally, a function that returns `sdk.ExtendVoteHandler` is needed too, and this is where our vote extension logic will live. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { // here we'd have a helper function that gets all the prices and does a weighted average using the volume of each market prices := h.getAllVolumeWeightedPrices() voteExt := OracleVoteExtension{ Height: req.Height, Prices: prices, } bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("failed to marshal vote extension: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil }} -``` - -As you can see above, the creation of a vote extension is pretty simple and we just have to return bytes. CometBFT will handle the signing of these bytes for us. We ignored the process of getting the prices but you can see a more complete example [here:](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle/abci/vote_extensions.go) - -Here we’ll do some simple checks like: - -* Is the vote extension unmarshaled correctly? -* Is the vote extension for the right height? -* Some other validation, for example, are the prices from this extension too deviated from my own prices? Or maybe checks that can detect malicious behavior. - -``` -func (h *VoteExtHandler) VerifyVoteExtensionHandler() sdk.VerifyVoteExtensionHandler { return func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { var voteExt OracleVoteExtension err := json.Unmarshal(req.VoteExtension, &voteExt) if err != nil { return nil, fmt.Errorf("failed to unmarshal vote extension: %w", err) } if voteExt.Height != req.Height { return nil, fmt.Errorf("vote extension height does not match request height; expected: %d, got: %d", req.Height, voteExt.Height) } // Verify incoming prices from a validator are valid. Note, verification during // VerifyVoteExtensionHandler MUST be deterministic. For brevity and demo // purposes, we omit implementation. if err := h.verifyOraclePrices(ctx, voteExt.Prices); err != nil { return nil, fmt.Errorf("failed to verify oracle prices from validator %X: %w", req.ValidatorAddress, err) } return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil }} -``` - -## Implement PrepareProposal[​](#implement-prepareproposal "Direct link to Implement PrepareProposal") - -``` -type ProposalHandler struct { logger log.Logger keeper keeper.Keeper // our oracle module keeper valStore baseapp.ValidatorStore // to get the current validators' pubkeys} -``` - -And we create the struct for our “special tx”, that will contain the prices and the votes so validators can later re-check in ProcessPRoposal that they get the same result than the block’s proposer. With this we could also check if all the votes have been used by comparing the votes received in ProcessProposal. - -``` -type StakeWeightedPrices struct { StakeWeightedPrices map[string]math.LegacyDec ExtendedCommitInfo abci.ExtendedCommitInfo} -``` - -Now we create the `PrepareProposalHandler`. In this step we’ll first check if the vote extensions’ signatures are correct using a helper function called ValidateVoteExtensions from the baseapp package. - -``` -func (h *ProposalHandler) PrepareProposal() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), req.LocalLastCommit) if err != nil { return nil, err }... -``` - -Then we proceed to make the calculations only if the current height if higher than the height at which vote extensions have been enabled. Remember that vote extensions are made available to the block proposer on the next block at which they are produced/enabled. - -``` -... proposalTxs := req.Txs if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, req.LocalLastCommit) if err != nil { return nil, errors.New("failed to compute stake-weighted oracle prices") } injectedVoteExtTx := StakeWeightedPrices{ StakeWeightedPrices: stakeWeightedPrices, ExtendedCommitInfo: req.LocalLastCommit, }... -``` - -Finally we inject the result as a transaction at a specific location, usually at the beginning of the block: - -## Implement ProcessProposal[​](#implement-processproposal "Direct link to Implement ProcessProposal") - -Now we can implement the method that all validators will execute to ensure the proposer is doing his work correctly. - -Here, if vote extensions are enabled, we’ll check if the tx at index 0 is an injected vote extension - -``` -func (h *ProposalHandler) ProcessProposal() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { var injectedVoteExtTx StakeWeightedPrices if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { h.logger.Error("failed to decode injected vote extension tx", "err", err) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil }... -``` - -Then we re-validate the vote extensions signatures using baseapp.ValidateVoteExtensions, re-calculate the results (just like in PrepareProposal) and compare them with the results we got from the injected tx. - -``` - err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), injectedVoteExtTx.ExtendedCommitInfo) if err != nil { return nil, err } // Verify the proposer's stake-weighted oracle prices by computing the same // calculation and comparing the results. We omit verification for brevity // and demo purposes. stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, injectedVoteExtTx.ExtendedCommitInfo) if err != nil { return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if err := compareOraclePrices(injectedVoteExtTx.StakeWeightedPrices, stakeWeightedPrices); err != nil { return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -Important: In this example we avoided using the mempool and other basics, please refer to the DefaultProposalHandler for a complete implementation: [https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/abci\_utils.go](https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/abci_utils.go) - -## Implement PreBlocker[​](#implement-preblocker "Direct link to Implement PreBlocker") - -Now validators are extending their vote, verifying other votes and including the result in the block. But how do we actually make use of this result? This is done in the PreBlocker which is code that is run before any other code during FinalizeBlock so we make sure we make this information available to the chain and its modules during the entire block execution (from BeginBlock). - -At this step we know that the injected tx is well-formatted and has been verified by the validators participating in consensus, so making use of it is straightforward. Just check if vote extensions are enabled, pick up the first transaction and use a method in your module’s keeper to set the result. - -``` -func (h *ProposalHandler) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { res := &sdk.ResponsePreBlock{} if len(req.Txs) == 0 { return res, nil } if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { var injectedVoteExtTx StakeWeightedPrices if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { h.logger.Error("failed to decode injected vote extension tx", "err", err) return nil, err } // set oracle prices using the passed in context, which will make these prices available in the current block if err := h.keeper.SetOraclePrices(ctx, injectedVoteExtTx.StakeWeightedPrices); err != nil { return nil, err } } return res, nil} -``` - -## Conclusion[​](#conclusion "Direct link to Conclusion") - -In this tutorial, we've created a simple price oracle module that incorporates vote extensions. We've seen how to implement `ExtendVote`, `VerifyVoteExtension`, `PrepareProposal`, `ProcessProposal`, and `PreBlocker` to handle the voting and verification process of vote extensions, as well as how to make use of the results during the block execution. diff --git a/docs/sdk/v0.50/user/run-node/run-node.mdx b/docs/sdk/v0.50/user/run-node/run-node.mdx index 0020856b..22b09dc0 100644 --- a/docs/sdk/v0.50/user/run-node/run-node.mdx +++ b/docs/sdk/v0.50/user/run-node/run-node.mdx @@ -100,9 +100,9 @@ One example config to tweak is the `minimum-gas-prices` field inside `app.toml`, When running a node (not a validator!) and not wanting to run the application mempool, set the `max-txs` field to `-1`. - ``` +``` [mempool]# Setting max-txs to 0 will allow for a unbounded amount of transactions in the mempool.# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool.# Setting max_txs to a positive number (> 0) will limit the number of transactions in the mempool, by the specified amount.## Note, this configuration only applies to SDK built-in app-side mempool# implementations.max-txs = "-1" - ``` +``` ## Run a Localnet[​](#run-a-localnet "Direct link to Run a Localnet") diff --git a/docs/sdk/v0.50/user/run-node/run-production.mdx b/docs/sdk/v0.50/user/run-node/run-production.mdx index 730a8c8e..372af34f 100644 --- a/docs/sdk/v0.50/user/run-node/run-production.mdx +++ b/docs/sdk/v0.50/user/run-node/run-production.mdx @@ -212,9 +212,9 @@ vim $HOME/.simd/config/config.tomlpriv_validator_laddr = "tcp://0.0.0.0:26659" It is recommended to comment or delete the lines that specify the path of the validator key and validator: - ``` +``` # Path to the JSON file containing the private key to use as a validator in the consensus protocol# priv_validator_key_file = "config/priv_validator_key.json"# Path to the JSON file containing the last sign state of a validator# priv_validator_state_file = "data/priv_validator_state.json" - ``` +``` 6. Start the two processes. diff --git a/docs/sdk/v0.50/user/run-node/txs.mdx b/docs/sdk/v0.50/user/run-node/txs.mdx index faf3c06a..a07aec1d 100644 --- a/docs/sdk/v0.50/user/run-node/txs.mdx +++ b/docs/sdk/v0.50/user/run-node/txs.mdx @@ -179,7 +179,7 @@ It is not possible to generate or sign a transaction using gRPC, only to broadca Broadcasting a transaction using the gRPC endpoint can be done by sending a `BroadcastTx` request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -grpcurl -plaintext \ -d '{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx +grpcurl -plaintext \ -d '{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx ``` ## Using REST[​](#using-rest "Direct link to Using REST") @@ -191,7 +191,7 @@ It is not possible to generate or sign a transaction using REST, only to broadca Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) can be done by sending a POST request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs +curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs ``` ## Using CosmJS (JavaScript & TypeScript)[​](#using-cosmjs-javascript--typescript "Direct link to Using CosmJS (JavaScript & TypeScript)") diff --git a/docs/sdk/v0.53/apis-clients/autocli.mdx b/docs/sdk/v0.53/apis-clients/autocli.mdx index f2a9e5c4..86f0c92a 100644 --- a/docs/sdk/v0.53/apis-clients/autocli.mdx +++ b/docs/sdk/v0.53/apis-clients/autocli.mdx @@ -53,9 +53,9 @@ Here's an example of how to use `autocli` in your app: AutoCLI provides a better UX than normal CLI as it allows to resolve key names directly from the keyring in all transactions and commands. - ``` +``` q bank balances alice tx bank send alice bob 1000denom - ``` +``` The keyring used for resolving names and signing transactions is provided via the `client.Context`. The keyring is then converted to the `client/v2/autocli/keyring` interface. If no keyring is provided, the `autocli` generated command will not be able to sign transactions, but will still be able to query the chain. @@ -63,9 +63,9 @@ The keyring used for resolving names and signing transactions is provided via th The Cosmos SDK keyring and Hubl keyring both implement the `client/v2/autocli/keyring` interface, thanks to the following wrapper: - ``` +``` keyring.NewAutoCLIKeyring(kb) - ``` +``` ## Signing[​](#signing "Direct link to Signing") diff --git a/docs/sdk/v0.53/apis-clients/cli.mdx b/docs/sdk/v0.53/apis-clients/cli.mdx index ae1447ba..11922cdf 100644 --- a/docs/sdk/v0.53/apis-clients/cli.mdx +++ b/docs/sdk/v0.53/apis-clients/cli.mdx @@ -210,7 +210,7 @@ The `InterceptConfigsPreRunHandler` call creates a viper literal, default `serve When willing to configure which logger is used, do not use `InterceptConfigsPreRunHandler`, which sets the default SDK logger, but instead use `InterceptConfigsAndCreateContext` and set the server context and the logger manually: - ``` +``` -return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig)+serverCtx, err := server.InterceptConfigsAndCreateContext(cmd, customAppTemplate, customAppConfig, customCMTConfig)+if err != nil {+ return err+}+// overwrite default server logger+logger, err := server.CreateSDKLogger(serverCtx, cmd.OutOrStdout())+if err != nil {+ return err+}+serverCtx.Logger = logger.With(log.ModuleKey, "server")+// set server context+return server.SetCmdServerContext(cmd, serverCtx) - ``` +``` diff --git a/docs/sdk/v0.53/apis-clients/grpc_rest.mdx b/docs/sdk/v0.53/apis-clients/grpc_rest.mdx index aa196f2a..61c23bd5 100644 --- a/docs/sdk/v0.53/apis-clients/grpc_rest.mdx +++ b/docs/sdk/v0.53/apis-clients/grpc_rest.mdx @@ -66,7 +66,7 @@ All routes are configured under the following fields in `~/.simapp/config/app.to If, for various reasons, you cannot use gRPC (for example, you are building a web application, and browsers don't support HTTP2 on which gRPC is built), then the Cosmos SDK offers REST routes via gRPC-gateway. -[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway `"/cosmos/bank/v1beta1/balances/{address}"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: +[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each gRPC endpoint defined in a Protobuf `Query` service, the Cosmos SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.QueryAllBalances` gRPC endpoint, or alternatively via the gRPC-gateway ``"/cosmos/bank/v1beta1/balances/``{address}```"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf `Query` service, the corresponding REST endpoint is defined as an option: proto/cosmos/bank/v1beta1/query.proto @@ -97,8 +97,8 @@ Some CometBFT RPC endpoints are directly related to the Cosmos SDK: * any Protobuf fully-qualified service method, such as `/cosmos.bank.v1beta1.Query/AllBalances`. The `data` field should then include the method's request parameter(s) encoded as bytes using Protobuf. * `/app/simulate`: this will simulate a transaction, and return some information such as gas used. * `/app/version`: this will return the application's version. - * `/store/{storeName}/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. - * `/store/{storeName}/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. + * ``/store/``{storeName}```/key`: this will directly query the named store for data associated with the key represented in the `data` parameter. + * ``/store/``{storeName}```/subspace`: this will directly query the named store for key/value pairs in which the key has the value of the `data` parameter as a prefix. * `/p2p/filter/addr/{port}`: this will return a filtered list of the node's P2P peers by address port. * `/p2p/filter/id/{id}`: this will return a filtered list of the node's P2P peers by ID. diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx index 7906406c..3aa5fa87 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-go-di.mdx @@ -31,7 +31,7 @@ The `app_config.go` file is the single place to configure all modules parameters 1. Create the `AppConfig` variable: ```go reference - https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L289-L303 +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go#L289-L303 ``` Where the `appConfig` combines the [runtime](/docs/sdk/v0.53/00-runtime.md) configuration and the (extra) modules configuration. @@ -66,7 +66,6 @@ The `app_config.go` file is the single place to configure all modules parameters See the complete `app_config.go` file for `SimApp` [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/simapp/app_config.go). ### Alternative formats - ```go ``` @@ -141,8 +140,11 @@ app.App = appBuilder.Build(db, traceStore, baseAppOptions...) // register module manually app.RegisterStores(storetypes.NewKVStoreKey(example.ModuleName)) + app.ExampleKeeper = examplekeeper.NewKeeper(app.appCodec, app.AccountKeeper.AddressCodec(), runtime.NewKVStoreService(app.GetKey(example.ModuleName)), authtypes.NewModuleAddress(govtypes.ModuleName).String()) + exampleAppModule := examplemodule.NewAppModule(app.ExampleKeeper) + if err := app.RegisterModules(&exampleAppModule); err != nil { panic(err) } diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx index af678dc7..fefda1ee 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-mempool.mdx @@ -35,7 +35,9 @@ By default, the SDK uses the [No-op Mempool](#no-op-mempool), but it can be repl ```go nonceMempool := mempool.NewSenderNonceMempool() + mempoolOpt := baseapp.SetMempool(nonceMempool) + baseAppOptions = append(baseAppOptions, mempoolOpt) ``` diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx index 06766c78..823c0a6f 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-testnet.mdx @@ -13,12 +13,13 @@ We allow developers to take the state from their mainnet and run tests against t We will be breaking down the steps to create a testnet from mainnet state. ```go - // InitSimAppForTestnet is broken down into two sections: +// InitSimAppForTestnet is broken down into two sections: // Required Changes: Changes that, if not made, will cause the testnet to halt or panic // Optional Changes: Changes to customize the testnet to one's liking (lower vote times, fund accounts, etc) - func InitSimAppForTestnet(app *SimApp, newValAddr bytes.HexBytes, newValPubKey crypto.PubKey, newOperatorAddress, upgradeToTrigger string) *SimApp { + +func InitSimAppForTestnet(app *SimApp, newValAddr bytes.HexBytes, newValPubKey crypto.PubKey, newOperatorAddress, upgradeToTrigger string) *SimApp { ... - } +} ``` ### Required Changes @@ -28,72 +29,87 @@ We will be breaking down the steps to create a testnet from mainnet state. When creating a testnet the important part is migrate the validator set from many validators to one or a few. This allows developers to spin up the chain without needing to replace validator keys. ```go - ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) - pubkey := &ed25519.PubKey{Key: newValPubKey.Bytes()} +ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{ +}) + +pubkey := &ed25519.PubKey{ + Key: newValPubKey.Bytes() +} pubkeyAny, err := types.NewAnyWithValue(pubkey) - if err != nil { - tmos.Exit(err.Error()) - } + +if err != nil { + tmos.Exit(err.Error()) +} // STAKING // // Create Validator struct for our new validator. _, bz, err := bech32.DecodeAndConvert(newOperatorAddress) - if err != nil { - tmos.Exit(err.Error()) - } + +if err != nil { + tmos.Exit(err.Error()) +} bech32Addr, err := bech32.ConvertAndEncode("simvaloper", bz) - if err != nil { - tmos.Exit(err.Error()) - } + +if err != nil { + tmos.Exit(err.Error()) +} newVal := stakingtypes.Validator{ - OperatorAddress: bech32Addr, + OperatorAddress: bech32Addr, ConsensusPubkey: pubkeyAny, Jailed: false, Status: stakingtypes.Bonded, Tokens: sdk.NewInt(900000000000000), DelegatorShares: sdk.MustNewDecFromStr("10000000"), Description: stakingtypes.Description{ - Moniker: "Testnet Validator", - }, + Moniker: "Testnet Validator", +}, Commission: stakingtypes.Commission{ - CommissionRates: stakingtypes.CommissionRates{ - Rate: sdk.MustNewDecFromStr("0.05"), + CommissionRates: stakingtypes.CommissionRates{ + Rate: sdk.MustNewDecFromStr("0.05"), MaxRate: sdk.MustNewDecFromStr("0.1"), MaxChangeRate: sdk.MustNewDecFromStr("0.05"), - }, - }, +}, +}, MinSelfDelegation: sdk.OneInt(), - } +} // Remove all validators from power store stakingKey := app.GetKey(stakingtypes.ModuleName) - stakingStore := ctx.KVStore(stakingKey) - iterator := app.StakingKeeper.ValidatorsPowerStoreIterator(ctx) - for ; iterator.Valid(); iterator.Next() { - stakingStore.Delete(iterator.Key()) - } + +stakingStore := ctx.KVStore(stakingKey) + +iterator := app.StakingKeeper.ValidatorsPowerStoreIterator(ctx) + +for ; iterator.Valid(); iterator.Next() { + stakingStore.Delete(iterator.Key()) +} iterator.Close() // Remove all validators from last validators store iterator = app.StakingKeeper.LastValidatorsIterator(ctx) - for ; iterator.Valid(); iterator.Next() { - app.StakingKeeper.LastValidatorPower.Delete(iterator.Key()) - } + +for ; iterator.Valid(); iterator.Next() { + app.StakingKeeper.LastValidatorPower.Delete(iterator.Key()) +} iterator.Close() // Add our validator to power and last validators store app.StakingKeeper.SetValidator(ctx, newVal) - err = app.StakingKeeper.SetValidatorByConsAddr(ctx, newVal) - if err != nil { - panic(err) - } + +err = app.StakingKeeper.SetValidatorByConsAddr(ctx, newVal) + +if err != nil { + panic(err) +} app.StakingKeeper.SetValidatorByPowerIndex(ctx, newVal) - app.StakingKeeper.SetLastValidatorPower(ctx, newVal.GetOperator(), 0) - if err := app.StakingKeeper.Hooks().AfterValidatorCreated(ctx, newVal.GetOperator()); err != nil { - panic(err) - } + +app.StakingKeeper.SetLastValidatorPower(ctx, newVal.GetOperator(), 0) + +if err := app.StakingKeeper.Hooks().AfterValidatorCreated(ctx, newVal.GetOperator()); err != nil { + panic(err) +} ``` #### Distribution @@ -101,11 +117,18 @@ When creating a testnet the important part is migrate the validator set from man Since the validator set has changed, we need to update the distribution records for the new validator. ```go - // Initialize records for this validator across all distribution stores - app.DistrKeeper.ValidatorHistoricalRewards.Set(ctx, newVal.GetOperator(), 0, distrtypes.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1)) - app.DistrKeeper.ValidatorCurrentRewards.Set(ctx, newVal.GetOperator(), distrtypes.NewValidatorCurrentRewards(sdk.DecCoins{}, 1)) - app.DistrKeeper.ValidatorAccumulatedCommission.Set(ctx, newVal.GetOperator(), distrtypes.InitialValidatorAccumulatedCommission()) - app.DistrKeeper.ValidatorOutstandingRewards.Set(ctx, newVal.GetOperator(), distrtypes.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}}) +// Initialize records for this validator across all distribution stores + app.DistrKeeper.ValidatorHistoricalRewards.Set(ctx, newVal.GetOperator(), 0, distrtypes.NewValidatorHistoricalRewards(sdk.DecCoins{ +}, 1)) + +app.DistrKeeper.ValidatorCurrentRewards.Set(ctx, newVal.GetOperator(), distrtypes.NewValidatorCurrentRewards(sdk.DecCoins{ +}, 1)) + +app.DistrKeeper.ValidatorAccumulatedCommission.Set(ctx, newVal.GetOperator(), distrtypes.InitialValidatorAccumulatedCommission()) + +app.DistrKeeper.ValidatorOutstandingRewards.Set(ctx, newVal.GetOperator(), distrtypes.ValidatorOutstandingRewards{ + Rewards: sdk.DecCoins{ +}}) ``` #### Slashing @@ -113,16 +136,17 @@ Since the validator set has changed, we need to update the distribution records We also need to set the validator signing info for the new validator. ```go - // SLASHING +// SLASHING // // Set validator signing info for our new validator. newConsAddr := sdk.ConsAddress(newValAddr.Bytes()) - newValidatorSigningInfo := slashingtypes.ValidatorSigningInfo{ - Address: newConsAddr.String(), + +newValidatorSigningInfo := slashingtypes.ValidatorSigningInfo{ + Address: newConsAddr.String(), StartHeight: app.LastBlockHeight() - 1, Tombstoned: false, - } +} app.SlashingKeeper.ValidatorSigningInfo.Set(ctx, newConsAddr, newValidatorSigningInfo) ``` @@ -131,13 +155,13 @@ We also need to set the validator signing info for the new validator. It is useful to create new accounts for your testing purposes. This avoids the need to have the same key as you may have on mainnet. ```go - // BANK +// BANK // defaultCoins := sdk.NewCoins(sdk.NewInt64Coin("ustake", 1000000000000)) - localSimAppAccounts := []sdk.AccAddress{ - sdk.MustAccAddressFromBech32("cosmos12smx2wdlyttvyzvzg54y2vnqwq2qjateuf7thj"), +localSimAppAccounts := []sdk.AccAddress{ + sdk.MustAccAddressFromBech32("cosmos12smx2wdlyttvyzvzg54y2vnqwq2qjateuf7thj"), sdk.MustAccAddressFromBech32("cosmos1cyyzpxplxdzkeea7kwsydadg87357qnahakaks"), sdk.MustAccAddressFromBech32("cosmos18s5lynnmx37hq4wlrw9gdn68sg2uxp5rgk26vv"), sdk.MustAccAddressFromBech32("cosmos1qwexv7c6sm95lwhzn9027vyu2ccneaqad4w8ka"), @@ -148,19 +172,23 @@ It is useful to create new accounts for your testing purposes. This avoids the n sdk.MustAccAddressFromBech32("cosmos1f4tvsdukfwh6s9swrc24gkuz23tp8pd3e9r5fa"), sdk.MustAccAddressFromBech32("cosmos1myv43sqgnj5sm4zl98ftl45af9cfzk7nhjxjqh"), sdk.MustAccAddressFromBech32("cosmos14gs9zqh8m49yy9kscjqu9h72exyf295afg6kgk"), - sdk.MustAccAddressFromBech32("cosmos1jllfytsz4dryxhz5tl7u73v29exsf80vz52ucc")} + sdk.MustAccAddressFromBech32("cosmos1jllfytsz4dryxhz5tl7u73v29exsf80vz52ucc") +} // Fund localSimApp accounts for _, account := range localSimAppAccounts { - err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, defaultCoins) - if err != nil { - tmos.Exit(err.Error()) - } + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, defaultCoins) + +if err != nil { + tmos.Exit(err.Error()) +} err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, account, defaultCoins) - if err != nil { - tmos.Exit(err.Error()) - } - } + +if err != nil { + tmos.Exit(err.Error()) +} + +} ``` #### Upgrade @@ -168,19 +196,22 @@ It is useful to create new accounts for your testing purposes. This avoids the n If you would like to schedule an upgrade the below can be used. ```go - // UPGRADE +// UPGRADE // - if upgradeToTrigger != "" { - upgradePlan := upgradetypes.Plan{ - Name: upgradeToTrigger, + if upgradeToTrigger != " + " { + upgradePlan := upgradetypes.Plan{ + Name: upgradeToTrigger, Height: app.LastBlockHeight(), - } +} err = app.UpgradeKeeper.ScheduleUpgrade(ctx, upgradePlan) - if err != nil { - panic(err) - } - } + +if err != nil { + panic(err) +} + +} ``` ### Optional Changes @@ -194,7 +225,7 @@ Before we can run the testnet we must plug everything together. in `root.go`, in the `initRootCmd` function we add: ```diff - server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, createSimAppAndExport, addModuleInitFlags) +server.AddCommands(rootCmd, simapp.DefaultNodeHome, newApp, createSimAppAndExport, addModuleInitFlags) ++ server.AddTestnetCreatorCommand(rootCmd, simapp.DefaultNodeHome, newTestnetApp, addModuleInitFlags) ``` @@ -208,25 +239,25 @@ func newTestnetApp(logger log.Logger, db cometbftdb.DB, traceStore io.Writer, ap app := newApp(logger, db, traceStore, appOpts) simApp, ok := app.(*simapp.SimApp) if !ok { - panic("app created from newApp is not of type simApp") - } + panic("app created from newApp is not of type simApp") +} newValAddr, ok := appOpts.Get(server.KeyNewValAddr).(bytes.HexBytes) if !ok { - panic("newValAddr is not of type bytes.HexBytes") - } + panic("newValAddr is not of type bytes.HexBytes") +} newValPubKey, ok := appOpts.Get(server.KeyUserPubKey).(crypto.PubKey) if !ok { - panic("newValPubKey is not of type crypto.PubKey") - } + panic("newValPubKey is not of type crypto.PubKey") +} newOperatorAddress, ok := appOpts.Get(server.KeyNewOpAddr).(string) if !ok { - panic("newOperatorAddress is not of type string") - } + panic("newOperatorAddress is not of type string") +} upgradeToTrigger, ok := appOpts.Get(server.KeyTriggerTestnetUpgrade).(string) if !ok { - panic("upgradeToTrigger is not of type string") - } + panic("upgradeToTrigger is not of type string") +} // Make modifications to the normal SimApp required to run the network locally return simapp.InitSimAppForTestnet(simApp, newValAddr, newValPubKey, newOperatorAddress, upgradeToTrigger) diff --git a/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx index f4e3560a..574b634b 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/app-upgrade.mdx @@ -62,10 +62,10 @@ keeper's PreBlocker method: ```go func (app *myApp) PreBlocker(ctx sdk.Context, req req.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { - // For demonstration sake, the app PreBlocker only returns the upgrade module pre-blocker. - // In a real app, the module manager should call all pre-blockers - // return app.ModuleManager.PreBlock(ctx, req) - return app.upgradeKeeper.PreBlocker(ctx, req) + // For demonstration sake, the app PreBlocker only returns the upgrade module pre-blocker. + // In a real app, the module manager should call all pre-blockers + // return app.ModuleManager.PreBlock(ctx, req) + return app.upgradeKeeper.PreBlocker(ctx, req) } ``` @@ -98,18 +98,21 @@ Here is a sample code to set store migrations with an upgrade: app.UpgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx context.Context, plan upgrade.Plan) { // upgrade changes here }) + upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { // handle error } if upgradeInfo.Name == "my-fancy-upgrade" && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := store.StoreUpgrades{ - Renamed: []store.StoreRename{{ - OldKey: "foo", + storeUpgrades := store.StoreUpgrades{ + Renamed: []store.StoreRename{{ + OldKey: "foo", NewKey: "bar", - }}, - Deleted: []string{}, - } +}}, + Deleted: []string{ +}, +} // configure store loader that checks if version == upgradeHeight and applies store upgrades app.SetStoreLoader(upgrade.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) } @@ -121,7 +124,7 @@ Before halting the ABCI state machine in the BeginBlocker method, the upgrade mo that looks like: ```text - UPGRADE "" NEEDED at height : +UPGRADE "" NEEDED at height : ``` where `Name` and `Info` are the values of the respective fields on the upgrade Plan. @@ -185,24 +188,24 @@ Here is a sample structure of the `pre-upgrade` command: ```go func preUpgradeCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "pre-upgrade", - Short: "Pre-upgrade command", - Long: "Pre-upgrade command to implement custom pre-upgrade handling", - Run: func(cmd *cobra.Command, args []string) { + cmd := &cobra.Command{ + Use: "pre-upgrade", + Short: "Pre-upgrade command", + Long: "Pre-upgrade command to implement custom pre-upgrade handling", + Run: func(cmd *cobra.Command, args []string) { - err := HandlePreUpgrade() + err := HandlePreUpgrade() - if err != nil { - os.Exit(30) - } + if err != nil { + os.Exit(30) + } - os.Exit(0) + os.Exit(0) - }, - } + }, + } - return cmd + return cmd } ``` diff --git a/docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx b/docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx index dc758e85..5bb0f452 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/baseapp.mdx @@ -355,9 +355,9 @@ loading... baseapp/baseapp.go - ``` +``` loading... - ``` +``` [See full example on GitHub](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L746-L770) diff --git a/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx index 9b531b00..82c5f1f8 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/runtime.mdx @@ -19,12 +19,12 @@ The runtime App struct contains several key components: ```go type App struct { - *baseapp.BaseApp - ModuleManager *module.Manager - configurator module.Configurator - config *runtimev1alpha1.Module - storeKeys []storetypes.StoreKey - // ... other fields + *baseapp.BaseApp + ModuleManager *module.Manager + configurator module.Configurator + config *runtimev1alpha1.Module + storeKeys []storetypes.StoreKey + // ... other fields } ``` @@ -86,7 +86,11 @@ Even when using manual registration, the module should still be configured in th ```go -func (a *App) RegisterModules(modules ...module.AppModule) error +func (a *App) + +RegisterModules(modules ...module.AppModule) + +error ``` The SDK recommends using the declarative approach with `depinject` for module registration whenever possible. diff --git a/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx index 8328d64f..35bacf31 100644 --- a/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx +++ b/docs/sdk/v0.53/app-wiring-runtime/vote-extensions.mdx @@ -79,28 +79,31 @@ An example of how a pre-FinalizeBlock hook could look like is shown below: ```go app.SetPreBlocker(func(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { - allVEs := []VE{} // store all parsed vote extensions here + allVEs := []VE{ +} // store all parsed vote extensions here for _, tx := range req.Txs { // define a custom function that tries to parse the tx as a vote extension ve, ok := parseVoteExtension(tx) - if !ok { - continue - } + +if !ok { + continue +} allVEs = append(allVEs, ve) - } +} // perform any necessary computation on the vote extensions and store the result // in the cached store result := compute(allVEs) - err := storeVEResult(ctx, result) - if err != nil { - return err - } + +err := storeVEResult(ctx, result) + +if err != nil { + return err +} return nil }) - ``` Then, in an app's module, the application can retrieve the result of the computation @@ -108,15 +111,15 @@ of vote extensions from the cached store: ```go func (k Keeper) BeginBlocker(ctx context.Context) error { - // retrieve the result of the computation of vote extensions from the cached store - result, err := k.GetVEResult(ctx) - if err != nil { - return err - } + // retrieve the result of the computation of vote extensions from the cached store + result, err := k.GetVEResult(ctx) + if err != nil { + return err + } - // use the result of the computation of vote extensions - k.setSomething(result) + // use the result of the computation of vote extensions + k.setSomething(result) - return nil + return nil } ``` diff --git a/docs/sdk/v0.53/build.mdx b/docs/sdk/v0.53/build.mdx deleted file mode 100644 index c70fc97b..00000000 --- a/docs/sdk/v0.53/build.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: "Build" -description: "Version: v0.53" ---- - -* [Building Apps](./build/building-apps/app-go) - The documentation in this section will guide you through the process of developing your dApp using the Cosmos SDK framework. -* [Modules](./build/modules) - Information about the various modules available in the Cosmos SDK: Auth, Authz, Bank, Circuit, Consensus, Distribution, Epochs, Evidence, Feegrant, Governance, Group, Mint, NFT, Protocolpool, Slashing, Staking, Upgrade, Genutil. -* [Migrations](./build/migrations/intro) - See what has been updated in each release the process of the transition between versions. -* [Packages](./build/packages) - Explore a curated collection of pre-built modules and functionalities, streamlining the development process. -* [Tooling](./build/tooling) - A suite of utilities designed to enhance the development workflow, optimizing the efficiency of Cosmos SDK-based projects. -* [ADR's](./build/architecture) - Provides a structured repository of key decisions made during the development process, which have been documented and offers rationale behind key decisions being made. -* [REST API](https://docs.cosmos.network/api) - A comprehensive reference for the application programming interfaces (APIs) provided by the SDK. diff --git a/docs/sdk/v0.53/changelog/release-notes.mdx b/docs/sdk/v0.53/changelog/release-notes.mdx index e723019e..1c4b08c5 100644 --- a/docs/sdk/v0.53/changelog/release-notes.mdx +++ b/docs/sdk/v0.53/changelog/release-notes.mdx @@ -1,508 +1,6 @@ --- title: "Release Notes" description: "Cosmos SDK release notes and changelog" -mode: "custom" --- - - - {/* - - Guiding Principles: - - Changelogs are for humans, not machines. - - There should be an entry for every single version. - - The same types of changes should be grouped. - - Versions and sections should be linkable. - - The latest version comes first. - - The release date of each version is displayed. - - Mention whether you follow Semantic Versioning. - - Usage: - - Change log entries are to be added to the Unreleased section under the - - appropriate stanza (see below). Each entry is required to include a tag and - - the Github issue reference in the following format: - - * () \# message - - The tag should consist of where the change is being made ex. (x/staking), (store) - - The issue numbers will later be link-ified during the release process so you do - - not have to worry about including a link manually, but you can if you wish. - - Types of changes (Stanzas): - - "Features" for new features. - - "Improvements" for changes in existing functionality. - - "Deprecated" for soon-to-be removed features. - - "Bug Fixes" for any bug fixes. - - "Client Breaking" for breaking Protobuf, gRPC and REST routes used by end-users. - - "CLI Breaking" for breaking CLI commands. - - "API Breaking" for breaking exported APIs used by developers building on SDK. - - "State Machine Breaking" for any changes that result in a different AppState given same genesisState and txList. - - Ref: https://keepachangelog.com/en/1.0.0/ - - */} - - # Changelog - - ## [v0.53.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.3) - 2025-07-25 - - This patch update also includes minor dependency bumps. - - ### Features - - * (abci_utils) [#25008](https://github.com/cosmos/cosmos-sdk/pull/24861) add the ability to assign a custom signer extraction adapter in `DefaultProposalHandler`. - - ## [v0.53.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.3) - 2025-07-08 - - ### Bug Fixes - - * [GHSA-p22h-3m2v-cmgh](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-p22h-3m2v-cmgh) Fix x/distribution can halt when historical rewards overflow. - - ## [v0.53.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.2) - 2025-06-02 - - This patch update also includes minor dependency bumps. - - ### Bug Fixes - - * (x/epochs) [#24770](https://github.com/cosmos/cosmos-sdk/pull/24770) Fix register of epoch hooks in `InvokeSetHooks`. - - ## [v0.53.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.53.0) - 2025-04-29 - - ### Features - - * (simsx) [#24062](https://github.com/cosmos/cosmos-sdk/pull/24062) [#24145](https://github.com/cosmos/cosmos-sdk/pull/24145) Add new simsx framework on top of simulations for better module dev experience. - - * (baseapp) [#24069](https://github.com/cosmos/cosmos-sdk/pull/24069) Create CheckTxHandler to allow extending the logic of CheckTx. - - * (types) [#24093](https://github.com/cosmos/cosmos-sdk/pull/24093) Added a new method, `IsGT`, for `types.Coin`. This method is used to check if a `types.Coin` is greater than another `types.Coin`. - - * (client/keys) [#24071](https://github.com/cosmos/cosmos-sdk/pull/24071) Add support for importing hex key using standard input. - - * (types) [#23780](https://github.com/cosmos/cosmos-sdk/pull/23780) Add a ValueCodec for the math.Uint type that can be used in collections maps. - - * (perf)[#24045](https://github.com/cosmos/cosmos-sdk/pull/24045) Sims: Replace runsim command with Go stdlib testing. CLI: `Commit` default true, `Lean`, `SimulateEveryOperation`, `PrintAllInvariants`, `DBBackend` params removed - - * (crypto/keyring) [#24040](https://github.com/cosmos/cosmos-sdk/pull/24040) Expose the db keyring used in the keystore. - - * (types) [#23919](https://github.com/cosmos/cosmos-sdk/pull/23919) Add MustValAddressFromBech32 function. - - * (all) [#23708](https://github.com/cosmos/cosmos-sdk/pull/23708) Add unordered transaction support. - - * Adds a `--timeout-timestamp` flag that allows users to specify a block time at which the unordered transactions should expire from the mempool. - - * (x/epochs) [#23815](https://github.com/cosmos/cosmos-sdk/pull/23815) Upstream `x/epochs` from Osmosis - - * (client) [#23811](https://github.com/cosmos/cosmos-sdk/pull/23811) Add auto cli for node service. - - * (genutil) [#24018](https://github.com/cosmos/cosmos-sdk/pull/24018) Allow manually setting the consensus key type in genesis - - * (client) [#18557](https://github.com/cosmos/cosmos-sdk/pull/18557) Add `--qrcode` flag to `keys show` command to support displaying keys address QR code. - - * (x/auth) [#24030](https://github.com/cosmos/cosmos-sdk/pull/24030) Allow usage of ed25519 keys for transaction signing. - - * (baseapp) [#24163](https://github.com/cosmos/cosmos-sdk/pull/24163) Add `StreamingManager` to baseapp to extend the abci listeners. - - * (x/protocolpool) [#23933](https://github.com/cosmos/cosmos-sdk/pull/23933) Add x/protocolpool module. - - * x/distribution can now utilize an externally managed community pool. NOTE: this will make the message handlers for FundCommunityPool and CommunityPoolSpend error, as well as the query handler for CommunityPool. - - * (client) [#18101](https://github.com/cosmos/cosmos-sdk/pull/18101) Add a `keyring-default-keyname` in `client.toml` for specifying a default key name, and skip the need to use the `--from` flag when signing transactions. - - * (x/gov) [#24355](https://github.com/cosmos/cosmos-sdk/pull/24355) Allow users to set a custom CalculateVoteResultsAndVotingPower function to be used in govkeeper.Tally. - - * (x/mint) [#24436](https://github.com/cosmos/cosmos-sdk/pull/24436) Allow users to set a custom minting function used in the `x/mint` begin blocker. - - * The `InflationCalculationFn` argument to `mint.NewAppModule()` is now ignored and must be nil. To set a custom `InflationCalculationFn` on the default minter, use `mintkeeper.WithMintFn(mintkeeper.DefaultMintFn(customInflationFn))`. - - * (api) [#24428](https://github.com/cosmos/cosmos-sdk/pull/24428) Add block height to response headers - - ### Improvements - - * (client) [#24561](https://github.com/cosmos/cosmos-sdk/pull/24561) TimeoutTimestamp flag has been changed to TimeoutDuration, which now sets the timeout timestamp of unordered transactions to the current time + duration passed. - - * (telemetry) [#24541](https://github.com/cosmos/cosmos-sdk/pull/24541) Telemetry now includes a pre_blocker metric key. x/upgrade should migrate to this key in v0.54.0. - - * (x/auth) [#24541](https://github.com/cosmos/cosmos-sdk/pull/24541) x/auth's PreBlocker now emits telemetry under the pre_blocker metric key. - - * (x/bank) [#24431](https://github.com/cosmos/cosmos-sdk/pull/24431) Reduce the number of `ValidateDenom` calls in `bank.SendCoins` and `Coin`. - - * The `AmountOf()` method on`sdk.Coins` no longer will `panic` if given an invalid denom and will instead return a zero value. - - * (x/staking) [#24391](https://github.com/cosmos/cosmos-sdk/pull/24391) Replace panics with error results; more verbose error messages - - * (x/staking) [#24354](https://github.com/cosmos/cosmos-sdk/pull/24354) Optimize validator endblock by reducing bech32 conversions, resulting in significant performance improvement - - * (client/keys) [#18950](https://github.com/cosmos/cosmos-sdk/pull/18950) Improve ` keys add`, ` keys import` and ` keys rename` by checking name validation. - - * (client/keys) [#18703](https://github.com/cosmos/cosmos-sdk/pull/18703) Improve ` keys add` and ` keys show` by checking whether there are duplicate keys in the multisig case. - - * (client/keys) [#18745](https://github.com/cosmos/cosmos-sdk/pull/18745) Improve ` keys export` and ` keys mnemonic` by adding --yes option to skip interactive confirmation. - - * (x/bank) [#24106](https://github.com/cosmos/cosmos-sdk/pull/24106) `SendCoins` now checks for `SendRestrictions` before instead of after deducting coins using `subUnlockedCoins`. - - * (crypto/ledger) [#24036](https://github.com/cosmos/cosmos-sdk/pull/24036) Improve error message when deriving paths using index > 100 - - * (gRPC) [#23844](https://github.com/cosmos/cosmos-sdk/pull/23844) Add debug log prints for each gRPC request. - - * (gRPC) [#24073](https://github.com/cosmos/cosmos-sdk/pull/24073) Adds error handling for out-of-gas panics in grpc query handlers. - - * (server) [#24072](https://github.com/cosmos/cosmos-sdk/pull/24072) Return BlockHeader by shallow copy in server Context. - - * (x/bank) [#24053](https://github.com/cosmos/cosmos-sdk/pull/24053) Resolve a foot-gun by swapping send restrictions check in `InputOutputCoins` before coin deduction. - - * (codec/types) [#24336](https://github.com/cosmos/cosmos-sdk/pull/24336) Most types definitions were moved to `github.com/cosmos/gogoproto/types/any` with aliases to these left in `codec/types` so that there should be no breakage to existing code. This allows protobuf generated code to optionally reference the SDK's custom `Any` type without a direct dependency on the SDK. This can be done by changing the `protoc` `M` parameter for `any.proto` to `Mgoogle/protobuf/any.proto=github.com/cosmos/gogoproto/types/any`. - - ### Bug Fixes - - * (x/gov)[#24460](https://github.com/cosmos/cosmos-sdk/pull/24460) Do not call Remove during Walk in defaultCalculateVoteResultsAndVotingPower. - - * (baseapp) [24261](https://github.com/cosmos/cosmos-sdk/pull/24261) Fix post handler error always results in code 1 - - * (server) [#24068](https://github.com/cosmos/cosmos-sdk/pull/24068) Allow align block header with skip check header in grpc server. - - * (x/gov) [#24044](https://github.com/cosmos/cosmos-sdk/pull/24044) Fix some places in which we call Remove inside a Walk (x/gov). - - * (baseapp) [#24042](https://github.com/cosmos/cosmos-sdk/pull/24042) Fixed a data race inside BaseApp.getContext, found by end-to-end (e2e) tests. - - * (client/server) [#24059](https://github.com/cosmos/cosmos-sdk/pull/24059) Consistently set viper prefix in client and server. It defaults for the binary name for both client and server. - - * (client/keys) [#24041](https://github.com/cosmos/cosmos-sdk/pull/24041) `keys delete` won't terminate when a key is not found, but will log the error. - - * (baseapp) [#24027](https://github.com/cosmos/cosmos-sdk/pull/24027) Ensure that `BaseApp.Init` checks that the commit multistore is set to protect against nil dereferences. - - * (x/group) [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker - - * (x/distribution) [#23934](https://github.com/cosmos/cosmos-sdk/pull/23934) Fix vulnerability in `incrementReferenceCount` in distribution. - - * (baseapp) [#23879](https://github.com/cosmos/cosmos-sdk/pull/23879) Ensure finalize block response is not empty in the defer check of FinalizeBlock to avoid panic by nil pointer. - - * (query) [#23883](https://github.com/cosmos/cosmos-sdk/pull/23883) Fix NPE in query pagination. - - * (client) [#23860](https://github.com/cosmos/cosmos-sdk/pull/23860) Add missing `unordered` field for legacy amino signing of tx body. - - * (x/bank) [#23836](https://github.com/cosmos/cosmos-sdk/pull/23836) Fix `DenomMetadata` rpc allow value with slashes. - - * (query) [87d3a43](https://github.com/cosmos/cosmos-sdk/commit/87d3a432af95f4cf96aa02351ed5fcc51cca6e7b) Fix collection filtered pagination. - - * (sims) [#23952](https://github.com/cosmos/cosmos-sdk/pull/23952) Use liveness matrix for validator sign status in sims - - * (baseapp) [#24055](https://github.com/cosmos/cosmos-sdk/pull/24055) Align block header when query with latest height. - - * (baseapp) [#24074](https://github.com/cosmos/cosmos-sdk/pull/24074) Use CometBFT's ComputeProtoSizeForTxs in defaultTxSelector.SelectTxForProposal for consistency. - - * (cli) [#24090](https://github.com/cosmos/cosmos-sdk/pull/24090) Prune cmd should disable async pruning. - - * (x/auth) [#19239](https://github.com/cosmos/cosmos-sdk/pull/19239) Sets from flag in multi-sign command to avoid no key name provided error. - - * (x/auth) [#23741](https://github.com/cosmos/cosmos-sdk/pull/23741) Support legacy global AccountNumber for legacy compatibility. - - * (baseapp) [#24526](https://github.com/cosmos/cosmos-sdk/pull/24526) Fix incorrect retention height when `commitHeight` equals `minRetainBlocks`. - - * (x/protocolpool) [#24594](https://github.com/cosmos/cosmos-sdk/pull/24594) Fix NPE when initializing module via depinject. - - * (x/epochs) [#24610](https://github.com/cosmos/cosmos-sdk/pull/24610) Fix semantics of `CurrentEpochStartHeight` being set before epoch has started. - - ## [v0.50.13](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.13) - 2025-03-12 - - ### Bug Fixes - - * [GHSA-47ww-ff84-4jrg](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-47ww-ff84-4jrg) Fix x/group can halt when erroring in EndBlocker - - ## [v0.50.12](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.12) - 2025-02-20 - - ### Bug Fixes - - * [GHSA-x5vx-95h7-rv4p](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-x5vx-95h7-rv4p) Fix Group module can halt chain when handling a malicious proposal. - - ## [v0.50.11](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.11) - 2024-12-16 - - ### Features - - * (crypto/keyring) [#21653](https://github.com/cosmos/cosmos-sdk/pull/21653) New Linux-only backend that adds Linux kernel's `keyctl` support. - - ### Improvements - - * (server) [#21941](https://github.com/cosmos/cosmos-sdk/pull/21941) Regenerate addrbook.json for in place testnet. - - ### Bug Fixes - - * Fix [ABS-0043/ABS-0044](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-8wcc-m6j2-qxvm) Limit recursion depth for unknown field detection and unpack any - - * (server) [#22564](https://github.com/cosmos/cosmos-sdk/pull/22564) Fix fallback genesis path in server - - * (x/group) [#22425](https://github.com/cosmos/cosmos-sdk/pull/22425) Proper address rendering in error - - * (sims) [#21906](https://github.com/cosmos/cosmos-sdk/pull/21906) Skip sims test when running dry on validators - - * (cli) [#21919](https://github.com/cosmos/cosmos-sdk/pull/21919) Query address-by-acc-num by account_id instead of id. - - * (x/group) [#22229](https://github.com/cosmos/cosmos-sdk/pull/22229) Accept `1` and `try` in CLI for group proposal exec. - - ## [v0.50.10](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.10) - 2024-09-20 - - ### Features - - * (cli) [#20779](https://github.com/cosmos/cosmos-sdk/pull/20779) Added `module-hash-by-height` command to query and retrieve module hashes at a specified blockchain height, enhancing debugging capabilities. - - * (cli) [#21372](https://github.com/cosmos/cosmos-sdk/pull/21372) Added a `bulk-add-genesis-account` genesis command to add many genesis accounts at once. - - * (types/collections) [#21724](https://github.com/cosmos/cosmos-sdk/pull/21724) Added `LegacyDec` collection value. - - ### Improvements - - * (x/bank) [#21460](https://github.com/cosmos/cosmos-sdk/pull/21460) Added `Sender` attribute in `MsgMultiSend` event. - - * (genutil) [#21701](https://github.com/cosmos/cosmos-sdk/pull/21701) Improved error messages for genesis validation. - - * (testutil/integration) [#21816](https://github.com/cosmos/cosmos-sdk/pull/21816) Allow to pass baseapp options in `NewIntegrationApp`. - - ### Bug Fixes - - * (runtime) [#21769](https://github.com/cosmos/cosmos-sdk/pull/21769) Fix baseapp options ordering to avoid overwriting options set by modules. - - * (x/consensus) [#21493](https://github.com/cosmos/cosmos-sdk/pull/21493) Fix regression that prevented to upgrade to > v0.50.7 without consensus version params. - - * (baseapp) [#21256](https://github.com/cosmos/cosmos-sdk/pull/21256) Halt height will not commit the block indicated, meaning that if halt-height is set to 10, only blocks until 9 (included) will be committed. This is to go back to the original behavior before a change was introduced in v0.50.0. - - * (baseapp) [#21444](https://github.com/cosmos/cosmos-sdk/pull/21444) Follow-up, Return PreBlocker events in FinalizeBlockResponse. - - * (baseapp) [#21413](https://github.com/cosmos/cosmos-sdk/pull/21413) Fix data race in sdk mempool. - - ## [v0.50.9](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.9) - 2024-08-07 - - ## Bug Fixes - - * (baseapp) [#21159](https://github.com/cosmos/cosmos-sdk/pull/21159) Return PreBlocker events in FinalizeBlockResponse. - - * [#20939](https://github.com/cosmos/cosmos-sdk/pull/20939) Fix collection reverse iterator to include `pagination.key` in the result. - - * (client/grpc) [#20969](https://github.com/cosmos/cosmos-sdk/pull/20969) Fix `node.NewQueryServer` method not setting `cfg`. - - * (testutil/integration) [#21006](https://github.com/cosmos/cosmos-sdk/pull/21006) Fix `NewIntegrationApp` method not writing default genesis to state. - - * (runtime) [#21080](https://github.com/cosmos/cosmos-sdk/pull/21080) Fix `app.yaml` / `app.json` incompatibility with `depinject v1.0.0`. - - ## [v0.50.8](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.8) - 2024-07-15 - - ## Features - - * (client) [#20690](https://github.com/cosmos/cosmos-sdk/pull/20690) Import mnemonic from file - - ## Improvements - - * (x/authz,x/feegrant) [#20590](https://github.com/cosmos/cosmos-sdk/pull/20590) Provide updated keeper in depinject for authz and feegrant modules. - - * [#20631](https://github.com/cosmos/cosmos-sdk/pull/20631) Fix json parsing in the wait-tx command. - - * (x/auth) [#20438](https://github.com/cosmos/cosmos-sdk/pull/20438) Add `--skip-signature-verification` flag to multisign command to allow nested multisigs. - - ## Bug Fixes - - * (simulation) [#17911](https://github.com/cosmos/cosmos-sdk/pull/17911) Fix all problems with executing command `make test-sim-custom-genesis-fast` for simulation test. - - * (simulation) [#18196](https://github.com/cosmos/cosmos-sdk/pull/18196) Fix the problem of `validator set is empty after InitGenesis` in simulation test. - - ## [v0.50.7](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.7) - 2024-06-04 - - ### Improvements - - * (debug) [#20328](https://github.com/cosmos/cosmos-sdk/pull/20328) Add consensus address for debug cmd. - - * (runtime) [#20264](https://github.com/cosmos/cosmos-sdk/pull/20264) Expose grpc query router via depinject. - - * (x/consensus) [#20381](https://github.com/cosmos/cosmos-sdk/pull/20381) Use Comet utility for consensus module consensus param updates. - - * (client) [#20356](https://github.com/cosmos/cosmos-sdk/pull/20356) Overwrite client context when available in `SetCmdClientContext`. - - ### Bug Fixes - - * (baseapp) [#20346](https://github.com/cosmos/cosmos-sdk/pull/20346) Correctly assign `execModeSimulate` to context for `simulateTx`. - - * (baseapp) [#20144](https://github.com/cosmos/cosmos-sdk/pull/20144) Remove txs from mempool when AnteHandler fails in recheck. - - * (baseapp) [#20107](https://github.com/cosmos/cosmos-sdk/pull/20107) Avoid header height overwrite block height. - - * (cli) [#20020](https://github.com/cosmos/cosmos-sdk/pull/20020) Make bootstrap-state command support both new and legacy genesis format. - - * (testutil/sims) [#20151](https://github.com/cosmos/cosmos-sdk/pull/20151) Set all signatures and don't overwrite the previous one in `GenSignedMockTx`. - - ## [v0.50.6](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.6) - 2024-04-22 - - ### Features - - * (types) [#19759](https://github.com/cosmos/cosmos-sdk/pull/19759) Align SignerExtractionAdapter in PriorityNonceMempool Remove. - - * (client) [#19870](https://github.com/cosmos/cosmos-sdk/pull/19870) Add new query command `wait-tx`. Alias `event-query-tx-for` to `wait-tx` for backward compatibility. - - ### Improvements - - * (telemetry) [#19903](https://github.com/cosmos/cosmos-sdk/pull/19903) Conditionally emit metrics based on enablement. - - * **Introduction of `Now` Function**: Added a new function called `Now` to the telemetry package. It returns the current system time if telemetry is enabled, or a zero time if telemetry is not enabled. - - * **Atomic Global Variable**: Implemented an atomic global variable to manage the state of telemetry's enablement. This ensures thread safety for the telemetry state. - - * **Conditional Telemetry Emission**: All telemetry functions have been updated to emit metrics only when telemetry is enabled. They perform a check with `isTelemetryEnabled()` and return early if telemetry is disabled, minimizing unnecessary operations and overhead. - - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Upgrade prometheus version and fix API breaking change due to prometheus bump. - - * (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Bump `cosmossdk.io/store` to v1.1.0. - - * (server) [#19884](https://github.com/cosmos/cosmos-sdk/pull/19884) Add start customizability to start command options. - - * (x/gov) [#19853](https://github.com/cosmos/cosmos-sdk/pull/19853) Emit `depositor` in `EventTypeProposalDeposit`. - - * (x/gov) [#19844](https://github.com/cosmos/cosmos-sdk/pull/19844) Emit the proposer of governance proposals. - - * (baseapp) [#19616](https://github.com/cosmos/cosmos-sdk/pull/19616) Don't share gas meter in tx execution. - - ## Bug Fixes - - * (x/authz) [#20114](https://github.com/cosmos/cosmos-sdk/pull/20114) Follow up of [GHSA-4j93-fm92-rp4m](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-4j93-fm92-rp4m) for `x/authz`. - - * (crypto) [#19691](https://github.com/cosmos/cosmos-sdk/pull/19745) Fix tx sign doesn't throw an error when incorrect Ledger is used. - - * (baseapp) [#19970](https://github.com/cosmos/cosmos-sdk/pull/19970) Fix default config values to use no-op mempool as default. - - * (crypto) [#20027](https://github.com/cosmos/cosmos-sdk/pull/20027) secp256r1 keys now implement gogoproto's customtype interface. - - * (x/bank) [#20028](https://github.com/cosmos/cosmos-sdk/pull/20028) Align query with multi denoms for send-enabled. - - ## [v0.50.5](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.5) - 2024-03-12 - - ### Features - - * (baseapp) [#19626](https://github.com/cosmos/cosmos-sdk/pull/19626) Add `DisableBlockGasMeter` option to `BaseApp`, which removes the block gas meter during transaction execution. - - ### Improvements - - * (x/distribution) [#19707](https://github.com/cosmos/cosmos-sdk/pull/19707) Add autocli config for `DelegationTotalRewards` for CLI consistency with `q rewards` commands in previous versions. - - * (x/auth) [#19651](https://github.com/cosmos/cosmos-sdk/pull/19651) Allow empty public keys in `GetSignBytesAdapter`. - - ### Bug Fixes - - * (x/gov) [#19725](https://github.com/cosmos/cosmos-sdk/pull/19725) Fetch a failed proposal tally from proposal.FinalTallyResult in the gprc query. - - * (types) [#19709](https://github.com/cosmos/cosmos-sdk/pull/19709) Fix skip staking genesis export when using `CoreAppModuleAdaptor` / `CoreAppModuleBasicAdaptor` for it. - - * (x/auth) [#19549](https://github.com/cosmos/cosmos-sdk/pull/19549) Accept custom get signers when injecting `x/auth/tx`. - - * (x/staking) Fix a possible bypass of delegator slashing: [GHSA-86h5-xcpx-cfqc](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-86h5-xcpx-cfqc) - - * (baseapp) Fix a bug in `baseapp.ValidateVoteExtensions` helper ([GHSA-95rx-m9m5-m94v](https://github.com/cosmos/cosmos-sdk/security/advisories/GHSA-95rx-m9m5-m94v)). The helper has been fixed and for avoiding API breaking changes `currentHeight` and `chainID` arguments are ignored. Those arguments are removed from the helper in v0.51+. - - ## [v0.50.4](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.4) - 2024-02-19 - - ### Features - - * (server) [#19280](https://github.com/cosmos/cosmos-sdk/pull/19280) Adds in-place testnet CLI command. - - ### Improvements - - * (client) [#19393](https://github.com/cosmos/cosmos-sdk/pull/19393/) Add `ReadDefaultValuesFromDefaultClientConfig` to populate the default values from the default client config in client.Context without creating a app folder. - - ### Bug Fixes - - * (x/auth/vesting) [GHSA-4j93-fm92-rp4m](#bug-fixes) Add `BlockedAddr` check in `CreatePeriodicVestingAccount`. - - * (baseapp) [#19338](https://github.com/cosmos/cosmos-sdk/pull/19338) Set HeaderInfo in context when calling `setState`. - - * (baseapp): [#19200](https://github.com/cosmos/cosmos-sdk/pull/19200) Ensure that sdk side ve math matches cometbft. - - * [#19106](https://github.com/cosmos/cosmos-sdk/pull/19106) Allow empty public keys when setting signatures. Public keys aren't needed for every transaction. - - * (baseapp) [#19198](https://github.com/cosmos/cosmos-sdk/pull/19198) Remove usage of pointers in logs in all optimistic execution goroutines. - - * (baseapp) [#19177](https://github.com/cosmos/cosmos-sdk/pull/19177) Fix baseapp `DefaultProposalHandler` same-sender non-sequential sequence. - - * (crypto) [#19371](https://github.com/cosmos/cosmos-sdk/pull/19371) Avoid CLI redundant log in stdout, log to stderr instead. - - ## [v0.50.3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.3) - 2024-01-15 - - ### Features - - * (types) [#18991](https://github.com/cosmos/cosmos-sdk/pull/18991) Add SignerExtractionAdapter to PriorityNonceMempool/Config and provide Default implementation matching existing behavior. - - * (gRPC) [#19043](https://github.com/cosmos/cosmos-sdk/pull/19043) Add `halt_height` to the gRPC `/cosmos/base/node/v1beta1/config` request. - - ### Improvements - - * (x/bank) [#18956](https://github.com/cosmos/cosmos-sdk/pull/18956) Introduced a new `DenomOwnersByQuery` query method for `DenomOwners`, which accepts the denom value as a query string parameter, resolving issues with denoms containing slashes. - - * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. - - * (x/auth/tx) [#18772](https://github.com/cosmos/cosmos-sdk/pull/18772) Remove misleading gas wanted from tx simulation failure log. - - * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. - - * (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 - - * (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 - - * (baseapp) [#18915](https://github.com/cosmos/cosmos-sdk/pull/18915) Add a new `ExecModeVerifyVoteExtension` exec mode and ensure it's populated in the `Context` during `VerifyVoteExtension` execution. - - * (testutil) [#18930](https://github.com/cosmos/cosmos-sdk/pull/18930) Add NodeURI for clientCtx. - - ### Bug Fixes - - * (baseapp) [#19058](https://github.com/cosmos/cosmos-sdk/pull/19058) Fix baseapp posthandler branch would fail if the `runMsgs` had returned an error. - - * (baseapp) [#18609](https://github.com/cosmos/cosmos-sdk/issues/18609) Fixed accounting in the block gas meter after module's beginBlock and before DeliverTx, ensuring transaction processing always starts with the expected zeroed out block gas meter. - - * (baseapp) [#18895](https://github.com/cosmos/cosmos-sdk/pull/18895) Fix de-duplicating vote extensions during validation in ValidateVoteExtensions. - - ## [v0.50.2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.2) - 2023-12-11 - - ### Features - - * (debug) [#18219](https://github.com/cosmos/cosmos-sdk/pull/18219) Add debug commands for application codec types. - - * (client/keys) [#17639](https://github.com/cosmos/cosmos-sdk/pull/17639) Allows using and saving public keys encoded as base64. - - * (server) [#17094](https://github.com/cosmos/cosmos-sdk/pull/17094) Add a `shutdown-grace` flag for waiting a given time before exit. - - ### Improvements - - * (telemetry) [#18646] (https://github.com/cosmos/cosmos-sdk/pull/18646) Enable statsd and dogstatsd telemetry sinks. - - * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. - - * (x/gov) [#18025](https://github.com/cosmos/cosmos-sdk/pull/18025) Improve ` q gov proposer` by querying directly a proposal instead of tx events. It is an alias of `q gov proposal` as the proposer is a field of the proposal. - - * (version) [#18063](https://github.com/cosmos/cosmos-sdk/pull/18063) Allow to define extra info to be displayed in ` version --long` command. - - * (codec/unknownproto)[#18541](https://github.com/cosmos/cosmos-sdk/pull/18541) Remove the use of "protoc-gen-gogo/descriptor" in favour of using the official protobuf descriptorpb types inside unknownproto. - - ### Bug Fixes - - * (x/auth) [#18564](https://github.com/cosmos/cosmos-sdk/pull/18564) Fix total fees calculation when batch signing. - - * (server) [#18537](https://github.com/cosmos/cosmos-sdk/pull/18537) Fix panic when defining minimum gas config as `100stake;100uatom`. Use a `,` delimiter instead of `;`. Fixes the server config getter to use the correct delimiter. - - * [#18531](https://github.com/cosmos/cosmos-sdk/pull/18531) Baseapp's `GetConsensusParams` returns an empty struct instead of panicking if no params are found. - - * (client/tx) [#18472](https://github.com/cosmos/cosmos-sdk/pull/18472) Utilizes the correct Pubkey when simulating a transaction. - - * (baseapp) [#18486](https://github.com/cosmos/cosmos-sdk/pull/18486) Fixed FinalizeBlock calls not being passed to ABCIListeners. - - * (baseapp) [#18627](https://github.com/cosmos/cosmos-sdk/pull/18627) Post handlers are run on non successful transaction executions too. - - * (baseapp) [#18654](https://github.com/cosmos/cosmos-sdk/pull/18654) Fixes an issue in which `gogoproto.Merge` does not work with gogoproto messages with custom types. - - ## [v0.50.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.50.1) - 2023-11-07 - - > v0.50.0 has been retracted due to a mistake in tagging the release. Please use v0.50.1 instead. - - ### Features - - * (baseapp) [#18071](https://github.com/cosmos/cosmos-sdk/pull/18071) Add hybrid handlers to `MsgServiceRouter`. - - * (server) [#18162](https://github.com/cosmos/cosmos-sdk/pull/18162) Start gRPC & API server in standalone mode. - - * (baseapp & types) [#17712](https://github.com/cosmos/cosmos-sdk/pull/17712) Introduce `PreBlock`, which runs before begin blocker other modules, and allows to modify consensus parameters, and the changes are visible to the following state machine logics. Additionally it can be used for vote extensions. - - * (genutil) [#17571](https://github.com/cosmos/cosmos-sdk/pull/17571) Allow creation of `AppGenesis` without a file lookup. - - * (codec) [#17042](https://github.com/cosmos/cosmos-sdk/pull/17042) Add `CollValueV2` which supports encoding of protov2 messages in collections. - - * (x/gov) [#16976](https://github.com/cosmos/cosmos-sdk/pull/16976) Add `failed_reason` field to `Proposal` under `x/gov` to indicate the reason for a failed proposal. Referenced from [#238](https://github.com/bnb-chain/greenfield-cosmos-sdk/pull/238) under `bnb-chain/greenfield-cosmos-sdk`. - - * (baseapp) [#16898](https://github.com/cosmos/cosmos-sdk/pull/16898) Add `preFinalizeBlockHook` to allow vote extensions persistence. - - * (cli) [#16887](https://github.com/cosmos/cosmos-sdk/pull/16887) Add two new CLI commands: ` tx simulate` for simulating a transaction; ` query block-results` for querying CometBFT RPC for block results. - - * (x/bank) [#16852](https://github.com/cosmos/cosmos-sdk/pull/16852) Add `DenomMetadataByQueryString` query in bank module to support metadata query by query string. - - * (baseapp) [#16581](https://github.com/cosmos/cosmos-sdk/pull/16581) Implement Optimistic Execution as an experimental feature (not enabled by default). - - * (types) [#16257](https://github.com/cosmos/cosmos-sdk/pull/16257) Allow setting the base denom in the denom registry. - - * (baseapp) [#16239](https://github.com/cosmos/cosmos-sdk/pull/16239) Add Gas Limits to allow node operators to resource bound queries. - - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Make `StartCmd` more customizable. - - * (types/simulation) [#16074](https://github.com/cosmos/cosmos-sdk/pull/16074) Add generic SimulationStoreDecoder for modules using collections. - - * (genutil) [#16046](https://github.com/cosmos/cosmos-sdk/pull/16046) Add "module-name" flag to genutil `add-genesis-account` to enable intializing module accounts at genesis.* [#15970](https://github.com/cosmos/cosmos-sdk/pull/15970) Enable SIGN_MODE_TEXTUAL. - - * (types) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Add `module.NewBasicManagerFromManager` for creating a basic module manager from a module manager. - - * (types/module) [#15829](https://github.com/cosmos/cosmos-sdk/pull/15829) Add new endblocker interface to handle valset updates. - - * (runtime) [#15818](https://github.com/cosmos/cosmos-sdk/pull/15818) Provide logger through `depinject` instead of appBuilder. - - * (types) [#15735](https://github.com/cosmos/cosmos-sdk/pull/15735) Make `ValidateBasic() error` method of `Msg` interface optional. Modules should validate messages directly in their message handlers ([RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation)). - - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) Allow applications to specify a custom genesis migration function for the `genesis migrate` command. - - * (telemetry) [#15657](https://github.com/cosmos/cosmos-sdk/pull/15657) Emit more data (go version, sdk version, upgrade height) in prom metrics. - - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) Add status endpoint for clients. - - * (testutil/integration) [#15556](https://github.com/cosmos/cosmos-sdk/pull/15556) Introduce `testutil/integration` package for module integration testing. - - * (runtime) [#15547](https://github.com/cosmos/cosmos-sdk/pull/15547) Allow runtime to pass event core api service to modules. - - * (client) [#15458](https://github.com/cosmos/cosmos-sdk/pull/15458) Add a `CmdContext` field to client.Context initialized to cobra command's context. - - * (x/genutil) [#15301](https://github.com/cosmos/cosmos-sdk/pull/15031) Add application genesis. The genesis is now entirely managed by the application and passed to CometBFT at note instantiation. Functions that were taking a `cmttypes.GenesisDoc{}` now takes a `genutiltypes.AppGenesis{}`. - - * (core) [#15133](https://github.com/cosmos/cosmos-sdk/pull/15133) Implement RegisterServices in the module manager. - - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Return a human readable denomination for IBC vouchers when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest` and `--resolve-denom` flag to `GetBalancesCmd()`. - - * (core) [#14860](https://github.com/cosmos/cosmos-sdk/pull/14860) Add `Precommit` and `PrepareCheckState` AppModule callbacks. - - * (x/gov) [#14720](https://github.com/cosmos/cosmos-sdk/pull/14720) Upstream expedited proposals from Osmosis. - - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by events with queries directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. - - * (x/auth) [#14650](https://github.com/cosmos/cosmos-sdk/pull/14650) Add Textual SignModeHandler. Enable `SIGN_MODE_TEXTUAL` by following the [UPGRADING.md](./UPGRADING.md) instructions. - - * (x/crisis) [#14588](https://github.com/cosmos/cosmos-sdk/pull/14588) Use CacheContext() in AssertInvariants(). - - * (mempool) [#14484](https://github.com/cosmos/cosmos-sdk/pull/14484) Add priority nonce mempool option for transaction replacement. - - * (query) [#14468](https://github.com/cosmos/cosmos-sdk/pull/14468) Implement pagination for collections. - - * (x/gov) [#14373](https://github.com/cosmos/cosmos-sdk/pull/14373) Add new proto field `constitution` of type `string` to gov module genesis state, which allows chain builders to lay a strong foundation by specifying purpose. - - * (client) [#14342](https://github.com/cosmos/cosmos-sdk/pull/14342) Add ` config` command is now a sub-command, for setting, getting and migrating Cosmos SDK configuration files. - - * (x/distribution) [#14322](https://github.com/cosmos/cosmos-sdk/pull/14322) Introduce a new gRPC message handler, `DepositValidatorRewardsPool`, that allows explicit funding of a validator's reward pool. - - * (x/bank) [#14224](https://github.com/cosmos/cosmos-sdk/pull/14224) Allow injection of restrictions on transfers using `AppendSendRestriction` or `PrependSendRestriction`. - - ### Improvements - - * (x/gov) [#18189](https://github.com/cosmos/cosmos-sdk/pull/18189) Limit the accepted deposit coins for a proposal to the minimum proposal deposit denoms. - - * (x/staking) [#18049](https://github.com/cosmos/cosmos-sdk/pull/18049) Return early if Slash encounters zero tokens to burn. - - * (x/staking) [#18035](https://github.com/cosmos/cosmos-sdk/pull/18035) Hoisted out of the redelegation loop, the non-changing validator and delegator addresses parsing. - - * (keyring) [#17913](https://github.com/cosmos/cosmos-sdk/pull/17913) Add `NewAutoCLIKeyring` for creating an AutoCLI keyring from a SDK keyring. - - * (x/consensus) [#18041](https://github.com/cosmos/cosmos-sdk/pull/18041) Let `ToProtoConsensusParams()` return an error. - - * (x/gov) [#17780](https://github.com/cosmos/cosmos-sdk/pull/17780) Recover panics and turn them into errors when executing x/gov proposals. - - * (baseapp) [#17667](https://github.com/cosmos/cosmos-sdk/pull/17667) Close databases opened by SDK in `baseApp.Close()`. - - * (types/module) [#17554](https://github.com/cosmos/cosmos-sdk/pull/17554) Introduce `HasABCIGenesis` which is implemented by a module only when a validatorset update needs to be returned. - - * (cli) [#17389](https://github.com/cosmos/cosmos-sdk/pull/17389) gRPC CometBFT commands have been added under ` q consensus comet`. CometBFT commands placement in the SDK has been simplified. See the exhaustive list below. - - * `client/rpc.StatusCommand()` is now at `server.StatusCommand()` - - * (testutil) [#17216](https://github.com/cosmos/cosmos-sdk/issues/17216) Add `DefaultContextWithKeys` to `testutil` package. - - * (cli) [#17187](https://github.com/cosmos/cosmos-sdk/pull/17187) Do not use `ctx.PrintObjectLegacy` in commands anymore. - - * ` q gov proposer [proposal-id]` now returns a proposal id as int instead of string. - - * (x/staking) [#17164](https://github.com/cosmos/cosmos-sdk/pull/17164) Add `BondedTokensAndPubKeyByConsAddr` to the keeper to enable vote extension verification. - - * (x/group, x/gov) [#17109](https://github.com/cosmos/cosmos-sdk/pull/17109) Let proposal summary be 40x longer than metadata limit. - - * (version) [#17096](https://github.com/cosmos/cosmos-sdk/pull/17096) Improve `getSDKVersion()` to handle module replacements. - - * (types) [#16890](https://github.com/cosmos/cosmos-sdk/pull/16890) Remove `GetTxCmd() *cobra.Command` and `GetQueryCmd() *cobra.Command` from `module.AppModuleBasic` interface. - - * (x/authz) [#16869](https://github.com/cosmos/cosmos-sdk/pull/16869) Improve error message when grant not found. - - * (all) [#16497](https://github.com/cosmos/cosmos-sdk/pull/16497) Removed all exported vestiges of `sdk.MustSortJSON` and `sdk.SortJSON`. - - * (server) [#16238](https://github.com/cosmos/cosmos-sdk/pull/16238) Don't setup p2p node keys if starting a node in GRPC only mode. - - * (cli) [#16206](https://github.com/cosmos/cosmos-sdk/pull/16206) Make ABCI handshake profileable. - - * (types) [#16076](https://github.com/cosmos/cosmos-sdk/pull/16076) Optimize `ChainAnteDecorators`/`ChainPostDecorators` to instantiate the functions once instead of on every invocation of the returned `AnteHandler`/`PostHandler`. - - * (server) [#16071](https://github.com/cosmos/cosmos-sdk/pull/16071) When `mempool.max-txs` is set to a negative value, use a no-op mempool (effectively disable the app mempool). - - * (types/query) [#16041](https://github.com/cosmos/cosmos-sdk/pull/16041) Change pagination max limit to a variable in order to be modifed by application devs. - - * (simapp) [#15958](https://github.com/cosmos/cosmos-sdk/pull/15958) Refactor SimApp for removing the global basic manager. - - * (all modules) [#15901](https://github.com/cosmos/cosmos-sdk/issues/15901) All core Cosmos SDK modules query commands have migrated to [AutoCLI](https://docs.cosmos.network/main/core/autocli), ensuring parity between gRPC and CLI queries. - - * (x/auth) [#15867](https://github.com/cosmos/cosmos-sdk/pull/15867) Support better logging for signature verification failure. - - * (store/cachekv) [#15767](https://github.com/cosmos/cosmos-sdk/pull/15767) Reduce peak RAM usage during and after `InitGenesis`. - - * (x/bank) [#15764](https://github.com/cosmos/cosmos-sdk/pull/15764) Speedup x/bank `InitGenesis`. - - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) Refactor the validator's missed block signing window to be a chunked bitmap instead of a "logical" bitmap, significantly reducing the storage footprint. - - * (x/gov) [#15554](https://github.com/cosmos/cosmos-sdk/pull/15554) Add proposal result log in `active_proposal` event. When a proposal passes but fails to execute, the proposal result is logged in the `active_proposal` event. - - * (x/consensus) [#15553](https://github.com/cosmos/cosmos-sdk/pull/15553) Migrate consensus module to use collections. - - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Add `server.InterceptConfigsAndCreateContext` as alternative to `server.InterceptConfigsPreRunHandler` which does not set the server context and the default SDK logger. - - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) Improve the `PriorityNonceMempool`: - - * Support generic transaction prioritization, instead of `ctx.Priority()` - - * Improve construction through the use of a single `PriorityNonceMempoolConfig` instead of option functions - - * (x/authz) [#15164](https://github.com/cosmos/cosmos-sdk/pull/15164) Add `MsgCancelUnbondingDelegation` to staking authorization. - - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Remove unnecessary sleeps from gRPC and API server initiation. The servers will start and accept requests as soon as they're ready. - - * (baseapp) [#15023](https://github.com/cosmos/cosmos-sdk/pull/15023) & [#15213](https://github.com/cosmos/cosmos-sdk/pull/15213) Add `MessageRouter` interface to baseapp and pass it to authz, gov and groups instead of concrete type. - - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) Introduce `cosmossdk.io/log` package to provide a consistent logging interface through the SDK. CometBFT logger is now replaced by `cosmossdk.io/log.Logger`. - - * (x/staking) [#14864](https://github.com/cosmos/cosmos-sdk/pull/14864) ` tx staking create-validator` CLI command now takes a json file as an arg instead of using required flags. - - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Allow transaction event queries to directly passed to Tendermint, which will allow for full query operator support, e.g. `>`. - - * (x/evidence) [#14757](https://github.com/cosmos/cosmos-sdk/pull/14757) Evidence messages do not need to implement a `.Type()` anymore. - - * (x/auth/tx) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove `.Type()` and `Route()` methods from all msgs and `legacytx.LegacyMsg` interface. - - * (cli) [#14659](https://github.com/cosmos/cosmos-sdk/pull/14659) Added ability to query blocks by either height/hash ` q block --type=height|hash `. - - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) Return undelegate amount in MsgUndelegateResponse. - - * [#14529](https://github.com/cosmos/cosmos-sdk/pull/14529) Add new property `BondDenom` to `SimulationState` struct. - - * (store) [#14439](https://github.com/cosmos/cosmos-sdk/pull/14439) Remove global metric gatherer from store. - - * By default store has a no op metric gatherer, the application developer must set another metric gatherer or us the provided one in `store/metrics`. - - * (store) [#14438](https://github.com/cosmos/cosmos-sdk/pull/14438) Pass logger from baseapp to store. - - * (baseapp) [#14417](https://github.com/cosmos/cosmos-sdk/pull/14417) The store package no longer has a dependency on baseapp. - - * (module) [#14415](https://github.com/cosmos/cosmos-sdk/pull/14415) Loosen assertions in SetOrderBeginBlockers() and SetOrderEndBlockers(). - - * (store) [#14410](https://github.com/cosmos/cosmos-sdk/pull/14410) `rootmulti.Store.loadVersion` has validation to check if all the module stores' height is correct, it will error if any module store has incorrect height. - - * [#14406](https://github.com/cosmos/cosmos-sdk/issues/14406) Migrate usage of `types/store.go` to `store/types/..`. - - * (context)[#14384](https://github.com/cosmos/cosmos-sdk/pull/14384) Refactor(context): Pass EventManager to the context as an interface. - - * (types) [#14354](https://github.com/cosmos/cosmos-sdk/pull/14354) Improve performance on Context.KVStore and Context.TransientStore by 40%. - - * (crypto/keyring) [#14151](https://github.com/cosmos/cosmos-sdk/pull/14151) Move keys presentation from `crypto/keyring` to `client/keys` - - * (signing) [#14087](https://github.com/cosmos/cosmos-sdk/pull/14087) Add SignModeHandlerWithContext interface with a new `GetSignBytesWithContext` to get the sign bytes using `context.Context` as an argument to access state. - - * (server) [#14062](https://github.com/cosmos/cosmos-sdk/pull/14062) Remove rosetta from server start. - - * (crypto) [#3129](https://github.com/cosmos/cosmos-sdk/pull/3129) New armor and keyring key derivation uses aead and encryption uses chacha20poly. - - ### State Machine Breaking - - * (x/gov) [#18146](https://github.com/cosmos/cosmos-sdk/pull/18146) Add denom check to reject denoms outside of those listed in `MinDeposit`. A new `MinDepositRatio` param is added (with a default value of `0.001`) and now deposits are required to be at least `MinDepositRatio*MinDeposit` to be accepted. - - * (x/group,x/gov) [#16235](https://github.com/cosmos/cosmos-sdk/pull/16235) A group and gov proposal is rejected if the proposal metadata title and summary do not match the proposal title and summary. - - * (baseapp) [#15930](https://github.com/cosmos/cosmos-sdk/pull/15930) change vote info provided by prepare and process proposal to the one in the block. - - * (x/staking) [#15731](https://github.com/cosmos/cosmos-sdk/pull/15731) Introducing a new index to retrieve the delegations by validator efficiently. - - * (x/staking) [#15701](https://github.com/cosmos/cosmos-sdk/pull/15701) The `HistoricalInfoKey` has been updated to use a binary format. - - * (x/slashing) [#15580](https://github.com/cosmos/cosmos-sdk/pull/15580) The validator slashing window now stores "chunked" bitmap entries for each validator's signing window instead of a single boolean entry per signing window index. - - * (x/staking) [#14590](https://github.com/cosmos/cosmos-sdk/pull/14590) `MsgUndelegateResponse` now includes undelegated amount. `x/staking` module's `keeper.Undelegate` now returns 3 values (completionTime,undelegateAmount,error) instead of 2. - - * (x/feegrant) [#14294](https://github.com/cosmos/cosmos-sdk/pull/14294) Moved the logic of rejecting duplicate grant from `msg_server` to `keeper` method. - - ### API Breaking Changes - - * (x/auth) [#17787](https://github.com/cosmos/cosmos-sdk/pull/17787) Remove Tip functionality. - - * (types) `module.EndBlockAppModule` has been replaced by Core API `appmodule.HasEndBlocker` or `module.HasABCIEndBlock` when needing validator updates. - - * (types) `module.BeginBlockAppModule` has been replaced by Core API `appmodule.HasBeginBlocker`. - - * (types) [#17358](https://github.com/cosmos/cosmos-sdk/pull/17358) Remove deprecated `sdk.Handler`, use `baseapp.MsgServiceHandler` instead. - - * (client) [#17197](https://github.com/cosmos/cosmos-sdk/pull/17197) `keys.Commands` does not take a home directory anymore. It is inferred from the root command. - - * (x/staking) [#17157](https://github.com/cosmos/cosmos-sdk/pull/17157) `GetValidatorsByPowerIndexKey` and `ValidateBasic` for historical info takes a validator address codec in order to be able to decode/encode addresses. - - * `GetOperator()` now returns the address as it is represented in state, by default this is an encoded address - - * `GetConsAddr() ([]byte, error)` returns `[]byte` instead of sdk.ConsAddres. - - * `FromABCIEvidence` & `GetConsensusAddress(consAc address.Codec)` now take a consensus address codec to be able to decode the incoming address. - - * (x/distribution) `Delegate` & `SlashValidator` helper function added the mock staking keeper as a parameter passed to the function - - * (x/staking) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgCreateValidator`, `NewValidator`, `NewMsgCancelUnbondingDelegation`, `NewMsgUndelegate`, `NewMsgBeginRedelegate`, `NewMsgDelegate` and `NewMsgEditValidator` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`: - - * `NewRedelegation` and `NewUnbondingDelegation` takes a validatorAddressCodec and a delegatorAddressCodec in order to decode the addresses. - - * `NewRedelegationResponse` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. - - * `NewMsgCreateValidator.Validate()` takes an address codec in order to decode the address. - - * `BuildCreateValidatorMsg` takes a ValidatorAddressCodec in order to decode addresses. - - * (x/slashing) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgUnjail` takes a string instead of `sdk.ValAddress` - - * (x/genutil) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `GenAppStateFromConfig`, AddGenesisAccountCmd and `GenTxCmd` takes an addresscodec to decode addresses. - - * (x/distribution) [#17098](https://github.com/cosmos/cosmos-sdk/pull/17098) `NewMsgDepositValidatorRewardsPool`, `NewMsgFundCommunityPool`, `NewMsgWithdrawValidatorCommission` and `NewMsgWithdrawDelegatorReward` takes a string instead of `sdk.ValAddress` or `sdk.AccAddress`. - - * (x/staking) [#16959](https://github.com/cosmos/cosmos-sdk/pull/16959) Add validator and consensus address codec as staking keeper arguments. - - * (x/staking) [#16958](https://github.com/cosmos/cosmos-sdk/pull/16958) DelegationI interface `GetDelegatorAddr` & `GetValidatorAddr` have been migrated to return string instead of sdk.AccAddress and sdk.ValAddress respectively. stakingtypes.NewDelegation takes a string instead of sdk.AccAddress and sdk.ValAddress. - - * (testutil) [#16899](https://github.com/cosmos/cosmos-sdk/pull/16899) The *cli testutil* `QueryBalancesExec` has been removed. Use the gRPC or REST query instead. - - * (x/staking) [#16795](https://github.com/cosmos/cosmos-sdk/pull/16795) `DelegationToDelegationResponse`, `DelegationsToDelegationResponses`, `RedelegationsToRedelegationResponses` are no longer exported. - - * (x/auth/vesting) [#16741](https://github.com/cosmos/cosmos-sdk/pull/16741) Vesting account constructor now return an error with the result of their validate function. - - * (x/auth) [#16650](https://github.com/cosmos/cosmos-sdk/pull/16650) The *cli testutil* `QueryAccountExec` has been removed. Use the gRPC or REST query instead. - - * (x/auth) [#16621](https://github.com/cosmos/cosmos-sdk/pull/16621) Pass address codec to auth new keeper constructor. - - * (x/auth) [#16423](https://github.com/cosmos/cosmos-sdk/pull/16423) `helpers.AddGenesisAccount` has been moved to `x/genutil` to remove the cyclic dependency between `x/auth` and `x/genutil`. - - * (baseapp) [#16342](https://github.com/cosmos/cosmos-sdk/pull/16342) NewContext was renamed to NewContextLegacy. The replacement (NewContext) now does not take a header, instead you should set the header via `WithHeaderInfo` or `WithBlockHeight`. Note that `WithBlockHeight` will soon be depreacted and its recommneded to use `WithHeaderInfo`. - - * (x/mint) [#16329](https://github.com/cosmos/cosmos-sdk/pull/16329) Use collections for state management: - - * Removed: keeper `GetParams`, `SetParams`, `GetMinter`, `SetMinter`. - - * (x/crisis) [#16328](https://github.com/cosmos/cosmos-sdk/pull/16328) Use collections for state management: - - * Removed: keeper `GetConstantFee`, `SetConstantFee` - - * (x/staking) [#16324](https://github.com/cosmos/cosmos-sdk/pull/16324) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. Notable changes: - - * `Validator` method now returns `types.ErrNoValidatorFound` instead of `nil` when not found. - - * (x/distribution) [#16302](https://github.com/cosmos/cosmos-sdk/pull/16302) Use collections for FeePool state management. - - * Removed: keeper `GetFeePool`, `SetFeePool`, `GetFeePoolCommunityCoins` - - * (types) [#16272](https://github.com/cosmos/cosmos-sdk/pull/16272) `FeeGranter` in the `FeeTx` interface returns `[]byte` instead of `string`. - - * (x/gov) [#16268](https://github.com/cosmos/cosmos-sdk/pull/16268) Use collections for proposal state management (part 2): - - * this finalizes the gov collections migration - - * Removed: types all the key related functions - - * Removed: keeper `InsertActiveProposalsQueue`, `RemoveActiveProposalsQueue`, `InsertInactiveProposalsQueue`, `RemoveInactiveProposalsQueue`, `IterateInactiveProposalsQueue`, `IterateActiveProposalsQueue`, `ActiveProposalsQueueIterator`, `InactiveProposalsQueueIterator` - - * (x/slashing) [#16246](https://github.com/cosmos/cosmos-sdk/issues/16246) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. `GetValidatorSigningInfo` now returns an error instead of a `found bool`, the error can be `nil` (found), `ErrNoSigningInfoFound` (not found) and any other error. - - * (module) [#16227](https://github.com/cosmos/cosmos-sdk/issues/16227) `manager.RunMigrations()` now take a `context.Context` instead of a `sdk.Context`. - - * (x/crisis) [#16216](https://github.com/cosmos/cosmos-sdk/issues/16216) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` instead of panicking. - - * (x/distribution) [#16211](https://github.com/cosmos/cosmos-sdk/pull/16211) Use collections for params state management. - - * (cli) [#16209](https://github.com/cosmos/cosmos-sdk/pull/16209) Add API `StartCmdWithOptions` to create customized start command. - - * (x/mint) [#16179](https://github.com/cosmos/cosmos-sdk/issues/16179) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error`. - - * (x/gov) [#16171](https://github.com/cosmos/cosmos-sdk/pull/16171) Use collections for proposal state management (part 1): - - * Removed: keeper: `GetProposal`, `UnmarshalProposal`, `MarshalProposal`, `IterateProposal`, `GetProposal`, `GetProposalFiltered`, `GetProposals`, `GetProposalID`, `SetProposalID` - - * Removed: errors unused errors - - * (x/gov) [#16164](https://github.com/cosmos/cosmos-sdk/pull/16164) Use collections for vote state management: - - * Removed: types `VoteKey`, `VoteKeys` - - * Removed: keeper `IterateVotes`, `IterateAllVotes`, `GetVotes`, `GetVote`, `SetVote` - - * (sims) [#16155](https://github.com/cosmos/cosmos-sdk/pull/16155) - - * `simulation.NewOperationMsg` now marshals the operation msg as proto bytes instead of legacy amino JSON bytes. - - * `simulation.NewOperationMsg` is now 2-arity instead of 3-arity with the obsolete argument `codec.ProtoCodec` removed. - - * The field `OperationMsg.Msg` is now of type `[]byte` instead of `json.RawMessage`. - - * (x/gov) [#16127](https://github.com/cosmos/cosmos-sdk/pull/16127) Use collections for deposit state management: - - * The following methods are removed from the gov keeper: `GetDeposit`, `GetAllDeposits`, `IterateAllDeposits`. - - * The following functions are removed from the gov types: `DepositKey`, `DepositsKey`. - - * (x/gov) [#16118](https://github.com/cosmos/cosmos-sdk/pull/16118/) Use collections for constituion and params state management. - - * (x/gov) [#16106](https://github.com/cosmos/cosmos-sdk/pull/16106) Remove gRPC query methods from gov keeper. - - * (x/*all*) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetSignBytes` implementations on messages and global legacy amino codec definitions have been removed from all modules. - - * (sims) [#16052](https://github.com/cosmos/cosmos-sdk/pull/16062) `GetOrGenerate` no longer requires a codec argument is now 4-arity instead of 5-arity. - - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16798) Remove aliases in `types/math.go` (part 2). - - * (types/math) [#16040](https://github.com/cosmos/cosmos-sdk/pull/16040) Remove aliases in `types/math.go` (part 1). - - * (x/auth) [#16016](https://github.com/cosmos/cosmos-sdk/pull/16016) Use collections for accounts state management: - - * removed: keeper `HasAccountByID`, `AccountAddressByID`, `SetParams - - * (x/genutil) [#15999](https://github.com/cosmos/cosmos-sdk/pull/15999) Genutil now takes the `GenesisTxHanlder` interface instead of deliverTx. The interface is implemented on baseapp - - * (x/gov) [#15988](https://github.com/cosmos/cosmos-sdk/issues/15988) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context` and return an `error` (instead of panicking or returning a `found bool`). Iterators callback functions now return an error instead of a `bool`. - - * (x/auth) [#15985](https://github.com/cosmos/cosmos-sdk/pull/15985) The `AccountKeeper` does not expose the `QueryServer` and `MsgServer` APIs anymore. - - * (x/authz) [#15962](https://github.com/cosmos/cosmos-sdk/issues/15962) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`, methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. The `Authorization` interface's `Accept` method now takes a `context.Context` instead of a `sdk.Context`. - - * (x/distribution) [#15948](https://github.com/cosmos/cosmos-sdk/issues/15948) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Keeper methods also now return an `error`. - - * (x/bank) [#15891](https://github.com/cosmos/cosmos-sdk/issues/15891) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. Also `FundAccount` and `FundModuleAccount` from the `testutil` package accept a `context.Context` instead of a `sdk.Context`, and it's position was moved to the first place. - - * (x/slashing) [#15875](https://github.com/cosmos/cosmos-sdk/pull/15875) `x/slashing.NewAppModule` now requires an `InterfaceRegistry` parameter. - - * (x/crisis) [#15852](https://github.com/cosmos/cosmos-sdk/pull/15852) Crisis keeper now takes a instance of the address codec to be able to decode user addresses - - * (x/auth) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The type of struct field `ante.HandlerOptions.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. - - * (client) [#15822](https://github.com/cosmos/cosmos-sdk/pull/15822) The return type of the interface method `TxConfig.SignModeHandler` has been changed to `x/tx/signing.HandlerMap`. - - * The signature of `VerifySignature` has been changed to accept a `x/tx/signing.HandlerMap` and other structs from `x/tx` as arguments. - - * The signature of `NewTxConfigWithTextual` has been deprecated and its signature changed to accept a `SignModeOptions`. - - * The signature of `NewSigVerificationDecorator` has been changed to accept a `x/tx/signing.HandlerMap`. - - * (x/bank) [#15818](https://github.com/cosmos/cosmos-sdk/issues/15818) `BaseViewKeeper`'s `Logger` method now doesn't require a context. `NewBaseKeeper`, `NewBaseSendKeeper` and `NewBaseViewKeeper` now also require a `log.Logger` to be passed in. - - * (x/genutil) [#15679](https://github.com/cosmos/cosmos-sdk/pull/15679) `MigrateGenesisCmd` now takes a `MigrationMap` instead of having the SDK genesis migration hardcoded. - - * (client) [#15673](https://github.com/cosmos/cosmos-sdk/pull/15673) Move `client/keys.OutputFormatJSON` and `client/keys.OutputFormatText` to `client/flags` package. - - * (x/*all*) [#15648](https://github.com/cosmos/cosmos-sdk/issues/15648) Make `SetParams` consistent across all modules and validate the params at the message handling instead of `SetParams` method. - - * (codec) [#15600](https://github.com/cosmos/cosmos-sdk/pull/15600) [#15873](https://github.com/cosmos/cosmos-sdk/pull/15873) add support for getting signers to `codec.Codec` and `InterfaceRegistry`: - - * `InterfaceRegistry` is has unexported methods and implements `protodesc.Resolver` plus the `RangeFiles` and `SigningContext` methods. All implementations of `InterfaceRegistry` by other users must now embed the official implementation. - - * `Codec` has new methods `InterfaceRegistry`, `GetMsgAnySigners`, `GetMsgV1Signers`, and `GetMsgV2Signers` as well as unexported methods. All implementations of `Codec` by other users must now embed an official implementation from the `codec` package. - - * `AminoCodec` is marked as deprecated and no longer implements `Codec. - - * (client) [#15597](https://github.com/cosmos/cosmos-sdk/pull/15597) `RegisterNodeService` now requires a config parameter. - - * (x/nft) [#15588](https://github.com/cosmos/cosmos-sdk/pull/15588) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. - - * (baseapp) [#15568](https://github.com/cosmos/cosmos-sdk/pull/15568) `SetIAVLLazyLoading` is removed from baseapp. - - * (x/genutil) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `CollectGenTxsCmd` & `GenTxCmd` takes a address.Codec to be able to decode addresses. - - * (x/bank) [#15567](https://github.com/cosmos/cosmos-sdk/pull/15567) `GenesisBalance.GetAddress` now returns a string instead of `sdk.AccAddress` - - * `MsgSendExec` test helper function now takes a address.Codec - - * (x/auth) [#15520](https://github.com/cosmos/cosmos-sdk/pull/15520) `NewAccountKeeper` now takes a `KVStoreService` instead of a `StoreKey` and methods in the `Keeper` now take a `context.Context` instead of a `sdk.Context`. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) `runTxMode`s were renamed to `execMode`. `ModeDeliver` as changed to `ModeFinalize` and a new `ModeVoteExtension` was added for vote extensions. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Writing of state to the multistore was moved to `FinalizeBlock`. `Commit` still handles the committing values to disk. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) Calls to BeginBlock and EndBlock have been replaced with core api beginblock & endblock. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) BeginBlock and EndBlock are now internal to baseapp. For testing, user must call `FinalizeBlock`. BeginBlock and EndBlock calls are internal to Baseapp. - - * (baseapp) [#15519](https://github.com/cosmos/cosmos-sdk/pull/15519/files) All calls to ABCI methods now accept a pointer of the abci request and response types - - * (x/consensus) [#15517](https://github.com/cosmos/cosmos-sdk/pull/15517) `NewKeeper` now takes a `KVStoreService` instead of a `StoreKey`. - - * (x/bank) [#15477](https://github.com/cosmos/cosmos-sdk/pull/15477) `banktypes.NewMsgMultiSend` and `keeper.InputOutputCoins` only accept one input. - - * (server) [#15358](https://github.com/cosmos/cosmos-sdk/pull/15358) Remove `server.ErrorCode` that was not used anywhere. - - * (x/capability) [#15344](https://github.com/cosmos/cosmos-sdk/pull/15344) Capability module was removed and is now housed in [IBC-GO](https://github.com/cosmos/ibc-go). - - * (mempool) [#15328](https://github.com/cosmos/cosmos-sdk/pull/15328) The `PriorityNonceMempool` is now generic over type `C comparable` and takes a single `PriorityNonceMempoolConfig[C]` argument. See `DefaultPriorityNonceMempoolConfig` for how to construct the configuration and a `TxPriority` type. - - * [#15299](https://github.com/cosmos/cosmos-sdk/pull/15299) Remove `StdTx` transaction and signing APIs. No SDK version has actually supported `StdTx` since before Stargate. - - * [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) - - * (x/gov) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. - - * (x/authx) [#15284](https://github.com/cosmos/cosmos-sdk/pull/15284) `NewKeeper` now requires `codec.Codec`. - - * `types/tx.Tx` no longer implements `sdk.Tx`. - - * `sdk.Tx` now requires a new method `GetMsgsV2()`. - - * `sdk.Msg.GetSigners` was deprecated and is no longer supported. Use the `cosmos.msg.v1.signer` protobuf annotation instead. - - * `TxConfig` has a new method `SigningContext() *signing.Context`. - - * `SigVerifiableTx.GetSigners()` now returns `([][]byte, error)` instead of `[]sdk.AccAddress`. - - * `AccountKeeper` now has an `AddressCodec() address.Codec` method and the expected `AccountKeeper` for `x/auth/ante` expects this method. - - * [#15211](https://github.com/cosmos/cosmos-sdk/pull/15211) Remove usage of `github.com/cometbft/cometbft/libs/bytes.HexBytes` in favor of `[]byte` thorough the SDK. - - * (crypto) [#15070](https://github.com/cosmos/cosmos-sdk/pull/15070) `GenerateFromPassword` and `Cost` from `bcrypt.go` now take a `uint32` instead of a `int` type. - - * (types) [#15067](https://github.com/cosmos/cosmos-sdk/pull/15067) Remove deprecated alias from `types/errors`. Use `cosmossdk.io/errors` instead. - - * (server) [#15041](https://github.com/cosmos/cosmos-sdk/pull/15041) Refactor how gRPC and API servers are started to remove unnecessary sleeps: - - * `api.Server#Start` now accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the API server can gracefully exit. The caller does not need to stop the server. - - * To start the gRPC server you must first create the server via `NewGRPCServer`, after which you can start the gRPC server via `StartGRPCServer` which accepts a `context.Context`. The caller is responsible for ensuring that the context is canceled such that the gRPC server can gracefully exit. The caller does not need to stop the server. - - * Rename `WaitForQuitSignals` to `ListenForQuitSignals`. Note, this function is no longer blocking. Thus the caller is expected to provide a `context.CancelFunc` which indicates that when a signal is caught, that any spawned processes can gracefully exit. - - * Remove `ServerStartTime` constant. - - * [#15011](https://github.com/cosmos/cosmos-sdk/pull/15011) All functions that were taking a CometBFT logger, now take `cosmossdk.io/log.Logger` instead. - - * (simapp) [#14977](https://github.com/cosmos/cosmos-sdk/pull/14977) Move simulation helpers functions (`AppStateFn` and `AppStateRandomizedFn`) to `testutil/sims`. These takes an extra genesisState argument which is the default state of the app. - - * (x/bank) [#14894](https://github.com/cosmos/cosmos-sdk/pull/14894) Allow a human readable denomination for coins when querying bank balances. Added a `ResolveDenom` parameter to `types.QueryAllBalancesRequest`. - - * [#14847](https://github.com/cosmos/cosmos-sdk/pull/14847) App and ModuleManager methods `InitGenesis`, `ExportGenesis`, `BeginBlock` and `EndBlock` now also return an error. - - * (x/upgrade) [#14764](https://github.com/cosmos/cosmos-sdk/pull/14764) The `x/upgrade` module is extracted to have a separate go.mod file which allows it to be a standalone module. - - * (x/auth) [#14758](https://github.com/cosmos/cosmos-sdk/pull/14758) Refactor transaction searching: - - * Refactor `QueryTxsByEvents` to accept a `query` of type `string` instead of `events` of type `[]string` - - * Refactor CLI methods to accept `--query` flag instead of `--events` - - * Pass `prove=false` to Tendermint's `TxSearch` RPC method - - * (simulation) [#14751](https://github.com/cosmos/cosmos-sdk/pull/14751) Remove the `MsgType` field from `simulation.OperationInput` struct. - - * (store) [#14746](https://github.com/cosmos/cosmos-sdk/pull/14746) Extract Store in its own go.mod and rename the package to `cosmossdk.io/store`. - - * (x/nft) [#14725](https://github.com/cosmos/cosmos-sdk/pull/14725) Extract NFT in its own go.mod and rename the package to `cosmossdk.io/x/nft`. - +{/* Release notes content will be added here soon */} \ No newline at end of file diff --git a/docs/sdk/v0.53/core-concepts/events.mdx b/docs/sdk/v0.53/core-concepts/events.mdx index 5f442299..a3848207 100644 --- a/docs/sdk/v0.53/core-concepts/events.mdx +++ b/docs/sdk/v0.53/core-concepts/events.mdx @@ -14,7 +14,7 @@ description: "Version: v0.53" ## Events[​](#events-1 "Direct link to Events") -Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: `{eventType}.{attributeKey}={attributeValue}`. +Events are implemented in the Cosmos SDK as an alias of the ABCI `Event` type and take the form of: ``{eventType}.``{attributeKey}```={attributeValue}`. proto/tendermint/abci/types.proto @@ -36,7 +36,7 @@ An Event contains: *Typed Events* are Protobuf-defined [messages](/v0.53/build/architecture/adr-032-typed-events) used by the Cosmos SDK for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`. *Legacy Events* are defined on a **per-module basis** in the module's `/types/events.go` file. They are triggered from the module's Protobuf [`Msg` service](/v0.53/build/building-modules/msg-services) by using the [`EventManager`](#eventmanager). -In addition, each module documents its events under in the `Events` sections of its specs (x/\{moduleName}/`README.md`). +In addition, each module documents its events under in the `Events` sections of its specs (x/\`{moduleName}`/`README.md`). Lastly, Events are returned to the underlying consensus engine in the response of the following ABCI messages: diff --git a/docs/sdk/v0.53/learn.mdx b/docs/sdk/v0.53/learn.mdx deleted file mode 100644 index 763e99fb..00000000 --- a/docs/sdk/v0.53/learn.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: "Learn" -description: "Version: v0.53" ---- - -* [Introduction](./learn/intro/overview) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, laying the groundwork for understanding blockchain development. In this section we provide a High-Level Overview of the SDK, then dive deeper into Core concepts such as Application-Specific Blockchains, Blockchain Architecture, and finally we begin to explore the main components of the SDK. -* [Beginner](./learn/beginner/app-anatomy) - Start your journey with beginner-friendly resources in the Cosmos SDK's "Learn" section, providing a gentle entry point for newcomers to blockchain development. Here we focus on a little more detail, covering the Anatomy of a Cosmos SDK Application, Transaction Lifecycles, Accounts and lastly, Gas and Fees. -* [Advanced](./learn/advanced/baseapp) - Level up your Cosmos SDK expertise with advanced topics, tailored for experienced developers diving into intricate blockchain application development. We cover the Cosmos SDK on a lower level as we dive into the core of the SDK with BaseApp, Transactions, Context, Node Client (Daemon), Store, Encoding, gRPC, REST, and CometBFT Endpoints, CLI, Events, Telemetry, Object-Capability Model, RunTx recovery middleware, Cosmos Blockchain Simulator, Protobuf Documentation, In-Place Store Migrations, Configuration and AutoCLI. diff --git a/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx index e52b94b6..d307951b 100644 --- a/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx +++ b/docs/sdk/v0.53/messaging-queries/messages-and-queries.mdx @@ -29,7 +29,7 @@ Defining Protobuf `Msg` services is the recommended way to handle messages. A Pr Each `Msg` service method must have exactly one argument, which must implement the `sdk.Msg` interface, and a Protobuf response. The naming convention is to call the RPC argument `Msg` and the RPC response `MsgResponse`. For example: ```protobuf - rpc Send(MsgSend) returns (MsgSendResponse); +rpc Send(MsgSend) returns (MsgSendResponse); ``` See an example of a `Msg` service definition from `x/bank` module: @@ -61,14 +61,14 @@ If there is a need for custom signers then there is an alternative path which ca ```go func ProvideBankSendTransactionGetSigners() signing.CustomGetSigner { - // Extract the signer from the signature. - signer, err := coretypes.LatestSigner(Tx).Sender(ethTx) - if err != nil { - return nil, err - } + // Extract the signer from the signature. + signer, err := coretypes.LatestSigner(Tx).Sender(ethTx) + if err != nil { + return nil, err + } - // Return the signer in the required format. - return [][]byte{signer.Bytes()}, nil + // Return the signer in the required format. + return [][]byte{signer.Bytes()}, nil } ``` diff --git a/docs/sdk/v0.53/messaging-queries/msg-services.mdx b/docs/sdk/v0.53/messaging-queries/msg-services.mdx index c41a0e09..e941dd7d 100644 --- a/docs/sdk/v0.53/messaging-queries/msg-services.mdx +++ b/docs/sdk/v0.53/messaging-queries/msg-services.mdx @@ -55,10 +55,11 @@ It is recommended to implement all validation checks in a separate function that ```go ValidateMsgA(msg MsgA, now Time, gm GasMeter) error { if now.Before(msg.Expire) { - return sdkerrrors.ErrInvalidRequest.Wrap("msg expired") - } + return sdkerrrors.ErrInvalidRequest.Wrap("msg expired") +} gm.ConsumeGas(1000, "signature verification") - return signatureVerificaton(msg.Prover, msg.Data) + +return signatureVerificaton(msg.Prover, msg.Data) } ``` @@ -77,7 +78,9 @@ Before returning, `msgServer` methods generally emit one or more [events](../../ ```go ctx.EventManager().EmitTypedEvent( - &group.EventABC{Key1: Value1, Key2, Value2}) + &group.EventABC{ + Key1: Value1, Key2, Value2 +}) ``` or the older `EmitEvent` function: diff --git a/docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx b/docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx index 765e3f5f..f6d77386 100644 --- a/docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx +++ b/docs/sdk/v0.53/messaging-queries/query-lifecycle.mdx @@ -44,7 +44,7 @@ Another interface through which users can make queries is [gRPC](https://grpc.io One such tool is [grpcurl](https://github.com/fullstorydev/grpcurl), and a gRPC request for `MyQuery` using this client looks like: ``` -grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name +grpcurl \ -plaintext # We want results in plain test -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '\{"address":"$MY_DELEGATOR"}' \ # Query arguments localhost:9090 \ # gRPC server endpoint cosmos.staking.v1beta1.Query/Delegations # Fully-qualified service method name ``` ### REST[​](#rest "Direct link to REST") @@ -54,7 +54,7 @@ Another interface through which users can make queries is through HTTP Requests An example HTTP request for `MyQuery` looks like: ``` -GET http://localhost:1317/cosmos/staking/v1beta1/delegators/{delegatorAddr}/delegations +GET http://localhost:1317/cosmos/staking/v1beta1/delegators/`{delegatorAddr}`/delegations ``` ## How Queries are Handled by the CLI[​](#how-queries-are-handled-by-the-cli "Direct link to How Queries are Handled by the CLI") diff --git a/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx index 99d31a16..004383eb 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/errors.mdx @@ -16,7 +16,7 @@ execution context. ## Registration -Modules should define and register their custom errors in `x/{module}/errors.go`. +Modules should define and register their custom errors in ``x/``{module}```/errors.go`. Registration of errors is handled via the [`errors` package](https://github.com/cosmos/cosmos-sdk/blob/main/errors/errors.go). Example: diff --git a/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx index 150d4679..b76651b2 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/invariants.mdx @@ -33,8 +33,8 @@ In practice, each module implements `Invariant`s in a `keeper/invariants.go` fil func BalanceInvariants(k Keeper) sdk.Invariant { return func(ctx context.Context) (string, bool) { - // Implement checks for balance-related invariants - } + // Implement checks for balance-related invariants + } } ``` diff --git a/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx index 9fd43f7b..25e83fd1 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/keeper.mdx @@ -30,13 +30,13 @@ The core idea behind the object-capabilities approach is to only reveal what is ```go type Keeper struct { - // External keepers, if any + // External keepers, if any - // Store key(s) + // Store key(s) - // codec + // codec - // authority + // authority } ``` @@ -62,7 +62,11 @@ Of course, it is possible to define different types of internal `keeper`s for th Typically, a *getter* method will have the following signature ```go -func (k Keeper) Get(ctx context.Context, key string) returnType +func (k Keeper) + +Get(ctx context.Context, key string) + +returnType ``` and the method will go through the following steps: @@ -74,7 +78,9 @@ and the method will go through the following steps: Similarly, a *setter* method will have the following signature ```go -func (k Keeper) Set(ctx context.Context, key string, value valueType) +func (k Keeper) + +Set(ctx context.Context, key string, value valueType) ``` and the method will go through the following steps: diff --git a/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx index 5b411e8a..601b37dd 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/module-interfaces.mdx @@ -66,8 +66,8 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/module.go#L84-L This section is being rewritten. Refer to [AutoCLI](https://docs.cosmos.network/main/core/autocli) while this section is being updated. - +{/* TODO: leaving this here to update docs with core api changes */} diff --git a/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx index afc2b382..86069fc4 100644 --- a/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx +++ b/docs/sdk/v0.53/module-anatomy-keepers/structure.mdx @@ -15,10 +15,18 @@ A typical Cosmos SDK module can be structured as follows: ```shell proto -└── {project_name} -    └── {module_name} -    └── {proto_version} -       ├── {module_name}.proto +└── { + project_name +} +    └── { + module_name +} +    └── { + proto_version +} +       ├── { + module_name +}.proto       ├── event.proto       ├── genesis.proto       ├── query.proto @@ -32,7 +40,9 @@ proto * `tx.proto`: The module's Msg service and related message type definitions. ```shell -x/{module_name} +x/{ + module_name +} ├── client │   ├── cli │   │ ├── query.go @@ -60,7 +70,9 @@ x/{module_name} │   ├── genesis.go │   ├── operations.go │   └── params.go -├── {module_name}.pb.go +├── { + module_name +}.pb.go ├── codec.go ├── errors.go ├── events.go diff --git a/docs/sdk/v0.53/module-reference/auth.mdx b/docs/sdk/v0.53/module-reference/auth.mdx index 61479757..9c4858a1 100644 --- a/docs/sdk/v0.53/module-reference/auth.mdx +++ b/docs/sdk/v0.53/module-reference/auth.mdx @@ -513,7 +513,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' \ + -d '{"address":"cosmos1.." +}' \ localhost:9090 \ cosmos.auth.v1beta1.Query/Account ``` @@ -528,9 +529,9 @@ Example Output: "pubKey":{ "@type":"/cosmos.crypto.secp256k1.PubKey", "key":"ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD" - }, +}, "sequence":"1" - } +} } ``` @@ -561,92 +562,92 @@ Example Output: "pubKey":{ "@type":"/cosmos.crypto.secp256k1.PubKey", "key":"ApDrE38zZdd7wLmFS9YmqO684y5DG6fjZ4rVeihF/AQD" - }, +}, "sequence":"1" - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos1yl6hdjhmkf37639730gffanpzndzdpmhwlkfhr", "accountNumber":"8" - }, +}, "name":"transfer", "permissions":[ "minter", "burner" ] - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", "accountNumber":"4" - }, +}, "name":"bonded_tokens_pool", "permissions":[ "burner", "staking" ] - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos1tygms3xhhs3yv487phx3dw4a95jn7t7lpm470r", "accountNumber":"5" - }, +}, "name":"not_bonded_tokens_pool", "permissions":[ "burner", "staking" ] - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos10d07y265gmmuvt4z0w9aw880jnsr700j6zn9kn", "accountNumber":"6" - }, +}, "name":"gov", "permissions":[ "burner" ] - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos1jv65s3grqf6v6jl3dp4t6c9t9rk99cd88lyufl", "accountNumber":"3" - }, +}, "name":"distribution" - }, +}, { "@type":"/cosmos.auth.v1beta1.BaseAccount", "accountNumber":"1", "address":"cosmos147k3r7v2tvwqhcmaxcfql7j8rmkrlsemxshd3j" - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos1m3h30wlvsf8llruxtpukdvsy0km2kum8g38c8q", "accountNumber":"7" - }, +}, "name":"mint", "permissions":[ "minter" ] - }, +}, { "@type":"/cosmos.auth.v1beta1.ModuleAccount", "baseAccount":{ "address":"cosmos17xpfvakm2amg962yls6f84z3kell8c5lserqta", "accountNumber":"2" - }, +}, "name":"fee_collector" - } +} ], "pagination":{ "total":"9" - } +} } ``` @@ -676,7 +677,7 @@ Example Output: "txSizeCostPerByte": "10", "sigVerifyCostEd25519": "590", "sigVerifyCostSecp256k1": "1000" - } +} } ``` @@ -689,7 +690,9 @@ A user can query the `auth` module using REST endpoints. The `account` endpoint allow users to query for an account by it's address. ```bash -/cosmos/auth/v1beta1/account?address={address} +/cosmos/auth/v1beta1/account?address={ + address +} ``` #### Accounts diff --git a/docs/sdk/v0.53/module-reference/authz.mdx b/docs/sdk/v0.53/module-reference/authz.mdx index ac6227bb..25d60630 100644 --- a/docs/sdk/v0.53/module-reference/authz.mdx +++ b/docs/sdk/v0.53/module-reference/authz.mdx @@ -239,7 +239,7 @@ simd tx authz --help The `exec` command allows a grantee to execute a transaction on behalf of granter. ```bash - simd tx authz exec [tx-json-file] --from [grantee] [flags] +simd tx authz exec [tx-json-file] --from [grantee] [flags] ``` Example: @@ -260,7 +260,7 @@ simd tx authz grant Note: `allowed-validators` and `deny-validators` cannot both be empty. `spend-limit` represents the `MaxTokens` @@ -309,7 +309,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"granter":"cosmos1..","grantee":"cosmos1..","msg_type_url":"/cosmos.bank.v1beta1.MsgSend"}' \ + -d '{"granter":"cosmos1..","grantee":"cosmos1..","msg_type_url":"/cosmos.bank.v1beta1.MsgSend" +}' \ localhost:9090 \ cosmos.authz.v1beta1.Query/Grants ``` @@ -326,11 +327,11 @@ Example Output: { "denom":"stake", "amount":"100" - } +} ] - }, +}, "expiration": "2022-01-01T00:00:00Z" - } +} ] } ``` @@ -361,11 +362,11 @@ Example Output: { "denom": "stake", "amount": "100" - } +} ] - }, +}, "expiration": "2022-01-01T00:00:00Z" - } +} ], "pagination": null } diff --git a/docs/sdk/v0.53/module-reference/bank.mdx b/docs/sdk/v0.53/module-reference/bank.mdx index 3cbe919f..3f9ecce4 100644 --- a/docs/sdk/v0.53/module-reference/bank.mdx +++ b/docs/sdk/v0.53/module-reference/bank.mdx @@ -72,11 +72,11 @@ The `ModuleAccount` interface is defined as follows: ```go type ModuleAccount interface { - auth.Account // same methods as the Account interface + auth.Account // same methods as the Account interface - GetName() string // name of the module; used to obtain the address - GetPermissions() []string // permissions of module account - HasPermission(string) bool + GetName() string // name of the module; used to obtain the address + GetPermissions() []string // permissions of module account + HasPermission(string) bool } ``` @@ -192,36 +192,36 @@ Restricted permission to mint per module could be achieved by using baseKeeper w // Keeper defines a module interface that facilitates the transfer of coins // between accounts. type Keeper interface { - SendKeeper - WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper - - InitGenesis(context.Context, *types.GenesisState) - ExportGenesis(context.Context) *types.GenesisState - - GetSupply(ctx context.Context, denom string) sdk.Coin - HasSupply(ctx context.Context, denom string) bool - GetPaginatedTotalSupply(ctx context.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) - IterateTotalSupply(ctx context.Context, cb func(sdk.Coin) bool) - GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, bool) - HasDenomMetaData(ctx context.Context, denom string) bool - SetDenomMetaData(ctx context.Context, denomMetaData types.Metadata) - IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) - - SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - DelegateCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - UndelegateCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx context.Context, moduleName string, amt sdk.Coins) error - - DelegateCoins(ctx context.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error - UndelegateCoins(ctx context.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error - - // GetAuthority gets the address capable of executing governance proposal messages. Usually the gov module account. - GetAuthority() string - - types.QueryServer + SendKeeper + WithMintCoinsRestriction(MintingRestrictionFn) BaseKeeper + + InitGenesis(context.Context, *types.GenesisState) + ExportGenesis(context.Context) *types.GenesisState + + GetSupply(ctx context.Context, denom string) sdk.Coin + HasSupply(ctx context.Context, denom string) bool + GetPaginatedTotalSupply(ctx context.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) + IterateTotalSupply(ctx context.Context, cb func(sdk.Coin) bool) + GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, bool) + HasDenomMetaData(ctx context.Context, denom string) bool + SetDenomMetaData(ctx context.Context, denomMetaData types.Metadata) + IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) + + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx context.Context, senderModule, recipientModule string, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + DelegateCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + UndelegateCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + + DelegateCoins(ctx context.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error + UndelegateCoins(ctx context.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error + + // GetAuthority gets the address capable of executing governance proposal messages. Usually the gov module account. + GetAuthority() string + + types.QueryServer } ``` @@ -234,29 +234,29 @@ accounts. The send keeper does not alter the total supply (mint or burn coins). // SendKeeper defines a module interface that facilitates the transfer of coins // between accounts without the possibility of creating coins. type SendKeeper interface { - ViewKeeper + ViewKeeper - AppendSendRestriction(restriction SendRestrictionFn) - PrependSendRestriction(restriction SendRestrictionFn) - ClearSendRestriction() + AppendSendRestriction(restriction SendRestrictionFn) + PrependSendRestriction(restriction SendRestrictionFn) + ClearSendRestriction() - InputOutputCoins(ctx context.Context, input types.Input, outputs []types.Output) error - SendCoins(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error + InputOutputCoins(ctx context.Context, input types.Input, outputs []types.Output) error + SendCoins(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error - GetParams(ctx context.Context) types.Params - SetParams(ctx context.Context, params types.Params) error + GetParams(ctx context.Context) types.Params + SetParams(ctx context.Context, params types.Params) error - IsSendEnabledDenom(ctx context.Context, denom string) bool - SetSendEnabled(ctx context.Context, denom string, value bool) - SetAllSendEnabled(ctx context.Context, sendEnableds []*types.SendEnabled) - DeleteSendEnabled(ctx context.Context, denom string) - IterateSendEnabledEntries(ctx context.Context, cb func(denom string, sendEnabled bool) (stop bool)) - GetAllSendEnabledEntries(ctx context.Context) []types.SendEnabled + IsSendEnabledDenom(ctx context.Context, denom string) bool + SetSendEnabled(ctx context.Context, denom string, value bool) + SetAllSendEnabled(ctx context.Context, sendEnableds []*types.SendEnabled) + DeleteSendEnabled(ctx context.Context, denom string) + IterateSendEnabledEntries(ctx context.Context, cb func(denom string, sendEnabled bool) (stop bool)) + GetAllSendEnabledEntries(ctx context.Context) []types.SendEnabled - IsSendEnabledCoin(ctx context.Context, coin sdk.Coin) bool - IsSendEnabledCoins(ctx context.Context, coins ...sdk.Coin) error + IsSendEnabledCoin(ctx context.Context, coin sdk.Coin) bool + IsSendEnabledCoins(ctx context.Context, coins ...sdk.Coin) error - BlockedAddr(addr sdk.AccAddress) bool + BlockedAddr(addr sdk.AccAddress) bool } ``` @@ -305,7 +305,7 @@ The bank keeper should be provided to your keeper's constructor so the send rest ```golang func NewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, bankKeeper mymodule.BankKeeper) Keeper { - rv := Keeper{/*...*/} + rv := Keeper{ /*...*/ } bankKeeper.AppendSendRestriction(rv.SendRestrictionFn) return rv } @@ -353,18 +353,18 @@ The view keeper provides read-only access to account balances. The view keeper d // ViewKeeper defines a module interface that facilitates read only access to // account balances. type ViewKeeper interface { - ValidateBalance(ctx context.Context, addr sdk.AccAddress) error - HasBalance(ctx context.Context, addr sdk.AccAddress, amt sdk.Coin) bool - - GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins - GetAccountsBalances(ctx context.Context) []types.Balance - GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin - LockedCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoin(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin - - IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(coin sdk.Coin) (stop bool)) - IterateAllBalances(ctx context.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) + ValidateBalance(ctx context.Context, addr sdk.AccAddress) error + HasBalance(ctx context.Context, addr sdk.AccAddress, amt sdk.Coin) bool + + GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins + GetAccountsBalances(ctx context.Context) []types.Balance + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + LockedCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoin(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + + IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(coin sdk.Coin) (stop bool)) + IterateAllBalances(ctx context.Context, cb func(address sdk.AccAddress, coin sdk.Coin) (stop bool)) } ``` @@ -435,21 +435,21 @@ The bank module emits the following events: | Type | Attribute Key | Attribute Value | | -------- | ------------- | ------------------ | -| transfer | recipient | {recipientAddress} | -| transfer | amount | {amount} | +| transfer | recipient | `{recipientAddress}` | +| transfer | amount | `{amount}` | | message | module | bank | | message | action | send | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | #### MsgMultiSend | Type | Attribute Key | Attribute Value | | -------- | ------------- | ------------------ | -| transfer | recipient | {recipientAddress} | -| transfer | amount | {amount} | +| transfer | recipient | `{recipientAddress}` | +| transfer | amount | `{amount}` | | message | module | bank | | message | action | multisend | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ### Keeper Events @@ -698,7 +698,7 @@ send_enabled: - denom: barcoin pagination: next-key: null - total: 2 + total: 2 ``` #### Transactions @@ -739,7 +739,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"address":"cosmos1..","denom":"stake"}' \ + -d '{"address":"cosmos1..","denom":"stake" +}' \ localhost:9090 \ cosmos.bank.v1beta1.Query/Balance ``` @@ -767,7 +768,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' \ + -d '{"address":"cosmos1.." +}' \ localhost:9090 \ cosmos.bank.v1beta1.Query/AllBalances ``` @@ -800,7 +802,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"denom":"stake"}' \ + -d '{"denom":"stake" +}' \ localhost:9090 \ cosmos.bank.v1beta1.Query/DenomMetadata ``` @@ -882,7 +885,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"denom":"stake"}' \ + -d '{"denom":"stake" +}' \ localhost:9090 \ cosmos.bank.v1beta1.Query/DenomOwners ``` @@ -893,22 +897,24 @@ Example Output: { "denomOwners": [ { - "address": "cosmos1..", - "balance": { - "denom": "stake", - "amount": "5000000000" + "address": "cosmos1..", + "balance": { + "denom": "stake", + "amount": "5000000000" } - }, + +}, { - "address": "cosmos1..", - "balance": { - "denom": "stake", - "amount": "5000000000" + "address": "cosmos1..", + "balance": { + "denom": "stake", + "amount": "5000000000" } - }, + +}, ], "pagination": { - "total": "2" + "total": "2" } } ``` @@ -957,7 +963,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"denom":"stake"}' \ + -d '{"denom":"stake" +}' \ localhost:9090 \ cosmos.bank.v1beta1.Query/SupplyOf ``` diff --git a/docs/sdk/v0.53/module-reference/crisis.mdx b/docs/sdk/v0.53/module-reference/crisis.mdx index 1c792d8f..483c9887 100644 --- a/docs/sdk/v0.53/module-reference/crisis.mdx +++ b/docs/sdk/v0.53/module-reference/crisis.mdx @@ -70,10 +70,10 @@ The crisis module emits the following events: | Type | Attribute Key | Attribute Value | |-----------|---------------|------------------| -| invariant | route | {invariantRoute} | +| invariant | route | `{invariantRoute}` | | message | module | crisis | | message | action | verify_invariant | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ## Parameters @@ -81,7 +81,7 @@ The crisis module contains the following parameters: | Key | Type | Example | |-------------|---------------|-----------------------------------| -| ConstantFee | object (coin) | {"denom":"uatom","amount":"1000"} | +| ConstantFee | object (coin) | `{"denom":"uatom","amount":"1000"}` | ## Client diff --git a/docs/sdk/v0.53/module-reference/distribution.mdx b/docs/sdk/v0.53/module-reference/distribution.mdx index ddb61dc1..cfeaf90d 100644 --- a/docs/sdk/v0.53/module-reference/distribution.mdx +++ b/docs/sdk/v0.53/module-reference/distribution.mdx @@ -168,8 +168,8 @@ When coins are distributed from the pool they are truncated back to type DecCoins []DecCoin type DecCoin struct { - Amount math.LegacyDec - Denom string + Amount math.LegacyDec + Denom string } ``` @@ -189,9 +189,9 @@ Validator distribution information for the relevant validator is updated each ti ```go type ValidatorDistInfo struct { - OperatorAddress sdk.AccAddress - SelfBondRewards sdkmath.DecCoins - ValidatorCommission types.ValidatorAccumulatedCommission + OperatorAddress sdk.AccAddress + SelfBondRewards sdkmath.DecCoins + ValidatorCommission types.ValidatorAccumulatedCommission } ``` @@ -207,7 +207,7 @@ only the height of the last withdrawal and its current properties. ```go type DelegationDistInfo struct { - WithdrawalHeight int64 // last time this delegation withdrew rewards + WithdrawalHeight int64 // last time this delegation withdrew rewards } ``` @@ -360,12 +360,14 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/distribution/ ```go func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error if k.blockedAddrs[withdrawAddr.String()] { - fail with "`{withdrawAddr}` is not allowed to receive external funds" - } + fail with "`{ + withdrawAddr +}` is not allowed to receive external funds" +} if !k.GetWithdrawAddrEnabled(ctx) { - fail with `ErrSetWithdrawAddrDisabled` - } + fail with `ErrSetWithdrawAddrDisabled` +} k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) ``` @@ -396,7 +398,8 @@ previous := A for P in P1, ..., PN`: rewards = (R(P) - previous) * stake stake = stake * F(P) - previous = P + +previous = P rewards = rewards + (R(B) - R(PN)) * stake ``` @@ -430,22 +433,22 @@ The transaction fails if the amount cannot be transferred from the sender to the ```go func (k Keeper) FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { - return err - } + if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount); err != nil { + return err + } - feePool, err := k.FeePool.Get(ctx) - if err != nil { - return err - } + feePool, err := k.FeePool.Get(ctx) + if err != nil { + return err + } - feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) - - if err := k.FeePool.Set(ctx, feePool); err != nil { - return err - } + feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amount...)...) - return nil + if err := k.FeePool.Set(ctx, feePool); err != nil { + return err + } + + return nil } ``` @@ -461,8 +464,8 @@ Initializing a delegation increments the validator period and keeps track of the ```go // initialize starting info for a new delegation func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) { - // period has already been incremented - we want to store the period ended by this delegation action - previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1 + // period has already been incremented - we want to store the period ended by this delegation action + previousPeriod := k.GetValidatorCurrentRewards(ctx, val).Period - 1 // increment reference count for the period we're going to track k.incrementReferenceCount(ctx, val, previousPeriod) @@ -553,12 +556,12 @@ The distribution module emits the following events: | Type | Attribute Key | Attribute Value | |-----------------|---------------|--------------------| -| proposer_reward | validator | {validatorAddress} | -| proposer_reward | reward | {proposerReward} | -| commission | amount | {commissionAmount} | -| commission | validator | {validatorAddress} | -| rewards | amount | {rewardAmount} | -| rewards | validator | {validatorAddress} | +| proposer_reward | validator | `{validatorAddress}` | +| proposer_reward | reward | `{proposerReward}` | +| commission | amount | `{commissionAmount}` | +| commission | validator | `{validatorAddress}` | +| rewards | amount | `{rewardAmount}` | +| rewards | validator | `{validatorAddress}` | ### Handlers @@ -566,29 +569,29 @@ The distribution module emits the following events: | Type | Attribute Key | Attribute Value | |----------------------|------------------|----------------------| -| set_withdraw_address | withdraw_address | {withdrawAddress} | +| set_withdraw_address | withdraw_address | `{withdrawAddress}` | | message | module | distribution | | message | action | set_withdraw_address | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | #### MsgWithdrawDelegatorReward | Type | Attribute Key | Attribute Value | |---------|---------------|---------------------------| -| withdraw_rewards | amount | {rewardAmount} | -| withdraw_rewards | validator | {validatorAddress} | +| withdraw_rewards | amount | `{rewardAmount}` | +| withdraw_rewards | validator | `{validatorAddress}` | | message | module | distribution | | message | action | withdraw_delegator_reward | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | #### MsgWithdrawValidatorCommission | Type | Attribute Key | Attribute Value | |------------|---------------|-------------------------------| -| withdraw_commission | amount | {commissionAmount} | +| withdraw_commission | amount | `{commissionAmount}` | | message | module | distribution | | message | action | withdraw_validator_commission | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ## Parameters @@ -884,7 +887,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1..."}' \ + -d '{"validator_address":"cosmosvalop1..." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/ValidatorDistributionInfo ``` @@ -919,7 +923,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ + -d '{"validator_address":"cosmosvalop1.." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/ValidatorOutstandingRewards ``` @@ -947,7 +952,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ + -d '{"validator_address":"cosmosvalop1.." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/ValidatorCommission ``` @@ -975,7 +981,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"validator_address":"cosmosvalop1.."}' \ + -d '{"validator_address":"cosmosvalop1.." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/ValidatorSlashes ``` @@ -1004,7 +1011,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1...","validator_address":"cosmosvalop1..."}' \ + -d '{"delegator_address":"cosmos1...","validator_address":"cosmosvalop1..." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/DelegationRewards ``` @@ -1030,7 +1038,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ + -d '{"delegator_address":"cosmos1..." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/DelegationTotalRewards ``` @@ -1067,7 +1076,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ + -d '{"delegator_address":"cosmos1..." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/DelegatorValidators ``` @@ -1076,7 +1086,9 @@ Example Output: ```json { - "validators": ["cosmosvaloper1..."] + "validators": [ + "cosmosvaloper1..." + ] } ``` @@ -1088,7 +1100,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"delegator_address":"cosmos1..."}' \ + -d '{"delegator_address":"cosmos1..." +}' \ localhost:9090 \ cosmos.distribution.v1beta1.Query/DelegatorWithdrawAddress ``` diff --git a/docs/sdk/v0.53/module-reference/epochs.mdx b/docs/sdk/v0.53/module-reference/epochs.mdx index 9144fb30..e7104728 100644 --- a/docs/sdk/v0.53/module-reference/epochs.mdx +++ b/docs/sdk/v0.53/module-reference/epochs.mdx @@ -1,9 +1,7 @@ --- title: "`x/epochs`" - --- - ## Abstract Often in the SDK, we would like to run certain code every-so often. The @@ -53,14 +51,14 @@ The `epochs` module emits the following events: | Type | Attribute Key | Attribute Value | | ----------- | ------------- | --------------- | -| epoch_start | epoch_number | {epoch_number} | -| epoch_start | start_time | {start_time} | +| epoch_start | epoch_number | `{epoch_number}` | +| epoch_start | start_time | `{start_time}` | ### EndBlocker | Type | Attribute Key | Attribute Value | | --------- | ------------- | --------------- | -| epoch_end | epoch_number | {epoch_number} | +| epoch_end | epoch_number | `{epoch_number}` | ## Keepers @@ -71,7 +69,7 @@ Epochs keeper module provides utility functions to manage epochs. ## Hooks ```go - // the first block whose timestamp is after the duration is counted as the end of the epoch +// the first block whose timestamp is after the duration is counted as the end of the epoch AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) // new epoch is next block of epoch end block BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber int64) @@ -88,11 +86,10 @@ This is the standard dev UX of this: ```golang func (k MyModuleKeeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) { - params := k.GetParams(ctx) - if epochIdentifier == params.DistrEpochIdentifier { + params := k.GetParams(ctx) + +if epochIdentifier == params.DistrEpochIdentifier { // my logic - } -} ``` ### Panic isolation @@ -114,9 +111,10 @@ The Epochs module provides the following queries to check the module's state. ```protobuf service Query { // EpochInfos provide running epochInfos - rpc EpochInfos(QueryEpochsInfoRequest) returns (QueryEpochsInfoResponse) {} + rpc EpochInfos(QueryEpochsInfoRequest) returns (QueryEpochsInfoResponse) { +} // CurrentEpoch provide current epoch of specified identifier - rpc CurrentEpoch(QueryCurrentEpochRequest) returns (QueryCurrentEpochResponse) {} + rpc CurrentEpoch(QueryCurrentEpochRequest) returns (QueryCurrentEpochResponse) { } ``` @@ -125,16 +123,15 @@ service Query { Query the currently running epochInfos ```sh - query epochs epoch-infos +<appd> query epochs epoch-infos ``` -```sh -``` - + **Example** An example output: +```sh expandable epochs: - current_epoch: "183" current_epoch_start_height: "2438409" @@ -150,30 +147,31 @@ epochs: epoch_counting_started: true identifier: week start_time: "2021-06-18T17:00:00Z" +``` - + ### Current Epoch Query the current epoch by the specified identifier ```sh - query epochs current-epoch [identifier] +<appd> query epochs current-epoch [identifier] ``` -```sh -``` -```sh -``` - + **Example** Query the current `day` epoch: - query epochs current-epoch day +```sh +<appd> query epochs current-epoch day +``` Which in this example outputs: +```sh current_epoch: "183" +``` - + \ No newline at end of file diff --git a/docs/sdk/v0.53/module-reference/evidence.mdx b/docs/sdk/v0.53/module-reference/evidence.mdx index 620d197e..5b66b9c7 100644 --- a/docs/sdk/v0.53/module-reference/evidence.mdx +++ b/docs/sdk/v0.53/module-reference/evidence.mdx @@ -52,13 +52,21 @@ has also been created to define a contract for evidence against malicious valida type Evidence interface { proto.Message - Route() string - String() string + Route() + + string + String() + + string Hash() []byte - ValidateBasic() error + ValidateBasic() + + error // Height at which the infraction occurred - GetHeight() int64 + GetHeight() + + int64 } // ValidatorEvidence extends Evidence interface to define contract @@ -67,13 +75,19 @@ type ValidatorEvidence interface { Evidence // The consensus address of the malicious validator at time of infraction - GetConsensusAddress() sdk.ConsAddress + GetConsensusAddress() + + sdk.ConsAddress // The total power of the malicious validator at time of infraction - GetValidatorPower() int64 + GetValidatorPower() + + int64 // The total validator set power at time of infraction - GetTotalPower() int64 + GetTotalPower() + + int64 } ``` @@ -87,11 +101,20 @@ via the `Route` method. ```go type Router interface { - AddRoute(r string, h Handler) Router - HasRoute(r string) bool - GetRoute(path string) Handler - Seal() - Sealed() bool + AddRoute(r string, h Handler) + + Router + HasRoute(r string) + + bool + GetRoute(path string) + + Handler + Seal() + + Sealed() + + bool } ``` @@ -107,7 +130,9 @@ by the `Handler` should be persisted. // for executing all corresponding business logic necessary for verifying the // evidence as valid. In addition, the Handler may execute any necessary // slashing and potential jailing. -type Handler func(context.Context, Evidence) error +type Handler func(context.Context, Evidence) + +error ``` ## State @@ -121,7 +146,6 @@ message GenesisState { // evidence defines all the evidence at genesis. repeated google.protobuf.Any evidence = 1; } - ``` All `Evidence` is retrieved and stored via a prefix `KVStore` using prefix `0x00` (`KeyPrefixEvidence`). @@ -149,28 +173,31 @@ Given the `Evidence` is registered with a corresponding `Handler`, it is process as follows: ```go -func SubmitEvidence(ctx Context, evidence Evidence) error { - if _, err := GetEvidence(ctx, evidence.Hash()); err == nil { - return errorsmod.Wrap(types.ErrEvidenceExists, strings.ToUpper(hex.EncodeToString(evidence.Hash()))) - } - if !router.HasRoute(evidence.Route()) { - return errorsmod.Wrap(types.ErrNoEvidenceHandlerExists, evidence.Route()) - } - - handler := router.GetRoute(evidence.Route()) - if err := handler(ctx, evidence); err != nil { - return errorsmod.Wrap(types.ErrInvalidEvidence, err.Error()) - } - - ctx.EventManager().EmitEvent( +func SubmitEvidence(ctx Context, evidence Evidence) + +error { + if _, err := GetEvidence(ctx, evidence.Hash()); err == nil { + return errorsmod.Wrap(types.ErrEvidenceExists, strings.ToUpper(hex.EncodeToString(evidence.Hash()))) +} + if !router.HasRoute(evidence.Route()) { + return errorsmod.Wrap(types.ErrNoEvidenceHandlerExists, evidence.Route()) +} + handler := router.GetRoute(evidence.Route()) + +if err := handler(ctx, evidence); err != nil { + return errorsmod.Wrap(types.ErrInvalidEvidence, err.Error()) +} + +ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeSubmitEvidence, sdk.NewAttribute(types.AttributeKeyEvidenceHash, strings.ToUpper(hex.EncodeToString(evidence.Hash()))), ), ) - SetEvidence(ctx, evidence) - return nil +SetEvidence(ctx, evidence) + +return nil } ``` @@ -188,9 +215,9 @@ The `x/evidence` module emits the following events: | Type | Attribute Key | Attribute Value | | --------------- | ------------- | --------------- | -| submit_evidence | evidence_hash | {evidenceHash} | +| submit_evidence | evidence_hash | `{evidenceHash}` | | message | module | evidence | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | | message | action | submit_evidence | ## Parameters @@ -317,7 +344,9 @@ A user can query the `evidence` module using REST endpoints. Get evidence by hash ```bash -/cosmos/evidence/v1beta1/evidence/{hash} +/cosmos/evidence/v1beta1/evidence/{ + hash +} ``` Example: @@ -335,7 +364,7 @@ Example Output: "height": "11", "power": "100", "time": "2021-10-20T16:08:38.194017624Z" - } +} } ``` @@ -363,11 +392,11 @@ Example Output: "height": "11", "power": "100", "time": "2021-10-20T16:08:38.194017624Z" - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -386,7 +415,8 @@ cosmos.evidence.v1beta1.Query/Evidence Example: ```bash -grpcurl -plaintext -d '{"evidence_hash":"DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660"}' localhost:9090 cosmos.evidence.v1beta1.Query/Evidence +grpcurl -plaintext -d '{"evidence_hash":"DF0C23E8634E480F84B9D5674A7CDC9816466DEC28A3358F73260F68D28D7660" +}' localhost:9090 cosmos.evidence.v1beta1.Query/Evidence ``` Example Output: @@ -398,7 +428,7 @@ Example Output: "height": "11", "power": "100", "time": "2021-10-20T16:08:38.194017624Z" - } +} } ``` @@ -426,10 +456,10 @@ Example Output: "height": "11", "power": "100", "time": "2021-10-20T16:08:38.194017624Z" - } +} ], "pagination": { "total": "1" - } +} } ``` diff --git a/docs/sdk/v0.53/module-reference/feegrant.mdx b/docs/sdk/v0.53/module-reference/feegrant.mdx index d00f27a8..e08491ee 100644 --- a/docs/sdk/v0.53/module-reference/feegrant.mdx +++ b/docs/sdk/v0.53/module-reference/feegrant.mdx @@ -187,31 +187,31 @@ The feegrant module emits the following events: | Type | Attribute Key | Attribute Value | | ------- | ------------- | ---------------- | | message | action | set_feegrant | -| message | granter | {granterAddress} | -| message | grantee | {granteeAddress} | +| message | granter | `{granterAddress}` | +| message | grantee | `{granteeAddress}` | ### MsgRevokeAllowance | Type | Attribute Key | Attribute Value | | ------- | ------------- | ---------------- | | message | action | revoke_feegrant | -| message | granter | {granterAddress} | -| message | grantee | {granteeAddress} | +| message | granter | `{granterAddress}` | +| message | grantee | `{granteeAddress}` | ### Exec fee allowance | Type | Attribute Key | Attribute Value | | ------- | ------------- | ---------------- | | message | action | use_feegrant | -| message | granter | {granterAddress} | -| message | grantee | {granteeAddress} | +| message | granter | `{granterAddress}` | +| message | grantee | `{granteeAddress}` | ### Prune fee allowances | Type | Attribute Key | Attribute Value | | ------- | ------------- | ---------------- | | message | action | prune_feegrant | -| message | pruner | {prunerAddress} | +| message | pruner | `{prunerAddress}` | ## Client @@ -343,7 +343,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"grantee":"cosmos1..","granter":"cosmos1.."}' \ + -d '{"grantee":"cosmos1..","granter":"cosmos1.." +}' \ localhost:9090 \ cosmos.feegrant.v1beta1.Query/Allowance ``` @@ -355,7 +356,15 @@ Example Output: "allowance": { "granter": "cosmos1..", "grantee": "cosmos1..", - "allowance": {"@type":"/cosmos.feegrant.v1beta1.BasicAllowance","spendLimit":[{"denom":"stake","amount":"100"}]} + "allowance": { + "@type": "/cosmos.feegrant.v1beta1.BasicAllowance", + "spendLimit": [ + { + "denom": "stake", + "amount": "100" + } + ] + } } } ``` @@ -372,7 +381,8 @@ Example: ```shell grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' \ + -d '{"address":"cosmos1.." +}' \ localhost:9090 \ cosmos.feegrant.v1beta1.Query/Allowances ``` @@ -385,7 +395,15 @@ Example Output: { "granter": "cosmos1..", "grantee": "cosmos1..", - "allowance": {"@type":"/cosmos.feegrant.v1beta1.BasicAllowance","spendLimit":[{"denom":"stake","amount":"100"}]} + "allowance": { + "@type": "/cosmos.feegrant.v1beta1.BasicAllowance", + "spendLimit": [ + { + "denom": "stake", + "amount": "100" + } + ] + } } ], "pagination": { diff --git a/docs/sdk/v0.53/module-reference/gov.mdx b/docs/sdk/v0.53/module-reference/gov.mdx index f4de2d19..fd010325 100644 --- a/docs/sdk/v0.53/module-reference/gov.mdx +++ b/docs/sdk/v0.53/module-reference/gov.mdx @@ -206,8 +206,7 @@ func myCustomVotingFunction( ) (totalVoterPower math.LegacyDec, results map[v1.VoteOption]math.LegacyDec, err error) { // ... tally logic } - -govKeeper := govkeeper.NewKeeper( + govKeeper := govkeeper.NewKeeper( appCodec, runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AccountKeeper, @@ -395,28 +394,28 @@ Additionally, we introduce some basic types: type Vote byte const ( - VoteYes = 0x1 - VoteNo = 0x2 - VoteNoWithVeto = 0x3 - VoteAbstain = 0x4 + VoteYes = 0x1 + VoteNo = 0x2 + VoteNoWithVeto = 0x3 + VoteAbstain = 0x4 ) -type ProposalType string +type ProposalType string const ( - ProposalTypePlainText = "Text" - ProposalTypeSoftwareUpgrade = "SoftwareUpgrade" + ProposalTypePlainText = "Text" + ProposalTypeSoftwareUpgrade = "SoftwareUpgrade" ) type ProposalStatus byte const ( - StatusNil ProposalStatus = 0x00 - StatusDepositPeriod ProposalStatus = 0x01 // Proposal is submitted. Participants can deposit on it but not vote - StatusVotingPeriod ProposalStatus = 0x02 // MinDeposit is reached, participants can vote - StatusPassed ProposalStatus = 0x03 // Proposal passed and successfully executed - StatusRejected ProposalStatus = 0x04 // Proposal has been rejected - StatusFailed ProposalStatus = 0x05 // Proposal passed but failed execution + StatusNil ProposalStatus = 0x00 + StatusDepositPeriod ProposalStatus = 0x01 // Proposal is submitted. Participants can deposit on it but not vote + StatusVotingPeriod ProposalStatus = 0x02 // MinDeposit is reached, participants can vote + StatusPassed ProposalStatus = 0x03 // Proposal passed and successfully executed + StatusRejected ProposalStatus = 0x04 // Proposal has been rejected + StatusFailed ProposalStatus = 0x05 // Proposal passed but failed execution ) ``` @@ -431,10 +430,10 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/proto/cosmos/gov/v1/gov.pr This type is used in a temp map when tallying ```go - type ValidatorGovInfo struct { - Minus sdk.Dec - Vote Vote - } +type ValidatorGovInfo struct { + Minus sdk.Dec + Vote Vote +} ``` ## Stores @@ -474,56 +473,67 @@ For pseudocode purposes, here are the two function we will use to read or write And the pseudocode for the `ProposalProcessingQueue`: ```go - in EndBlock do - +in EndBlock do for finishedProposalID in GetAllFinishedProposalIDs(block.Time) - proposal = load(Governance, ) // proposal is a const key + +proposal = load(Governance, ) // proposal is a const key validators = Keeper.getAllValidators() - tmpValMap := map(sdk.AccAddress)ValidatorGovInfo + +tmpValMap := map(sdk.AccAddress) + +ValidatorGovInfo // Initiate mapping at 0. This is the amount of shares of the validator's vote that will be overridden by their delegator's votes - for each validator in validators + for each validator in validators tmpValMap(validator.OperatorAddr).Minus = 0 // Tally voterIterator = rangeQuery(Governance, ) //return all the addresses that voted on the proposal - for each (voterAddress, vote) in voterIterator - delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter + for each (voterAddress, vote) - for each delegation in delegations +in voterIterator + delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter + for each delegation in delegations // make sure delegation.Shares does NOT include shares being unbonded tmpValMap(delegation.ValidatorAddr).Minus += delegation.Shares proposal.updateTally(vote, delegation.Shares) _, isVal = stakingKeeper.getValidator(voterAddress) - if (isVal) - tmpValMap(voterAddress).Vote = vote + +if (isVal) + +tmpValMap(voterAddress).Vote = vote tallyingParam = load(GlobalParams, 'TallyingParam') // Update tally if validator voted - for each validator in validators - if tmpValMap(validator).HasVoted + for each validator in validators + if tmpValMap(validator).HasVoted proposal.updateTally(tmpValMap(validator).Vote, (validator.TotalShares - tmpValMap(validator).Minus)) // Check if proposal is accepted or rejected - totalNonAbstain := proposal.YesVotes + proposal.NoVotes + proposal.NoWithVetoVotes - if (proposal.Votes.YesVotes/totalNonAbstain > tallyingParam.Threshold AND proposal.Votes.NoWithVetoVotes/totalNonAbstain < tallyingParam.Veto) + totalNonAbstain := proposal.YesVotes + proposal.NoVotes + proposal.NoWithVetoVotes + if (proposal.Votes.YesVotes/totalNonAbstain > tallyingParam.Threshold AND proposal.Votes.NoWithVetoVotes/totalNonAbstain < tallyingParam.Veto) // proposal was accepted at the end of the voting period // refund deposits (non-voters already punished) - for each (amount, depositor) in proposal.Deposits + +for each (amount, depositor) + +in proposal.Deposits depositor.AtomBalance += amount stateWriter, err := proposal.Handler() - if err != nil + +if err != nil // proposal passed but failed during state execution proposal.CurrentStatus = ProposalStatusFailed else // proposal pass and state is persisted proposal.CurrentStatus = ProposalStatusAccepted stateWriter.save() - else + +else // proposal was rejected proposal.CurrentStatus = ProposalStatusRejected @@ -618,10 +628,10 @@ The governance module emits the following events: | Type | Attribute Key | Attribute Value | |-------------------|-----------------|------------------| -| inactive_proposal | proposal_id | {proposalID} | -| inactive_proposal | proposal_result | {proposalResult} | -| active_proposal | proposal_id | {proposalID} | -| active_proposal | proposal_result | {proposalResult} | +| inactive_proposal | proposal_id | `{proposalID}` | +| inactive_proposal | proposal_result | `{proposalResult}` | +| active_proposal | proposal_id | `{proposalID}` | +| active_proposal | proposal_result | `{proposalResult}` | ### Handlers @@ -629,13 +639,13 @@ The governance module emits the following events: | Type | Attribute Key | Attribute Value | |---------------------|---------------------|-----------------| -| submit_proposal | proposal_id | {proposalID} | -| submit_proposal [0] | voting_period_start | {proposalID} | -| proposal_deposit | amount | {depositAmount} | -| proposal_deposit | proposal_id | {proposalID} | +| submit_proposal | proposal_id | `{proposalID}` | +| submit_proposal [0] | voting_period_start | `{proposalID}` | +| proposal_deposit | amount | `{depositAmount}` | +| proposal_deposit | proposal_id | `{proposalID}` | | message | module | governance | | message | action | submit_proposal | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | * [0] Event only emitted if the voting period starts during the submission. @@ -643,32 +653,32 @@ The governance module emits the following events: | Type | Attribute Key | Attribute Value | |---------------|---------------|-----------------| -| proposal_vote | option | {voteOption} | -| proposal_vote | proposal_id | {proposalID} | +| proposal_vote | option | `{voteOption}` | +| proposal_vote | proposal_id | `{proposalID}` | | message | module | governance | | message | action | vote | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | #### MsgVoteWeighted | Type | Attribute Key | Attribute Value | |---------------|---------------|-----------------------| -| proposal_vote | option | {weightedVoteOptions} | -| proposal_vote | proposal_id | {proposalID} | +| proposal_vote | option | `{weightedVoteOptions}` | +| proposal_vote | proposal_id | `{proposalID}` | | message | module | governance | | message | action | vote | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | #### MsgDeposit | Type | Attribute Key | Attribute Value | |----------------------|---------------------|-----------------| -| proposal_deposit | amount | {depositAmount} | -| proposal_deposit | proposal_id | {proposalID} | -| proposal_deposit [0] | voting_period_start | {proposalID} | +| proposal_deposit | amount | `{depositAmount}` | +| proposal_deposit | proposal_id | `{proposalID}` | +| proposal_deposit [0] | voting_period_start | `{proposalID}` | | message | module | governance | | message | action | deposit | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | * [0] Event only emitted if the voting period starts during the submission. @@ -678,7 +688,7 @@ The governance module contains the following parameters: | Key | Type | Example | |-------------------------------|------------------|-----------------------------------------| -| min_deposit | array (coins) | [{"denom":"uatom","amount":"10000000"}] | +| min_deposit | array (coins) | `[{"denom":"uatom","amount":"10000000"}]` | | max_deposit_period | string (time ns) | "172800000000000" (17280s) | | voting_period | string (time ns) | "172800000000000" (17280s) | | quorum | string (dec) | "0.334000000000000000" | @@ -686,7 +696,7 @@ The governance module contains the following parameters: | veto | string (dec) | "0.334000000000000000" | | expedited_threshold | string (time ns) | "0.667000000000000000" | | expedited_voting_period | string (time ns) | "86400000000000" (8600s) | -| expedited_min_deposit | array (coins) | [{"denom":"uatom","amount":"50000000"}] | +| expedited_min_deposit | array (coins) | `[{"denom":"uatom","amount":"50000000"}]` | | burn_proposal_deposit_prevote | bool | false | | burn_vote_quorum | bool | false | | burn_vote_veto | bool | true | @@ -1087,10 +1097,12 @@ where `proposal.json` contains: { "messages": [ { - "@type": "/cosmos.bank.v1beta1.MsgSend", - "from_address": "cosmos1...", // The gov module module address + "@type": "/cosmos.bank.v1beta1.MsgSend", + "from_address": "cosmos1...", // The gov module module address "to_address": "cosmos1...", - "amount":[{"denom": "stake","amount": "10"}] + "amount":[{ + "denom": "stake", + "amount": "10"}] } ], "metadata": "AQ==", @@ -1203,7 +1215,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Proposal ``` @@ -1214,27 +1227,28 @@ Example Output: { "proposal": { "proposalId": "1", - "content": {"@type":"/cosmos.gov.v1beta1.TextProposal","description":"testing, testing, 1, 2, 3","title":"Test Proposal"}, + "content": {"@type":"/cosmos.gov.v1beta1.TextProposal","description":"testing, testing, 1, 2, 3","title":"Test Proposal" +}, "status": "PROPOSAL_STATUS_VOTING_PERIOD", "finalTallyResult": { "yes": "0", "abstain": "0", "no": "0", "noWithVeto": "0" - }, +}, "submitTime": "2021-09-16T19:40:08.712440474Z", "depositEndTime": "2021-09-18T19:40:08.712440474Z", "totalDeposit": [ { "denom": "stake", "amount": "10000000" - } +} ], "votingStartTime": "2021-09-16T19:40:08.712440474Z", "votingEndTime": "2021-09-18T19:40:08.712440474Z", "title": "Test Proposal", "summary": "testing, testing, 1, 2, 3" - } +} } ``` @@ -1248,7 +1262,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1.Query/Proposal ``` @@ -1260,7 +1275,9 @@ Example Output: "proposal": { "id": "1", "messages": [ - {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10" +}],"fromAddress":"cosmos1..","toAddress":"cosmos1.." +} ], "status": "PROPOSAL_STATUS_VOTING_PERIOD", "finalTallyResult": { @@ -1268,21 +1285,21 @@ Example Output: "abstainCount": "0", "noCount": "0", "noWithVetoCount": "0" - }, +}, "submitTime": "2022-03-28T11:50:20.819676256Z", "depositEndTime": "2022-03-30T11:50:20.819676256Z", "totalDeposit": [ { "denom": "stake", "amount": "10000000" - } +} ], "votingStartTime": "2022-03-28T14:25:26.644857113Z", "votingEndTime": "2022-03-30T14:25:26.644857113Z", "metadata": "AQ==", "title": "Test Proposal", "summary": "testing, testing, 1, 2, 3" - } +} } ``` @@ -1317,18 +1334,18 @@ Example Output: "abstain": "0", "no": "0", "noWithVeto": "0" - }, +}, "submitTime": "2022-03-28T11:50:20.819676256Z", "depositEndTime": "2022-03-30T11:50:20.819676256Z", "totalDeposit": [ { "denom": "stake", "amount": "10000000010" - } +} ], "votingStartTime": "2022-03-28T14:25:26.644857113Z", "votingEndTime": "2022-03-30T14:25:26.644857113Z" - }, +}, { "proposalId": "2", "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", @@ -1337,24 +1354,23 @@ Example Output: "abstain": "0", "no": "0", "noWithVeto": "0" - }, +}, "submitTime": "2022-03-28T14:02:41.165025015Z", "depositEndTime": "2022-03-30T14:02:41.165025015Z", "totalDeposit": [ { "denom": "stake", "amount": "10" - } +} ], "votingStartTime": "0001-01-01T00:00:00Z", "votingEndTime": "0001-01-01T00:00:00Z" - } +} ], "pagination": { "total": "2" - } } - +} ``` Using v1: @@ -1379,7 +1395,9 @@ Example Output: { "id": "1", "messages": [ - {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10" +}],"fromAddress":"cosmos1..","toAddress":"cosmos1.." +} ], "status": "PROPOSAL_STATUS_VOTING_PERIOD", "finalTallyResult": { @@ -1387,25 +1405,27 @@ Example Output: "abstainCount": "0", "noCount": "0", "noWithVetoCount": "0" - }, +}, "submitTime": "2022-03-28T11:50:20.819676256Z", "depositEndTime": "2022-03-30T11:50:20.819676256Z", "totalDeposit": [ { "denom": "stake", "amount": "10000000010" - } +} ], "votingStartTime": "2022-03-28T14:25:26.644857113Z", "votingEndTime": "2022-03-30T14:25:26.644857113Z", "metadata": "AQ==", "title": "Proposal Title", "summary": "Proposal Summary" - }, +}, { "id": "2", "messages": [ - {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"10" +}],"fromAddress":"cosmos1..","toAddress":"cosmos1.." +} ], "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", "finalTallyResult": { @@ -1413,23 +1433,23 @@ Example Output: "abstainCount": "0", "noCount": "0", "noWithVetoCount": "0" - }, +}, "submitTime": "2022-03-28T14:02:41.165025015Z", "depositEndTime": "2022-03-30T14:02:41.165025015Z", "totalDeposit": [ { "denom": "stake", "amount": "10" - } +} ], "metadata": "AQ==", "title": "Proposal Title", "summary": "Proposal Summary" - } +} ], "pagination": { "total": "2" - } +} } ``` @@ -1447,7 +1467,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + -d '{"proposal_id":"1","voter":"cosmos1.." +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Vote ``` @@ -1464,9 +1485,9 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1000000000000000000" - } +} ] - } +} } ``` @@ -1480,7 +1501,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1","voter":"cosmos1.."}' \ + -d '{"proposal_id":"1","voter":"cosmos1.." +}' \ localhost:9090 \ cosmos.gov.v1.Query/Vote ``` @@ -1497,9 +1519,9 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ] - } +} } ``` @@ -1517,7 +1539,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Votes ``` @@ -1534,13 +1557,13 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1000000000000000000" - } +} ] - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1554,7 +1577,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1.Query/Votes ``` @@ -1571,13 +1595,13 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ] - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1585,7 +1609,7 @@ Example Output: The `Params` endpoint allows users to query all parameters for the `gov` module. - +{/* TODO: #10197 Querying governance params outputs nil values */} Using legacy v1beta1: @@ -1597,7 +1621,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"params_type":"voting"}' \ + -d '{"params_type":"voting" +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Params ``` @@ -1608,15 +1633,15 @@ Example Output: { "votingParams": { "votingPeriod": "172800s" - }, +}, "depositParams": { "maxDepositPeriod": "0s" - }, +}, "tallyParams": { "quorum": "MA==", "threshold": "MA==", "vetoThreshold": "MA==" - } +} } ``` @@ -1630,7 +1655,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"params_type":"voting"}' \ + -d '{"params_type":"voting" +}' \ localhost:9090 \ cosmos.gov.v1.Query/Params ``` @@ -1641,7 +1667,7 @@ Example Output: { "votingParams": { "votingPeriod": "172800s" - } +} } ``` @@ -1659,7 +1685,8 @@ Example: ```bash grpcurl -plaintext \ - '{"proposal_id":"1","depositor":"cosmos1.."}' \ + '{"proposal_id":"1","depositor":"cosmos1.." +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Deposit ``` @@ -1675,9 +1702,9 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} } ``` @@ -1691,7 +1718,8 @@ Example: ```bash grpcurl -plaintext \ - '{"proposal_id":"1","depositor":"cosmos1.."}' \ + '{"proposal_id":"1","depositor":"cosmos1.." +}' \ localhost:9090 \ cosmos.gov.v1.Query/Deposit ``` @@ -1707,9 +1735,9 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} } ``` @@ -1727,7 +1755,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/Deposits ``` @@ -1744,13 +1773,13 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1764,7 +1793,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1.Query/Deposits ``` @@ -1781,13 +1811,13 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1805,7 +1835,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1beta1.Query/TallyResult ``` @@ -1819,7 +1850,7 @@ Example Output: "abstain": "0", "no": "0", "noWithVeto": "0" - } +} } ``` @@ -1833,7 +1864,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' \ + -d '{"proposal_id":"1" +}' \ localhost:9090 \ cosmos.gov.v1.Query/TallyResult ``` @@ -1847,7 +1879,7 @@ Example Output: "abstain": "0", "no": "0", "noWithVeto": "0" - } +} } ``` @@ -1862,7 +1894,9 @@ The `proposals` endpoint allows users to query a given proposal. Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id} +/cosmos/gov/v1beta1/proposals/{ + proposal_id +} ``` Example: @@ -1884,25 +1918,27 @@ Example Output: "abstain": "0", "no": "0", "no_with_veto": "0" - }, +}, "submit_time": "2022-03-28T11:50:20.819676256Z", "deposit_end_time": "2022-03-30T11:50:20.819676256Z", "total_deposit": [ { "denom": "stake", "amount": "10000000010" - } +} ], "voting_start_time": "2022-03-28T14:25:26.644857113Z", "voting_end_time": "2022-03-30T14:25:26.644857113Z" - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id} +/cosmos/gov/v1/proposals/{ + proposal_id +} ``` Example: @@ -1926,9 +1962,9 @@ Example Output: { "denom": "stake", "amount": "10" - } +} ] - } +} ], "status": "PROPOSAL_STATUS_VOTING_PERIOD", "final_tally_result": { @@ -1936,21 +1972,21 @@ Example Output: "abstain_count": "0", "no_count": "0", "no_with_veto_count": "0" - }, +}, "submit_time": "2022-03-28T11:50:20.819676256Z", "deposit_end_time": "2022-03-30T11:50:20.819676256Z", "total_deposit": [ { "denom": "stake", "amount": "10000000" - } +} ], "voting_start_time": "2022-03-28T14:25:26.644857113Z", "voting_end_time": "2022-03-30T14:25:26.644857113Z", "metadata": "AQ==", "title": "Proposal Title", "summary": "Proposal Summary" - } +} } ``` @@ -1984,18 +2020,18 @@ Example Output: "abstain": "0", "no": "0", "no_with_veto": "0" - }, +}, "submit_time": "2022-03-28T11:50:20.819676256Z", "deposit_end_time": "2022-03-30T11:50:20.819676256Z", "total_deposit": [ { "denom": "stake", "amount": "10000000" - } +} ], "voting_start_time": "2022-03-28T14:25:26.644857113Z", "voting_end_time": "2022-03-30T14:25:26.644857113Z" - }, +}, { "proposal_id": "2", "content": null, @@ -2005,23 +2041,23 @@ Example Output: "abstain": "0", "no": "0", "no_with_veto": "0" - }, +}, "submit_time": "2022-03-28T14:02:41.165025015Z", "deposit_end_time": "2022-03-30T14:02:41.165025015Z", "total_deposit": [ { "denom": "stake", "amount": "10" - } +} ], "voting_start_time": "0001-01-01T00:00:00Z", "voting_end_time": "0001-01-01T00:00:00Z" - } +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -2053,9 +2089,9 @@ Example Output: { "denom": "stake", "amount": "10" - } +} ] - } +} ], "status": "PROPOSAL_STATUS_VOTING_PERIOD", "final_tally_result": { @@ -2063,21 +2099,21 @@ Example Output: "abstain_count": "0", "no_count": "0", "no_with_veto_count": "0" - }, +}, "submit_time": "2022-03-28T11:50:20.819676256Z", "deposit_end_time": "2022-03-30T11:50:20.819676256Z", "total_deposit": [ { "denom": "stake", "amount": "10000000010" - } +} ], "voting_start_time": "2022-03-28T14:25:26.644857113Z", "voting_end_time": "2022-03-30T14:25:26.644857113Z", "metadata": "AQ==", "title": "Proposal Title", "summary": "Proposal Summary" - }, +}, { "id": "2", "messages": [ @@ -2089,9 +2125,9 @@ Example Output: { "denom": "stake", "amount": "10" - } +} ] - } +} ], "status": "PROPOSAL_STATUS_DEPOSIT_PERIOD", "final_tally_result": { @@ -2099,26 +2135,26 @@ Example Output: "abstain_count": "0", "no_count": "0", "no_with_veto_count": "0" - }, +}, "submit_time": "2022-03-28T14:02:41.165025015Z", "deposit_end_time": "2022-03-30T14:02:41.165025015Z", "total_deposit": [ { "denom": "stake", "amount": "10" - } +} ], "voting_start_time": null, "voting_end_time": null, "metadata": "AQ==", "title": "Proposal Title", "summary": "Proposal Summary" - } +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -2129,7 +2165,11 @@ The `votes` endpoint allows users to query a vote for a given proposal. Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id}/votes/{voter} +/cosmos/gov/v1beta1/proposals/{ + proposal_id +}/votes/{ + voter +} ``` Example: @@ -2150,16 +2190,20 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ] - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id}/votes/{voter} +/cosmos/gov/v1/proposals/{ + proposal_id +}/votes/{ + voter +} ``` Example: @@ -2179,10 +2223,10 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ], "metadata": "" - } +} } ``` @@ -2193,7 +2237,9 @@ The `votes` endpoint allows users to query all votes for a given proposal. Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id}/votes +/cosmos/gov/v1beta1/proposals/{ + proposal_id +}/votes ``` Example: @@ -2215,21 +2261,23 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id}/votes +/cosmos/gov/v1/proposals/{ + proposal_id +}/votes ``` Example: @@ -2250,15 +2298,15 @@ Example Output: { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" - } +} ], "metadata": "" - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2266,12 +2314,14 @@ Example Output: The `params` endpoint allows users to query all parameters for the `gov` module. - +{/* TODO: #10197 Querying governance params outputs nil values */} Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/params/{params_type} +/cosmos/gov/v1beta1/params/{ + params_type +} ``` Example: @@ -2286,24 +2336,26 @@ Example Output: { "voting_params": { "voting_period": "172800s" - }, +}, "deposit_params": { "min_deposit": [ ], "max_deposit_period": "0s" - }, +}, "tally_params": { "quorum": "0.000000000000000000", "threshold": "0.000000000000000000", "veto_threshold": "0.000000000000000000" - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/params/{params_type} +/cosmos/gov/v1/params/{ + params_type +} ``` Example: @@ -2318,17 +2370,17 @@ Example Output: { "voting_params": { "voting_period": "172800s" - }, +}, "deposit_params": { "min_deposit": [ ], "max_deposit_period": "0s" - }, +}, "tally_params": { "quorum": "0.000000000000000000", "threshold": "0.000000000000000000", "veto_threshold": "0.000000000000000000" - } +} } ``` @@ -2339,7 +2391,11 @@ The `deposits` endpoint allows users to query a deposit for a given proposal fro Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits/{depositor} +/cosmos/gov/v1beta1/proposals/{ + proposal_id +}/deposits/{ + depositor +} ``` Example: @@ -2359,16 +2415,20 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id}/deposits/{depositor} +/cosmos/gov/v1/proposals/{ + proposal_id +}/deposits/{ + depositor +} ``` Example: @@ -2388,9 +2448,9 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} } ``` @@ -2401,7 +2461,9 @@ The `deposits` endpoint allows users to query all deposits for a given proposal. Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id}/deposits +/cosmos/gov/v1beta1/proposals/{ + proposal_id +}/deposits ``` Example: @@ -2422,21 +2484,23 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id}/deposits +/cosmos/gov/v1/proposals/{ + proposal_id +}/deposits ``` Example: @@ -2457,14 +2521,14 @@ Example Output: { "denom": "stake", "amount": "10000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2475,7 +2539,9 @@ The `tally` endpoint allows users to query the tally of a given proposal. Using legacy v1beta1: ```bash -/cosmos/gov/v1beta1/proposals/{proposal_id}/tally +/cosmos/gov/v1beta1/proposals/{ + proposal_id +}/tally ``` Example: @@ -2493,14 +2559,16 @@ Example Output: "abstain": "0", "no": "0", "no_with_veto": "0" - } +} } ``` Using v1: ```bash -/cosmos/gov/v1/proposals/{proposal_id}/tally +/cosmos/gov/v1/proposals/{ + proposal_id +}/tally ``` Example: @@ -2518,7 +2586,7 @@ Example Output: "abstain": "0", "no": "0", "no_with_veto": "0" - } +} } ``` diff --git a/docs/sdk/v0.53/module-reference/group.mdx b/docs/sdk/v0.53/module-reference/group.mdx index 7e0f970e..55a18f07 100644 --- a/docs/sdk/v0.53/module-reference/group.mdx +++ b/docs/sdk/v0.53/module-reference/group.mdx @@ -519,74 +519,74 @@ The group module emits the following events: | Type | Attribute Key | Attribute Value | | -------------------------------- | ------------- | -------------------------------- | | message | action | /cosmos.group.v1.Msg/CreateGroup | -| cosmos.group.v1.EventCreateGroup | group_id | {groupId} | +| cosmos.group.v1.EventCreateGroup | group_id | `{groupId}` | ### EventUpdateGroup | Type | Attribute Key | Attribute Value | | -------------------------------- | ------------- | ---------------------------------------------------------- | -| message | action | /cosmos.group.v1.Msg/UpdateGroup{Admin\|Metadata\|Members} | -| cosmos.group.v1.EventUpdateGroup | group_id | {groupId} | +| message | action | `/cosmos.group.v1.Msg/UpdateGroup{Admin\|Metadata\|Members}` | +| cosmos.group.v1.EventUpdateGroup | group_id | `{groupId}` | ### EventCreateGroupPolicy | Type | Attribute Key | Attribute Value | | -------------------------------------- | ------------- | -------------------------------------- | | message | action | /cosmos.group.v1.Msg/CreateGroupPolicy | -| cosmos.group.v1.EventCreateGroupPolicy | address | {groupPolicyAddress} | +| cosmos.group.v1.EventCreateGroupPolicy | address | `{groupPolicyAddress}` | ### EventUpdateGroupPolicy | Type | Attribute Key | Attribute Value | | -------------------------------------- | ------------- | ----------------------------------------------------------------------- | -| message | action | /cosmos.group.v1.Msg/UpdateGroupPolicy{Admin\|Metadata\|DecisionPolicy} | -| cosmos.group.v1.EventUpdateGroupPolicy | address | {groupPolicyAddress} | +| message | action | `/cosmos.group.v1.Msg/UpdateGroupPolicy{Admin\|Metadata\|DecisionPolicy}` | +| cosmos.group.v1.EventUpdateGroupPolicy | address | `{groupPolicyAddress}` | ### EventCreateProposal | Type | Attribute Key | Attribute Value | | ----------------------------------- | ------------- | ----------------------------------- | | message | action | /cosmos.group.v1.Msg/CreateProposal | -| cosmos.group.v1.EventCreateProposal | proposal_id | {proposalId} | +| cosmos.group.v1.EventCreateProposal | proposal_id | `{proposalId}` | ### EventWithdrawProposal | Type | Attribute Key | Attribute Value | | ------------------------------------- | ------------- | ------------------------------------- | | message | action | /cosmos.group.v1.Msg/WithdrawProposal | -| cosmos.group.v1.EventWithdrawProposal | proposal_id | {proposalId} | +| cosmos.group.v1.EventWithdrawProposal | proposal_id | `{proposalId}` | ### EventVote | Type | Attribute Key | Attribute Value | | ------------------------- | ------------- | ------------------------- | | message | action | /cosmos.group.v1.Msg/Vote | -| cosmos.group.v1.EventVote | proposal_id | {proposalId} | +| cosmos.group.v1.EventVote | proposal_id | `{proposalId}` | ## EventExec | Type | Attribute Key | Attribute Value | | ------------------------- | ------------- | ------------------------- | | message | action | /cosmos.group.v1.Msg/Exec | -| cosmos.group.v1.EventExec | proposal_id | {proposalId} | -| cosmos.group.v1.EventExec | logs | {logs_string} | +| cosmos.group.v1.EventExec | proposal_id | `{proposalId}` | +| cosmos.group.v1.EventExec | logs | `{logs_string}` | ### EventLeaveGroup | Type | Attribute Key | Attribute Value | | ------------------------------- | ------------- | ------------------------------- | | message | action | /cosmos.group.v1.Msg/LeaveGroup | -| cosmos.group.v1.EventLeaveGroup | proposal_id | {proposalId} | -| cosmos.group.v1.EventLeaveGroup | address | {address} | +| cosmos.group.v1.EventLeaveGroup | proposal_id | `{proposalId}` | +| cosmos.group.v1.EventLeaveGroup | address | `{address}` | ### EventProposalPruned | Type | Attribute Key | Attribute Value | |-------------------------------------|---------------|---------------------------------| | message | action | /cosmos.group.v1.Msg/LeaveGroup | -| cosmos.group.v1.EventProposalPruned | proposal_id | {proposalId} | -| cosmos.group.v1.EventProposalPruned | status | {ProposalStatus} | -| cosmos.group.v1.EventProposalPruned | tally_result | {TallyResult} | +| cosmos.group.v1.EventProposalPruned | proposal_id | `{proposalId}` | +| cosmos.group.v1.EventProposalPruned | status | `{ProposalStatus}` | +| cosmos.group.v1.EventProposalPruned | tally_result | `{TallyResult}` | ## Client @@ -1068,7 +1068,8 @@ simd tx group create-group-policy [admin] [group-id] [metadata] [decision-policy Example: ```bash -simd tx group create-group-policy cosmos1.. 1 "AQ==" '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +simd tx group create-group-policy cosmos1.. 1 "AQ==" '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s" +}}' ``` #### create-group-with-policy @@ -1082,7 +1083,8 @@ simd tx group create-group-with-policy [admin] [group-metadata] [group-policy-me Example: ```bash -simd tx group create-group-with-policy cosmos1.. "AQ==" "AQ==" members.json '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +simd tx group create-group-with-policy cosmos1.. "AQ==" "AQ==" members.json '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows": {"voting_period": "120h", "min_execution_period": "0s" +}}' ``` #### update-group-policy-admin @@ -1124,7 +1126,8 @@ simd tx group update-group-policy-decision-policy [admin] [group-policy-account Example: ```bash -simd tx group update-group-policy-decision-policy cosmos1.. cosmos1.. '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"2", "windows": {"voting_period": "120h", "min_execution_period": "0s"}}' +simd tx group update-group-policy-decision-policy cosmos1.. cosmos1.. '{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"2", "windows": {"voting_period": "120h", "min_execution_period": "0s" +}}' ``` #### submit-proposal @@ -1213,7 +1216,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"group_id":1}' localhost:9090 cosmos.group.v1.Query/GroupInfo + -d '{"group_id":1 +}' localhost:9090 cosmos.group.v1.Query/GroupInfo ``` Example Output: @@ -1226,7 +1230,7 @@ Example Output: "metadata": "AQ==", "version": "1", "totalWeight": "3" - } +} } ``` @@ -1242,7 +1246,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupPolicyInfo + -d '{"address":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/GroupPolicyInfo ``` Example Output: @@ -1254,8 +1259,9 @@ Example Output: "groupId": "1", "admin": "cosmos1..", "version": "1", - "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows": {"voting_period": "120h", "min_execution_period": "0s"}}, - } + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows": {"voting_period": "120h", "min_execution_period": "0s" +}}, +} } ``` @@ -1271,7 +1277,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"group_id":"1"}' localhost:9090 cosmos.group.v1.Query/GroupMembers + -d '{"group_id":"1" +}' localhost:9090 cosmos.group.v1.Query/GroupMembers ``` Example Output: @@ -1284,19 +1291,21 @@ Example Output: "member": { "address": "cosmos1..", "weight": "1" - } - }, +} + +}, { "groupId": "1", "member": { "address": "cosmos1..", "weight": "2" - } - } +} + +} ], "pagination": { "total": "2" - } +} } ``` @@ -1312,7 +1321,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"admin":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupsByAdmin + -d '{"admin":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/GroupsByAdmin ``` Example Output: @@ -1326,18 +1336,18 @@ Example Output: "metadata": "AQ==", "version": "1", "totalWeight": "3" - }, +}, { "groupId": "2", "admin": "cosmos1..", "metadata": "AQ==", "version": "1", "totalWeight": "3" - } +} ], "pagination": { "total": "2" - } +} } ``` @@ -1353,7 +1363,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"group_id":"1"}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByGroup + -d '{"group_id":"1" +}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByGroup ``` Example Output: @@ -1366,19 +1377,21 @@ Example Output: "groupId": "1", "admin": "cosmos1..", "version": "1", - "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, - }, + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s" +}}, +}, { "address": "cosmos1..", "groupId": "1", "admin": "cosmos1..", "version": "1", - "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, - } + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s" +}}, +} ], "pagination": { "total": "2" - } +} } ``` @@ -1394,7 +1407,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"admin":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByAdmin + -d '{"admin":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/GroupPoliciesByAdmin ``` Example Output: @@ -1407,19 +1421,21 @@ Example Output: "groupId": "1", "admin": "cosmos1..", "version": "1", - "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, - }, + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s" +}}, +}, { "address": "cosmos1..", "groupId": "1", "admin": "cosmos1..", "version": "1", - "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s"}}, - } + "decisionPolicy": {"@type":"/cosmos.group.v1.ThresholdDecisionPolicy","threshold":"1","windows":{"voting_period": "120h", "min_execution_period": "0s" +}}, +} ], "pagination": { "total": "2" - } +} } ``` @@ -1435,7 +1451,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' localhost:9090 cosmos.group.v1.Query/Proposal + -d '{"proposal_id":"1" +}' localhost:9090 cosmos.group.v1.Query/Proposal ``` Example Output: @@ -1458,18 +1475,20 @@ Example Output: "noCount": "0", "abstainCount": "0", "vetoCount": "0" - }, +}, "windows": { "min_execution_period": "0s", "voting_period": "432000s" - }, +}, "executorResult": "EXECUTOR_RESULT_NOT_RUN", "messages": [ - {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000" +}],"fromAddress":"cosmos1..","toAddress":"cosmos1.." +} ], "title": "Title", "summary": "Summary", - } +} } ``` @@ -1485,7 +1504,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"address":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/ProposalsByGroupPolicy + -d '{"address":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/ProposalsByGroupPolicy ``` Example Output: @@ -1509,22 +1529,24 @@ Example Output: "noCount": "0", "abstainCount": "0", "vetoCount": "0" - }, +}, "windows": { "min_execution_period": "0s", "voting_period": "432000s" - }, +}, "executorResult": "EXECUTOR_RESULT_NOT_RUN", "messages": [ - {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000"}],"fromAddress":"cosmos1..","toAddress":"cosmos1.."} + {"@type":"/cosmos.bank.v1beta1.MsgSend","amount":[{"denom":"stake","amount":"100000000" +}],"fromAddress":"cosmos1..","toAddress":"cosmos1.." +} ], "title": "Title", "summary": "Summary", - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1540,7 +1562,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1","voter":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/VoteByProposalVoter + -d '{"proposal_id":"1","voter":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/VoteByProposalVoter ``` Example Output: @@ -1552,7 +1575,7 @@ Example Output: "voter": "cosmos1..", "choice": "CHOICE_YES", "submittedAt": "2021-12-17T08:05:02.490164009Z" - } +} } ``` @@ -1568,7 +1591,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"proposal_id":"1"}' localhost:9090 cosmos.group.v1.Query/VotesByProposal + -d '{"proposal_id":"1" +}' localhost:9090 cosmos.group.v1.Query/VotesByProposal ``` Example Output: @@ -1581,11 +1605,11 @@ Example Output: "voter": "cosmos1..", "choice": "CHOICE_YES", "submittedAt": "2021-12-17T08:05:02.490164009Z" - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1601,7 +1625,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"voter":"cosmos1.."}' localhost:9090 cosmos.group.v1.Query/VotesByVoter + -d '{"voter":"cosmos1.." +}' localhost:9090 cosmos.group.v1.Query/VotesByVoter ``` Example Output: @@ -1614,11 +1639,11 @@ Example Output: "voter": "cosmos1..", "choice": "CHOICE_YES", "submittedAt": "2021-12-17T08:05:02.490164009Z" - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1631,7 +1656,7 @@ A user can query the `group` module using REST endpoints. The `GroupInfo` endpoint allows users to query for group info by given group id. ```bash -/cosmos/group/v1/group_info/{group_id} +/cosmos/group/v1/group_info/`{group_id}` ``` Example: @@ -1650,7 +1675,7 @@ Example Output: "metadata": "AQ==", "version": "1", "total_weight": "3" - } +} } ``` @@ -1659,7 +1684,7 @@ Example Output: The `GroupPolicyInfo` endpoint allows users to query for group policy info by account address of group policy. ```bash -/cosmos/group/v1/group_policy_info/{address} +/cosmos/group/v1/group_policy_info/`{address}` ``` Example: @@ -1684,9 +1709,10 @@ Example Output: "windows": { "voting_period": "120h", "min_execution_period": "0s" - } - }, - } +} + +}, +} } ``` @@ -1695,7 +1721,7 @@ Example Output: The `GroupMembers` endpoint allows users to query for group members by group id with pagination flags. ```bash -/cosmos/group/v1/group_members/{group_id} +/cosmos/group/v1/group_members/`{group_id}` ``` Example: @@ -1715,20 +1741,21 @@ Example Output: "address": "cosmos1..", "weight": "1", "metadata": "AQ==" - } - }, +} + +}, { "group_id": "1", "member": { "address": "cosmos1..", "weight": "2", "metadata": "AQ==" - } +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -1737,7 +1764,7 @@ Example Output: The `GroupsByAdmin` endpoint allows users to query for groups by admin account address with pagination flags. ```bash -/cosmos/group/v1/groups_by_admin/{admin} +/cosmos/group/v1/groups_by_admin/`{admin}` ``` Example: @@ -1757,19 +1784,19 @@ Example Output: "metadata": "AQ==", "version": "1", "total_weight": "3" - }, +}, { "id": "2", "admin": "cosmos1..", "metadata": "AQ==", "version": "1", "total_weight": "3" - } +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -1778,7 +1805,7 @@ Example Output: The `GroupPoliciesByGroup` endpoint allows users to query for group policies by group id with pagination flags. ```bash -/cosmos/group/v1/group_policies_by_group/{group_id} +/cosmos/group/v1/group_policies_by_group/`{group_id}` ``` Example: @@ -1804,9 +1831,10 @@ Example Output: "windows": { "voting_period": "120h", "min_execution_period": "0s" - } - }, - }, +} + +}, +}, { "address": "cosmos1..", "group_id": "1", @@ -1819,14 +1847,15 @@ Example Output: "windows": { "voting_period": "120h", "min_execution_period": "0s" - } - }, - } +} + +}, +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -1835,7 +1864,7 @@ Example Output: The `GroupPoliciesByAdmin` endpoint allows users to query for group policies by admin account address with pagination flags. ```bash -/cosmos/group/v1/group_policies_by_admin/{admin} +/cosmos/group/v1/group_policies_by_admin/`{admin}` ``` Example: @@ -1861,9 +1890,9 @@ Example Output: "windows": { "voting_period": "120h", "min_execution_period": "0s" - } - }, - }, +} +}, +}, { "address": "cosmos1..", "group_id": "1", @@ -1876,14 +1905,15 @@ Example Output: "windows": { "voting_period": "120h", "min_execution_period": "0s" - } - }, - } +} + +}, +} ], "pagination": { "next_key": null, "total": "2" - } +} ``` #### Proposal @@ -1891,7 +1921,7 @@ Example Output: The `Proposal` endpoint allows users to query for proposal by id. ```bash -/cosmos/group/v1/proposal/{proposal_id} +/cosmos/group/v1/proposal/`{proposal_id}` ``` Example: @@ -1921,11 +1951,11 @@ Example Output: "no_count": "0", "abstain_count": "0", "veto_count": "0" - }, +}, "windows": { "min_execution_period": "0s", "voting_period": "432000s" - }, +}, "executor_result": "EXECUTOR_RESULT_NOT_RUN", "messages": [ { @@ -1936,13 +1966,13 @@ Example Output: { "denom": "stake", "amount": "100000000" - } +} ] - } +} ], "title": "Title", "summary": "Summary", - } +} } ``` @@ -1951,7 +1981,7 @@ Example Output: The `ProposalsByGroupPolicy` endpoint allows users to query for proposals by account address of group policy with pagination flags. ```bash -/cosmos/group/v1/proposals_by_group_policy/{address} +/cosmos/group/v1/proposals_by_group_policy/`{address}` ``` Example: @@ -1982,11 +2012,11 @@ Example Output: "no_count": "0", "abstain_count": "0", "veto_count": "0" - }, +}, "windows": { "min_execution_period": "0s", "voting_period": "432000s" - }, +}, "executor_result": "EXECUTOR_RESULT_NOT_RUN", "messages": [ { @@ -1997,16 +2027,16 @@ Example Output: { "denom": "stake", "amount": "100000000" - } +} ] - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2015,7 +2045,7 @@ Example Output: The `VoteByProposalVoter` endpoint allows users to query for vote by proposal id and voter account address. ```bash -/cosmos/group/v1/vote_by_proposal_voter/{proposal_id}/{voter} +/cosmos/group/v1/vote_by_proposal_voter/`{proposal_id}`/`{voter}` ``` Example: @@ -2034,7 +2064,7 @@ Example Output: "choice": "CHOICE_YES", "metadata": "AQ==", "submitted_at": "2021-12-17T08:05:02.490164009Z" - } +} } ``` @@ -2043,7 +2073,7 @@ Example Output: The `VotesByProposal` endpoint allows users to query for votes by proposal id with pagination flags. ```bash -/cosmos/group/v1/votes_by_proposal/{proposal_id} +/cosmos/group/v1/votes_by_proposal/`{proposal_id}` ``` Example: @@ -2063,12 +2093,12 @@ Example Output: "option": "CHOICE_YES", "metadata": "AQ==", "submit_time": "2021-12-17T08:05:02.490164009Z" - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2077,7 +2107,7 @@ Example Output: The `VotesByVoter` endpoint allows users to query for votes by voter account address with pagination flags. ```bash -/cosmos/group/v1/votes_by_voter/{voter} +/cosmos/group/v1/votes_by_voter/`{voter}` ``` Example: @@ -2097,12 +2127,12 @@ Example Output: "choice": "CHOICE_YES", "metadata": "AQ==", "submitted_at": "2021-12-17T08:05:02.490164009Z" - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` diff --git a/docs/sdk/v0.53/module-reference/mint.mdx b/docs/sdk/v0.53/module-reference/mint.mdx index 45c3f03d..02247bec 100644 --- a/docs/sdk/v0.53/module-reference/mint.mdx +++ b/docs/sdk/v0.53/module-reference/mint.mdx @@ -56,7 +56,9 @@ The function signature that a `MintFn` must implement is as follows: ```go // MintFn defines the function that needs to be implemented in order to customize the minting process. -type MintFn func(ctx sdk.Context, k *Keeper) error +type MintFn func(ctx sdk.Context, k *Keeper) + +error ``` This can be passed to the `Keeper` upon creation with an additional `Option`: @@ -83,15 +85,22 @@ First, we will define a function that takes our required dependencies, and retur ```go // MyCustomMintFunction is a custom mint function that doubles the supply of `foo` coin. -func MyCustomMintFunction(bank bankkeeper.BaseKeeper) mintkeeper.MintFn { - return func(ctx sdk.Context, k *mintkeeper.Keeper) error { - supply := bank.GetSupply(ctx, "foo") - err := k.MintCoins(ctx, sdk.NewCoins(supply.Add(supply))) - if err != nil { - return err - } - return nil - } +func MyCustomMintFunction(bank bankkeeper.BaseKeeper) + +mintkeeper.MintFn { + return func(ctx sdk.Context, k *mintkeeper.Keeper) + +error { + supply := bank.GetSupply(ctx, "foo") + +err := k.MintCoins(ctx, sdk.NewCoins(supply.Add(supply))) + +if err != nil { + return err +} + +return nil +} } ``` @@ -100,25 +109,26 @@ Then, pass the function defined above into the `depinject.Supply` function with ```go // NewSimApp returns a reference to an initialized SimApp. func NewSimApp( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - loadLatest bool, - appOpts servertypes.AppOptions, - baseAppOptions ...func(*baseapp.BaseApp), + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + loadLatest bool, + appOpts servertypes.AppOptions, + baseAppOptions ...func(*baseapp.BaseApp), ) *SimApp { - var ( - app = &SimApp{} - appBuilder *runtime.AppBuilder - appConfig = depinject.Configs( - AppConfig, - depinject.Supply( - appOpts, - logger, - // our custom mint function with the necessary dependency passed in. - MyCustomMintFunction(app.BankKeeper), - ), - ) + var ( + app = &SimApp{} + + appBuilder *runtime.AppBuilder + appConfig = depinject.Configs( + AppConfig, + depinject.Supply( + appOpts, + logger, + // our custom mint function with the necessary dependency passed in. + MyCustomMintFunction(app.BankKeeper), + ), + ) ) // ... } @@ -160,7 +170,9 @@ inflation calculation logic is needed, this can be achieved by defining and passing a function that matches `InflationCalculationFn`'s signature. ```go -type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) math.LegacyDec +type InflationCalculationFn func(ctx sdk.Context, minter Minter, params Params, bondedRatio math.LegacyDec) + +math.LegacyDec ``` #### NextInflationRate @@ -178,14 +190,14 @@ NextInflationRate(params Params, bondedRatio math.LegacyDec) (inflation math.Leg // increase the new annual inflation for this next block inflation += inflationRateChange - if inflation > params.InflationMax { - inflation = params.InflationMax - } - if inflation < params.InflationMin { - inflation = params.InflationMin - } - - return inflation + if inflation > params.InflationMax { + inflation = params.InflationMax +} + if inflation < params.InflationMin { + inflation = params.InflationMin +} + +return inflation } ``` @@ -204,7 +216,9 @@ NextAnnualProvisions(params Params, totalSupply math.LegacyDec) (provisions math Calculate the provisions generated for each block based on current annual provisions. The provisions are then minted by the `mint` module's `ModuleMinterAccount` and then transferred to the `auth`'s `FeeCollector` `ModuleAccount`. ```go -BlockProvision(params Params) sdk.Coin { +BlockProvision(params Params) + +sdk.Coin { provisionAmt = AnnualProvisions/ params.BlocksPerYear return sdk.NewCoin(params.MintDenom, provisionAmt.Truncate()) ``` @@ -230,10 +244,10 @@ The minting module emits the following events: | Type | Attribute Key | Attribute Value | |------|-------------------|--------------------| -| mint | bonded_ratio | {bondedRatio} | -| mint | inflation | {inflation} | -| mint | annual_provisions | {annualProvisions} | -| mint | amount | {amount} | +| mint | bonded_ratio | `{bondedRatio}` | +| mint | inflation | `{inflation}` | +| mint | annual_provisions | `{annualProvisions}` | +| mint | amount | `{amount}` | ## Client diff --git a/docs/sdk/v0.53/module-reference/protocolpool.mdx b/docs/sdk/v0.53/module-reference/protocolpool.mdx index 9895df98..f555310b 100644 --- a/docs/sdk/v0.53/module-reference/protocolpool.mdx +++ b/docs/sdk/v0.53/module-reference/protocolpool.mdx @@ -34,7 +34,7 @@ If you have services that rely on this functionality from `x/distribution`, plea FundCommunityPool can be called by any valid account to send funds to the `x/protocolpool` module account. ```protobuf - // FundCommunityPool defines a method to allow an account to directly +// FundCommunityPool defines a method to allow an account to directly // fund the community pool. rpc FundCommunityPool(MsgFundCommunityPool) returns (MsgFundCommunityPoolResponse); ``` @@ -44,7 +44,7 @@ FundCommunityPool can be called by any valid account to send funds to the `x/pro CommunityPoolSpend can be called by the module authority (default governance module account) or any account with authorization to spend funds from the `x/protocolpool` module account to a receiver address. ```protobuf - // CommunityPoolSpend defines a governance operation for sending tokens from +// CommunityPoolSpend defines a governance operation for sending tokens from // the community pool in the x/protocolpool module to another account, which // could be the governance module itself. The authority is defined in the // keeper. @@ -57,7 +57,7 @@ CreateContinuousFund is a message used to initiate a continuous fund for a speci NOTE: This feature is designed to work with the SDK's default bond denom. ```protobuf - // CreateContinuousFund defines a method to distribute a percentage of funds to an address continuously. +// CreateContinuousFund defines a method to distribute a percentage of funds to an address continuously. // This ContinuousFund can be indefinite or run until a given expiry time. // Funds come from validator block rewards from x/distribution, but may also come from // any user who funds the ProtocolPoolEscrow module account directly through x/bank. @@ -69,7 +69,7 @@ NOTE: This feature is designed to work with the SDK's default bond denom. CancelContinuousFund is a message used to cancel an existing continuous fund proposal for a specific recipient. Cancelling a continuous fund stops further distribution of funds, and the state object is removed from storage. ```protobuf - // CancelContinuousFund defines a method for cancelling continuous fund. +// CancelContinuousFund defines a method for cancelling continuous fund. rpc CancelContinuousFund(MsgCancelContinuousFund) returns (MsgCancelContinuousFundResponse); ``` diff --git a/docs/sdk/v0.53/module-reference/slashing.mdx b/docs/sdk/v0.53/module-reference/slashing.mdx index 6785048e..fb13eb5c 100644 --- a/docs/sdk/v0.53/module-reference/slashing.mdx +++ b/docs/sdk/v0.53/module-reference/slashing.mdx @@ -179,18 +179,19 @@ Below is a pseudocode of the `MsgSrv/Unjail` RPC: ```go unjail(tx MsgUnjail) - validator = getValidator(tx.ValidatorAddr) - if validator == nil - fail with "No validator found" +validator = getValidator(tx.ValidatorAddr) + +if validator == nil + fail with "No validator found" if getSelfDelegation(validator) == 0 fail with "validator must self delegate before unjailing" - if !validator.Jailed fail with "Validator not jailed, cannot unjail" info = GetValidatorSigningInfo(operator) - if info.Tombstoned + +if info.Tombstoned fail with "Tombstoned validator cannot be unjailed" if block time < info.JailedUntil fail with "Validator still jailed, cannot unjail until period has expired" @@ -198,7 +199,7 @@ unjail(tx MsgUnjail) validator.Jailed = false setValidator(validator) - return +return ``` If the validator has enough stake to be in the top `n = MaximumBondedValidators`, it will be automatically rebonded, @@ -230,48 +231,48 @@ for `DowntimeJailDuration`, and have the following values reset: ```go height := block.Height - -for vote in block.LastCommitInfo.Votes { - signInfo := GetValidatorSigningInfo(vote.Validator.Address) + for vote in block.LastCommitInfo.Votes { + signInfo := GetValidatorSigningInfo(vote.Validator.Address) // This is a relative index, so we counts blocks the validator SHOULD have // signed. We use the 0-value default signing info if not present, except for // start height. - index := signInfo.IndexOffset % SignedBlocksWindow() - signInfo.IndexOffset++ + index := signInfo.IndexOffset % SignedBlocksWindow() + +signInfo.IndexOffset++ // Update MissedBlocksBitArray and MissedBlocksCounter. The MissedBlocksCounter // just tracks the sum of MissedBlocksBitArray. That way we avoid needing to // read/write the whole array each time. - missedPrevious := GetValidatorMissedBlockBitArray(vote.Validator.Address, index) - missed := !signed + missedPrevious := GetValidatorMissedBlockBitArray(vote.Validator.Address, index) - switch { - case !missedPrevious && missed: +missed := !signed + switch { + case !missedPrevious && missed: // array index has changed from not missed to missed, increment counter SetValidatorMissedBlockBitArray(vote.Validator.Address, index, true) - signInfo.MissedBlocksCounter++ - case missedPrevious && !missed: +signInfo.MissedBlocksCounter++ + case missedPrevious && !missed: // array index has changed from missed to not missed, decrement counter SetValidatorMissedBlockBitArray(vote.Validator.Address, index, false) - signInfo.MissedBlocksCounter-- + +signInfo.MissedBlocksCounter-- default: // array index at this index has not changed; no need to update counter - } - - if missed { +} + if missed { // emit events... - } +} + minHeight := signInfo.StartHeight + SignedBlocksWindow() - minHeight := signInfo.StartHeight + SignedBlocksWindow() - maxMissed := SignedBlocksWindow() - MinSignedPerWindow() +maxMissed := SignedBlocksWindow() - MinSignedPerWindow() // If we are past the minimum height and the validator has missed too many // jail and slash them. - if height > minHeight && signInfo.MissedBlocksCounter > maxMissed { - validator := ValidatorByConsAddr(vote.Validator.Address) + if height > minHeight && signInfo.MissedBlocksCounter > maxMissed { + validator := ValidatorByConsAddr(vote.Validator.Address) // emit events... @@ -285,18 +286,19 @@ for vote in block.LastCommitInfo.Votes { distributionHeight := height - sdk.ValidatorUpdateDelay - 1 SlashWithInfractionReason(vote.Validator.Address, distributionHeight, vote.Validator.Power, SlashFractionDowntime(), stakingtypes.Downtime) - Jail(vote.Validator.Address) - signInfo.JailedUntil = block.Time.Add(DowntimeJailDuration()) +Jail(vote.Validator.Address) + +signInfo.JailedUntil = block.Time.Add(DowntimeJailDuration()) // We need to reset the counter & array so that the validator won't be // immediately slashed for downtime upon rebonding. signInfo.MissedBlocksCounter = 0 signInfo.IndexOffset = 0 ClearValidatorMissedBlockBitArray(vote.Validator.Address) - } +} - SetValidatorSigningInfo(vote.Validator.Address, signInfo) +SetValidatorSigningInfo(vote.Validator.Address, signInfo) } ``` @@ -324,22 +326,25 @@ If the validator was out of the validator set and gets bonded again, its new bon ```go onValidatorBonded(address sdk.ValAddress) - signingInfo, found = GetValidatorSigningInfo(address) - if !found { - signingInfo = ValidatorSigningInfo { - StartHeight : CurrentHeight, +signingInfo, found = GetValidatorSigningInfo(address) + +if !found { + signingInfo = ValidatorSigningInfo { + StartHeight : CurrentHeight, IndexOffset : 0, JailedUntil : time.Unix(0, 0), Tombstone : false, MissedBloskCounter : 0 - } else { - signingInfo.StartHeight = CurrentHeight - } +} - setValidatorSigningInfo(signingInfo) - } +else { + signingInfo.StartHeight = CurrentHeight +} - return +setValidatorSigningInfo(signingInfo) +} + +return ``` ## Events @@ -353,7 +358,7 @@ The slashing module emits the following events: | Type | Attribute Key | Attribute Value | | ------- | ------------- | ------------------ | | message | module | slashing | -| message | sender | {validatorAddress} | +| message | sender | `{validatorAddress}` | ### Keeper @@ -361,19 +366,19 @@ The slashing module emits the following events: | Type | Attribute Key | Attribute Value | | ----- | ------------- | --------------------------- | -| slash | address | {validatorConsensusAddress} | -| slash | power | {validatorPower} | -| slash | reason | {slashReason} | -| slash | jailed [0] | {validatorConsensusAddress} | +| slash | address | `{validatorConsensusAddress}` | +| slash | power | `{validatorPower}` | +| slash | reason | `{slashReason}` | +| slash | jailed [0] | `{validatorConsensusAddress}` | | slash | burned coins | {math.Int} | * [0] Only included if the validator is jailed. | Type | Attribute Key | Attribute Value | | -------- | ------------- | --------------------------- | -| liveness | address | {validatorConsensusAddress} | -| liveness | missed_blocks | {missedBlocksCounter} | -| liveness | height | {blockHeight} | +| liveness | address | `{validatorConsensusAddress}` | +| liveness | missed_blocks | `{missedBlocksCounter}` | +| liveness | height | `{blockHeight}` | #### Slash @@ -383,7 +388,7 @@ The slashing module emits the following events: | Type | Attribute Key | Attribute Value | | ----- | ------------- | ------------------ | -| slash | jailed | {validatorAddress} | +| slash | jailed | `{validatorAddress}` | ## Staking Tombstone @@ -568,8 +573,8 @@ simd query slashing signing-infos [flags] Example: ```shell -simd query slashing signing-info '{"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys6jD5B6tPgC8="}' - +simd query slashing signing-info '{"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys6jD5B6tPgC8=" +}' ``` Example Output: @@ -677,7 +682,8 @@ cosmos.slashing.v1beta1.Query/SigningInfo Example: ```shell -grpcurl -plaintext -d '{"cons_address":"cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c"}' localhost:9090 cosmos.slashing.v1beta1.Query/SigningInfo +grpcurl -plaintext -d '{"cons_address":"cosmosvalcons1nrqsld3aw6lh6t082frdqc84uwxn0t958c" +}' localhost:9090 cosmos.slashing.v1beta1.Query/SigningInfo ``` Example Output: @@ -744,11 +750,11 @@ Example Output: ```json { "params": { - "signed_blocks_window": "100", - "min_signed_per_window": "0.500000000000000000", - "downtime_jail_duration": "600s", - "slash_fraction_double_sign": "0.050000000000000000", - "slash_fraction_downtime": "0.010000000000000000" + "signed_blocks_window": "100", + "min_signed_per_window": "0.500000000000000000", + "downtime_jail_duration": "600s", + "slash_fraction_double_sign": "0.050000000000000000", + "slash_fraction_downtime": "0.010000000000000000" } ``` diff --git a/docs/sdk/v0.53/module-reference/staking.mdx b/docs/sdk/v0.53/module-reference/staking.mdx index 531745e2..a0054840 100644 --- a/docs/sdk/v0.53/module-reference/staking.mdx +++ b/docs/sdk/v0.53/module-reference/staking.mdx @@ -782,7 +782,7 @@ delegated to this validator). At this point the validator is said to be an after the unbonding period has passed. Each block the validator queue is to be checked for mature unbonding validators -(namely with a completion time <= current time and completion height <= current +(namely with a completion time <= current time and completion height <= current block height). At this point any mature validators which do not have any delegations remaining are deleted from state. For all other mature unbonding validators that still have remaining delegations, the `validator.Status` is @@ -850,13 +850,13 @@ The staking module emits the following events: | Type | Attribute Key | Attribute Value | | --------------------- | --------------------- | ------------------------- | -| complete_unbonding | amount | {totalUnbondingAmount} | -| complete_unbonding | validator | {validatorAddress} | -| complete_unbonding | delegator | {delegatorAddress} | -| complete_redelegation | amount | {totalRedelegationAmount} | -| complete_redelegation | source_validator | {srcValidatorAddress} | -| complete_redelegation | destination_validator | {dstValidatorAddress} | -| complete_redelegation | delegator | {delegatorAddress} | +| complete_unbonding | amount | `{totalUnbondingAmount}` | +| complete_unbonding | validator | `{validatorAddress}` | +| complete_unbonding | delegator | `{delegatorAddress}` | +| complete_redelegation | amount | `{totalRedelegationAmount}` | +| complete_redelegation | source_validator | `{srcValidatorAddress}` | +| complete_redelegation | destination_validator | `{dstValidatorAddress}` | +| complete_redelegation | delegator | `{delegatorAddress}` | ## Msg's @@ -864,42 +864,42 @@ The staking module emits the following events: | Type | Attribute Key | Attribute Value | | ---------------- | ------------- | ------------------ | -| create_validator | validator | {validatorAddress} | -| create_validator | amount | {delegationAmount} | +| create_validator | validator | `{validatorAddress}` | +| create_validator | amount | `{delegationAmount}` | | message | module | staking | | message | action | create_validator | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ### MsgEditValidator | Type | Attribute Key | Attribute Value | | -------------- | ------------------- | ------------------- | -| edit_validator | commission_rate | {commissionRate} | -| edit_validator | min_self_delegation | {minSelfDelegation} | +| edit_validator | commission_rate | `{commissionRate}` | +| edit_validator | min_self_delegation | `{minSelfDelegation}` | | message | module | staking | | message | action | edit_validator | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ### MsgDelegate | Type | Attribute Key | Attribute Value | | -------- | ------------- | ------------------ | -| delegate | validator | {validatorAddress} | -| delegate | amount | {delegationAmount} | +| delegate | validator | `{validatorAddress}` | +| delegate | amount | `{delegationAmount}` | | message | module | staking | | message | action | delegate | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ### MsgUndelegate | Type | Attribute Key | Attribute Value | | ------- | ------------------- | ------------------ | -| unbond | validator | {validatorAddress} | -| unbond | amount | {unbondAmount} | -| unbond | completion_time [0] | {completionTime} | +| unbond | validator | `{validatorAddress}` | +| unbond | amount | `{unbondAmount}` | +| unbond | completion_time [0] | `{completionTime}` | | message | module | staking | | message | action | begin_unbonding | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | * [0] Time is formatted in the RFC3339 standard @@ -907,25 +907,25 @@ The staking module emits the following events: | Type | Attribute Key | Attribute Value | | ----------------------------- | ------------------ | ------------------------------------| -| cancel_unbonding_delegation | validator | {validatorAddress} | -| cancel_unbonding_delegation | delegator | {delegatorAddress} | -| cancel_unbonding_delegation | amount | {cancelUnbondingDelegationAmount} | -| cancel_unbonding_delegation | creation_height | {unbondingCreationHeight} | +| cancel_unbonding_delegation | validator | `{validatorAddress}` | +| cancel_unbonding_delegation | delegator | `{delegatorAddress}` | +| cancel_unbonding_delegation | amount | `{cancelUnbondingDelegationAmount}` | +| cancel_unbonding_delegation | creation_height | `{unbondingCreationHeight}` | | message | module | staking | | message | action | cancel_unbond | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | ### MsgBeginRedelegate | Type | Attribute Key | Attribute Value | | ---------- | --------------------- | --------------------- | -| redelegate | source_validator | {srcValidatorAddress} | -| redelegate | destination_validator | {dstValidatorAddress} | -| redelegate | amount | {unbondAmount} | -| redelegate | completion_time [0] | {completionTime} | +| redelegate | source_validator | `{srcValidatorAddress}` | +| redelegate | destination_validator | `{dstValidatorAddress}` | +| redelegate | amount | `{unbondAmount}` | +| redelegate | completion_time [0] | `{completionTime}` | | message | module | staking | | message | action | begin_redelegate | -| message | sender | {senderAddress} | +| message | sender | `{senderAddress}` | * [0] Time is formatted in the RFC3339 standard @@ -1385,7 +1385,6 @@ unbonding_responses: creation_height: "55078" initial_balance: "52000000" validator_address: cosmosvaloper1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzmvtaaa - ``` ##### unbonding-delegations-from @@ -1584,7 +1583,10 @@ where `validator.json` contains: ```json { - "pubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"BnbwFpeONLqvWqJb3qaUbL5aoIcW3fSuAp9nT3z5f20="}, + "pubkey": { + "@type": "/cosmos.crypto.ed25519.PubKey", + "key": "BnbwFpeONLqvWqJb3qaUbL5aoIcW3fSuAp9nT3z5f20=" + }, "amount": "1000000stake", "moniker": "my-moniker", "website": "https://myweb.site", @@ -1704,28 +1706,29 @@ Example Output: "validators": [ { "operatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", - "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8="}, + "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8=" +}, "status": "BOND_STATUS_BONDED", "tokens": "10000000", "delegatorShares": "10000000000000000000000000", "description": { "moniker": "myvalidator" - }, +}, "unbondingTime": "1970-01-01T00:00:00Z", "commission": { "commissionRates": { "rate": "100000000000000000", "maxRate": "200000000000000000", "maxChangeRate": "10000000000000000" - }, +}, "updateTime": "2021-10-01T05:52:50.380144238Z" - }, +}, "minSelfDelegation": "1" - } +} ], "pagination": { "total": "1" - } +} } ``` @@ -1740,7 +1743,8 @@ cosmos.staking.v1beta1.Query/Validator Example: ```bash -grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/Validator ``` @@ -1750,24 +1754,25 @@ Example Output: { "validator": { "operatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", - "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8="}, + "consensusPubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8=" +}, "status": "BOND_STATUS_BONDED", "tokens": "10000000", "delegatorShares": "10000000000000000000000000", "description": { "moniker": "myvalidator" - }, +}, "unbondingTime": "1970-01-01T00:00:00Z", "commission": { "commissionRates": { "rate": "100000000000000000", "maxRate": "200000000000000000", "maxChangeRate": "10000000000000000" - }, +}, "updateTime": "2021-10-01T05:52:50.380144238Z" - }, +}, "minSelfDelegation": "1" - } +} } ``` @@ -1782,7 +1787,8 @@ cosmos.staking.v1beta1.Query/ValidatorDelegations Example: ```bash -grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/ValidatorDelegations ``` @@ -1796,16 +1802,17 @@ Example Output: "delegatorAddress": "cosmos1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgy3ua5t", "validatorAddress": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", "shares": "10000000000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "10000000" - } - } +} + +} ], "pagination": { "total": "1" - } +} } ``` @@ -1820,7 +1827,8 @@ cosmos.staking.v1beta1.Query/ValidatorUnbondingDelegations Example: ```bash -grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +grpcurl -plaintext -d '{"validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/ValidatorUnbondingDelegations ``` @@ -1838,9 +1846,9 @@ Example Output: "completion_time": "2021-10-31T09:24:36.797320636Z", "initial_balance": "20000000", "balance": "20000000" - } +} ] - }, +}, { "delegator_address": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", "validator_address": "cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", @@ -1850,14 +1858,14 @@ Example Output: "completion_time": "2021-10-30T12:53:02.272266791Z", "initial_balance": "1000000", "balance": "1000000" - } +} ] - }, +}, ], "pagination": { "next_key": null, "total": "8" - } +} } ``` @@ -1873,7 +1881,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/Delegation ``` @@ -1888,13 +1897,14 @@ Example Output: "delegator_address":"cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", "validator_address":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc", "shares":"25083119936.000000000000000000" - }, +}, "balance": { "denom":"stake", "amount":"25083119936" - } - } +} + +} } ``` @@ -1910,7 +1920,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc"}' \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77", validator_addr":"cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/UnbondingDelegation ``` @@ -1927,15 +1938,15 @@ Example Output: "completion_time": "2021-11-08T05:38:47.505593891Z", "initial_balance": "400000000", "balance": "400000000" - }, +}, { "creation_height": "137005", "completion_time": "2021-11-08T05:40:53.526196312Z", "initial_balance": "385000000", "balance": "385000000" - } +} ] - } +} } ``` @@ -1951,7 +1962,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77"}' \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/DelegatorDelegations ``` @@ -1960,12 +1972,14 @@ Example Output: ```bash { "delegation_responses": [ - {"delegation":{"delegator_address":"cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77","validator_address":"cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8","shares":"25083339023.000000000000000000"},"balance":{"denom":"stake","amount":"25083339023"}} + {"delegation":{"delegator_address":"cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77","validator_address":"cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8","shares":"25083339023.000000000000000000" +},"balance":{"denom":"stake","amount":"25083339023" +}} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -1981,7 +1995,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77"}' \ +-d '{"delegator_addr": "cosmos1y8nyfvmqh50p6ldpzljk3yrglppdv3t8phju77" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/DelegatorUnbondingDelegations ``` @@ -1999,20 +2014,20 @@ Example Output: "completion_time": "2021-11-08T05:38:47.505593891Z", "initial_balance": "400000000", "balance": "400000000" - }, +}, { "creation_height": "137005", "completion_time": "2021-11-08T05:40:53.526196312Z", "initial_balance": "385000000", "balance": "385000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2028,7 +2043,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf", "src_validator_addr" : "cosmosvaloper1j7euyj85fv2jugejrktj540emh9353ltgppc3g", "dst_validator_addr" : "cosmosvaloper1yy3tnegzmkdcm7czzcy3flw5z0zyr9vkkxrfse"}' \ +-d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf", "src_validator_addr" : "cosmosvaloper1j7euyj85fv2jugejrktj540emh9353ltgppc3g", "dst_validator_addr" : "cosmosvaloper1yy3tnegzmkdcm7czzcy3flw5z0zyr9vkkxrfse" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/Redelegations ``` @@ -2043,7 +2059,7 @@ Example Output: "validator_src_address": "cosmosvaloper1j7euyj85fv2jugejrktj540emh9353ltgppc3g", "validator_dst_address": "cosmosvaloper1yy3tnegzmkdcm7czzcy3flw5z0zyr9vkkxrfse", "entries": null - }, +}, "entries": [ { "redelegation_entry": { @@ -2051,11 +2067,11 @@ Example Output: "completion_time": "2021-11-08T03:52:55.299147901Z", "initial_balance": "2900000", "shares_dst": "2900000.000000000000000000" - }, +}, "balance": "2900000" - } +} ] - } +} ], "pagination": null } @@ -2073,7 +2089,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf"}' \ +-d '{"delegator_addr": "cosmos1ld5p7hn43yuh8ht28gm9pfjgj2fctujp2tgwvf" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/DelegatorValidators ``` @@ -2087,7 +2104,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "UPwHWxH1zHJWGOa/m6JB3f5YjHMvPQPkVbDqqi+U7Uw=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "347260647559", @@ -2098,7 +2115,7 @@ Example Output: "website": "https://boubounode.com", "security_contact": "", "details": "AI-based Validator. #1 AI Validator on Game of Stakes. Fairly priced. Don't trust (humans), verify. Made with BouBou love." - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2106,16 +2123,16 @@ Example Output: "rate": "0.061000000000000000", "max_rate": "0.300000000000000000", "max_change_rate": "0.150000000000000000" - }, +}, "update_time": "2021-10-01T15:00:00Z" - }, +}, "min_self_delegation": "1" - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2131,7 +2148,8 @@ Example: ```bash grpcurl -plaintext \ --d '{"delegator_addr": "cosmos1eh5mwu044gd5ntkkc2xgfg8247mgc56f3n8rr7", "validator_addr": "cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8"}' \ +-d '{"delegator_addr": "cosmos1eh5mwu044gd5ntkkc2xgfg8247mgc56f3n8rr7", "validator_addr": "cosmosvaloper1eh5mwu044gd5ntkkc2xgfg8247mgc56fww3vc8" +}' \ localhost:9090 cosmos.staking.v1beta1.Query/DelegatorValidator ``` @@ -2144,7 +2162,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "UPwHWxH1zHJWGOa/m6JB3f5YjHMvPQPkVbDqqi+U7Uw=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "347262754841", @@ -2155,7 +2173,7 @@ Example Output: "website": "https://boubounode.com", "security_contact": "", "details": "AI-based Validator. #1 AI Validator on Game of Stakes. Fairly priced. Don't trust (humans), verify. Made with BouBou love." - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2163,11 +2181,11 @@ Example Output: "rate": "0.061000000000000000", "max_rate": "0.300000000000000000", "max_change_rate": "0.150000000000000000" - }, +}, "update_time": "2021-10-01T15:00:00Z" - }, +}, "min_self_delegation": "1" - } +} } ``` @@ -2180,7 +2198,8 @@ cosmos.staking.v1beta1.Query/HistoricalInfo Example: ```bash -grpcurl -plaintext -d '{"height" : 1}' localhost:9090 cosmos.staking.v1beta1.Query/HistoricalInfo +grpcurl -plaintext -d '{"height" : 1 +}' localhost:9090 cosmos.staking.v1beta1.Query/HistoricalInfo ``` Example Output: @@ -2192,7 +2211,7 @@ Example Output: "version": { "block": "11", "app": "0" - }, +}, "chain_id": "simd-1", "height": "140142", "time": "2021-10-11T10:56:29.720079569Z", @@ -2201,8 +2220,9 @@ Example Output: "part_set_header": { "total": 1, "hash": "Hk1+C864uQkl9+I6Zn7IurBZBKUevqlVtU7VqaZl1tc=" - } - }, +} + +}, "last_commit_hash": "VxrcS27GtvGruS3I9+AlpT7udxIT1F0OrRklrVFSSKc=", "data_hash": "80BjOrqNYUOkTnmgWyz9AQ8n7SoEmPVi4QmAe8RbQBY=", "validators_hash": "95W49n2hw8RWpr1GPTAO5MSPi6w6Wjr3JjjS7AjpBho=", @@ -2212,14 +2232,14 @@ Example Output: "last_results_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", "evidence_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", "proposer_address": "aH6dO428B+ItuoqPq70efFHrSMY=" - }, +}, "valset": [ { "operator_address": "cosmosvaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw", "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "1426045203613", @@ -2230,7 +2250,7 @@ Example Output: "website": "https://sg-1.online", "security_contact": "", "details": "SG-1 - your favorite validator on Witval. We offer 100% Soft Slash protection." - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2238,15 +2258,14 @@ Example Output: "rate": "0.037500000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.030000000000000000" - }, +}, "update_time": "2021-10-01T15:00:00Z" - }, +}, "min_self_delegation": "1" - } +} ] - } } - +} ``` #### Pool @@ -2270,7 +2289,7 @@ Example Output: "pool": { "not_bonded_tokens": "369054400189", "bonded_tokens": "15657192425623" - } +} } ``` @@ -2298,7 +2317,7 @@ Example Output: "maxEntries": 7, "historicalEntries": 10000, "bondDenom": "stake" - } +} } ``` @@ -2311,7 +2330,9 @@ A user can query the `staking` module using REST endpoints. The `DelegtaorDelegations` REST endpoint queries all delegations of a given delegator address. ```bash -/cosmos/staking/v1beta1/delegations/{delegatorAddr} +/cosmos/staking/v1beta1/delegations/{ + delegatorAddr +} ``` Example: @@ -2330,28 +2351,30 @@ Example Output: "delegator_address": "cosmos1vcs68xf2tnqes5tg0khr0vyevm40ff6zdxatp5", "validator_address": "cosmosvaloper1quqxfrxkycr0uzt4yk0d57tcq3zk7srm7sm6r8", "shares": "256250000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "256250000" - } - }, +} + +}, { "delegation": { "delegator_address": "cosmos1vcs68xf2tnqes5tg0khr0vyevm40ff6zdxatp5", "validator_address": "cosmosvaloper194v8uwee2fvs2s8fa5k7j03ktwc87h5ym39jfv", "shares": "255150000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "255150000" - } - } +} + +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` @@ -2360,7 +2383,9 @@ Example Output: The `Redelegations` REST endpoint queries redelegations of given address. ```bash -/cosmos/staking/v1beta1/delegators/{delegatorAddr}/redelegations +/cosmos/staking/v1beta1/delegators/{ + delegatorAddr +}/redelegations ``` Example: @@ -2382,7 +2407,7 @@ Example Output: "validator_src_address": "cosmosvaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qx4cuznf", "validator_dst_address": "cosmosvaloper1vq8tw77kp8lvxq9u3c8eeln9zymn68rng8pgt4", "entries": null - }, +}, "entries": [ { "redelegation_entry": { @@ -2390,11 +2415,11 @@ Example Output: "completion_time": "2021-11-09T06:03:25.640682116Z", "initial_balance": "200000000", "shares_dst": "200000000.000000000000000000" - }, +}, "balance": "200000000" - } +} ] - } +} ], "pagination": null } @@ -2405,7 +2430,9 @@ Example Output: The `DelegatorUnbondingDelegations` REST endpoint queries all unbonding delegations of a given delegator address. ```bash -/cosmos/staking/v1beta1/delegators/{delegatorAddr}/unbonding_delegations +/cosmos/staking/v1beta1/delegators/{ + delegatorAddr +}/unbonding_delegations ``` Example: @@ -2430,14 +2457,14 @@ Example Output: "completion_time": "2021-10-12T10:59:03.797335857Z", "initial_balance": "50000000000", "balance": "50000000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2446,7 +2473,9 @@ Example Output: The `DelegatorValidators` REST endpoint queries all validators information for given delegator address. ```bash -/cosmos/staking/v1beta1/delegators/{delegatorAddr}/validators +/cosmos/staking/v1beta1/delegators/{ + delegatorAddr +}/validators ``` Example: @@ -2467,7 +2496,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "5v4n3px3PkfNnKflSgepDnsMQR1hiNXnqOC11Y72/PQ=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "21592843799", @@ -2478,7 +2507,7 @@ Example Output: "website": "https://twitter.com/JoeAbbey", "security_contact": "", "details": "just another dad in the cosmos" - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2486,16 +2515,16 @@ Example Output: "rate": "0.100000000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.100000000000000000" - }, +}, "update_time": "2021-10-09T19:03:54.984821705Z" - }, +}, "min_self_delegation": "1" - } +} ], "pagination": { "next_key": null, "total": "1" - } +} } ``` @@ -2504,7 +2533,11 @@ Example Output: The `DelegatorValidator` REST endpoint queries validator information for given delegator validator pair. ```bash -/cosmos/staking/v1beta1/delegators/{delegatorAddr}/validators/{validatorAddr} +/cosmos/staking/v1beta1/delegators/{ + delegatorAddr +}/validators/{ + validatorAddr +} ``` Example: @@ -2524,7 +2557,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "5v4n3px3PkfNnKflSgepDnsMQR1hiNXnqOC11Y72/PQ=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "21592843799", @@ -2535,7 +2568,7 @@ Example Output: "website": "https://twitter.com/JoeAbbey", "security_contact": "", "details": "just another dad in the cosmos" - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2543,11 +2576,11 @@ Example Output: "rate": "0.100000000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.100000000000000000" - }, +}, "update_time": "2021-10-09T19:03:54.984821705Z" - }, +}, "min_self_delegation": "1" - } +} } ``` @@ -2556,7 +2589,9 @@ Example Output: The `HistoricalInfo` REST endpoint queries the historical information for given height. ```bash -/cosmos/staking/v1beta1/historical_info/{height} +/cosmos/staking/v1beta1/historical_info/{ + height +} ``` Example: @@ -2574,7 +2609,7 @@ Example Output: "version": { "block": "11", "app": "0" - }, +}, "chain_id": "cosmos-1", "height": "153332", "time": "2021-10-12T09:05:35.062230221Z", @@ -2583,8 +2618,9 @@ Example Output: "part_set_header": { "total": 1, "hash": "zLQ2FiKM5tooL3BInt+VVfgzjlBXfq0Hc8Iux/xrhdg=" - } - }, +} + +}, "last_commit_hash": "P6IJrK8vSqU3dGEyRHnAFocoDGja0bn9euLuy09s350=", "data_hash": "eUd+6acHWrNXYju8Js449RJ99lOYOs16KpqQl4SMrEM=", "validators_hash": "mB4pravvMsJKgi+g8aYdSeNlt0kPjnRFyvtAQtaxcfw=", @@ -2594,14 +2630,14 @@ Example Output: "last_results_hash": "p/BPexV4LxAzlVcPRvW+lomgXb6Yze8YLIQUo/4Kdgc=", "evidence_hash": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", "proposer_address": "G0MeY8xQx7ooOsni8KE/3R/Ib3Q=" - }, +}, "valset": [ { "operator_address": "cosmosvaloper196ax4vc0lwpxndu9dyhvca7jhxp70rmcqcnylw", "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "/O7BtNW0pafwfvomgR4ZnfldwPXiFfJs9mHg3gwfv5Q=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "1416521659632", @@ -2612,7 +2648,7 @@ Example Output: "website": "https://sg-1.online", "security_contact": "", "details": "SG-1 - your favorite validator on cosmos. We offer 100% Soft Slash protection." - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2620,17 +2656,17 @@ Example Output: "rate": "0.037500000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.030000000000000000" - }, +}, "update_time": "2021-10-01T15:00:00Z" - }, +}, "min_self_delegation": "1" - }, +}, { "operator_address": "cosmosvaloper1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzmvtaaa", "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "uExZyjNLtr2+FFIhNDAMcQ8+yTrqE7ygYTsI7khkA5Y=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "1348298958808", @@ -2641,7 +2677,7 @@ Example Output: "website": "https://www.cosmostation.io", "security_contact": "admin@stamper.network", "details": "Cosmostation validator node. Delegate your tokens and Start Earning Staking Rewards" - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2649,13 +2685,13 @@ Example Output: "rate": "0.050000000000000000", "max_rate": "1.000000000000000000", "max_change_rate": "0.200000000000000000" - }, +}, "update_time": "2021-10-01T15:06:38.821314287Z" - }, +}, "min_self_delegation": "1" - } +} ] - } +} } ``` @@ -2683,7 +2719,7 @@ Example Output: "max_entries": 7, "historical_entries": 10000, "bond_denom": "stake" - } +} } ``` @@ -2708,7 +2744,7 @@ Example Output: "pool": { "not_bonded_tokens": "432805737458", "bonded_tokens": "15783637712645" - } +} } ``` @@ -2736,7 +2772,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "N7BPyek2aKuNZ0N/8YsrqSDhGZmgVaYUBuddY8pwKaE=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "383301887799", @@ -2747,7 +2783,7 @@ Example Output: "website": "https://smartnodes.co", "security_contact": "", "details": "Earn Rewards with Crypto Staking & Node Deployment" - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2755,17 +2791,17 @@ Example Output: "rate": "0.050000000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.100000000000000000" - }, +}, "update_time": "2021-10-01T15:51:31.596618510Z" - }, +}, "min_self_delegation": "1" - }, +}, { "operator_address": "cosmosvaloper1q5ku90atkhktze83j9xjaks2p7uruag5zp6wt7", "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "GDNpuKDmCg9GnhnsiU4fCWktuGUemjNfvpCZiqoRIYA=" - }, +}, "jailed": false, "status": "BOND_STATUS_UNBONDING", "tokens": "1017819654", @@ -2776,7 +2812,7 @@ Example Output: "website": "http://noderunners.biz", "security_contact": "info@noderunners.biz", "details": "Noderunners is a professional validator in POS networks. We have a huge node running experience, reliable soft and hardware. Our commissions are always low, our support to delegators is always full. Stake with us and start receiving your cosmos rewards now!" - }, +}, "unbonding_height": "147302", "unbonding_time": "2021-11-08T22:58:53.718662452Z", "commission": { @@ -2784,16 +2820,16 @@ Example Output: "rate": "0.050000000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.100000000000000000" - }, +}, "update_time": "2021-10-04T18:02:21.446645619Z" - }, +}, "min_self_delegation": "1" - } +} ], "pagination": { "next_key": "FONDBFkE4tEEf7yxWWKOD49jC2NK", "total": "2" - } +} } ``` @@ -2802,7 +2838,9 @@ Example Output: The `Validator` REST endpoint queries validator information for given validator address. ```bash -/cosmos/staking/v1beta1/validators/{validatorAddr} +/cosmos/staking/v1beta1/validators/{ + validatorAddr +} ``` Example: @@ -2822,7 +2860,7 @@ Example Output: "consensus_pubkey": { "@type": "/cosmos.crypto.ed25519.PubKey", "key": "sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc=" - }, +}, "jailed": false, "status": "BOND_STATUS_BONDED", "tokens": "33027900000", @@ -2833,7 +2871,7 @@ Example Output: "website": "", "security_contact": "", "details": "Witval is the validator arm from Vitwit. Vitwit is into software consulting and services business since 2015. We are working closely with Cosmos ecosystem since 2018. We are also building tools for the ecosystem, Aneka is our explorer for the cosmos ecosystem." - }, +}, "unbonding_height": "0", "unbonding_time": "1970-01-01T00:00:00Z", "commission": { @@ -2841,11 +2879,11 @@ Example Output: "rate": "0.050000000000000000", "max_rate": "0.200000000000000000", "max_change_rate": "0.020000000000000000" - }, +}, "update_time": "2021-10-01T19:24:52.663191049Z" - }, +}, "min_self_delegation": "1" - } +} } ``` @@ -2854,7 +2892,9 @@ Example Output: The `ValidatorDelegations` REST endpoint queries delegate information for given validator. ```bash -/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations +/cosmos/staking/v1beta1/validators/{ + validatorAddr +}/delegations ``` Example: @@ -2873,61 +2913,66 @@ Example Output: "delegator_address": "cosmos190g5j8aszqhvtg7cprmev8xcxs6csra7xnk3n3", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "31000000000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "31000000000" - } - }, +} + +}, { "delegation": { "delegator_address": "cosmos1ddle9tczl87gsvmeva3c48nenyng4n56qwq4ee", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "628470000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "628470000" - } - }, +} + +}, { "delegation": { "delegator_address": "cosmos10fdvkczl76m040smd33lh9xn9j0cf26kk4s2nw", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "838120000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "838120000" - } - }, +} + +}, { "delegation": { "delegator_address": "cosmos1n8f5fknsv2yt7a8u6nrx30zqy7lu9jfm0t5lq8", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "500000000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "500000000" - } - }, +} + +}, { "delegation": { "delegator_address": "cosmos16msryt3fqlxtvsy8u5ay7wv2p8mglfg9hrek2e", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "61310000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "61310000" - } - } +} + +} ], "pagination": { "next_key": null, "total": "5" - } +} } ``` @@ -2936,7 +2981,11 @@ Example Output: The `Delegation` REST endpoint queries delegate information for given validator delegator pair. ```bash -/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations/{delegatorAddr} +/cosmos/staking/v1beta1/validators/{ + validatorAddr +}/delegations/{ + delegatorAddr +} ``` Example: @@ -2956,12 +3005,13 @@ Example Output: "delegator_address": "cosmos1n8f5fknsv2yt7a8u6nrx30zqy7lu9jfm0t5lq8", "validator_address": "cosmosvaloper16msryt3fqlxtvsy8u5ay7wv2p8mglfg9g70e3q", "shares": "500000000.000000000000000000" - }, +}, "balance": { "denom": "stake", "amount": "500000000" - } - } +} + +} } ``` @@ -2970,7 +3020,11 @@ Example Output: The `UnbondingDelegation` REST endpoint queries unbonding information for given validator delegator pair. ```bash -/cosmos/staking/v1beta1/validators/{validatorAddr}/delegations/{delegatorAddr}/unbonding_delegation +/cosmos/staking/v1beta1/validators/{ + validatorAddr +}/delegations/{ + delegatorAddr +}/unbonding_delegation ``` Example: @@ -2994,9 +3048,9 @@ Example Output: "completion_time": "2021-11-09T09:41:18.352401903Z", "initial_balance": "525111", "balance": "525111" - } +} ] - } +} } ``` @@ -3005,7 +3059,9 @@ Example Output: The `ValidatorUnbondingDelegations` REST endpoint queries unbonding delegations of a validator. ```bash -/cosmos/staking/v1beta1/validators/{validatorAddr}/unbonding_delegations +/cosmos/staking/v1beta1/validators/{ + validatorAddr +}/unbonding_delegations ``` Example: @@ -3030,9 +3086,9 @@ Example Output: "completion_time": "2021-11-05T00:14:37.005841058Z", "initial_balance": "24000000", "balance": "24000000" - } +} ] - }, +}, { "delegator_address": "cosmos1qf36e6wmq9h4twhdvs6pyq9qcaeu7ye0s3dqq2", "validator_address": "cosmosvaloper13v4spsah85ps4vtrw07vzea37gq5la5gktlkeu", @@ -3042,13 +3098,13 @@ Example Output: "completion_time": "2021-11-01T22:47:26.714116854Z", "initial_balance": "8000000", "balance": "8000000" - } +} ] - } +} ], "pagination": { "next_key": null, "total": "2" - } +} } ``` diff --git a/docs/sdk/v0.53/module-reference/upgrade.mdx b/docs/sdk/v0.53/module-reference/upgrade.mdx index 144743e8..8ad169cb 100644 --- a/docs/sdk/v0.53/module-reference/upgrade.mdx +++ b/docs/sdk/v0.53/module-reference/upgrade.mdx @@ -43,9 +43,9 @@ automatically upgrade to. ```go type Plan struct { - Name string - Height int64 - Info string + Name string + Height int64 + Info string } ``` @@ -84,7 +84,9 @@ not defined on a per-module basis. Registering this `StoreLoader` is done via `app#SetStoreLoader` in the application. ```go -func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades) baseapp.StoreLoader +func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades) + +baseapp.StoreLoader ``` If there's a planned upgrade and the upgrade height is reached, the old binary writes `Plan` to the disk before panicking. @@ -188,13 +190,14 @@ Example Output: "parts": { "total": 1, "hash": "B13CBD23011C7480E6F11BE4594EE316548648E6A666B3575409F8F16EC6939E" - } - }, +} + +}, "block_size": "7213", "header": { "version": { "block": "11" - }, +}, "chain_id": "testnet-2", "height": "455200", "time": "2021-04-10T04:37:57.085493838Z", @@ -203,8 +206,9 @@ Example Output: "parts": { "total": 1, "hash": "8FE572A48CD10BC2CBB02653CA04CA247A0F6830FF19DC972F64D339A355E77D" - } - }, +} + +}, "last_commit_hash": "DE890239416A19E6164C2076B837CC1D7F7822FC214F305616725F11D2533140", "data_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", "validators_hash": "A31047ADE54AE9072EE2A12FF260A8990BA4C39F903EAF5636B50D58DBA72582", @@ -214,7 +218,7 @@ Example Output: "last_results_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", "evidence_hash": "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", "proposer_address": "2ABC4854B1A1C5AA8403C4EA853A81ACA901CC76" - }, +}, "num_txs": "0" } ``` @@ -320,7 +324,9 @@ The upgrade module supports the following transactions: ```bash simd tx upgrade software-upgrade v2 --title="Test Proposal" --summary="testing" --deposit="100000000stake" --upgrade-height 1000000 \ ---upgrade-info '{ "binaries": { "linux/amd64":"https://example.com/simd.zip?checksum=sha256:aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f" } }' --from cosmos1.. +--upgrade-info '{ "binaries": { "linux/amd64":"https://example.com/simd.zip?checksum=sha256:aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f" +} +}' --from cosmos1.. ``` * `cancel-software-upgrade` - cancels a previously submitted upgrade proposal: @@ -338,7 +344,9 @@ A user can query the `upgrade` module using REST endpoints. `AppliedPlan` queries a previously applied upgrade plan by its name. ```bash -/cosmos/upgrade/v1beta1/applied_plan/{name} +/cosmos/upgrade/v1beta1/applied_plan/{ + name +} ``` Example: @@ -399,67 +407,67 @@ Example Output: { "name": "auth", "version": "2" - }, +}, { "name": "authz", "version": "1" - }, +}, { "name": "bank", "version": "2" - }, +}, { "name": "distribution", "version": "2" - }, +}, { "name": "evidence", "version": "1" - }, +}, { "name": "feegrant", "version": "1" - }, +}, { "name": "genutil", "version": "1" - }, +}, { "name": "gov", "version": "2" - }, +}, { "name": "ibc", "version": "2" - }, +}, { "name": "mint", "version": "1" - }, +}, { "name": "params", "version": "1" - }, +}, { "name": "slashing", "version": "2" - }, +}, { "name": "staking", "version": "2" - }, +}, { "name": "transfer", "version": "1" - }, +}, { "name": "upgrade", "version": "1" - }, +}, { "name": "vesting", "version": "1" - } +} ] } ``` @@ -480,7 +488,8 @@ Example: ```bash grpcurl -plaintext \ - -d '{"name":"v2.0-upgrade"}' \ + -d '{"name":"v2.0-upgrade" +}' \ localhost:9090 \ cosmos.upgrade.v1beta1.Query/AppliedPlan ``` @@ -537,67 +546,67 @@ Example Output: { "name": "auth", "version": "2" - }, +}, { "name": "authz", "version": "1" - }, +}, { "name": "bank", "version": "2" - }, +}, { "name": "distribution", "version": "2" - }, +}, { "name": "evidence", "version": "1" - }, +}, { "name": "feegrant", "version": "1" - }, +}, { "name": "genutil", "version": "1" - }, +}, { "name": "gov", "version": "2" - }, +}, { "name": "ibc", "version": "2" - }, +}, { "name": "mint", "version": "1" - }, +}, { "name": "params", "version": "1" - }, +}, { "name": "slashing", "version": "2" - }, +}, { "name": "staking", "version": "2" - }, +}, { "name": "transfer", "version": "1" - }, +}, { "name": "upgrade", "version": "1" - }, +}, { "name": "vesting", "version": "1" - } +} ] } ``` diff --git a/docs/sdk/v0.53/node-operations/run-node.mdx b/docs/sdk/v0.53/node-operations/run-node.mdx index d2b22c8b..7547dbe3 100644 --- a/docs/sdk/v0.53/node-operations/run-node.mdx +++ b/docs/sdk/v0.53/node-operations/run-node.mdx @@ -100,9 +100,9 @@ One example config to tweak is the `minimum-gas-prices` field inside `app.toml`, When running a node (not a validator!) and not wanting to run the application mempool, set the `max-txs` field to `-1`. - ``` +``` [mempool]# Setting max-txs to 0 will allow for an unbounded amount of transactions in the mempool.# Setting max_txs to negative 1 (-1) will disable transactions from being inserted into the mempool.# Setting max_txs to a positive number (> 0) will limit the number of transactions in the mempool, by the specified amount.## Note, this configuration only applies to SDK built-in app-side mempool# implementations.max-txs = "-1" - ``` +``` ## Run a Localnet[​](#run-a-localnet "Direct link to Run a Localnet") diff --git a/docs/sdk/v0.53/node-operations/run-production.mdx b/docs/sdk/v0.53/node-operations/run-production.mdx index dd66e35c..b2a3f1e4 100644 --- a/docs/sdk/v0.53/node-operations/run-production.mdx +++ b/docs/sdk/v0.53/node-operations/run-production.mdx @@ -212,9 +212,9 @@ vim $HOME/.simd/config/config.tomlpriv_validator_laddr = "tcp://0.0.0.0:26659" It is recommended to comment or delete the lines that specify the path of the validator key and validator: - ``` +``` # Path to the JSON file containing the private key to use as a validator in the consensus protocol# priv_validator_key_file = "config/priv_validator_key.json"# Path to the JSON file containing the last sign state of a validator# priv_validator_state_file = "data/priv_validator_state.json" - ``` +``` 6. Start the two processes. diff --git a/docs/sdk/v0.53/node-operations/txs.mdx b/docs/sdk/v0.53/node-operations/txs.mdx index 1e55a2f7..08cdf376 100644 --- a/docs/sdk/v0.53/node-operations/txs.mdx +++ b/docs/sdk/v0.53/node-operations/txs.mdx @@ -199,7 +199,7 @@ It is not possible to generate or sign a transaction using gRPC, only to broadca Broadcasting a transaction using the gRPC endpoint can be done by sending a `BroadcastTx` request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -grpcurl -plaintext \ -d '{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx +grpcurl -plaintext \ -d '{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:9090 \ cosmos.tx.v1beta1.Service/BroadcastTx ``` ## Using REST[​](#using-rest "Direct link to Using REST") @@ -211,7 +211,7 @@ It is not possible to generate or sign a transaction using REST, only to broadca Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) can be done by sending a POST request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction: ``` -curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs +curl -X POST \ -H "Content-Type: application/json" \ -d'{"tx_bytes":"{`{txBytes}`}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs ``` ## Using CosmJS (JavaScript & TypeScript)[​](#using-cosmjs-javascript--typescript "Direct link to Using CosmJS (JavaScript & TypeScript)") diff --git a/docs/sdk/v0.53/overview.mdx b/docs/sdk/v0.53/overview.mdx index f4d46f81..637cf087 100644 --- a/docs/sdk/v0.53/overview.mdx +++ b/docs/sdk/v0.53/overview.mdx @@ -1,98 +1,44 @@ --- -title: "Overview" -description: "The Cosmos SDK is an open-source framework for building multi-asset public Proof-of-Stake (PoS) blockchains and permissioned Proof-of-Authority (PoA) blockchains. Build application-specific blockchains with modular architecture and native interoperability." -mode: "wide" +title: "Website" +description: "Version: v0.53" --- -import { Card, CardGroup } from '@mintlify/components' +This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. - - - Learn the fundamentals of the Cosmos SDK architecture and application-specific blockchains - - - Start building your blockchain application with step-by-step guides - - - Explore pre-built modules for staking, governance, token issuance, and more - - - Enable cross-chain communication with the Inter-Blockchain Communication protocol - - +### Installation -## What is the Cosmos SDK +``` +$ yarn +``` -The [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is a framework that facilitates the development of secure state machines on top of CometBFT. At its core, the SDK is a boilerplate implementation of the ABCI in Go. It comes with a `multistore` to persist data and a `router` to handle transactions. +### Local Development -The SDK design is based on the following principles: +``` +$ yarn start +``` -- **Composability**: Build custom blockchains by composing different modules -- **Capabilities**: Object-capability model for secure inter-module interactions -- **Flexibility**: Choose consensus engines, customize modules, and configure parameters -- **Sovereignty**: Full control over your blockchain's governance and economics +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. -## Key Features +### Build - - - Plug-and-play modules for common blockchain functionality - - - Support for CometBFT, Rollkit, and other consensus engines - - - Built-in IBC support for cross-chain communication - - - Deterministic state transitions with ABCI integration - - - CLI scaffolding, testing frameworks, and simulation tools - - - Battle-tested in production by Cosmos Hub, Osmosis, and many others - - +``` +$ yarn build +``` -## Quick Start +This command generates static content into the `build` directory and can be served using any static contents hosting service. -Get started with the Cosmos SDK by exploring these essential resources: +### Deployment - - - Set up your development environment and build your first app - - - Learn through hands-on examples and guided tutorials - - - Create custom modules for your blockchain - - - Explore the complete API documentation - - +Using SSH: -## Architecture Overview +``` +$ USE_SSH=true yarn deploy +``` -The Cosmos SDK follows a modular architecture where functionality is organized into discrete modules: +Not using SSH: -- **Core Modules**: Essential modules like `auth`, `bank`, `staking`, and `gov` -- **IBC Modules**: Enable cross-chain communication and asset transfers -- **Custom Modules**: Build your own modules for application-specific logic -- **Keeper Pattern**: Encapsulate module state and expose controlled interfaces +``` +$ GIT_USER= yarn deploy +``` -Learn more about the [SDK architecture](/docs/sdk/v0.53/core-concepts/baseapp) and [module system](/docs/sdk/v0.53/building-modules/intro). - -## Version Information - -This documentation covers Cosmos SDK v0.53, which includes: - -- Enhanced ABCI++ integration for vote extensions and optimistic execution -- Improved module interfaces and dependency injection -- AutoCLI for automatic CLI generation -- Circuit breaker for runtime safety -- Optimized state management and performance improvements - -For migration guides and breaking changes, see the [Release Notes](/docs/sdk/v0.53/changelog/release-notes). +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. \ No newline at end of file diff --git a/docs/sdk/v0.53/release-notes.mdx b/docs/sdk/v0.53/release-notes.mdx deleted file mode 100644 index 03cedac2..00000000 --- a/docs/sdk/v0.53/release-notes.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: "Release Notes" -description: "Cosmos SDK v0.53 release notes and changelog" ---- - -## Overview - -This page provides release notes and changelog information for Cosmos SDK v0.53. - - -For the most up-to-date and detailed changelog, please refer to the official Cosmos SDK repository. - - -## Resources - -- [Full Changelog on GitHub](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md) -- [Release Notes](https://github.com/cosmos/cosmos-sdk/releases?q=v0.53&expanded=true) -- [Migration Guide](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/UPGRADING.md) - -## Major Changes in v0.53 - -### Key Features -- Enhanced ABCI 2.0 support with vote extensions -- Improved module system with better dependency injection -- Optimized state management and store improvements -- Enhanced testing framework with better simulation tools - -### Breaking Changes -- Module interfaces have been updated -- Changes to keeper patterns -- Updated transaction handling - -### Module Updates -- **x/auth**: Enhanced account management -- **x/bank**: Improved token handling -- **x/staking**: Optimized delegation logic -- **x/gov**: Enhanced governance features - -For complete details on all changes, bug fixes, and improvements, please consult the [official changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md). diff --git a/docs/sdk/v0.53/runtime-abci/checktx.mdx b/docs/sdk/v0.53/runtime-abci/checktx.mdx index 9cfed380..52c921b7 100644 --- a/docs/sdk/v0.53/runtime-abci/checktx.mdx +++ b/docs/sdk/v0.53/runtime-abci/checktx.mdx @@ -47,7 +47,8 @@ func NewSimApp( ... // Create ChecktxHandler checktxHandler := abci.NewCustomCheckTxHandler(...) - app.SetCheckTxHandler(checktxHandler) + +app.SetCheckTxHandler(checktxHandler) ... } ``` diff --git a/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx b/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx index 794d6f3e..51854ad7 100644 --- a/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx +++ b/docs/sdk/v0.53/runtime-abci/prepare-proposal.mdx @@ -40,8 +40,9 @@ favor of a custom implementation in [`app_di.go`](../building-apps/01-app-go-di. ```go prepareOpt := func(app *baseapp.BaseApp) { - abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) - app.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) + abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) + +app.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) } baseAppOptions = append(baseAppOptions, prepareOpt) diff --git a/docs/sdk/v0.53/runtime-abci/process-proposal.mdx b/docs/sdk/v0.53/runtime-abci/process-proposal.mdx index a6297a30..515e8815 100644 --- a/docs/sdk/v0.53/runtime-abci/process-proposal.mdx +++ b/docs/sdk/v0.53/runtime-abci/process-proposal.mdx @@ -27,8 +27,9 @@ provided in the proposal DO NOT exceed the maximum block gas and `maxtxbytes` (i ```go processOpt := func(app *baseapp.BaseApp) { - abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) - app.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) + abciPropHandler := baseapp.NewDefaultProposalHandler(mempool, app) + +app.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) } baseAppOptions = append(baseAppOptions, processOpt) diff --git a/docs/sdk/v0.53/testing-simulation/simulator.mdx b/docs/sdk/v0.53/testing-simulation/simulator.mdx index bd11551f..f58822e1 100644 --- a/docs/sdk/v0.53/testing-simulation/simulator.mdx +++ b/docs/sdk/v0.53/testing-simulation/simulator.mdx @@ -146,7 +146,7 @@ Finally, the application should expose the `SimulationManager` via the following ```go // SimulationManager implements the SimulationApp interface func (app *SimApp) SimulationManager() *module.SimulationManager { -return app.sm + return app.sm } ``` diff --git a/docs/sdk/v0.53/testing-simulation/testing.mdx b/docs/sdk/v0.53/testing-simulation/testing.mdx index 77c721d3..e44c19e2 100644 --- a/docs/sdk/v0.53/testing-simulation/testing.mdx +++ b/docs/sdk/v0.53/testing-simulation/testing.mdx @@ -61,7 +61,7 @@ The goal of these integration tests is to test how a component interacts with ot Integration tests interact with the tested module via the defined `Msg` and `Query` services. The result of the test can be verified by checking the state of the application, by checking the emitted events or the response. It is adviced to combine two of these methods to verify the result of the test. -The SDK provides small helpers for quickly setting up an integration tests. These helpers can be found at . +The SDK provides small helpers for quickly setting up an integration tests. These helpers can be found at [https://github.com/cosmos/cosmos-sdk/blob/main/testutil/integration](https://github.com/cosmos/cosmos-sdk/blob/main/testutil/integration). ### Example @@ -107,13 +107,13 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/simulation/operations_te End-to-end tests are at the top of the [test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html). They must test the whole application flow, from the user perspective (for instance, CLI tests). They are located under [`/tests/e2e`](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e). - +{/* @julienrbrt: makes more sense to use an app wired app to have 0 simapp dependencies */} For that, the SDK is using `simapp` but you should use your own application (`appd`). Here are some examples: -* SDK E2E tests: . -* Cosmos Hub E2E tests: . -* Osmosis E2E tests: . +* SDK E2E tests: [https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e). +* Cosmos Hub E2E tests: [https://github.com/cosmos/gaia/tree/main/tests/e2e](https://github.com/cosmos/gaia/tree/main/tests/e2e). +* Osmosis E2E tests: [https://github.com/osmosis-labs/osmosis/tree/main/tests/e2e](https://github.com/osmosis-labs/osmosis/tree/main/tests/e2e). **warning** diff --git a/docs/sdk/v0.53/tutorials.mdx b/docs/sdk/v0.53/tutorials.mdx index 2474f604..46ccc281 100644 --- a/docs/sdk/v0.53/tutorials.mdx +++ b/docs/sdk/v0.53/tutorials.mdx @@ -1,12 +1,29 @@ --- -title: "Tutorials" -description: "Version: v0.53" +title: Tutorials --- -## Advanced Tutorials[​](#advanced-tutorials "Direct link to Advanced Tutorials") +# Cosmos SDK Tutorials -This section provides a concise overview of tutorials focused on implementing vote extensions in the Cosmos SDK. Vote extensions are a powerful feature for enhancing the security and fairness of blockchain applications, particularly in scenarios like implementing oracles and mitigating auction front-running. +The tutorials for Cosmos SDK are maintained in a single location and apply across all SDK versions. These hands-on guides will help you master key concepts and advanced features through practical examples. -* **Implementing Oracle with Vote Extensions** - This tutorial details how to use vote extensions for the implementation of a secure and reliable oracle within a blockchain application. It demonstrates the use of vote extensions to securely include oracle data submissions in blocks, ensuring the data's integrity and reliability for the blockchain. +## Available Tutorials -* **Mitigating Auction Front-Running with Vote Extensions** - Explore how to prevent auction front-running using vote extensions. This tutorial outlines the creation of a module aimed at mitigating front-running in nameservice auctions, emphasising the `ExtendVote`, `PrepareProposal`, and `ProcessProposal` functions to facilitate a fair auction process. +### Transaction Building +- **[Building a Transaction](../next/tutorials/transactions/building-a-transaction.mdx)** - Learn to construct, sign, and broadcast transactions + +### Vote Extensions +Advanced consensus features for building sophisticated applications: + +#### Oracle Implementation +- **[What is an Oracle?](../next/tutorials/vote-extensions/oracle/what-is-an-oracle.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/oracle/getting-started.mdx)** +- **[Implementing Vote Extensions](../next/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx)** +- **[Testing Oracle](../next/tutorials/vote-extensions/oracle/testing-oracle.mdx)** + +#### Mitigating Front-Running +- **[Understanding Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/understanding-frontrunning.mdx)** +- **[Getting Started](../next/tutorials/vote-extensions/auction-frontrunning/getting-started.mdx)** +- **[Mitigating Front-Running with Vote Extensions](../next/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx)** +- **[Demo of Mitigating Front-Running](../next/tutorials/vote-extensions/auction-frontrunning/demo-of-mitigating-front-running.mdx)** + +Visit the [full tutorials section](../next/tutorials/tutorials.mdx) for detailed guides and learning paths. \ No newline at end of file diff --git a/docs/sdk/v0.53/tutorials/transactions/building-a-transaction.mdx b/docs/sdk/v0.53/tutorials/transactions/building-a-transaction.mdx deleted file mode 100644 index 7dbe51c7..00000000 --- a/docs/sdk/v0.53/tutorials/transactions/building-a-transaction.mdx +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: "Building a Transaction" -description: "Version: v0.53" ---- - -These are the steps to build, sign and broadcast a transaction using v2 semantics. - -1. Correctly set up imports - -``` -import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" apisigning "cosmossdk.io/api/cosmos/tx/signing/v1beta1" "cosmossdk.io/client/v2/broadcast/comet" "cosmossdk.io/client/v2/tx" "cosmossdk.io/core/transaction" "cosmossdk.io/math" banktypes "cosmossdk.io/x/bank/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/codec" addrcodec "github.com/cosmos/cosmos-sdk/codec/address" sdk "github.com/cosmos/cosmos-sdk/types") -``` - -2. Create a gRPC connection - -``` -clientConn, err := grpc.NewClient("127.0.0.1:9090", grpc.WithTransportCredentials(insecure.NewCredentials()))if err != nil { log.Fatal(err)} -``` - -3. Setup codec and interface registry - -``` - // Setup interface registry and register necessary interfaces interfaceRegistry := codectypes.NewInterfaceRegistry() banktypes.RegisterInterfaces(interfaceRegistry) authtypes.RegisterInterfaces(interfaceRegistry) cryptocodec.RegisterInterfaces(interfaceRegistry) // Create a ProtoCodec for encoding/decoding protoCodec := codec.NewProtoCodec(interfaceRegistry) -``` - -4. Initialize keyring - -``` - ckr, err := keyring.New("autoclikeyring", "test", home, nil, protoCodec) if err != nil { log.Fatal("error creating keyring", err) } kr, err := keyring.NewAutoCLIKeyring(ckr, addrcodec.NewBech32Codec("cosmos")) if err != nil { log.Fatal("error creating auto cli keyring", err) } -``` - -5. Setup transaction parameters - -``` - // Setup transaction parameters txParams := tx.TxParameters{ ChainID: "simapp-v2-chain", SignMode: apisigning.SignMode_SIGN_MODE_DIRECT, AccountConfig: tx.AccountConfig{ FromAddress: "cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", FromName: "alice", }, } // Configure gas settings gasConfig, err := tx.NewGasConfig(100, 100, "0stake") if err != nil { log.Fatal("error creating gas config: ", err) } txParams.GasConfig = gasConfig // Create auth query client authClient := authtypes.NewQueryClient(clientConn) // Retrieve account information for the sender fromAccount, err := getAccount("cosmos1t0fmn0lyp2v99ga55mm37mpnqrlnc4xcs2hhhy", authClient, protoCodec) if err != nil { log.Fatal("error getting from account: ", err) } // Update txParams with the correct account number and sequence txParams.AccountConfig.AccountNumber = fromAccount.GetAccountNumber() txParams.AccountConfig.Sequence = fromAccount.GetSequence() // Retrieve account information for the recipient toAccount, err := getAccount("cosmos1e2wanzh89mlwct7cs7eumxf7mrh5m3ykpsh66m", authClient, protoCodec) if err != nil { log.Fatal("error getting to account: ", err) } // Configure transaction settings txConf, _ := tx.NewTxConfig(tx.ConfigOptions{ AddressCodec: addrcodec.NewBech32Codec("cosmos"), Cdc: protoCodec, ValidatorAddressCodec: addrcodec.NewBech32Codec("cosmosval"), EnabledSignModes: []apisigning.SignMode{apisigning.SignMode_SIGN_MODE_DIRECT}, }) -``` - -6. Build the transaction - -``` -// Create a transaction factory f, err := tx.NewFactory(kr, codec.NewProtoCodec(codectypes.NewInterfaceRegistry()), nil, txConf, addrcodec.NewBech32Codec("cosmos"), clientConn, txParams) if err != nil { log.Fatal("error creating factory", err) } // Define the transaction message msgs := []transaction.Msg{ &banktypes.MsgSend{ FromAddress: fromAccount.GetAddress().String(), ToAddress: toAccount.GetAddress().String(), Amount: sdk.Coins{ sdk.NewCoin("stake", math.NewInt(1000000)), }, }, } // Build and sign the transaction tx, err := f.BuildsSignedTx(context.Background(), msgs...) if err != nil { log.Fatal("error building signed tx", err) } -``` - -7. Broadcast the transaction - -``` -// Create a broadcaster for the transaction c, err := comet.NewCometBFTBroadcaster("http://127.0.0.1:26657", comet.BroadcastSync, protoCodec) if err != nil { log.Fatal("error creating comet broadcaster", err) } // Broadcast the transaction res, err := c.Broadcast(context.Background(), tx.Bytes()) if err != nil { log.Fatal("error broadcasting tx", err) } -``` - -8. Helpers - -``` -// getAccount retrieves account information using the provided addressfunc getAccount(address string, authClient authtypes.QueryClient, codec codec.Codec) (sdk.AccountI, error) { // Query account info accountQuery, err := authClient.Account(context.Background(), &authtypes.QueryAccountRequest{ Address: string(address), }) if err != nil { return nil, fmt.Errorf("error getting account: %w", err) } // Unpack the account information var account sdk.AccountI err = codec.InterfaceRegistry().UnpackAny(accountQuery.Account, &account) if err != nil { return nil, fmt.Errorf("error unpacking account: %w", err) } return account, nil} -``` diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx b/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx deleted file mode 100644 index f91c4c01..00000000 --- a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extensions.mdx +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Mitigating Front-running with Vote Extensions" -description: "Version: v0.53" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [Prerequisites](#prerequisites) -* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) -* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") - -Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. - -In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. - -### Implementing Structs for Vote Extensions[​](#implementing-structs-for-vote-extensions "Direct link to Implementing Structs for Vote Extensions") - -First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: - -``` -package abciimport ( //import the necessary files)type PrepareProposalHandler struct { logger log.Logger txConfig client.TxConfig cdc codec.Codec mempool *mempool.ThresholdMempool txProvider provider.TxProvider keyname string runProvider bool} -``` - -The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. - -``` -type ProcessProposalHandler struct { TxConfig client.TxConfig Codec codec.Codec Logger log.Logger} -``` - -After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 mempool *mempool.ThresholdMempool cdc codec.Codec} -``` - -This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. - -``` -type InjectedVoteExt struct { VoteExtSigner []byte Bids [][]byte}type InjectedVotes struct { Votes []InjectedVoteExt} -``` - -These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. - -``` -type AppVoteExtension struct { Height int64 Bids [][]byte} -``` - -This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. - -``` -type SpecialTransaction struct { Height int Bids [][]byte} -``` - -This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. - -### Implementing Handlers and Configuring Handlers[​](#implementing-handlers-and-configuring-handlers "Direct link to Implementing Handlers and Configuring Handlers") - -To establish the `VoteExtensionHandler`, follow these steps: - -1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. - -2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. - -``` -func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { return &VoteExtHandler{ logger: lg, mempool: mp, cdc: cdc, } } -``` - -3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) voteExtBids := [][]byte{} // Get mempool txs itr := h.mempool.SelectPending(context.Background(), nil) for itr != nil { tmptx := itr.Tx() sdkMsgs := tmptx.GetMsgs() // Iterate through msgs, check for any bids for _, msg := range sdkMsgs { switch msg := msg.(type) { case *nstypes.MsgBid: // Marshal sdk bids to []byte bz, err := h.cdc.Marshal(msg) if err != nil { h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) break } voteExtBids = append(voteExtBids, bz) default: } } // Move tx to ready pool err := h.mempool.Update(context.Background(), tmptx) // Remove tx from app side mempool if err != nil { h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) } itr = itr.Next() } // Create vote extension voteExt := AppVoteExtension{ Height: req.Height, Bids: voteExtBids, } // Encode Vote Extension bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("Error marshalling VE: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil} -``` - -4. Configure the handler in `app/app.go` as shown below - -``` -bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...)voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec)bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) -``` - -To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. - -To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: - -``` -if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } -``` - -This is how the whole function should look: - -``` -func (h *PrepareProposalHandler) PrepareProposalHandler() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) var proposalTxs [][]byte var txs []sdk.Tx // Get Vote Extensions if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } itr := h.mempool.Select(context.Background(), nil) for itr != nil { tmptx := itr.Tx() txs = append(txs, tmptx) itr = itr.Next() } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) if h.runProvider { tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) if err != nil { h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) } txs = tmpMsgs } for _, sdkTxs := range txs { txBytes, err := h.txConfig.TxEncoder()(sdkTxs) if err != nil { h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) } proposalTxs = append(proposalTxs, txBytes) } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) return &abci.ResponsePrepareProposal{Txs: proposalTxs}, nil }} -``` - -As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. - -5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. - -``` -func (h *ProcessProposalHandler) ProcessProposalHandler() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) // The first transaction will always be the Special Transaction numTxs := len(req.Txs) h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) if numTxs >= 1 { var st SpecialTransaction err = json.Unmarshal(req.Txs[0], &st) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) } if len(st.Bids) > 0 { h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) var bids []nstypes.MsgBid for i, b := range st.Bids { var bid nstypes.MsgBid h.Codec.Unmarshal(b, &bid) h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) bids = append(bids, bid) } // Validate Bids in Tx txs := req.Txs[1:] ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if !ok { h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. - -``` -func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) // Create empty response st := SpecialTransaction{ 0, [][]byte{}, } // Get Vote Ext for H-1 from Req voteExt := req.GetLocalLastCommit() votes := voteExt.Votes // Iterate through votes var ve AppVoteExtension for _, vote := range votes { // Unmarshal to AppExt err := json.Unmarshal(vote.VoteExtension, &ve) if err != nil { log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) } st.Height = int(ve.Height) // If Bids in VE, append to Special Transaction if len(ve.Bids) > 0 { log.Info("🛠️ :: Bids in VE") for _, b := range ve.Bids { st.Bids = append(st.Bids, b) } } } return st, nil} -``` - -7. Configure the `ProcessProposalHandler()` in app/app.go: - -``` -processPropHandler := abci2.ProcessProposalHandler{app.txConfig, appCodec, logger}bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) -``` - -This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. - -To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx b/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx deleted file mode 100644 index f91c4c01..00000000 --- a/docs/sdk/v0.53/tutorials/vote-extensions/auction-frontrunning/mitigating-front-running-with-vote-extesions.mdx +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Mitigating Front-running with Vote Extensions" -description: "Version: v0.53" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [Prerequisites](#prerequisites) -* [Implementing Structs for Vote Extensions](#implementing-structs-for-vote-extensions) -* [Implementing Handlers and Configuring Handlers](#implementing-handlers-and-configuring-handlers) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") - -Before implementing vote extensions to mitigate front-running, ensure you have a module ready to implement the vote extensions with. If you need to create or reference a similar module, see `x/auction` for guidance. - -In this section, we will discuss the steps to mitigate front-running using vote extensions. We will introduce new types within the `abci/types.go` file. These types will be used to handle the process of preparing proposals, processing proposals, and handling vote extensions. - -### Implementing Structs for Vote Extensions[​](#implementing-structs-for-vote-extensions "Direct link to Implementing Structs for Vote Extensions") - -First, copy the following structs into the `abci/types.go` and each of these structs serves a specific purpose in the process of mitigating front-running using vote extensions: - -``` -package abciimport ( //import the necessary files)type PrepareProposalHandler struct { logger log.Logger txConfig client.TxConfig cdc codec.Codec mempool *mempool.ThresholdMempool txProvider provider.TxProvider keyname string runProvider bool} -``` - -The `PrepareProposalHandler` struct is used to handle the preparation of a proposal in the consensus process. It contains several fields: logger for logging information and errors, txConfig for transaction configuration, cdc (Codec) for encoding and decoding transactions, mempool for referencing the set of unconfirmed transactions, txProvider for building the proposal with transactions, keyname for the name of the key used for signing transactions, and runProvider, a boolean flag indicating whether the provider should be run to build the proposal. - -``` -type ProcessProposalHandler struct { TxConfig client.TxConfig Codec codec.Codec Logger log.Logger} -``` - -After the proposal has been prepared and vote extensions have been included, the `ProcessProposalHandler` is used to process the proposal. This includes validating the proposal and the included vote extensions. The `ProcessProposalHandler` allows you to access the transaction configuration and codec, which are necessary for processing the vote extensions. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 mempool *mempool.ThresholdMempool cdc codec.Codec} -``` - -This struct is used to handle vote extensions. It contains a logger for logging events, the current block number, a mempool for storing transactions, and a codec for encoding and decoding. Vote extensions are a key part of the process to mitigate front-running, as they allow for additional information to be included with each vote. - -``` -type InjectedVoteExt struct { VoteExtSigner []byte Bids [][]byte}type InjectedVotes struct { Votes []InjectedVoteExt} -``` - -These structs are used to handle injected vote extensions. They include the signer of the vote extension and the bids associated with the vote extension. Each byte array in Bids is a serialised form of a bid transaction. Injected vote extensions are used to add additional information to a vote after it has been created, which can be useful for adding context or additional data to a vote. The serialised bid transactions provide a way to include complex transaction data in a compact, efficient format. - -``` -type AppVoteExtension struct { Height int64 Bids [][]byte} -``` - -This struct is used for application vote extensions. It includes the height of the block and the bids associated with the vote extension. Application vote extensions are used to add additional information to a vote at the application level, which can be useful for adding context or additional data to a vote that is specific to the application. - -``` -type SpecialTransaction struct { Height int Bids [][]byte} -``` - -This struct is used for special transactions. It includes the height of the block and the bids associated with the transaction. Special transactions are used for transactions that need to be handled differently from regular transactions, such as transactions that are part of the process to mitigate front-running. - -### Implementing Handlers and Configuring Handlers[​](#implementing-handlers-and-configuring-handlers "Direct link to Implementing Handlers and Configuring Handlers") - -To establish the `VoteExtensionHandler`, follow these steps: - -1. Navigate to the `abci/proposal.go` file. This is where we will implement the \`VoteExtensionHandler\`\`. - -2. Implement the `NewVoteExtensionHandler` function. This function is a constructor for the `VoteExtHandler` struct. It takes a logger, a mempool, and a codec as parameters and returns a new instance of `VoteExtHandler`. - -``` -func NewVoteExtensionHandler(lg log.Logger, mp *mempool.ThresholdMempool, cdc codec.Codec) *VoteExtHandler { return &VoteExtHandler{ logger: lg, mempool: mp, cdc: cdc, } } -``` - -3. Implement the `ExtendVoteHandler()` method. This method should handle the logic of extending votes, including inspecting the mempool and submitting a list of all pending bids. This will allow you to access the list of unconfirmed transactions in the abci.`RequestPrepareProposal` during the ensuing block. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { h.logger.Info(fmt.Sprintf("Extending votes at block height : %v", req.Height)) voteExtBids := [][]byte{} // Get mempool txs itr := h.mempool.SelectPending(context.Background(), nil) for itr != nil { tmptx := itr.Tx() sdkMsgs := tmptx.GetMsgs() // Iterate through msgs, check for any bids for _, msg := range sdkMsgs { switch msg := msg.(type) { case *nstypes.MsgBid: // Marshal sdk bids to []byte bz, err := h.cdc.Marshal(msg) if err != nil { h.logger.Error(fmt.Sprintf("Error marshalling VE Bid : %v", err)) break } voteExtBids = append(voteExtBids, bz) default: } } // Move tx to ready pool err := h.mempool.Update(context.Background(), tmptx) // Remove tx from app side mempool if err != nil { h.logger.Info(fmt.Sprintf("Unable to update mempool tx: %v", err)) } itr = itr.Next() } // Create vote extension voteExt := AppVoteExtension{ Height: req.Height, Bids: voteExtBids, } // Encode Vote Extension bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("Error marshalling VE: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil} -``` - -4. Configure the handler in `app/app.go` as shown below - -``` -bApp := baseapp.NewBaseApp(AppName, logger, db, txConfig.TxDecoder(), baseAppOptions...)voteExtHandler := abci2.NewVoteExtensionHandler(logger, mempool, appCodec)bApp.SetExtendVoteHandler(voteExtHandler.ExtendVoteHandler()) -``` - -To give a bit of context on what is happening above, we first create a new instance of `VoteExtensionHandler` with the necessary dependencies (logger, mempool, and codec). Then, we set this handler as the `ExtendVoteHandler` for our application. This means that whenever a vote needs to be extended, our custom `ExtendVoteHandler()` method will be called. - -To test if vote extensions have been propagated, add the following to the `PrepareProposalHandler`: - -``` -if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } -``` - -This is how the whole function should look: - -``` -func (h *PrepareProposalHandler) PrepareProposalHandler() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { h.logger.Info(fmt.Sprintf("🛠️ :: Prepare Proposal")) var proposalTxs [][]byte var txs []sdk.Tx // Get Vote Extensions if req.Height > 2 { voteExt := req.GetLocalLastCommit() h.logger.Info(fmt.Sprintf("🛠️ :: Get vote extensions: %v", voteExt)) } itr := h.mempool.Select(context.Background(), nil) for itr != nil { tmptx := itr.Tx() txs = append(txs, tmptx) itr = itr.Next() } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions available from mempool: %v", len(txs))) if h.runProvider { tmpMsgs, err := h.txProvider.BuildProposal(ctx, txs) if err != nil { h.logger.Error(fmt.Sprintf("❌️ :: Error Building Custom Proposal: %v", err)) } txs = tmpMsgs } for _, sdkTxs := range txs { txBytes, err := h.txConfig.TxEncoder()(sdkTxs) if err != nil { h.logger.Info(fmt.Sprintf("❌~Error encoding transaction: %v", err.Error())) } proposalTxs = append(proposalTxs, txBytes) } h.logger.Info(fmt.Sprintf("🛠️ :: Number of Transactions in proposal: %v", len(proposalTxs))) return &abci.ResponsePrepareProposal{Txs: proposalTxs}, nil }} -``` - -As mentioned above, we check if vote extensions have been propagated, you can do this by checking the logs for any relevant messages such as `🛠️ :: Get vote extensions:`. If the logs do not provide enough information, you can also reinitialise your local testing environment by running the `./scripts/single_node/setup.sh` script again. - -5. Implement the `ProcessProposalHandler()`. This function is responsible for processing the proposal. It should handle the logic of processing vote extensions, including inspecting the proposal and validating the bids. - -``` -func (h *ProcessProposalHandler) ProcessProposalHandler() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (resp *abci.ResponseProcessProposal, err error) { h.Logger.Info(fmt.Sprintf("⚙️ :: Process Proposal")) // The first transaction will always be the Special Transaction numTxs := len(req.Txs) h.Logger.Info(fmt.Sprintf("⚙️:: Number of transactions :: %v", numTxs)) if numTxs >= 1 { var st SpecialTransaction err = json.Unmarshal(req.Txs[0], &st) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error unmarshalling special Tx in Process Proposal :: %v", err)) } if len(st.Bids) > 0 { h.Logger.Info(fmt.Sprintf("⚙️:: There are bids in the Special Transaction")) var bids []nstypes.MsgBid for i, b := range st.Bids { var bid nstypes.MsgBid h.Codec.Unmarshal(b, &bid) h.Logger.Info(fmt.Sprintf("⚙️:: Special Transaction Bid No %v :: %v", i, bid)) bids = append(bids, bid) } // Validate Bids in Tx txs := req.Txs[1:] ok, err := ValidateBids(h.TxConfig, bids, txs, h.Logger) if err != nil { h.Logger.Error(fmt.Sprintf("❌️:: Error validating bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if !ok { h.Logger.Error(fmt.Sprintf("❌️:: Unable to validate bids in Process Proposal :: %v", err)) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } h.Logger.Info("⚙️:: Successfully validated bids in Process Proposal") } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -6. Implement the `ProcessVoteExtensions()` function. This function should handle the logic of processing vote extensions, including validating the bids. - -``` -func processVoteExtensions(req *abci.RequestPrepareProposal, log log.Logger) (SpecialTransaction, error) { log.Info(fmt.Sprintf("🛠️ :: Process Vote Extensions")) // Create empty response st := SpecialTransaction{ 0, [][]byte{}, } // Get Vote Ext for H-1 from Req voteExt := req.GetLocalLastCommit() votes := voteExt.Votes // Iterate through votes var ve AppVoteExtension for _, vote := range votes { // Unmarshal to AppExt err := json.Unmarshal(vote.VoteExtension, &ve) if err != nil { log.Error(fmt.Sprintf("❌ :: Error unmarshalling Vote Extension")) } st.Height = int(ve.Height) // If Bids in VE, append to Special Transaction if len(ve.Bids) > 0 { log.Info("🛠️ :: Bids in VE") for _, b := range ve.Bids { st.Bids = append(st.Bids, b) } } } return st, nil} -``` - -7. Configure the `ProcessProposalHandler()` in app/app.go: - -``` -processPropHandler := abci2.ProcessProposalHandler{app.txConfig, appCodec, logger}bApp.SetProcessProposal(processPropHandler.ProcessProposalHandler()) -``` - -This sets the `ProcessProposalHandler()` for our application. This means that whenever a proposal needs to be processed, our custom `ProcessProposalHandler()` method will be called. - -To test if the proposal processing and vote extensions are working correctly, you can check the logs for any relevant messages. If the logs do not provide enough information, you can also reinitialize your local testing environment by running `./scripts/single_node/setup.sh` script. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started.mdx b/docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started.mdx deleted file mode 100644 index a642f244..00000000 --- a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/getting-started.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: "Getting Started" -description: "Version: v0.53" ---- - -## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") - -* [What is an Oracle?](/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle) -* [Implementing Vote Extensions](/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions) -* [Testing the Oracle Module](/v0.53/tutorials/vote-extensions/oracle/testing-oracle) - -## Prerequisites[​](#prerequisites "Direct link to Prerequisites") - -Before you start with this tutorial, make sure you have: - -* A working chain project. This tutorial won't cover the steps of creating a new chain/module. -* Familiarity with the Cosmos SDK. If you're not, we suggest you start with [Cosmos SDK Tutorials](https://tutorials.cosmos.network), as ABCI++ is considered an advanced topic. -* Read and understood [What is an Oracle?](/v0.53/tutorials/vote-extensions/oracle/what-is-an-oracle). This provides necessary background information for understanding the Oracle module. -* Basic understanding of Go programming language. - -## What are Vote extensions?[​](#what-are-vote-extensions "Direct link to What are Vote extensions?") - -Vote extensions is arbitrary information which can be inserted into a block. This feature is part of ABCI 2.0, which is available for use in the SDK 0.50 release and part of the 0.38 CometBFT release. - -More information about vote extensions can be seen [here](https://docs.cosmos.network/main/build/abci/vote-extensions). - -## Overview of the project[​](#overview-of-the-project "Direct link to Overview of the project") - -We’ll go through the creation of a simple price oracle module focusing on the vote extensions implementation, ignoring the details inside the price oracle itself. - -We’ll go through the implementation of: - -* `ExtendVote` to get information from external price APIs. -* `VerifyVoteExtension` to check that the format of the provided votes is correct. -* `PrepareProposal` to process the vote extensions from the previous block and include them into the proposal as a transaction. -* `ProcessProposal` to check that the first transaction in the proposal is actually a “special tx” that contains the price information. -* `PreBlocker` to make price information available during FinalizeBlock. - -If you would like to see the complete working oracle module please see [here](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle) diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx b/docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx deleted file mode 100644 index 9d5232c2..00000000 --- a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/implementing-vote-extensions.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: "Implementing Vote Extensions" -description: "Version: v0.53" ---- - -## Implement ExtendVote[​](#implement-extendvote "Direct link to Implement ExtendVote") - -First we’ll create the `OracleVoteExtension` struct, this is the object that will be marshaled as bytes and signed by the validator. - -In our example we’ll use JSON to marshal the vote extension for simplicity but we recommend to find an encoding that produces a smaller output, given that large vote extensions could impact CometBFT’s performance. Custom encodings and compressed bytes can be used out of the box. - -``` -// OracleVoteExtension defines the canonical vote extension structure.type OracleVoteExtension struct { Height int64 Prices map[string]math.LegacyDec} -``` - -Then we’ll create a `VoteExtensionsHandler` struct that contains everything we need to query for prices. - -``` -type VoteExtHandler struct { logger log.Logger currentBlock int64 // current block height lastPriceSyncTS time.Time // last time we synced prices providerTimeout time.Duration // timeout for fetching prices from providers providers map[string]Provider // mapping of provider name to provider (e.g. Binance -> BinanceProvider) providerPairs map[string][]keeper.CurrencyPair // mapping of provider name to supported pairs (e.g. Binance -> [ATOM/USD]) Keeper keeper.Keeper // keeper of our oracle module} -``` - -Finally, a function that returns `sdk.ExtendVoteHandler` is needed too, and this is where our vote extension logic will live. - -``` -func (h *VoteExtHandler) ExtendVoteHandler() sdk.ExtendVoteHandler { return func(ctx sdk.Context, req *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) { // here we'd have a helper function that gets all the prices and does a weighted average using the volume of each market prices := h.getAllVolumeWeightedPrices() voteExt := OracleVoteExtension{ Height: req.Height, Prices: prices, } bz, err := json.Marshal(voteExt) if err != nil { return nil, fmt.Errorf("failed to marshal vote extension: %w", err) } return &abci.ResponseExtendVote{VoteExtension: bz}, nil }} -``` - -As you can see above, the creation of a vote extension is pretty simple and we just have to return bytes. CometBFT will handle the signing of these bytes for us. We ignored the process of getting the prices but you can see a more complete example [here:](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle/abci/vote_extensions.go) - -Here we’ll do some simple checks like: - -* Is the vote extension unmarshaled correctly? -* Is the vote extension for the right height? -* Some other validation, for example, are the prices from this extension too deviated from my own prices? Or maybe checks that can detect malicious behavior. - -``` -func (h *VoteExtHandler) VerifyVoteExtensionHandler() sdk.VerifyVoteExtensionHandler { return func(ctx sdk.Context, req *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) { var voteExt OracleVoteExtension err := json.Unmarshal(req.VoteExtension, &voteExt) if err != nil { return nil, fmt.Errorf("failed to unmarshal vote extension: %w", err) } if voteExt.Height != req.Height { return nil, fmt.Errorf("vote extension height does not match request height; expected: %d, got: %d", req.Height, voteExt.Height) } // Verify incoming prices from a validator are valid. Note, verification during // VerifyVoteExtensionHandler MUST be deterministic. For brevity and demo // purposes, we omit implementation. if err := h.verifyOraclePrices(ctx, voteExt.Prices); err != nil { return nil, fmt.Errorf("failed to verify oracle prices from validator %X: %w", req.ValidatorAddress, err) } return &abci.ResponseVerifyVoteExtension{Status: abci.ResponseVerifyVoteExtension_ACCEPT}, nil }} -``` - -## Implement PrepareProposal[​](#implement-prepareproposal "Direct link to Implement PrepareProposal") - -``` -type ProposalHandler struct { logger log.Logger keeper keeper.Keeper // our oracle module keeper valStore baseapp.ValidatorStore // to get the current validators' pubkeys} -``` - -And we create the struct for our “special tx”, that will contain the prices and the votes so validators can later re-check in ProcessPRoposal that they get the same result than the block’s proposer. With this we could also check if all the votes have been used by comparing the votes received in ProcessProposal. - -``` -type StakeWeightedPrices struct { StakeWeightedPrices map[string]math.LegacyDec ExtendedCommitInfo abci.ExtendedCommitInfo} -``` - -Now we create the `PrepareProposalHandler`. In this step we’ll first check if the vote extensions’ signatures are correct using a helper function called ValidateVoteExtensions from the baseapp package. - -``` -func (h *ProposalHandler) PrepareProposal() sdk.PrepareProposalHandler { return func(ctx sdk.Context, req *abci.RequestPrepareProposal) (*abci.ResponsePrepareProposal, error) { err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), req.LocalLastCommit) if err != nil { return nil, err }... -``` - -Then we proceed to make the calculations only if the current height if higher than the height at which vote extensions have been enabled. Remember that vote extensions are made available to the block proposer on the next block at which they are produced/enabled. - -``` -... proposalTxs := req.Txs if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, req.LocalLastCommit) if err != nil { return nil, errors.New("failed to compute stake-weighted oracle prices") } injectedVoteExtTx := StakeWeightedPrices{ StakeWeightedPrices: stakeWeightedPrices, ExtendedCommitInfo: req.LocalLastCommit, }... -``` - -Finally we inject the result as a transaction at a specific location, usually at the beginning of the block: - -## Implement ProcessProposal[​](#implement-processproposal "Direct link to Implement ProcessProposal") - -Now we can implement the method that all validators will execute to ensure the proposer is doing his work correctly. - -Here, if vote extensions are enabled, we’ll check if the tx at index 0 is an injected vote extension - -``` -func (h *ProposalHandler) ProcessProposal() sdk.ProcessProposalHandler { return func(ctx sdk.Context, req *abci.RequestProcessProposal) (*abci.ResponseProcessProposal, error) { if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { var injectedVoteExtTx StakeWeightedPrices if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { h.logger.Error("failed to decode injected vote extension tx", "err", err) return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil }... -``` - -Then we re-validate the vote extensions signatures using baseapp.ValidateVoteExtensions, re-calculate the results (just like in PrepareProposal) and compare them with the results we got from the injected tx. - -``` - err := baseapp.ValidateVoteExtensions(ctx, h.valStore, req.Height, ctx.ChainID(), injectedVoteExtTx.ExtendedCommitInfo) if err != nil { return nil, err } // Verify the proposer's stake-weighted oracle prices by computing the same // calculation and comparing the results. We omit verification for brevity // and demo purposes. stakeWeightedPrices, err := h.computeStakeWeightedOraclePrices(ctx, injectedVoteExtTx.ExtendedCommitInfo) if err != nil { return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } if err := compareOraclePrices(injectedVoteExtTx.StakeWeightedPrices, stakeWeightedPrices); err != nil { return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_REJECT}, nil } } return &abci.ResponseProcessProposal{Status: abci.ResponseProcessProposal_ACCEPT}, nil }} -``` - -Important: In this example we avoided using the mempool and other basics, please refer to the DefaultProposalHandler for a complete implementation: [https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/abci\_utils.go](https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/abci_utils.go) - -## Implement PreBlocker[​](#implement-preblocker "Direct link to Implement PreBlocker") - -Now validators are extending their vote, verifying other votes and including the result in the block. But how do we actually make use of this result? This is done in the PreBlocker which is code that is run before any other code during FinalizeBlock so we make sure we make this information available to the chain and its modules during the entire block execution (from BeginBlock). - -At this step we know that the injected tx is well-formatted and has been verified by the validators participating in consensus, so making use of it is straightforward. Just check if vote extensions are enabled, pick up the first transaction and use a method in your module’s keeper to set the result. - -``` -func (h *ProposalHandler) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { res := &sdk.ResponsePreBlock{} if len(req.Txs) == 0 { return res, nil } if req.Height > ctx.ConsensusParams().Abci.VoteExtensionsEnableHeight { var injectedVoteExtTx StakeWeightedPrices if err := json.Unmarshal(req.Txs[0], &injectedVoteExtTx); err != nil { h.logger.Error("failed to decode injected vote extension tx", "err", err) return nil, err } // set oracle prices using the passed in context, which will make these prices available in the current block if err := h.keeper.SetOraclePrices(ctx, injectedVoteExtTx.StakeWeightedPrices); err != nil { return nil, err } } return res, nil} -``` - -## Conclusion[​](#conclusion "Direct link to Conclusion") - -In this tutorial, we've created a simple price oracle module that incorporates vote extensions. We've seen how to implement `ExtendVote`, `VerifyVoteExtension`, `PrepareProposal`, `ProcessProposal`, and `PreBlocker` to handle the voting and verification process of vote extensions, as well as how to make use of the results during the block execution. diff --git a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle.mdx b/docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle.mdx deleted file mode 100644 index a956e96d..00000000 --- a/docs/sdk/v0.53/tutorials/vote-extensions/oracle/testing-oracle.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Testing the Oracle Module" -description: "Version: v0.53" ---- - -We will guide you through the process of testing the Oracle module in your application. The Oracle module uses vote extensions to provide current price data. If you would like to see the complete working oracle module please see [here](https://github.com/cosmos/sdk-tutorials/blob/master/tutorials/oracle/base/x/oracle). - -## Step 1: Compile and Install the Application[​](#step-1-compile-and-install-the-application "Direct link to Step 1: Compile and Install the Application") - -First, we need to compile and install the application. Please ensure you are in the `tutorials/oracle/base` directory. Run the following command in your terminal: - -``` -make install -``` - -This command compiles the application and moves the resulting binary to a location in your system's PATH. - -## Step 2: Initialise the Application[​](#step-2-initialise-the-application "Direct link to Step 2: Initialise the Application") - -Next, we need to initialise the application. Run the following command in your terminal: - -``` -make init -``` - -This command runs the script `tutorials/oracle/base/scripts/init.sh`, which sets up the necessary configuration for your application to run. This includes creating the `app.toml` configuration file and initialising the blockchain with a genesis block. - -## Step 3: Start the Application[​](#step-3-start-the-application "Direct link to Step 3: Start the Application") - -Now, we can start the application. Run the following command in your terminal: - -``` -exampled start -``` - -This command starts your application, begins the blockchain node, and starts processing transactions. - -## Step 4: Query the Oracle Prices[​](#step-4-query-the-oracle-prices "Direct link to Step 4: Query the Oracle Prices") - -Finally, we can query the current prices from the Oracle module. Run the following command in your terminal: - -``` -exampled q oracle prices -``` - -This command queries the current prices from the Oracle module. The expected output shows that the vote extensions were successfully included in the block and the Oracle module was able to retrieve the price data. - -## Understanding Vote Extensions in Oracle[​](#understanding-vote-extensions-in-oracle "Direct link to Understanding Vote Extensions in Oracle") - -In the Oracle module, the `ExtendVoteHandler` function is responsible for creating the vote extensions. This function fetches the current prices from the provider, creates a `OracleVoteExtension` struct with these prices, and then marshals this struct into bytes. These bytes are then set as the vote extension. - -In the context of testing, the Oracle module uses a mock provider to simulate the behavior of a real price provider. This mock provider is defined in the mockprovider package and is used to return predefined prices for specific currency pairs. - -## Conclusion[​](#conclusion "Direct link to Conclusion") - -In this tutorial, we've delved into the concept of Oracle's in blockchain technology, focusing on their role in providing external data to a blockchain network. We've explored vote extensions, a powerful feature of ABCI++, and integrated them into a Cosmos SDK application to create a price oracle module. - -Through hands-on exercises, you've implemented vote extensions, and tested their effectiveness in providing timely and accurate asset price information. You've gained practical insights by setting up a mock provider for testing and analysing the process of extending votes, verifying vote extensions, and preparing and processing proposals. - -Keep experimenting with these concepts, engage with the community, and stay updated on new advancements. The knowledge you've acquired here is crucial for developing robust and reliable blockchain applications that can interact with real-world data. diff --git a/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx index 670ef637..e8523c91 100644 --- a/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx +++ b/docs/sdk/v0.53/upgrades-migrations/module-upgrade.mdx @@ -35,13 +35,13 @@ You can register one or more migrations. If you register more than one migration ```go func (am AppModule) RegisterServices(cfg module.Configurator) { - // --snip-- - cfg.RegisterMigration(types.ModuleName, 1, func(ctx sdk.Context) error { - // Perform in-place store migrations from ConsensusVersion 1 to 2. - }) - cfg.RegisterMigration(types.ModuleName, 2, func(ctx sdk.Context) error { - // Perform in-place store migrations from ConsensusVersion 2 to 3. - }) + // --snip-- + cfg.RegisterMigration(types.ModuleName, 1, func(ctx sdk.Context) error { + // Perform in-place store migrations from ConsensusVersion 1 to 2. + }) + cfg.RegisterMigration(types.ModuleName, 2, func(ctx sdk.Context) error { + // Perform in-place store migrations from ConsensusVersion 2 to 3. + }) } ``` diff --git a/docs/sdk/v0.53/user.mdx.bak b/docs/sdk/v0.53/user.mdx.bak deleted file mode 100644 index 02faae65..00000000 --- a/docs/sdk/v0.53/user.mdx.bak +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: "User Guides" -description: "Version: v0.53" ---- - -This section is designed for developers who are using the Cosmos SDK to build applications. It provides essential guides and references to effectively use the SDK's features. - -* [Setting up keys](/v0.53/user/run-node/keyring) - Learn how to set up secure key management using the Cosmos SDK's keyring feature. This guide provides a streamlined approach to cryptographic key handling, which is crucial for securing your application. -* [Running a node](/v0.53/user/run-node/run-node) - This guide provides step-by-step instructions to deploy and manage a node in the Cosmos network. It ensures a smooth and reliable operation of your blockchain application by covering all the necessary setup and maintenance steps. -* [CLI](/v0.53/user/run-node/interact-node) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. diff --git a/scripts/MIGRATION_README.md b/scripts/MIGRATION_README.md new file mode 100644 index 00000000..b0263cd3 --- /dev/null +++ b/scripts/MIGRATION_README.md @@ -0,0 +1,169 @@ +# Docusaurus to Mintlify Migration Scripts + +Convert Docusaurus documentation to Mintlify format with proper MDX syntax, code formatting, and navigation structure. + +## Scripts + +### `migrate-docusaurus.js` +Full repository migration with versioning support and navigation updates. + +**Usage:** +```bash +# Interactive mode +node migrate-docusaurus.js + +# Non-interactive mode +node migrate-docusaurus.js [--target ] [--update-nav] + +# Example +node migrate-docusaurus.js /path/to/cosmos-sdk-docs sdk --target ./tmp +``` + +**Features:** +- Migrates all versioned documentation (`versioned_docs/version-*`) +- Preserves `sidebar_position` for navigation ordering +- Updates `docs.json` navigation (when `--update-nav` flag is used) +- AST-based processing for accuracy + +### `migrate-single-file.js` +Convert individual Docusaurus markdown files to Mintlify MDX. + +**Usage:** +```bash +node migrate-single-file.js + +# Example +node migrate-single-file.js ../cosmos-sdk-docs/docs/learn/events.md ../tmp/events.mdx +``` + +## Conversion Pipeline + +### Multi-Pass Processing (Sequential) + +1. **Fix Malformed Code Blocks** + - Remove whitespace before backticks + - Close unclosed code blocks + - Normalize code block structure + +2. **Handle Reference Syntax** + - Convert Docusaurus ````lang reference\nURL\n```' blocks + - Preserve URLs as comments in code blocks + - Maintain language specification + +3. **Enhance Code Blocks** + - Add `expandable` property for blocks >10 lines + - Auto-detect language from content + - Format code based on language + +4. **Fix Inline Code & Brackets** + - Wrap `{value}` patterns in backticks + - Handle `interface{}` and similar Go patterns + - Fix curly brackets in tables + +5. **Convert HTML Elements** + - Convert HTML comments `` to JSX `{/* */}` + - Replace `
` with `` + - Fix command placeholders (`` → `` `appd` ``) + - Handle comparison operators (`<=>` → `` `<=>` ``) + +## Conversions Applied + +### Admonitions +```markdown +# Docusaurus +:::note Title +Content +::: + +# Mintlify + +**Title** +Content + +``` + +### Code Blocks +- Removes "reference" keyword from language specification +- Adds `expandable` for blocks >10 lines +- Auto-detects language (Go, JavaScript, Python, JSON, etc.) +- Preserves reference URLs as comments + +### Links & Paths +- Fixes relative paths (`../file.md` → `/file.md`) +- Updates versioned links for products +- Maintains external links unchanged + +### MDX Compatibility +- HTML comments → JSX comments +- `
` → `` +- Problematic angle brackets wrapped in backticks +- Template variables `{foo}` wrapped in backticks + +### Frontmatter +- Preserves `sidebar_position` for navigation ordering +- Extracts title from content if not in frontmatter +- Generates clean Mintlify-compatible frontmatter +- Removes Docusaurus-specific fields + +## File Structure + +**Input (Docusaurus):** +``` +cosmos-sdk-docs/ +├── docs/ # Current/next version +├── versioned_docs/ +│ ├── version-0.47/ +│ ├── version-0.50/ +│ └── version-0.53/ +``` + +**Output (Mintlify):** +``` +docs/ +└── sdk/ + ├── next/ + ├── v0.47/ + ├── v0.50/ + └── v0.53/ +``` + +## Navigation + +When using `--update-nav`, the script updates `docs.json` with: +- Proper dropdown structure for products +- Version-specific navigation tabs +- Files sorted by `sidebar_position` +- Conflict resolution for duplicate positions + +## Edge Cases Handled + +- Code blocks with indented backticks +- Unclosed HTML comments +- Reference syntax with GitHub URLs +- Command placeholders in documentation +- Comparison operators and arrows +- Mixed content in admonitions +- Tables with curly brackets +- Go-specific patterns (`interface{}`, `map[string]interface{}`) + +## Dependencies + +```json +{ + "dependencies": { + "gray-matter": "^4.0.3", + "unified": "^11.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unist-util-visit": "^5.0.0" + } +} +``` + +## Notes + +- Code content is preserved exactly - no arbitrary removal +- Reference URLs are converted to comments, not deleted +- AST processing used where possible, regex as fallback +- Multiple passes ensure proper sequencing of fixes +- Code blocks are processed first to prevent syntax breaking \ No newline at end of file diff --git a/scripts/code-formatter.js b/scripts/code-formatter.js new file mode 100644 index 00000000..791c9106 --- /dev/null +++ b/scripts/code-formatter.js @@ -0,0 +1,250 @@ +#!/usr/bin/env node + +import fs from 'fs'; +import path from 'path'; +import { execSync } from 'child_process'; + +/** + * Perfect code formatting using native language tools + */ +class PerfectCodeFormatter { + constructor() { + this.tempDir = './tmp-code-formatting'; + this.ensureTempDir(); + } + + ensureTempDir() { + if (!fs.existsSync(this.tempDir)) { + fs.mkdirSync(this.tempDir, { recursive: true }); + } + } + + /** + * Format Go code using gofmt + */ + async formatGoCode(code) { + const tempFile = path.join(this.tempDir, `temp-${Date.now()}.go`); + + try { + // Create a valid Go file structure + const goFile = `package main\n\n${code}`; + fs.writeFileSync(tempFile, goFile); + + // Run gofmt + const formatted = execSync(`gofmt "${tempFile}"`, { encoding: 'utf8' }); + + // Remove the package declaration we added + const result = formatted.replace(/^package main\n\n/, '').trim(); + + fs.unlinkSync(tempFile); + return result; + } catch (error) { + // If gofmt fails, try basic cleanup + console.warn(`Go formatting failed for code block, using fallback`); + if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile); + return this.fallbackGoFormat(code); + } + } + + /** + * Format JavaScript/TypeScript using prettier (if available) + */ + async formatJavaScriptCode(code) { + const tempFile = path.join(this.tempDir, `temp-${Date.now()}.js`); + + try { + fs.writeFileSync(tempFile, code); + + // Try prettier if available + const formatted = execSync(`npx prettier --stdin-filepath="${tempFile}" < "${tempFile}"`, { encoding: 'utf8' }); + + fs.unlinkSync(tempFile); + return formatted.trim(); + } catch (error) { + console.warn(`JavaScript formatting failed, using fallback`); + if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile); + return this.fallbackJSFormat(code); + } + } + + /** + * Format JSON using native JSON.parse/stringify + */ + formatJsonCode(code) { + try { + const parsed = JSON.parse(code); + return JSON.stringify(parsed, null, 2); + } catch (error) { + console.warn(`JSON parsing failed, using fallback`); + return this.fallbackJsonFormat(code); + } + } + + /** + * Fallback Go formatting + */ + fallbackGoFormat(code) { + return code + .replace(/import\s*\(/g, 'import (\n\t') + .replace(/"\s*"/g, '"\n\t"') + .replace(/\)\s*\n\s*([a-zA-Z])/g, ')\n\n$1') + .replace(/\{\s*([a-zA-Z])/g, '{\n\t$1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + .replace(/\n{3,}/g, '\n\n') + .trim(); + } + + /** + * Fallback JavaScript formatting + */ + fallbackJSFormat(code) { + return code + .replace(/import\s*\{([^}]+)\}\s*from/g, (match, imports) => { + const cleanImports = imports.split(',').map(imp => imp.trim()).join(',\n '); + return `import {\n ${cleanImports}\n} from`; + }) + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + .replace(/\n{3,}/g, '\n\n') + .trim(); + } + + /** + * Fallback JSON formatting + */ + fallbackJsonFormat(code) { + return code + .replace(/\{\s*"/g, '{\n "') + .replace(/",\s*"/g, '",\n "') + .replace(/\}\s*,/g, '\n},') + .replace(/\n{3,}/g, '\n\n') + .trim(); + } + + /** + * Format code block content based on language + */ + async formatCodeBlock(language, code) { + const lang = language.toLowerCase(); + + switch (lang) { + case 'go': + case 'golang': + return await this.formatGoCode(code); + case 'javascript': + case 'js': + case 'typescript': + case 'ts': + return await this.formatJavaScriptCode(code); + case 'json': + case 'jsonc': + return this.formatJsonCode(code); + default: + // For other languages, just clean up basic structure + return code + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + .replace(/\n{3,}/g, '\n\n') + .trim(); + } + } + + /** + * Process all code blocks in content + */ + async formatAllCodeBlocks(content) { + const codeBlockRegex = /```(\w+)([^\n]*)\n([\s\S]*?)\n```/g; + let result = content; + const matches = [...content.matchAll(codeBlockRegex)]; + + for (const match of matches) { + const [fullMatch, language, params, code] = match; + console.log(` Formatting ${language} code block (${code.length} chars)`); + + const formattedCode = await this.formatCodeBlock(language, code); + const formattedBlock = '```' + language + params + '\n' + formattedCode + '\n```'; + + result = result.replace(fullMatch, formattedBlock); + } + + return result; + } + + cleanup() { + if (fs.existsSync(this.tempDir)) { + fs.rmSync(this.tempDir, { recursive: true, force: true }); + } + } +} + +/** + * Perfect bulk formatting using native tools + */ +async function perfectBulkFormat() { + console.log('=== Perfect Code Block Formatting ==='); + console.log('Using native language formatters for perfect results\n'); + + const formatter = new PerfectCodeFormatter(); + const docsPath = './docs/sdk'; + + let filesProcessed = 0; + let blocksFormatted = 0; + + // Find all MDX files + const mdxFiles = []; + function findMDXFiles(dir) { + const items = fs.readdirSync(dir); + for (const item of items) { + const fullPath = path.join(dir, item); + if (fs.statSync(fullPath).isDirectory()) { + findMDXFiles(fullPath); + } else if (item.endsWith('.mdx')) { + mdxFiles.push(fullPath); + } + } + } + + findMDXFiles(docsPath); + console.log(`Found ${mdxFiles.length} MDX files`); + + // Process files + for (let i = 0; i < mdxFiles.length; i++) { + const filePath = mdxFiles[i]; + const content = fs.readFileSync(filePath, 'utf8'); + + // Check if file has code blocks that might need formatting + const codeBlockCount = (content.match(/```/g) || []).length / 2; + + if (codeBlockCount > 0) { + console.log(`📁 ${path.relative(process.cwd(), filePath)} (${codeBlockCount} blocks)`); + + const formattedContent = await formatter.formatAllCodeBlocks(content); + + if (formattedContent !== content) { + fs.writeFileSync(filePath, formattedContent); + filesProcessed++; + blocksFormatted += codeBlockCount; + console.log(` ✅ Updated with perfect formatting`); + } else { + console.log(` ✓ Already well-formatted`); + } + } + + // Progress indicator + if ((i + 1) % 100 === 0) { + console.log(` Progress: ${i + 1}/${mdxFiles.length} files checked`); + } + } + + formatter.cleanup(); + + console.log('\n=== PERFECT FORMATTING COMPLETE ==='); + console.log(`📊 Files processed: ${filesProcessed}`); + console.log(`🎯 Code blocks formatted: ${blocksFormatted}`); + console.log('✅ All code now formatted with native language tools!'); +} + +// Run if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + perfectBulkFormat().catch(console.error); +} \ No newline at end of file diff --git a/scripts/convert-docusaurus-to-mintlify.js b/scripts/convert-docusaurus-to-mintlify.js deleted file mode 100755 index 5231752a..00000000 --- a/scripts/convert-docusaurus-to-mintlify.js +++ /dev/null @@ -1,405 +0,0 @@ -#!/usr/bin/env node - -import fs from 'fs'; -import path from 'path'; -import { fileURLToPath } from 'url'; -import readline from 'readline'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -// Create readline interface for prompts -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -const prompt = (question) => new Promise((resolve) => rl.question(question, resolve)); - -/** - * Parse Docusaurus frontmatter - */ -function parseDocusaurusFrontmatter(content) { - const lines = content.split('\n'); - const frontmatter = {}; - let contentStart = 0; - - if (lines[0] === '---') { - for (let i = 1; i < lines.length; i++) { - if (lines[i] === '---') { - contentStart = i + 1; - break; - } - const match = lines[i].match(/^(\w+):\s*(.*)$/); - if (match) { - const key = match[1]; - let value = match[2]; - // Remove quotes if present - value = value.replace(/^["']|["']$/g, ''); - frontmatter[key] = value; - } - } - } - - return { - frontmatter, - content: lines.slice(contentStart).join('\n') - }; -} - -/** - * Extract title from content (first H1 heading) - */ -function extractTitleFromContent(content) { - const match = content.match(/^#\s+(.+)$/m); - if (match) { - return { - title: match[1].trim(), - content: content.replace(match[0], '').trim() - }; - } - return { title: null, content }; -} - -/** - * Generate description from content - */ -function generateDescription(content, version = 'v0.53') { - // Remove markdown formatting - let plainText = content - .replace(/^#+\s+.*$/gm, '') // Remove headings - .replace(/```[\s\S]*?```/g, '') // Remove code blocks - .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Convert links to text - .replace(/[*_`]/g, '') // Remove formatting - .trim(); - - // Find first non-empty paragraph - const paragraphs = plainText.split(/\n\n+/); - for (const para of paragraphs) { - const cleaned = para.trim(); - if (cleaned && cleaned.length > 20) { - return cleaned.length > 150 ? cleaned.substring(0, 147) + '...' : cleaned; - } - } - - return `Cosmos SDK ${version} Documentation`; -} - -/** - * Convert Docusaurus admonitions to Mintlify callouts - */ -function convertAdmonitions(content) { - const admonitionMap = { - 'note': 'Note', - 'tip': 'Tip', - 'info': 'Info', - 'warning': 'Warning', - 'danger': 'Warning', - 'caution': 'Warning', - 'important': 'Info', - 'success': 'Check' - }; - - let result = content; - - // Match multiline admonitions - const admonitionRegex = /:::(note|tip|info|warning|danger|caution|important|success)(?:\s+(.+?))?\n([\s\S]*?)\n:::/gi; - - result = result.replace(admonitionRegex, (match, type, title, content) => { - const component = admonitionMap[type.toLowerCase()] || 'Note'; - const titleLine = title ? `**${title}**\n` : ''; - return `<${component}>\n${titleLine}${content.trim()}\n`; - }); - - // Also handle single-line admonitions - const singleLineRegex = /:::(note|tip|info|warning|danger|caution|important|success)\s+(.+?)\s*:::/gi; - - result = result.replace(singleLineRegex, (match, type, content) => { - const component = admonitionMap[type.toLowerCase()] || 'Note'; - return `<${component}>${content.trim()}`; - }); - - return result; -} - -/** - * Convert code blocks to Mintlify format with expandable for long blocks - */ -function convertCodeBlocks(content) { - const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g; - - return content.replace(codeBlockRegex, (match, lang, code) => { - const lines = code.split('\n'); - const lineCount = lines.length; - - // If more than 10 lines, make it expandable - if (lineCount > 10) { - // Get first few lines for preview - const preview = lines.slice(0, 3).join('\n'); - const title = lang ? `${lang} code` : 'Code'; - - return ` -\`\`\`${lang} -${code}\`\`\` -`; - } - - // Otherwise keep as regular code block - return match; - }); -} - -/** - * Fix internal documentation links - */ -function fixInternalLinks(content, version) { - let result = content; - - // Fix v0.53 links - result = result.replace(/\]\(\/v0\.53\/learn\/advanced\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/learn\/beginner\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/learn\/intro\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/build\/building-modules\//g, '](/docs/sdk/v0.53/module-anatomy-keepers/'); - result = result.replace(/\]\(\/v0\.53\/build\/building-apps\//g, '](/docs/sdk/v0.53/app-wiring-runtime/'); - result = result.replace(/\]\(\/v0\.53\/build\/modules\//g, '](/docs/sdk/v0.53/module-reference/'); - result = result.replace(/\]\(\/v0\.53\/build\/abci\//g, '](/docs/sdk/v0.53/runtime-abci/'); - result = result.replace(/\]\(\/v0\.53\/tutorials\//g, '](/docs/sdk/v0.53/tutorials/'); - result = result.replace(/\]\(\/v0\.53\/user\//g, '](/docs/sdk/v0.53/node-operations/'); - - // Fix v0.50 links - result = result.replace(/\]\(\/v0\.50\/learn\//g, '](/docs/sdk/v0.50/learn/'); - result = result.replace(/\]\(\/v0\.50\/build\//g, '](/docs/sdk/v0.50/build/'); - result = result.replace(/\]\(\/v0\.50\/user\//g, '](/docs/sdk/v0.50/user/'); - - // Fix v0.47 links - result = result.replace(/\]\(\/v0\.47\/learn\//g, '](/docs/sdk/v0.47/learn/'); - result = result.replace(/\]\(\/v0\.47\/build\//g, '](/docs/sdk/v0.47/build/'); - result = result.replace(/\]\(\/v0\.47\/user\//g, '](/docs/sdk/v0.47/user/'); - - // Remove Docusaurus-specific "Direct link" anchors - result = result.replace(/\[​\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, ''); - - // Remove heading anchors {#anchor} - result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1'); - - // Fix relative links (../ or ./) - result = result.replace(/\]\(\.\.\//g, ']('); - result = result.replace(/\]\(\.\//g, ']('); - - return result; -} - -/** - * Convert a single Docusaurus file to Mintlify format - */ -function convertDocusaurusToMintlify(content, options = {}) { - const { version = 'v0.53', keepTitle = false } = options; - - // Parse frontmatter and content - const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); - - // Extract or generate title - let title = frontmatter.title || frontmatter.sidebar_label; - let processedContent = mainContent; - - if (!title) { - const extracted = extractTitleFromContent(processedContent); - title = extracted.title || 'Documentation'; - processedContent = extracted.content; - } else if (!keepTitle) { - // Remove H1 if we have title from frontmatter - const extracted = extractTitleFromContent(processedContent); - if (extracted.title) { - processedContent = extracted.content; - } - } - - // Generate or use description - const description = frontmatter.description || generateDescription(processedContent, version); - - // Apply conversions - processedContent = convertAdmonitions(processedContent); - processedContent = convertCodeBlocks(processedContent); - processedContent = fixInternalLinks(processedContent, version); - - // Build Mintlify frontmatter - const mintlifyFrontmatter = { - title, - description - }; - - // Add icon if specified - if (frontmatter.icon) { - mintlifyFrontmatter.icon = frontmatter.icon; - } - - // Build final content - let finalContent = '---\n'; - for (const [key, value] of Object.entries(mintlifyFrontmatter)) { - finalContent += `${key}: "${value}"\n`; - } - finalContent += '---\n\n'; - finalContent += processedContent; - - // Clean up multiple empty lines - finalContent = finalContent.replace(/\n{3,}/g, '\n\n'); - - return { - content: finalContent, - metadata: { - title, - sidebarPosition: frontmatter.sidebar_position || frontmatter.sidebarPosition || 999 - } - }; -} - -/** - * Process a directory of Docusaurus files - */ -async function processDirectory(sourceDir, targetDir, version) { - const files = []; - - // Recursively find all .md and .mdx files - function findFiles(dir, baseDir = '') { - const items = fs.readdirSync(dir); - - for (const item of items) { - const fullPath = path.join(dir, item); - const relativePath = path.join(baseDir, item); - const stat = fs.statSync(fullPath); - - if (stat.isDirectory()) { - findFiles(fullPath, relativePath); - } else if (item.endsWith('.md') || item.endsWith('.mdx')) { - files.push({ - source: fullPath, - relative: relativePath, - name: item - }); - } - } - } - - findFiles(sourceDir); - - console.log(`Found ${files.length} files to convert`); - - const converted = []; - - for (const file of files) { - console.log(`Converting: ${file.relative}`); - - const content = fs.readFileSync(file.source, 'utf-8'); - const result = convertDocusaurusToMintlify(content, { version }); - - // Determine target path - const targetPath = path.join(targetDir, file.relative.replace('.md', '.mdx')); - const targetSubdir = path.dirname(targetPath); - - // Ensure target directory exists - if (!fs.existsSync(targetSubdir)) { - fs.mkdirSync(targetSubdir, { recursive: true }); - } - - // Write converted file - fs.writeFileSync(targetPath, result.content); - - converted.push({ - path: targetPath, - relativePath: file.relative.replace('.md', '.mdx'), - ...result.metadata - }); - } - - return converted; -} - -/** - * Update docs.json with new navigation entries - */ -async function updateDocsJson(files, version, product = 'SDK') { - const docsJsonPath = path.join(__dirname, '../docs.json'); - const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8')); - - // Sort files by sidebar position - files.sort((a, b) => a.sidebarPosition - b.sidebarPosition); - - console.log('\nWould you like to update docs.json navigation? (y/n)'); - const updateNav = await prompt('> '); - - if (updateNav.toLowerCase() === 'y') { - // Find the product and version in navigation - // Implementation depends on your specific docs.json structure - console.log('Navigation update feature to be implemented based on your docs.json structure'); - } -} - -/** - * Main interactive flow - */ -async function main() { - console.log('=== Docusaurus to Mintlify Converter ===\n'); - - // Get source directory - const defaultSource = '/Users/cordt/repos/cosmos-sdk-docs/versioned_docs'; - console.log(`Enter source directory (default: ${defaultSource}):`); - let sourceBase = await prompt('> '); - sourceBase = sourceBase.trim() || defaultSource; - - // List available versions - if (fs.existsSync(sourceBase)) { - const versions = fs.readdirSync(sourceBase) - .filter(d => d.startsWith('version-')) - .map(d => d.replace('version-', '')); - - console.log(`\nAvailable versions: ${versions.join(', ')}`); - console.log('Enter version to convert (e.g., 0.53):'); - const versionInput = await prompt('> '); - const sourceVersion = `version-${versionInput.trim()}`; - const sourceDir = path.join(sourceBase, sourceVersion); - - if (!fs.existsSync(sourceDir)) { - console.error(`Source directory not found: ${sourceDir}`); - process.exit(1); - } - - // Get target directory - const defaultTarget = `/Users/cordt/repos/docs/docs/sdk/v${versionInput.trim()}`; - console.log(`\nEnter target directory (default: ${defaultTarget}):`); - let targetDir = await prompt('> '); - targetDir = targetDir.trim() || defaultTarget; - - // Confirm before proceeding - console.log('\n=== Conversion Summary ==='); - console.log(`Source: ${sourceDir}`); - console.log(`Target: ${targetDir}`); - console.log(`Version: v${versionInput.trim()}`); - console.log('\nProceed with conversion? (y/n)'); - - const confirm = await prompt('> '); - if (confirm.toLowerCase() !== 'y') { - console.log('Conversion cancelled'); - process.exit(0); - } - - // Process files - console.log('\nProcessing files...\n'); - const convertedFiles = await processDirectory(sourceDir, targetDir, `v${versionInput.trim()}`); - - console.log(`\n✅ Successfully converted ${convertedFiles.length} files`); - - // Optionally update navigation - await updateDocsJson(convertedFiles, `v${versionInput.trim()}`); - - } else { - console.error(`Source directory not found: ${sourceBase}`); - process.exit(1); - } - - rl.close(); -} - -// Run if called directly -if (import.meta.url === `file://${process.argv[1]}`) { - main().catch(console.error); -} \ No newline at end of file diff --git a/scripts/docusaurus-to-mintlify.js b/scripts/docusaurus-to-mintlify.js deleted file mode 100644 index ed929814..00000000 --- a/scripts/docusaurus-to-mintlify.js +++ /dev/null @@ -1,405 +0,0 @@ -#!/usr/bin/env node - -import fs from 'fs'; -import path from 'path'; -import { fileURLToPath } from 'url'; -import readline from 'readline'; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -// Create readline interface for prompts -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -const prompt = (question) => new Promise((resolve) => rl.question(question, resolve)); - -/** - * Parse Docusaurus frontmatter - */ -function parseDocusaurusFrontmatter(content) { - const lines = content.split('\n'); - const frontmatter = {}; - let contentStart = 0; - - if (lines[0] === '---') { - for (let i = 1; i < lines.length; i++) { - if (lines[i] === '---') { - contentStart = i + 1; - break; - } - const match = lines[i].match(/^(\w+):\s*(.*)$/); - if (match) { - const key = match[1]; - let value = match[2]; - // Remove quotes if present - value = value.replace(/^["']|["']$/g, ''); - frontmatter[key] = value; - } - } - } - - return { - frontmatter, - content: lines.slice(contentStart).join('\n') - }; -} - -/** - * Extract title from content (first H1 heading) - */ -function extractTitleFromContent(content) { - const match = content.match(/^#\s+(.+)$/m); - if (match) { - return { - title: match[1].trim(), - content: content.replace(match[0], '').trim() - }; - } - return { title: null, content }; -} - -/** - * Generate description from content - */ -function generateDescription(content, version = 'v0.53') { - // Remove markdown formatting - let plainText = content - .replace(/^#+\s+.*$/gm, '') // Remove headings - .replace(/```[\s\S]*?```/g, '') // Remove code blocks - .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Convert links to text - .replace(/[*_`]/g, '') // Remove formatting - .trim(); - - // Find first non-empty paragraph - const paragraphs = plainText.split(/\n\n+/); - for (const para of paragraphs) { - const cleaned = para.trim(); - if (cleaned && cleaned.length > 20) { - return cleaned.length > 150 ? cleaned.substring(0, 147) + '...' : cleaned; - } - } - - return `Cosmos SDK ${version} Documentation`; -} - -/** - * Convert Docusaurus admonitions to Mintlify callouts - */ -function convertAdmonitions(content) { - const admonitionMap = { - 'note': 'Note', - 'tip': 'Tip', - 'info': 'Info', - 'warning': 'Warning', - 'danger': 'Warning', - 'caution': 'Warning', - 'important': 'Info', - 'success': 'Check' - }; - - let result = content; - - // Match multiline admonitions - const admonitionRegex = /:::(note|tip|info|warning|danger|caution|important|success)(?:\s+(.+?))?\n([\s\S]*?)\n:::/gi; - - result = result.replace(admonitionRegex, (match, type, title, content) => { - const component = admonitionMap[type.toLowerCase()] || 'Note'; - const titleLine = title ? `**${title}**\n` : ''; - return `<${component}>\n${titleLine}${content.trim()}\n`; - }); - - // Also handle single-line admonitions - const singleLineRegex = /:::(note|tip|info|warning|danger|caution|important|success)\s+(.+?)\s*:::/gi; - - result = result.replace(singleLineRegex, (match, type, content) => { - const component = admonitionMap[type.toLowerCase()] || 'Note'; - return `<${component}>${content.trim()}`; - }); - - return result; -} - -/** - * Convert code blocks to Mintlify format with expandable for long blocks - */ -function convertCodeBlocks(content) { - const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g; - - return content.replace(codeBlockRegex, (match, lang, code) => { - const lines = code.split('\n'); - const lineCount = lines.length; - - // If more than 10 lines, make it expandable - if (lineCount > 10) { - // Get first few lines for preview - const preview = lines.slice(0, 3).join('\n'); - const title = lang ? `${lang} code` : 'Code'; - - return ` -\`\`\`${lang} -${code}\`\`\` -`; - } - - // Otherwise keep as regular code block - return match; - }); -} - -/** - * Fix internal documentation links - */ -function fixInternalLinks(content, version) { - let result = content; - - // Fix v0.53 links - result = result.replace(/\]\(\/v0\.53\/learn\/advanced\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/learn\/beginner\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/learn\/intro\//g, '](/docs/sdk/v0.53/core-concepts/'); - result = result.replace(/\]\(\/v0\.53\/build\/building-modules\//g, '](/docs/sdk/v0.53/module-anatomy-keepers/'); - result = result.replace(/\]\(\/v0\.53\/build\/building-apps\//g, '](/docs/sdk/v0.53/app-wiring-runtime/'); - result = result.replace(/\]\(\/v0\.53\/build\/modules\//g, '](/docs/sdk/v0.53/module-reference/'); - result = result.replace(/\]\(\/v0\.53\/build\/abci\//g, '](/docs/sdk/v0.53/runtime-abci/'); - result = result.replace(/\]\(\/v0\.53\/tutorials\//g, '](/docs/sdk/v0.53/tutorials/'); - result = result.replace(/\]\(\/v0\.53\/user\//g, '](/docs/sdk/v0.53/node-operations/'); - - // Fix v0.50 links - result = result.replace(/\]\(\/v0\.50\/learn\//g, '](/docs/sdk/v0.50/learn/'); - result = result.replace(/\]\(\/v0\.50\/build\//g, '](/docs/sdk/v0.50/build/'); - result = result.replace(/\]\(\/v0\.50\/user\//g, '](/docs/sdk/v0.50/user/'); - - // Fix v0.47 links - result = result.replace(/\]\(\/v0\.47\/learn\//g, '](/docs/sdk/v0.47/learn/'); - result = result.replace(/\]\(\/v0\.47\/build\//g, '](/docs/sdk/v0.47/build/'); - result = result.replace(/\]\(\/v0\.47\/user\//g, '](/docs/sdk/v0.47/user/'); - - // Remove Docusaurus-specific "Direct link" anchors - result = result.replace(/\[​\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, ''); - - // Remove heading anchors {#anchor} - result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1'); - - // Fix relative links (../ or ./) - result = result.replace(/\]\(\.\.\//g, ']('); - result = result.replace(/\]\(\.\//g, ']('); - - return result; -} - -/** - * Convert a single Docusaurus file to Mintlify format - */ -function convertDocusaurusToMintlify(content, options = {}) { - const { version = 'v0.53', keepTitle = false } = options; - - // Parse frontmatter and content - const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); - - // Extract or generate title - let title = frontmatter.title || frontmatter.sidebar_label; - let processedContent = mainContent; - - if (!title) { - const extracted = extractTitleFromContent(processedContent); - title = extracted.title || 'Documentation'; - processedContent = extracted.content; - } else if (!keepTitle) { - // Remove H1 if we have title from frontmatter - const extracted = extractTitleFromContent(processedContent); - if (extracted.title) { - processedContent = extracted.content; - } - } - - // Generate or use description - const description = frontmatter.description || generateDescription(processedContent, version); - - // Apply conversions - processedContent = convertAdmonitions(processedContent); - processedContent = convertCodeBlocks(processedContent); - processedContent = fixInternalLinks(processedContent, version); - - // Build Mintlify frontmatter - const mintlifyFrontmatter = { - title, - description - }; - - // Add icon if specified - if (frontmatter.icon) { - mintlifyFrontmatter.icon = frontmatter.icon; - } - - // Build final content - let finalContent = '---\n'; - for (const [key, value] of Object.entries(mintlifyFrontmatter)) { - finalContent += `${key}: "${value}"\n`; - } - finalContent += '---\n\n'; - finalContent += processedContent; - - // Clean up multiple empty lines - finalContent = finalContent.replace(/\n{3,}/g, '\n\n'); - - return { - content: finalContent, - metadata: { - title, - sidebarPosition: frontmatter.sidebar_position || frontmatter.sidebarPosition || 999 - } - }; -} - -/** - * Process a directory of Docusaurus files - */ -async function processDirectory(sourceDir, targetDir, version) { - const files = []; - - // Recursively find all .md and .mdx files - function findFiles(dir, baseDir = '') { - const items = fs.readdirSync(dir); - - for (const item of items) { - const fullPath = path.join(dir, item); - const relativePath = path.join(baseDir, item); - const stat = fs.statSync(fullPath); - - if (stat.isDirectory()) { - findFiles(fullPath, relativePath); - } else if (item.endsWith('.md') || item.endsWith('.mdx')) { - files.push({ - source: fullPath, - relative: relativePath, - name: item - }); - } - } - } - - findFiles(sourceDir); - - console.log(`Found ${files.length} files to convert`); - - const converted = []; - - for (const file of files) { - console.log(`Converting: ${file.relative}`); - - const content = fs.readFileSync(file.source, 'utf-8'); - const result = convertDocusaurusToMintlify(content, { version }); - - // Determine target path - const targetPath = path.join(targetDir, file.relative.replace('.md', '.mdx')); - const targetSubdir = path.dirname(targetPath); - - // Ensure target directory exists - if (!fs.existsSync(targetSubdir)) { - fs.mkdirSync(targetSubdir, { recursive: true }); - } - - // Write converted file - fs.writeFileSync(targetPath, result.content); - - converted.push({ - path: targetPath, - relativePath: file.relative.replace('.md', '.mdx'), - ...result.metadata - }); - } - - return converted; -} - -/** - * Update docs.json with new navigation entries - */ -async function updateDocsJson(files, version, product = 'SDK') { - const docsJsonPath = path.join(__dirname, '../../docs.json'); - const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8')); - - // Sort files by sidebar position - files.sort((a, b) => a.sidebarPosition - b.sidebarPosition); - - console.log('\nWould you like to update docs.json navigation? (y/n)'); - const updateNav = await prompt('> '); - - if (updateNav.toLowerCase() === 'y') { - // Find the product and version in navigation - // Implementation depends on your specific docs.json structure - console.log('Navigation update feature to be implemented based on your docs.json structure'); - } -} - -/** - * Main interactive flow - */ -async function main() { - console.log('=== Docusaurus to Mintlify Converter ===\n'); - - // Get source directory - const defaultSource = '/Users/cordt/repos/cosmos-sdk-docs/versioned_docs'; - console.log(`Enter source directory (default: ${defaultSource}):`); - let sourceBase = await prompt('> '); - sourceBase = sourceBase.trim() || defaultSource; - - // List available versions - if (fs.existsSync(sourceBase)) { - const versions = fs.readdirSync(sourceBase) - .filter(d => d.startsWith('version-')) - .map(d => d.replace('version-', '')); - - console.log(`\nAvailable versions: ${versions.join(', ')}`); - console.log('Enter version to convert (e.g., 0.53):'); - const versionInput = await prompt('> '); - const sourceVersion = `version-${versionInput.trim()}`; - const sourceDir = path.join(sourceBase, sourceVersion); - - if (!fs.existsSync(sourceDir)) { - console.error(`Source directory not found: ${sourceDir}`); - process.exit(1); - } - - // Get target directory - const defaultTarget = `/Users/cordt/repos/docs/docs/sdk/v${versionInput.trim()}`; - console.log(`\nEnter target directory (default: ${defaultTarget}):`); - let targetDir = await prompt('> '); - targetDir = targetDir.trim() || defaultTarget; - - // Confirm before proceeding - console.log('\n=== Conversion Summary ==='); - console.log(`Source: ${sourceDir}`); - console.log(`Target: ${targetDir}`); - console.log(`Version: v${versionInput.trim()}`); - console.log('\nProceed with conversion? (y/n)'); - - const confirm = await prompt('> '); - if (confirm.toLowerCase() !== 'y') { - console.log('Conversion cancelled'); - process.exit(0); - } - - // Process files - console.log('\nProcessing files...\n'); - const convertedFiles = await processDirectory(sourceDir, targetDir, `v${versionInput.trim()}`); - - console.log(`\n✅ Successfully converted ${convertedFiles.length} files`); - - // Optionally update navigation - await updateDocsJson(convertedFiles, `v${versionInput.trim()}`); - - } else { - console.error(`Source directory not found: ${sourceBase}`); - process.exit(1); - } - - rl.close(); -} - -// Run if called directly -if (import.meta.url === `file://${process.argv[1]}`) { - main().catch(console.error); -} \ No newline at end of file diff --git a/scripts/migrate-docusaurus.js b/scripts/migrate-docusaurus.js new file mode 100755 index 00000000..56cb5f14 --- /dev/null +++ b/scripts/migrate-docusaurus.js @@ -0,0 +1,1197 @@ +#!/usr/bin/env node + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import readline from 'readline'; +import matter from 'gray-matter'; +import { unified } from 'unified'; +import remarkParse from 'remark-parse'; +import remarkStringify from 'remark-stringify'; +import { visit } from 'unist-util-visit'; +import { execSync } from 'child_process'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Create readline interface for prompts +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +const prompt = (question) => new Promise((resolve) => rl.question(question, resolve)); + +/** + * Safely process content while preserving code blocks and inline code + */ +function safeProcessContent(content, processor) { + // Extract all code blocks and inline code + const codeBlocks = []; + const inlineCode = []; + + let processed = content; + + // Replace code blocks with placeholders + processed = processed.replace(/```[\s\S]*?```/g, (match) => { + const index = codeBlocks.length; + codeBlocks.push(match); + return `__CODE_BLOCK_${index}__`; + }); + + // Replace inline code with placeholders + processed = processed.replace(/`[^`\n]+`/g, (match) => { + const index = inlineCode.length; + inlineCode.push(match); + return `__INLINE_CODE_${index}__`; + }); + + // Process the content without code + processed = processor(processed); + + // Restore inline code first + for (let i = 0; i < inlineCode.length; i++) { + processed = processed.replace(`__INLINE_CODE_${i}__`, inlineCode[i]); + } + + // Restore code blocks last + for (let i = 0; i < codeBlocks.length; i++) { + processed = processed.replace(`__CODE_BLOCK_${i}__`, codeBlocks[i]); + } + + return processed; +} + +/** + * Parse Docusaurus frontmatter using battle-tested gray-matter library + */ +function parseDocusaurusFrontmatter(content) { + const parsed = matter(content); + + return { + frontmatter: parsed.data, + content: parsed.content + }; +} + +/** + * Extract title from content (first H1 heading) + */ +function extractTitleFromContent(content) { + const match = content.match(/^#\s+(.+)$/m); + if (match) { + return { + title: match[1].trim(), + content: content.replace(/^#\s+.+\n?/m, '').trim() // Only remove the heading line, not random content + }; + } + return { title: null, content }; +} + + +/** + * Convert Docusaurus admonitions to Mintlify callouts + */ +function convertAdmonitions(content) { + const admonitionMap = { + 'note': 'Note', + 'tip': 'Tip', + 'info': 'Info', + 'warning': 'Warning', + 'danger': 'Warning', + 'caution': 'Warning', + 'important': 'Info', + 'success': 'Check', + 'details': 'Accordion' // For expandable sections + }; + + // Use line-by-line processing to handle complex nested cases + const lines = content.split('\n'); + const result = []; + const admonitionStack = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Check for opening admonition + const openMatch = line.match(/^:::(\w+)(?:\s+(.+))?$/); + if (openMatch) { + const type = openMatch[1].toLowerCase(); + const title = openMatch[2]; + + const component = admonitionMap[type] || 'Note'; + admonitionStack.push(component); + + if (title) { + result.push(`<${component}>`); + result.push(`**${title}**`); + } else { + result.push(`<${component}>`); + } + continue; + } + + // Check for closing admonition + if (line.trim() === ':::') { + if (admonitionStack.length > 0) { + const component = admonitionStack.pop(); + result.push(``); + } + continue; + } + + // Regular line + result.push(line); + } + + let finalResult = result.join('\n'); + + // Clean up any remaining ::: artifacts and malformed syntax + finalResult = finalResult.replace(/:::\s*\n/g, '\n'); + finalResult = finalResult.replace(/:::\./g, ''); // Handle malformed :::. + finalResult = finalResult.replace(/^\s*:::\s*$/gm, ''); + + // Fix unclosed tags by ensuring proper pairing + // If we find an opening tag without a closing tag, add the closing tag + const tagPattern = /<(Note|Warning|Tip|Info|Check)\b[^>]*>/g; + const openTags = finalResult.match(tagPattern) || []; + + for (const openTag of openTags) { + const tagName = openTag.match(/<(\w+)/)[1]; + const closeTag = ``; + + // Check if this opening tag has a corresponding closing tag + const openIndex = finalResult.indexOf(openTag); + const nextOpenIndex = finalResult.indexOf(`<${tagName}`, openIndex + openTag.length); + const closeIndex = finalResult.indexOf(closeTag, openIndex); + + // If no closing tag found, or closing tag is after the next opening tag, add one + if (closeIndex === -1 || (nextOpenIndex !== -1 && closeIndex > nextOpenIndex)) { + const insertPoint = nextOpenIndex !== -1 ? nextOpenIndex : finalResult.length; + finalResult = finalResult.slice(0, insertPoint) + `\n${closeTag}\n` + finalResult.slice(insertPoint); + } + } + + return finalResult; +} + + + +/** + * Format Go code + */ +function formatGoCode(code) { + return code + // Fix imports + .replace(/import \(/g, 'import (\n ') + .replace(/"\s+"/g, '"\n "') + .replace(/\)\s*([a-zA-Z])/g, ')\n\n$1') + + // Fix braces and structure + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + .replace(/\)\s*\{/g, ') {') + .replace(/\}\s*([a-zA-Z])/g, '}\n\n$1') + + // Fix struct declarations + .replace(/\{\s*([A-Z][a-zA-Z]*:)/g, '{\n $1') + .replace(/,\s*([A-Z][a-zA-Z]*:)/g, ',\n $1') + + // Basic indentation + .replace(/^(\s*)([a-z][a-zA-Z]*\s*:=)/gm, ' $2') + .replace(/^(\s*)(if|for|switch|case)/gm, ' $2') + + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +/** + * Format JavaScript/TypeScript code + */ +function formatJavaScriptCode(code) { + return code + // Fix imports + .replace(/import\s*\{([^}]+)\}\s*from/g, (match, imports) => { + const cleanImports = imports.split(',').map(imp => imp.trim()).join(',\n '); + return `import {\n ${cleanImports}\n} from`; + }) + + // Fix object/function braces + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + .replace(/\)\s*=>\s*\{/g, ') => {') + + // Fix function declarations + .replace(/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g, 'function $1(') + .replace(/\)\s*\{/g, ') {') + + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +/** + * Format Rust code + */ +function formatRustCode(code) { + return code + // Fix use statements + .replace(/use\s+([^;]+);/g, (match, usePath) => { + if (usePath.includes('{')) { + return match.replace(/\{\s*([^}]+)\s*\}/g, (m, items) => { + const cleanItems = items.split(',').map(item => item.trim()).join(',\n '); + return `{\n ${cleanItems}\n}`; + }); + } + return match; + }) + + // Fix function formatting + .replace(/fn\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g, 'fn $1(') + .replace(/\)\s*->\s*([^{]+)\s*\{/g, ') -> $1 {') + + // Fix struct/impl blocks + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +/** + * Format JSON code + */ +function formatJsonCode(code) { + try { + // Try to parse and reformat JSON + const parsed = JSON.parse(code); + return JSON.stringify(parsed, null, 2); + } catch { + // If not valid JSON, just clean up basic formatting + return code + .replace(/\{\s*"/g, '{\n "') + .replace(/",\s*"/g, '",\n "') + .replace(/\}\s*,/g, '\n},') + .replace(/\n{3,}/g, '\n\n') + .trim(); + } +} + +/** + * Generic code formatting for other languages + */ +function formatGenericCode(code) { + return code + // Basic brace formatting + .replace(/\{\s*([a-zA-Z])/g, '{\n $1') + .replace(/([^}\n])\s*\}/g, '$1\n}') + + // Basic function-like patterns + .replace(/\)\s*\{/g, ') {') + + // Clean up spacing + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +/** + * Fix internal documentation links + */ +function fixInternalLinks(content, version, product = 'generic') { + let result = content; + + // Remove Docusaurus-specific "Direct link" anchors + result = result.replace(/\[​\]\(#[^)]+\s+"Direct link to[^"]+"\)/g, ''); + + // Remove heading anchors {#anchor} + result = result.replace(/^(#+\s+.+?)\s*\{#[^}]+\}\s*$/gm, '$1'); + + // Fix relative links (../ or ./) + result = result.replace(/\]\(\.\.\//g, ']('); + result = result.replace(/\]\(\.\//g, ']('); + + return result; +} + +/** + * Fix common MDX parsing issues while preserving all code content + */ +function fixMDXIssues(content) { + return safeProcessContent(content, (nonCodeContent) => { + // Convert HTML comments to JSX comments, handling incomplete ones + nonCodeContent = nonCodeContent.replace(//gs, '{/* $1 */}'); + // Handle incomplete HTML comments that never close + nonCodeContent = nonCodeContent.replace(/)(?=\n|$)/g, '{/* $1 */}'); + + // Convert URLs in angle brackets to proper markdown links + nonCodeContent = nonCodeContent.replace(/<(https?:\/\/[^>]+)>/g, '[Link]($1)'); + + // Fix arrow operators that break parsing + nonCodeContent = nonCodeContent.replace(/([^`])<->([^`])/g, '$1`<->`$2'); + + // Remove stray closing tags + nonCodeContent = nonCodeContent.replace(/^\s*<\/[A-Z][a-zA-Z]*>\s*$/gm, ''); + + // Close unclosed details tags (add at end if missing) + if (nonCodeContent.includes('
') && !nonCodeContent.includes('
')) { + nonCodeContent += '\n
'; + } + + // Fix unclosed placeholder tags - these are template placeholders, not commands + nonCodeContent = nonCodeContent.replace(/<(appd|simd|gaiad|osmosisd|junod)>\s*([^<\n]*?)(?=\n|$)/g, '<$1> $2'); + nonCodeContent = nonCodeContent.replace(/<(appd|simd|gaiad|osmosisd|junod)>\s+([^<>]+?)(?=\s|<|$)/g, '<$1> $2'); + + // Convert all braces to proper inline code spans (complete units) + nonCodeContent = nonCodeContent + // 1. Complete API paths: /path{vars} → `complete path` + .replace(/(\/[a-zA-Z][a-zA-Z0-9/._-]*\{[^}]+\})/g, '`$1`') + + // 2. Complete event expressions: key.action={value} → `complete expression` + .replace(/([a-zA-Z][a-zA-Z0-9_]*\.[a-zA-Z][a-zA-Z0-9_]*\{[^}]+\})/g, '`$1`') + + // 3. Complete type references: map[type]interface{} → `complete type` + .replace(/(map\[[^\]]+\]interface\{\})/g, '`$1`') + .replace(/(\binterface\{\})(?!\s*[\{\"'])/g, '`$1`') + + // 4. Complete JSON objects: {"key":"value"} → `complete object` + .replace(/(\{\"[^}]+\"\})/g, '`$1`') + + // 5. Template variables with safe boundaries: {var} or {multi word} → `{var}` + .replace(/(?]+?)>/gi, (match, tag, content) => { + if (!/=/.test(content) && /\s/.test(content)) { + return `\`${tag} ${content}\``; + } + return match; + }); + + // Fix standalone closing tags + nonCodeContent = nonCodeContent.replace(/^\s*<\/[^>]+>\s*$/gm, ''); + + // Fix unclosed tags at the end of lines + nonCodeContent = nonCodeContent.replace(/<([a-z][a-z0-9-]*)\s*$/gm, '`<$1>`'); + + // Remove malformed import statements + nonCodeContent = nonCodeContent.replace(/^import\s+[^;]*$/gm, ''); + + return nonCodeContent; + }); +} + +/** + * AST processor for fixing links + */ +function createLinkFixerPlugin(version, product) { + return () => { + return (tree) => { + visit(tree, 'link', (node) => { + if (node.url) { + // Fix relative links + if (node.url.startsWith('../') || node.url.startsWith('./')) { + node.url = node.url.replace(/\.\.\//, '/'); + } + // Fix versioned links for SDK docs + if (product === 'sdk' && node.url.includes('/docs/')) { + node.url = node.url.replace('/docs/', `/docs/sdk/${version}/`); + } + } + }); + }; + }; +} + +/** + * AST processor for fixing HTML elements and problematic syntax + */ +function createHTMLFixerPlugin() { + return () => { + return (tree) => { + // Process HTML nodes + visit(tree, 'html', (node) => { + if (!node.value) return; + + // Convert HTML comments to JSX comments + node.value = node.value.replace(//gs, '{/* $1 */}'); + + // Convert
tags to Mintlify Expandable + if (node.value.includes(']*>\s*]*>(.*?)<\/summary>\s*([\s\S]*?)<\/details>/gi, + (match, summary, content) => { + return `\n${content.trim()}\n`; + }); + } + }); + + // Process text nodes to fix problematic angle brackets + visit(tree, 'text', (node, index, parent) => { + if (!node.value) return; + + // Skip if inside a code block or link + if (parent && (parent.type === 'code' || parent.type === 'inlineCode' || parent.type === 'link')) { + return; + } + + // Fix command placeholders like , + node.value = node.value.replace(/<(appd|simd|gaiad|osmosisd|junod|yourapp)>/g, '`$1`'); + + // Fix comparison operators and arrows + node.value = node.value.replace(/([^`])<=>([^`])/g, '$1`<=>`$2'); + node.value = node.value.replace(/([^`])<->([^`])/g, '$1`<->`$2'); + + // Fix generic placeholders like , + node.value = node.value.replace(/<([a-z]+(?:-[a-z]+)*)>/g, '`<$1>`'); + }); + }; + }; +} + +/** + * AST processor for enhancing code blocks + */ +function createCodeBlockEnhancerPlugin() { + return () => { + return (tree, file) => { + visit(tree, 'code', (node) => { + // Handle Docusaurus "reference" syntax + // e.g., ```go reference + // https://github.com/... + // ``` + if (node.lang && node.lang.includes(' reference')) { + const parts = node.lang.split(' '); + const lang = parts[0]; // Keep only the language part + + // Check if the code block contains just a URL (reference pattern) + if (node.value && node.value.trim().startsWith('https://')) { + const url = node.value.trim(); + // Convert to a comment with the reference URL preserved + if (lang === 'go' || lang === 'golang') { + node.value = `// Reference: ${url}`; + } else if (lang === 'protobuf' || lang === 'proto') { + node.value = `// Reference: ${url}`; + } else if (lang === 'javascript' || lang === 'js' || lang === 'typescript' || lang === 'ts') { + node.value = `// Reference: ${url}`; + } else if (lang === 'python' || lang === 'py') { + node.value = `# Reference: ${url}`; + } else if (lang === 'bash' || lang === 'shell' || lang === 'sh') { + node.value = `# Reference: ${url}`; + } else { + // Default to comment style + node.value = `// Reference: ${url}`; + } + } + + // Clean the lang to remove 'reference' + node.lang = lang; + } + + // Remove any "reference" from meta as well + if (node.meta && node.meta.includes('reference')) { + node.meta = node.meta.replace('reference', '').trim(); + } + + // Add expandable to long code blocks + if (node.value && node.value.split('\n').length > 10) { + if (!node.meta || !node.meta.includes('expandable')) { + node.meta = node.meta ? `${node.meta} expandable` : 'expandable'; + } + } + + // Ensure language is specified by detecting content + if (!node.lang && node.value) { + const codeContent = node.value.toLowerCase(); + + if (codeContent.includes('package ') || codeContent.includes('func ') || + codeContent.includes('import "') || codeContent.includes('interface{')) { + node.lang = 'go'; + } else if (codeContent.includes('const ') || codeContent.includes('let ') || + codeContent.includes('function ') || codeContent.includes('=> ')) { + node.lang = 'javascript'; + } else if (codeContent.includes('#!/bin/bash') || codeContent.includes('echo ') || + codeContent.includes('npm ') || codeContent.includes('yarn ')) { + node.lang = 'bash'; + } else if (codeContent.includes('def ') || codeContent.includes('class ')) { + node.lang = 'python'; + } else if (codeContent.trim().startsWith('{') && codeContent.includes('"')) { + node.lang = 'json'; + } else if (codeContent.includes('message ') || codeContent.includes('service ')) { + node.lang = 'protobuf'; + } + } + + // Format the code content if we have formatting functions available + if (node.lang && node.value) { + const formatted = formatCodeByLanguage(node.lang, node.value); + if (formatted !== node.value) { + node.value = formatted; + } + } + }); + }; + }; +} + +/** + * Helper function to format code by language + */ +function formatCodeByLanguage(lang, code) { + switch (lang.toLowerCase()) { + case 'go': + case 'golang': + return formatGoCode(code); + case 'javascript': + case 'js': + case 'typescript': + case 'ts': + return formatJavaScriptCode(code); + case 'json': + case 'jsonc': + return formatJsonCode(code); + default: + return code; + } +} + +/** + * Process markdown with AST for better accuracy + */ +function processMarkdownWithAST(content, version, product) { + try { + const file = unified() + .use(remarkParse) + .use(createLinkFixerPlugin(version, product)) + .use(createHTMLFixerPlugin()) + .use(createCodeBlockEnhancerPlugin()) + .use(remarkStringify) + .processSync(content); + return String(file); + } catch (error) { + console.warn('AST processing failed, falling back to regex:', error.message); + return content; + } +} + +/** + * Convert a single Docusaurus file to Mintlify format + */ +function convertDocusaurusToMintlify(content, options = {}) { + const { version = 'next', product = 'generic', keepTitle = false } = options; + + // Parse frontmatter and content + const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); + + // Extract or generate title + let title = frontmatter.title || frontmatter.sidebar_label; + let processedContent = mainContent; + + if (!title) { + const extracted = extractTitleFromContent(processedContent); + title = extracted.title || 'Documentation'; + processedContent = extracted.content; + } else if (!keepTitle) { + // Remove H1 if we have title from frontmatter + const extracted = extractTitleFromContent(processedContent); + if (extracted.title) { + processedContent = extracted.content; + } + } + + // Extract description from first paragraph after H1, or use frontmatter if it exists + let description = frontmatter.description || null; + + if (!description) { + // Look for first paragraph after H1 heading + const afterTitle = processedContent.replace(/^#+\s+.*\n/m, '').trim(); + const firstParagraph = afterTitle.split(/\n\n/)[0]; + + if (firstParagraph) { + // Clean up the paragraph - remove markdown formatting + const cleaned = firstParagraph + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Convert links to text + .replace(/[*_`]/g, '') // Remove formatting + .replace(/\s+/g, ' ') // Normalize whitespace + .trim(); + + // Use as description if it's reasonable length and not structural content + if (cleaned.length > 10 && + cleaned.length < 300 && + !cleaned.includes('|') && // Not table content + !cleaned.includes(':::') && // Not admonition + !cleaned.includes('```')) { // Not code + description = cleaned; + } + } + } + + // Apply conversions + // Convert HTML comments to JSX comments for MDX compatibility + // Handle both complete and incomplete HTML comments + processedContent = processedContent.replace(//gs, '{/* $1 */}'); + + // Handle malformed or incomplete HTML comments + processedContent = processedContent.replace(/)/g, '{/* $1 */}'); + + // Fix common MDX issues + // Use AST processing first for better accuracy (handles code blocks) + processedContent = processMarkdownWithAST(processedContent, version, product); + + // Fix MDX issues and apply conversions + processedContent = fixMDXIssues(processedContent); + processedContent = convertAdmonitions(processedContent); + processedContent = fixInternalLinks(processedContent, version, product); + + // Build Mintlify frontmatter + const mintlifyFrontmatter = { + title + }; + + // Only include description if we have suitable content + if (description) { + mintlifyFrontmatter.description = description; + } + + // Add icon if it actually exists in Docusaurus frontmatter + // (This is rare - Docusaurus doesn't typically use icon field) + if (frontmatter.icon) { + mintlifyFrontmatter.icon = frontmatter.icon; + } + + // Do NOT preserve Docusaurus navigation metadata in Mintlify frontmatter + // These fields (sidebar_position, sidebar_label, slug) are handled by docs.json navigation + + // Use gray-matter to safely generate frontmatter + const cleanFrontmatter = {}; + + for (const [key, value] of Object.entries(mintlifyFrontmatter)) { + const valueStr = String(value).trim(); + + // Skip fields with problematic content entirely + if (valueStr.includes('|') || // Tables + valueStr.includes(':::') || // Admonitions + valueStr.includes('```') || // Code blocks + valueStr.includes('{') || // Template variables + valueStr.includes('}') || + valueStr.includes('<') || // HTML/XML tags or template placeholders + valueStr.includes('>') || + valueStr.length > 250) { + continue; // Skip this field entirely + } + + cleanFrontmatter[key] = valueStr.replace(/\s+/g, ' ').trim(); + } + + // Use gray-matter to generate safe YAML frontmatter + let finalContent = matter.stringify(processedContent, cleanFrontmatter); + + // Clean up multiple empty lines + finalContent = finalContent.replace(/\n{3,}/g, '\n\n'); + + return { + content: finalContent, + metadata: { + title, + sidebarPosition: frontmatter.sidebar_position || frontmatter.sidebarPosition || 999 + } + }; +} + +/** + * Process a directory of Docusaurus files + */ +async function processDirectory(sourceDir, targetDir, version, product = 'generic') { + const files = []; + + // Recursively find all .md and .mdx files + function findFiles(dir, baseDir = '') { + const items = fs.readdirSync(dir); + + for (const item of items) { + const fullPath = path.join(dir, item); + const relativePath = path.join(baseDir, item); + const stat = fs.statSync(fullPath); + + if (stat.isDirectory()) { + findFiles(fullPath, relativePath); + } else if (item.endsWith('.md') || item.endsWith('.mdx')) { + files.push({ + source: fullPath, + relative: relativePath, + name: item + }); + } + } + } + + findFiles(sourceDir); + + console.log(`Found ${files.length} files to convert`); + + const converted = []; + + for (const file of files) { + console.log(`Converting: ${file.relative}`); + + const content = fs.readFileSync(file.source, 'utf-8'); + const result = convertDocusaurusToMintlify(content, { version, product }); + + // Determine target path - remove numbered prefixes from filenames + let cleanRelativePath = file.relative.replace(/\/(\d+-)/g, '/').replace(/^(\d+-)/, ''); + const targetPath = path.join(targetDir, cleanRelativePath.replace('.md', '.mdx')); + const targetSubdir = path.dirname(targetPath); + + // Ensure target directory exists + if (!fs.existsSync(targetSubdir)) { + fs.mkdirSync(targetSubdir, { recursive: true }); + } + + // Write converted file + fs.writeFileSync(targetPath, result.content); + + converted.push({ + path: targetPath, + relativePath: cleanRelativePath.replace('.md', '.mdx'), + sidebarPosition: result.metadata.sidebarPosition || 999, + title: result.metadata.title, + ...result.metadata + }); + } + + return converted; +} + + +/** + * Resolve sidebar position conflicts by sorting alphabetically and renumbering + */ +function resolveSidebarPositionConflicts(files) { + // First, sort by position then alphabetically by path + files.sort((a, b) => { + if (a.sidebarPosition !== b.sidebarPosition) { + return a.sidebarPosition - b.sidebarPosition; + } + // Same position - sort alphabetically by relative path + return a.relativePath.localeCompare(b.relativePath); + }); + + // Group by directory to handle conflicts within each directory separately + const groupedFiles = {}; + + for (const file of files) { + const dirPath = file.relativePath.includes('/') + ? file.relativePath.split('/').slice(0, -1).join('/') + : ''; + + if (!groupedFiles[dirPath]) { + groupedFiles[dirPath] = []; + } + groupedFiles[dirPath].push(file); + } + + // Resolve conflicts within each directory + const resolvedFiles = []; + + for (const [dirPath, dirFiles] of Object.entries(groupedFiles)) { + let currentPosition = 1; + + for (let i = 0; i < dirFiles.length; i++) { + const file = dirFiles[i]; + const nextFile = dirFiles[i + 1]; + + // Assign current position + file.resolvedPosition = currentPosition; + + // If next file exists and has same original position, increment for conflict resolution + if (nextFile && nextFile.sidebarPosition === file.sidebarPosition) { + currentPosition++; + } else { + // Jump to next original position if no conflict, or continue incrementing + currentPosition = nextFile ? Math.max(currentPosition + 1, nextFile.sidebarPosition) : currentPosition + 1; + } + } + + resolvedFiles.push(...dirFiles); + } + + // Final sort by resolved positions + return resolvedFiles.sort((a, b) => { + const aDirDepth = (a.relativePath.match(/\//g) || []).length; + const bDirDepth = (b.relativePath.match(/\//g) || []).length; + + if (aDirDepth !== bDirDepth) { + return aDirDepth - bDirDepth; // Root files first + } + + return (a.resolvedPosition || a.sidebarPosition) - (b.resolvedPosition || b.sidebarPosition); + }); +} + +/** + * Get appropriate icon for product + */ +function getProductIcon(product) { + const iconMap = { + 'sdk': 'gear', + 'ibc': 'link', + 'cometbft': 'star', + 'evm': 'code', + 'wasmd': 'cube', + 'hermes': 'rocket' + }; + return iconMap[product.toLowerCase()] || 'book'; +} + +/** + * Update docs.json and versions.json with complete navigation + */ +async function updateDocsJson(allVersionData, product = 'generic') { + const docsJsonPath = path.join(__dirname, '../docs.json'); + let docsJson; + + try { + docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8')); + } catch (error) { + console.error('Could not read docs.json:', error); + return; + } + + // Ensure navigation structure exists + if (!docsJson.navigation) { + docsJson.navigation = { dropdowns: [] }; + } + if (!docsJson.navigation.dropdowns) { + docsJson.navigation.dropdowns = []; + } + + // Generate product name for dropdown + const productName = product.toUpperCase(); + + // Find or create product dropdown + let productDropdown = docsJson.navigation.dropdowns.find(dropdown => + dropdown.dropdown === productName || + dropdown.dropdown === product || + dropdown.dropdown.toLowerCase() === product.toLowerCase() + ); + + if (!productDropdown) { + productDropdown = { + dropdown: productName, + icon: getProductIcon(product), + versions: [] + }; + docsJson.navigation.dropdowns.push(productDropdown); + } + + // Clear existing versions + productDropdown.versions = []; + + // Add version sections following the same structure as EVM + for (const [version, files] of Object.entries(allVersionData)) { + const versionData = { + version: version, + tabs: [ + { + tab: 'Documentation', + groups: [ + { + group: productName, + pages: [] + } + ] + } + ] + }; + + // Sort files by sidebar position with conflict resolution + const sortedFiles = resolveSidebarPositionConflicts(files); + + // Group files by directory structure for better organization + const groupedPages = {}; + + for (const file of sortedFiles) { + const relativePath = file.relativePath.replace('.mdx', ''); + const parts = relativePath.split('/'); + + if (parts.length === 1) { + // Root level files + versionData.tabs[0].groups[0].pages.push(`docs/${product}/${version}/${relativePath}`); + } else { + // Group by first directory + const groupName = parts[0].replace(/^\d+-/, '').replace(/-/g, ' ') + .replace(/\b\w/g, l => l.toUpperCase()); + + if (!groupedPages[groupName]) { + groupedPages[groupName] = []; + } + groupedPages[groupName].push(`docs/${product}/${version}/${relativePath}`); + } + } + + // Add grouped pages + for (const [groupName, pages] of Object.entries(groupedPages)) { + versionData.tabs[0].groups.push({ + group: groupName, + pages: pages + }); + } + + productDropdown.versions.push(versionData); + } + + // Update versions.json as well + const versionsJsonPath = path.join(__dirname, '../versions.json'); + let versionsJson; + + try { + versionsJson = JSON.parse(fs.readFileSync(versionsJsonPath, 'utf-8')); + } catch (error) { + versionsJson = { products: {} }; + } + + // Add product configuration + versionsJson.products[product] = { + versions: Object.keys(allVersionData).sort((a, b) => { + if (a === 'next') return -1; + if (b === 'next') return 1; + return b.localeCompare(a); // Reverse sort for versions + }), + defaultVersion: 'next' + }; + + // Write updated files + fs.writeFileSync(docsJsonPath, JSON.stringify(docsJson, null, 2)); + fs.writeFileSync(versionsJsonPath, JSON.stringify(versionsJson, null, 2)); + + console.log('✅ Updated docs.json and versions.json'); +} + +/** + * Migrate all versions from a Docusaurus repository + */ +async function migrateAllVersions(repositoryPath, targetDirectory, product = 'generic', options = {}) { + const { updateNavigation = false } = options; + + if (!targetDirectory) { + throw new Error('Target directory is required'); + } + + console.log(`=== Migrating All Versions for ${product.toUpperCase()} ===\n`); + + // Expand ~ to home directory if present + if (repositoryPath.startsWith('~/')) { + repositoryPath = repositoryPath.replace('~', process.env.HOME); + } + if (targetDirectory.startsWith('~/')) { + targetDirectory = targetDirectory.replace('~', process.env.HOME); + } + + const sourceBase = path.join(repositoryPath, 'versioned_docs'); + const currentDocsPath = path.join(repositoryPath, 'docs'); + const targetBase = targetDirectory; + + console.log(`Debug: Repository path: ${repositoryPath}`); + console.log(`Debug: Source base: ${sourceBase}`); + console.log(`Debug: Current docs: ${currentDocsPath}`); + console.log(`Debug: Target base: ${targetBase}\n`); + + const allVersionData = {}; + + // 1. Process versioned docs + if (fs.existsSync(sourceBase)) { + const versions = fs.readdirSync(sourceBase) + .filter(d => d.startsWith('version-')) + .map(d => d.replace('version-', '')); + + console.log(`Found versions: ${versions.join(', ')}`); + + for (const version of versions) { + console.log(`\n--- Processing ${version} ---`); + const sourceDir = path.join(sourceBase, `version-${version}`); + const targetDir = path.join(targetBase, version); + + const files = await processDirectory(sourceDir, targetDir, version, product); + allVersionData[version] = files; + + console.log(`✅ Converted ${files.length} files for ${version}`); + } + } + + // 2. Process current docs as 'next' version + if (fs.existsSync(currentDocsPath)) { + console.log(`\n--- Processing current docs as 'next' ---`); + const targetDir = path.join(targetBase, 'next'); + + const files = await processDirectory(currentDocsPath, targetDir, 'next', product); + allVersionData['next'] = files; + + console.log(`✅ Converted ${files.length} files for 'next'`); + } + + // 3. Update navigation (only if explicitly requested) + if (updateNavigation) { + console.log(`\n--- Updating navigation files ---`); + await updateDocsJson(allVersionData, product); + } else { + console.log(`\n--- Skipping navigation update (disabled) ---`); + } + + console.log(`\n🎉 Migration complete!`); + console.log(`📁 Files created in: ${targetBase}`); + console.log(`📋 Navigation updated in docs.json and versions.json`); + + return allVersionData; +} + +/** + * Main interactive flow + */ +async function main() { + console.log('=== Docusaurus to Mintlify Converter ===\n'); + + // Check for command line arguments for non-interactive mode + const args = process.argv.slice(2); + if (args.length >= 3) { + const [repoPath, targetDirectory, product, ...restArgs] = args; + let updateNavigation = false; + + // Parse additional arguments + for (let i = 0; i < restArgs.length; i++) { + if (restArgs[i] === '--update-nav') { + updateNavigation = true; + } + } + + console.log('Running in non-interactive mode...'); + console.log(`Repository: ${repoPath}`); + console.log(`Target directory: ${targetDirectory}`); + console.log(`Product: ${product || 'generic'}`); + console.log(`Update navigation: ${updateNavigation}`); + + await migrateAllVersions(repoPath, targetDirectory, product || 'generic', { updateNavigation }); + return; + } else if (args.length > 0 && args.length < 3) { + console.error('Error: Not enough arguments'); + console.error('Usage: node migrate-docusaurus.js [product] [--update-nav]'); + console.error('Example: node migrate-docusaurus.js ~/repos/cosmos-sdk-docs ./tmp/sdk sdk'); + process.exit(1); + } + + console.log('Migration options:'); + console.log('1. Migrate single version (original behavior)'); + console.log('2. Migrate all versions from repository'); + console.log('Enter choice (1 or 2):'); + + const choice = await prompt('> '); + + if (choice.trim() === '2') { + console.log('\nEnter repository path:'); + const repoPath = await prompt('> '); + + console.log('\nEnter target directory:'); + let targetDirectory = (await prompt('> ')).trim(); + if (!targetDirectory) { + console.error('Error: Target directory is required'); + process.exit(1); + } + + console.log('\nEnter product name (e.g., sdk, ibc, evm):'); + const product = (await prompt('> ')).trim() || 'generic'; + + console.log('\nUpdate navigation files? (y/n):'); + const updateNav = (await prompt('> ')).trim().toLowerCase() === 'y'; + + await migrateAllVersions(repoPath.trim(), targetDirectory, product, { updateNavigation: updateNav }); + rl.close(); + return; + } + + // Original single-version flow + console.log('Enter source directory:'); + let sourceBase = await prompt('> '); + sourceBase = sourceBase.trim(); + + // List available versions + if (fs.existsSync(sourceBase)) { + const versions = fs.readdirSync(sourceBase) + .filter(d => d.startsWith('version-')) + .map(d => d.replace('version-', '')); + + console.log(`\nAvailable versions: ${versions.join(', ')}`); + console.log('Enter version to convert:'); + const versionInput = await prompt('> '); + const sourceVersion = `version-${versionInput.trim()}`; + const sourceDir = path.join(sourceBase, sourceVersion); + + if (!fs.existsSync(sourceDir)) { + console.error(`Source directory not found: ${sourceDir}`); + process.exit(1); + } + + // Get target directory + console.log('\nEnter target directory:'); + let targetDir = await prompt('> '); + targetDir = targetDir.trim(); + + // Confirm before proceeding + console.log('\n=== Conversion Summary ==='); + console.log(`Source: ${sourceDir}`); + console.log(`Target: ${targetDir}`); + console.log(`Version: v${versionInput.trim()}`); + console.log('\nProceed with conversion? (y/n)'); + + const confirm = await prompt('> '); + if (confirm.toLowerCase() !== 'y') { + console.log('Conversion cancelled'); + process.exit(0); + } + + // Get product name + console.log('\nEnter product name:'); + const productName = (await prompt('> ')).trim() || 'generic'; + + // Process files + console.log('\nProcessing files...\n'); + const convertedFiles = await processDirectory(sourceDir, targetDir, `v${versionInput.trim()}`, productName); + + console.log(`\n✅ Successfully converted ${convertedFiles.length} files`); + + // Create single-version data structure for navigation update + const singleVersionData = {}; + singleVersionData[`v${versionInput.trim()}`] = convertedFiles; + + // Optionally update navigation + await updateDocsJson(singleVersionData, productName); + + } else { + console.error(`Source directory not found: ${sourceBase}`); + process.exit(1); + } + + rl.close(); +} + +// Export functions for use in other modules +export { + convertDocusaurusToMintlify, + processDirectory, + convertAdmonitions, + parseDocusaurusFrontmatter, + fixMDXIssues, + migrateAllVersions, + updateDocsJson, + resolveSidebarPositionConflicts, + formatGoCode, + formatJavaScriptCode, + formatRustCode, + formatJsonCode +}; + +// Run if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch(console.error); +} \ No newline at end of file diff --git a/scripts/migrate-single-file.js b/scripts/migrate-single-file.js new file mode 100755 index 00000000..1271739b --- /dev/null +++ b/scripts/migrate-single-file.js @@ -0,0 +1,550 @@ +#!/usr/bin/env node + +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import matter from 'gray-matter'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Get command line arguments +const args = process.argv.slice(2); +if (args.length < 2) { + console.error('Usage: node migrate-single-file.js '); + process.exit(1); +} + +const inputFile = args[0]; +const outputFile = args[1]; + +/** + * Safely process content while preserving code blocks and inline code + */ +function safeProcessContent(content, processor) { + const codeBlocks = []; + const inlineCode = []; + + let processed = content; + + // Replace code blocks with placeholders + processed = processed.replace(/```[\s\S]*?```/g, (match) => { + const index = codeBlocks.length; + codeBlocks.push(match); + return `__CODE_BLOCK_${index}__`; + }); + + // Replace inline code with placeholders + processed = processed.replace(/`[^`\n]+`/g, (match) => { + const index = inlineCode.length; + inlineCode.push(match); + return `__INLINE_CODE_${index}__`; + }); + + // Process the content without code + processed = processor(processed); + + // Restore inline code first + for (let i = 0; i < inlineCode.length; i++) { + processed = processed.replace(`__INLINE_CODE_${i}__`, inlineCode[i]); + } + + // Restore code blocks last + for (let i = 0; i < codeBlocks.length; i++) { + processed = processed.replace(`__CODE_BLOCK_${i}__`, codeBlocks[i]); + } + + return processed; +} + +/** + * Parse Docusaurus frontmatter using gray-matter library + */ +function parseDocusaurusFrontmatter(content) { + const parsed = matter(content); + return { + frontmatter: parsed.data, + content: parsed.content + }; +} + +/** + * Extract title from content (first H1 heading) + */ +function extractTitleFromContent(content) { + const match = content.match(/^#\s+(.+)$/m); + if (match) { + return { + title: match[1].trim(), + content: content.replace(/^#\s+.+\n?/m, '').trim() + }; + } + return { title: null, content }; +} + +/** + * PASS 1: Fix malformed code blocks (whitespace before backticks, etc.) + */ +function fixMalformedCodeBlocks(content) { + // Fix code blocks with leading whitespace before backticks + // This regex finds lines with whitespace before ``` and removes the whitespace + content = content.replace(/^[ \t]+```/gm, '```'); + + // Fix unclosed code blocks by ensuring each ``` has a matching closing ``` + const lines = content.split('\n'); + let inCodeBlock = false; + let codeBlockStartLine = -1; + + for (let i = 0; i < lines.length; i++) { + if (lines[i].startsWith('```')) { + if (!inCodeBlock) { + inCodeBlock = true; + codeBlockStartLine = i; + } else { + inCodeBlock = false; + } + } + } + + // If we ended while still in a code block, add closing backticks + if (inCodeBlock) { + lines.push('```'); + } + + return lines.join('\n'); +} + +/** + * PASS 2: Convert reference syntax code blocks + */ +function convertReferenceCodeBlocks(content) { + // Handle Docusaurus reference syntax: ```lang reference\nURL\n``` + return content.replace(/```([^\n]+)\s+reference\n(https:\/\/[^\n]+)\n```/g, (match, lang, url) => { + // Preserve the URL as a comment in the code block + const commentStyle = (lang === 'python' || lang === 'bash' || lang === 'shell') ? '#' : '//'; + return `\`\`\`${lang}\n${commentStyle} Reference: ${url}\n\`\`\``; + }); +} + +/** + * PASS 3: Add expandable to long code blocks and ensure language is specified + */ +function enhanceCodeBlocks(content) { + return content.replace(/```([^\n]*)\n([\s\S]*?)\n```/g, (match, header, code) => { + // Parse header to get language and existing parameters + const headerParts = header.trim().split(/\s+/); + let lang = headerParts[0] || ''; + const hasExpandable = headerParts.includes('expandable'); + + // Detect language if not specified + if (!lang && code) { + const codeLower = code.toLowerCase(); + if (codeLower.includes('package ') || codeLower.includes('func ') || + codeLower.includes('import "') || codeLower.includes('interface{')) { + lang = 'go'; + } else if (codeLower.includes('const ') || codeLower.includes('let ') || + codeLower.includes('function ') || codeLower.includes('=> ')) { + lang = 'javascript'; + } else if (codeLower.includes('#!/bin/bash') || codeLower.includes('echo ') || + codeLower.includes('npm ') || codeLower.includes('yarn ')) { + lang = 'bash'; + } else if (codeLower.includes('def ') || codeLower.includes('class ') || + codeLower.includes('import ') && codeLower.includes('from ')) { + lang = 'python'; + } else if (code.trim().startsWith('{') && code.includes('"')) { + lang = 'json'; + } else if (codeLower.includes('message ') || codeLower.includes('service ')) { + lang = 'protobuf'; + } + } + + // Count lines to determine if expandable is needed + const lineCount = code.split('\n').length; + const needsExpandable = lineCount > 10 && !hasExpandable; + + // Build new header + let newHeader = '```'; + if (lang) { + newHeader += lang; + } + if (needsExpandable || hasExpandable) { + newHeader += ' expandable'; + } + + return `${newHeader}\n${code}\n\`\`\``; + }); +} + +/** + * PASS 4: Fix inline code and curly brackets + */ +function fixInlineCodeAndBrackets(content) { + // Protect existing code blocks and inline code first + const codeBlocks = []; + const inlineCode = []; + + // Replace code blocks with placeholders + let processed = content.replace(/```[\s\S]*?```/g, (match) => { + const index = codeBlocks.length; + codeBlocks.push(match); + return `__CODE_BLOCK_${index}__`; + }); + + // Replace existing inline code with placeholders + processed = processed.replace(/`[^`\n]+`/g, (match) => { + const index = inlineCode.length; + inlineCode.push(match); + return `__INLINE_CODE_${index}__`; + }); + + // Now fix curly brackets in tables and other places + // Match table cells with {value} patterns + processed = processed.replace(/\|([^|\n]*\{[^}]+\}[^|\n]*)\|/g, (match, cell) => { + // Add backticks around {value} patterns in table cells + const fixed = cell.replace(/(\{[^}]+\})/g, '`$1`'); + return `|${fixed}|`; + }); + + // Fix standalone {value} patterns outside of JSX/MDX components + // But avoid touching JSX comments {/* */} or component props + processed = processed.replace(/(?}])/g, '`$1`'); + + // Fix interface{} and similar Go patterns + processed = processed.replace(/\binterface\{\}/g, '`interface{}`'); + processed = processed.replace(/\bmap\[[^\]]+\]interface\{\}/g, (match) => `\`${match}\``); + + // Restore inline code + for (let i = 0; i < inlineCode.length; i++) { + processed = processed.replace(`__INLINE_CODE_${i}__`, inlineCode[i]); + } + + // Restore code blocks + for (let i = 0; i < codeBlocks.length; i++) { + processed = processed.replace(`__CODE_BLOCK_${i}__`, codeBlocks[i]); + } + + return processed; +} + +/** + * PASS 5: Convert HTML elements and fix problematic angle brackets + */ +function convertHTMLElements(content) { + // Protect code blocks and inline code first + const codeBlocks = []; + const inlineCode = []; + + let processed = content.replace(/```[\s\S]*?```/g, (match) => { + const index = codeBlocks.length; + codeBlocks.push(match); + return `__CODE_BLOCK_${index}__`; + }); + + processed = processed.replace(/`[^`\n]+`/g, (match) => { + const index = inlineCode.length; + inlineCode.push(match); + return `__INLINE_CODE_${index}__`; + }); + + // Convert HTML comments to JSX comments + processed = processed.replace(//g, '{/* $1 */}'); + processed = processed.replace(//g, ''); + + // Clean up extra newlines + content = content.replace(/\n{4,}/g, '\n\n\n'); + + return content; +} + +/** + * Generate version-appropriate frontmatter + */ +function generateFrontmatter(title, description, version) { + const frontmatter = { + title: title || 'Documentation', + description: description || `Version: ${version}` + }; + + // Generate YAML frontmatter + let yaml = '---\n'; + for (const [key, value] of Object.entries(frontmatter)) { + if (value !== null && value !== undefined) { + // Escape quotes in values + const escapedValue = String(value).replace(/"/g, '\\"'); + yaml += `${key}: "${escapedValue}"\n`; + } + } + yaml += '---\n\n'; + + return yaml; +} + +/** + * Main conversion function + */ +function convertFile(inputPath, outputPath) { + try { + // Read the input file + if (!fs.existsSync(inputPath)) { + console.error(`Input file not found: ${inputPath}`); + return false; + } + + let content = fs.readFileSync(inputPath, 'utf-8'); + + // Parse frontmatter + const { frontmatter, content: mainContent } = parseDocusaurusFrontmatter(content); + + // Extract title from content if not in frontmatter + let processedContent = mainContent; + let title = frontmatter.title || frontmatter.sidebar_label; + + if (!title) { + const extracted = extractTitleFromContent(processedContent); + title = extracted.title; + processedContent = extracted.content; + } + + // Determine version from output path + let version = 'latest'; + const versionMatch = outputPath.match(/\/(v[\d.]+)\//); + if (versionMatch) { + version = versionMatch[1]; + } + + // FIRST: Process code blocks BEFORE other conversions + // This ensures all code is properly contained in code blocks + // and won't interfere with other syntax processing + processedContent = convertCodeBlocks(processedContent); + + // NOW: Apply other conversions with code block protection + processedContent = safeProcessContent(processedContent, (content) => { + // Convert admonitions + content = convertAdmonitions(content); + + // Fix heading anchors + content = fixHeadingAnchors(content); + + // Convert tabs + content = convertTabs(content); + + // Convert internal links + const relativePath = outputPath.replace(/^.*?\/docs\//, '/'); + content = convertInternalLinks(content, relativePath); + + // Clean up Docusaurus-specific syntax + content = cleanupDocusaurusSyntax(content); + + return content; + }); + + // Generate new frontmatter + const newFrontmatter = generateFrontmatter( + title, + frontmatter.description || frontmatter.sidebar_label, + version + ); + + // Combine frontmatter and content + const finalContent = newFrontmatter + processedContent; + + // Ensure output directory exists + const outputDir = path.dirname(outputPath); + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + + // Write the output file + fs.writeFileSync(outputPath, finalContent, 'utf-8'); + + console.log(`✓ Converted: ${inputPath} → ${outputPath}`); + return true; + } catch (error) { + console.error(`✗ Error converting ${inputPath}:`, error.message); + return false; + } +} + +// Run the conversion +convertFile(inputFile, outputFile); \ No newline at end of file diff --git a/scripts/package-lock.json b/scripts/package-lock.json index 53404ca2..41277595 100644 --- a/scripts/package-lock.json +++ b/scripts/package-lock.json @@ -8,12 +8,47 @@ "name": "cosmos-docs-scripts", "version": "1.0.0", "dependencies": { - "googleapis": "^128.0.0" + "googleapis": "^128.0.0", + "gray-matter": "^4.0.3", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.5", + "unist-util-visit": "^5.0.0" }, "engines": { "node": ">=18.0.0" } }, + "node_modules/@types/debug": { + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", + "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "license": "MIT" + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -23,6 +58,25 @@ "node": ">= 14" } }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/bail": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", + "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -87,6 +141,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -104,6 +168,41 @@ } } }, + "node_modules/decode-named-character-reference": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz", + "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -157,12 +256,37 @@ "node": ">= 0.4" } }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, + "node_modules/extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==", + "license": "MIT", + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -307,6 +431,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/gray-matter": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", + "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==", + "license": "MIT", + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "engines": { + "node": ">=6.0" + } + }, "node_modules/gtoken": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", @@ -357,6 +496,27 @@ "node": ">= 14" } }, + "node_modules/is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", @@ -369,6 +529,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/json-bigint": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", @@ -399,6 +572,25 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/longest-streak": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", + "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -408,6 +600,520 @@ "node": ">= 0.4" } }, + "node_modules/mdast-util-from-markdown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz", + "integrity": "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-phrasing": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz", + "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-markdown": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", + "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "longest-streak": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz", + "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", + "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", + "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-space": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", + "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-combine-extensions": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-string": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz", + "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -461,6 +1167,37 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/remark-parse": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz", + "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-stringify": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz", + "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-to-markdown": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -481,6 +1218,19 @@ ], "license": "MIT" }, + "node_modules/section-matter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz", + "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==", + "license": "MIT", + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -553,12 +1303,111 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "license": "BSD-3-Clause" + }, + "node_modules/strip-bom-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz", + "integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", "license": "MIT" }, + "node_modules/trough": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz", + "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/unified": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", + "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "bail": "^2.0.0", + "devlop": "^1.0.0", + "extend": "^3.0.0", + "is-plain-obj": "^4.0.0", + "trough": "^2.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz", + "integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz", + "integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/url-template": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz", @@ -578,6 +1427,34 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", + "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -593,6 +1470,16 @@ "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/scripts/package.json b/scripts/package.json index ba3e277c..f6ed56a3 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -16,9 +16,14 @@ "parse-changelog": "node parse-evm-changelog.js" }, "dependencies": { - "googleapis": "^128.0.0" + "googleapis": "^128.0.0", + "gray-matter": "^4.0.3", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.5", + "unist-util-visit": "^5.0.0" }, "engines": { "node": ">=18.0.0" } -} \ No newline at end of file +} diff --git a/tmp/changelog.md b/tmp/changelog.md deleted file mode 100644 index 4e3ad482..00000000 --- a/tmp/changelog.md +++ /dev/null @@ -1,88 +0,0 @@ -# CHANGELOG - -## UNRELEASED - -### DEPENDENCIES - -### BUG FIXES - -- [\#471](https://github.com/cosmos/evm/pull/471) Notify new block for mempool in time. -- [\#492](https://github.com/cosmos/evm/pull/492) Duplicate case switch to avoid empty execution block - -### IMPROVEMENTS - -- [\#467](https://github.com/cosmos/evm/pull/467) Replace GlobalEVMMempool by passing to JSONRPC on initiate. -- [\#352](https://github.com/cosmos/evm/pull/352) Remove the creation of a Geth EVM instance, stateDB during the AnteHandler balance check. - -### FEATURES - -- [\#346](https://github.com/cosmos/evm/pull/346) Add eth_createAccessList method and implementation - -### STATE BREAKING - -### API-BREAKING - -- [\#477](https://github.com/cosmos/evm/pull/477) Refactor precompile constructors to accept keeper interfaces instead of concrete implementations, breaking the existing `NewPrecompile` function signatures. - -## v0.4.1 - -### DEPENDENCIES - -- [\#459](https://github.com/cosmos/evm/pull/459) Update `cosmossdk.io/log` to `v1.6.1` to support Go `v1.25.0+`. -- [\#435](https://github.com/cosmos/evm/pull/435) Update Cosmos SDK to `v0.53.4` and CometBFT to `v0.38.18`. - -### BUG FIXES - -- [\#179](https://github.com/cosmos/evm/pull/179) Fix compilation error in server/start.go -- [\#245](https://github.com/cosmos/evm/pull/245) Use PriorityMempool with signer extractor to prevent missing signers error in tx execution -- [\#289](https://github.com/cosmos/evm/pull/289) Align revert reason format with go-ethereum (return hex-encoded result) -- [\#291](https://github.com/cosmos/evm/pull/291) Use proper address codecs in precompiles for bech32/hex conversion -- [\#296](https://github.com/cosmos/evm/pull/296) Add sanity checks to trace_tx RPC endpoint -- [\#316](https://github.com/cosmos/evm/pull/316) Fix estimate gas to handle missing fields for new transaction types -- [\#330](https://github.com/cosmos/evm/pull/330) Fix error propagation in BlockHash RPCs and address test flakiness -- [\#332](https://github.com/cosmos/evm/pull/332) Fix non-determinism in state transitions -- [\#350](https://github.com/cosmos/evm/pull/350) Fix p256 precompile test flakiness -- [\#376](https://github.com/cosmos/evm/pull/376) Fix precompile initialization for local node development script -- [\#384](https://github.com/cosmos/evm/pull/384) Fix debug_traceTransaction RPC failing with block height mismatch errors -- [\#441](https://github.com/cosmos/evm/pull/441) Align precompiles map with available static check to Prague. -- [\#452](https://github.com/cosmos/evm/pull/452) Cleanup unused cancel function in filter. -- [\#454](https://github.com/cosmos/evm/pull/454) Align multi decode functions instead of string contains check in HexAddressFromBech32String. -- [\#468](https://github.com/cosmos/evm/pull/468) Add pagination flags to `token-pairs` to improve query flexibility. - -### IMPROVEMENTS - -- [\#294](https://github.com/cosmos/evm/pull/294) Enforce single EVM transaction per Cosmos transaction for security -- [\#299](https://github.com/cosmos/evm/pull/299) Update dependencies for security and performance improvements -- [\#307](https://github.com/cosmos/evm/pull/307) Preallocate EVM access_list for better performance -- [\#317](https://github.com/cosmos/evm/pull/317) Fix EmitApprovalEvent to use owner address instead of precompile address -- [\#345](https://github.com/cosmos/evm/pull/345) Fix gas cap calculation and fee rounding errors in ante handler benchmarks -- [\#347](https://github.com/cosmos/evm/pull/347) Add loop break labels for optimization -- [\#370](https://github.com/cosmos/evm/pull/370) Use larger CI runners for resource-intensive tests -- [\#373](https://github.com/cosmos/evm/pull/373) Apply security audit patches -- [\#377](https://github.com/cosmos/evm/pull/377) Apply audit-related commit 388b5c0 -- [\#382](https://github.com/cosmos/evm/pull/382) Post-audit security fixes (batch 1) -- [\#388](https://github.com/cosmos/evm/pull/388) Post-audit security fixes (batch 2) -- [\#389](https://github.com/cosmos/evm/pull/389) Post-audit security fixes (batch 3) -- [\#392](https://github.com/cosmos/evm/pull/392) Post-audit security fixes (batch 5) -- [\#398](https://github.com/cosmos/evm/pull/398) Post-audit security fixes (batch 4) -- [\#442](https://github.com/cosmos/evm/pull/442) Prevent nil pointer by checking error in gov precompile FromResponse. -- [\#387](https://github.com/cosmos/evm/pull/387) (Experimental) EVM-compatible appside mempool -- [\#476](https://github.com/cosmos/evm/pull/476) Add revert error e2e tests for contract and precompile calls - -### FEATURES - -- [\#253](https://github.com/cosmos/evm/pull/253) Add comprehensive Solidity-based end-to-end tests for precompiles -- [\#301](https://github.com/cosmos/evm/pull/301) Add 4-node localnet infrastructure for testing multi-validator setups -- [\#304](https://github.com/cosmos/evm/pull/304) Add system test framework for integration testing -- [\#344](https://github.com/cosmos/evm/pull/344) Add txpool RPC namespace stubs in preparation for app-side mempool implementation -- [\#440](https://github.com/cosmos/evm/pull/440) Enforce app creator returning application implement AppWithPendingTxStream in build time. - -### STATE BREAKING - -### API-BREAKING - -- [\#456](https://github.com/cosmos/evm/pull/456) Remove non–go-ethereum JSON-RPC methods to align with Geth’s surface -- [\#443](https://github.com/cosmos/evm/pull/443) Move `ante` logic from the `evmd` Go package to the `evm` package to -be exported as a library. -- [\#422](https://github.com/cosmos/evm/pull/422) Align function and package names for consistency. -- [\#305](https://github.com/cosmos/evm/pull/305) Remove evidence precompile due to lack of use cases diff --git a/tmp/release-notes.mdx b/tmp/release-notes.mdx deleted file mode 100644 index 4fd9e370..00000000 --- a/tmp/release-notes.mdx +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: "Release Notes" -description: "Release history and changelog for Cosmos EVM" ---- - - - This page tracks all releases and changes from the [cosmos/evm](https://github.com/cosmos/evm) repository. - For the latest development updates, see the [UNRELEASED](https://github.com/cosmos/evm/blob/main/CHANGELOG.md#unreleased) section. - - - -## Features - -* Add comprehensive Solidity-based end-to-end tests for precompiles ([#253](https://github.com/cosmos/evm/pull/253)) -* Add 4-node localnet infrastructure for testing multi-validator setups ([#301](https://github.com/cosmos/evm/pull/301)) -* Add system test framework for integration testing ([#304](https://github.com/cosmos/evm/pull/304)) -* Add txpool RPC namespace stubs in preparation for app-side mempool implementation ([#344](https://github.com/cosmos/evm/pull/344)) -* Enforce app creator returning application implement AppWithPendingTxStream in build time. ([#440](https://github.com/cosmos/evm/pull/440)) - -## Improvements - -* Enforce single EVM transaction per Cosmos transaction for security ([#294](https://github.com/cosmos/evm/pull/294)) -* Update dependencies for security and performance improvements ([#299](https://github.com/cosmos/evm/pull/299)) -* Preallocate EVM access_list for better performance ([#307](https://github.com/cosmos/evm/pull/307)) -* Fix EmitApprovalEvent to use owner address instead of precompile address ([#317](https://github.com/cosmos/evm/pull/317)) -* Fix gas cap calculation and fee rounding errors in ante handler benchmarks ([#345](https://github.com/cosmos/evm/pull/345)) -* Add loop break labels for optimization ([#347](https://github.com/cosmos/evm/pull/347)) -* Use larger CI runners for resource-intensive tests ([#370](https://github.com/cosmos/evm/pull/370)) -* Apply security audit patches ([#373](https://github.com/cosmos/evm/pull/373)) -* Apply audit-related commit 388b5c0 ([#377](https://github.com/cosmos/evm/pull/377)) -* Post-audit security fixes (batch 1) ([#382](https://github.com/cosmos/evm/pull/382)) -* Post-audit security fixes (batch 2) ([#388](https://github.com/cosmos/evm/pull/388)) -* Post-audit security fixes (batch 3) ([#389](https://github.com/cosmos/evm/pull/389)) -* Post-audit security fixes (batch 5) ([#392](https://github.com/cosmos/evm/pull/392)) -* Post-audit security fixes (batch 4) ([#398](https://github.com/cosmos/evm/pull/398)) -* Prevent nil pointer by checking error in gov precompile FromResponse. ([#442](https://github.com/cosmos/evm/pull/442)) -* (Experimental) EVM-compatible appside mempool ([#387](https://github.com/cosmos/evm/pull/387)) -* Add revert error e2e tests for contract and precompile calls ([#476](https://github.com/cosmos/evm/pull/476)) - -## Bug Fixes - -* Fix compilation error in server/start.go ([#179](https://github.com/cosmos/evm/pull/179)) -* Use PriorityMempool with signer extractor to prevent missing signers error in tx execution ([#245](https://github.com/cosmos/evm/pull/245)) -* Align revert reason format with go-ethereum (return hex-encoded result) ([#289](https://github.com/cosmos/evm/pull/289)) -* Use proper address codecs in precompiles for bech32/hex conversion ([#291](https://github.com/cosmos/evm/pull/291)) -* Add sanity checks to trace_tx RPC endpoint ([#296](https://github.com/cosmos/evm/pull/296)) -* Fix estimate gas to handle missing fields for new transaction types ([#316](https://github.com/cosmos/evm/pull/316)) -* Fix error propagation in BlockHash RPCs and address test flakiness ([#330](https://github.com/cosmos/evm/pull/330)) -* Fix non-determinism in state transitions ([#332](https://github.com/cosmos/evm/pull/332)) -* Fix p256 precompile test flakiness ([#350](https://github.com/cosmos/evm/pull/350)) -* Fix precompile initialization for local node development script ([#376](https://github.com/cosmos/evm/pull/376)) -* Fix debug_traceTransaction RPC failing with block height mismatch errors ([#384](https://github.com/cosmos/evm/pull/384)) -* Align precompiles map with available static check to Prague. ([#441](https://github.com/cosmos/evm/pull/441)) -* Cleanup unused cancel function in filter. ([#452](https://github.com/cosmos/evm/pull/452)) -* Align multi decode functions instead of string contains check in HexAddressFromBech32String. ([#454](https://github.com/cosmos/evm/pull/454)) -* Add pagination flags to `token-pairs` to improve query flexibility. ([#468](https://github.com/cosmos/evm/pull/468)) - -## Dependencies - -* Update `cosmossdk.io/log` to `v1.6.1` to support Go `v1.25.0+`. ([#459](https://github.com/cosmos/evm/pull/459)) -* Update Cosmos SDK to `v0.53.4` and CometBFT to `v0.38.18`. ([#435](https://github.com/cosmos/evm/pull/435)) - -## API Breaking - -* Remove non–go-ethereum JSON-RPC methods to align with Geth’s surface ([#456](https://github.com/cosmos/evm/pull/456)) -* Move `ante` logic from the `evmd` Go package to the `evm` package to ([#443](https://github.com/cosmos/evm/pull/443)) -* Align function and package names for consistency. ([#422](https://github.com/cosmos/evm/pull/422)) -* Remove evidence precompile due to lack of use cases ([#305](https://github.com/cosmos/evm/pull/305)) - -## API Breaking - -* Remove non–go-ethereum JSON-RPC methods to align with Geth’s surface ([#456](https://github.com/cosmos/evm/pull/456)) -* Move `ante` logic from the `evmd` Go package to the `evm` package to ([#443](https://github.com/cosmos/evm/pull/443)) -* Align function and package names for consistency. ([#422](https://github.com/cosmos/evm/pull/422)) -* Remove evidence precompile due to lack of use cases ([#305](https://github.com/cosmos/evm/pull/305)) - - ---- - - - - See the complete changelog on GitHub - - - Report bugs or request features - - diff --git a/versions.json b/versions.json index bc2eb9b2..cdb023f2 100644 --- a/versions.json +++ b/versions.json @@ -11,19 +11,23 @@ "sdk": { "versions": [ "next", - "v0.53", - "v0.50", - "v0.47" + "0.53", + "0.5", + "0.47" ], - "defaultVersion": "v0.53" + "defaultVersion": "next" }, "ibc": { "versions": [ "next", - "v0.2.0" + "v8.5.x", + "v7.8.x", + "v6.3.x", + "v5.4.x", + "v4.6.x", + "v10.1.x" ], - "defaultVersion": "next", - "nextDev": "v0.3.0" + "defaultVersion": "next" } } -} +} \ No newline at end of file