### Simulation Operations Setup Example (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md Demonstrates how to set up simulation operations for a module, specifically the x/gov module, using a minimal application. This example highlights the use of `depinject` and `AppConfig` for configuring the simulation environment. ```Go package slashing_test import ( "testing" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/simapp/config" "github.com/cosmos/cosmos-sdk/types/module/simulation" ) func TestSlashingSimulation(t *testing.T) { // Create a new simulation app configuration cfg := config.NewConfig(true) // Use AppConfig configurator for inline configuration cfg.SetAppConfig(simapp.NewAppConfig( simapp.SetChainID("sim-1"), simapp.SetPruning("default"), simapp.SetMinGasPrices("0stake"), simapp.SetInterChainModules(), simapp.SetTxIndex(true), // ... other configurations ... )) // Run the simulation ssimulation.Simulate(t, slashingsimulation.AppModuleBasic{}, simapp.NewSimApp(cfg), cfg.GetAppConfig(), simulation.DefaultParams(), // ... other simulation parameters ... ) } ``` -------------------------------- ### Write a Basic System Test in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md An example of a basic Go system test file. It includes the necessary build tag, package declaration, import statements, and a test function that initializes the chain, queries the bank module's total supply, and logs the raw response. ```go //go:build system_test package systemtests import ( "testing" ) func TestQueryTotalSupply(t *testing.T) { sut.ResetChain(t) sut.StartChain(t) cli := NewCLIWrapper(t, sut, verbose) raw := cli.CustomQuery("q", "bank", "total-supply") t.Log("### got: " + raw) } ``` -------------------------------- ### Integration Test Setup Helper (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md Provides helper functions for setting up integration tests within the Cosmos SDK. These helpers simplify the process of creating test environments where modules interact without mocked dependencies. ```Go package integration_test import ( "testing" "github.com/cosmos/cosmos-sdk/testutil/integration" "github.com/cosmos/cosmos-sdk/testutil/network" ) func TestIntegrationExample(t *testing.T) { // Create a new network configuration for integration tests cfg := network.DefaultConfig() // ... configure the network as needed ... // Build the test network net := integration.NewTestNetwork(t, cfg) defer net.Cleanup() // Perform integration tests using the test network // ... interact with modules, assert results ... } ``` -------------------------------- ### Example Integration Test Case (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md A practical example of an integration test in the Cosmos SDK. This snippet demonstrates how to use the `testutil/integration` helpers to set up a test environment and interact with module services. ```Go package integration_test import ( "testing" "github.com/cosmos/cosmos-sdk/testutil/integration" "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/require" ) func TestSendCoinsIntegration(t *testing.T) { cfg := network.DefaultConfig() net := integration.NewTestNetwork(t, cfg) defer net.Cleanup() // Get client context clientCtx := net.Validators[0].ClientCtx // Create a MsgSend transaction fromAddr := net.Validators[0].Address toAddr := net.Validators[1].Address coins := "100stake" msg := types.NewMsgSend(fromAddr, toAddr, sdk.NewCoins(sdk.MustParseCoinsNormalized(coins))) // Broadcast the transaction and assert success _, err := integration.BroadcastTx(clientCtx, net.TxConfig, msg) require.NoError(t, err) // Verify the state changes // ... query balances and assert ... } ``` -------------------------------- ### Golang Pseudocode Algorithm Example Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/spec/SPEC_STANDARD.md An example of how to represent an algorithm using Golang functions for pseudocode. This demonstrates a simple get function for a cache, including conditional logic. ```go func get( store CacheKVStore, key Key) Value { value = store.cache.get(Key) if (value !== null) { return value } else { value = store.parent.get(key) store.cache.set(key, value) return value } } ``` -------------------------------- ### Set up App Simulator Manager (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/14-simulator.md This section details the setup of the SimulationManager at the application level, which is crucial for simulation test files. The SimulationManager is constructed using modules from ModuleManager and its RegisterStoreDecoders method is called. ```Go type CoolApp struct { // ... other fields sm *module.SimulationManager } // NewCoolApp constructor example func NewCoolApp(logger log.Logger, db dbm.DB, traceStore sim.TraceStore) *CoolApp { // ... other app initialization ... // Initialize the SimulationManager app.sm = module.NewSimulationManager(app.ModuleManager.Modules) // Register store decoders app.sm.RegisterStoreDecoders() // ... rest of the constructor ... return app } // SimulationManager implements the SimulationApp interface func (app *SimApp) SimulationManager() *module.SimulationManager { return app.sm } ``` -------------------------------- ### Simulation Operations Example (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md This Go code snippet shows an example of simulation operations for the x/gov module. Simulations use a minimal application built with depinject to test module behaviors under randomized conditions. ```Go package simulation_test import ( "math/rand" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/module/simulation" "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) func ExampleGovSimulateMsgSubmitProposal(r *rand.Rand, cdc *codec.ProtoCodec, app simulation.App) { // Setup simulation parameters and context appParams := simulation.AppParams{} ctx := simulation.NewSimulatedContext(r, cdc, app, appParams) // Get operation op := simulation.OperationWeightList{ {Wgt: simulation.DefaultWeightMsgSubmitProposal, Content: simulation.NewWeightedOperation( simulation.DefaultWeightMsgSubmitProposal, simulation.MsgJSONEncoderFunc(cdc.MarshalJSON), simulation.MsgJSONDecoderFunc(cdc.UnmarshalJSON), ), } // ... other operations ... // Run the simulation operation operation := simulation.Operations{}.NewOperation(ctx, appParams, r, cdc, app) // Perform assertions on the simulation results // ... } ``` -------------------------------- ### Install and Initialize tmkms (Bash) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/user/run-node/06-run-production.md This snippet demonstrates how to install the tmkms binary from source or using cargo, initialize its configuration, and generate a new softsign key. It requires git and Rust/Cargo to be installed. The output includes the initialization of the configuration and the generation of a secret key. ```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 ``` ```bash cargo install tmkms --features=softsign tmkms init config tmkms softsign keygen ./config/secrets/secret_connection_key ``` -------------------------------- ### KVStore Iterator Example Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/learn/advanced/04-store.md An example from the bank module's keeper demonstrating how to use the Iterator method of a KVStore to iterate over a range of keys, specifically for listing all account balances. ```go func (k Keeper) IterateAccounts(ctx Context) (accs []types.AccountI) { store := ctx.KVStore(k.storeKey) iterator := store.Iterator(nil, nil) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { // ... process account ... } return accs } ``` -------------------------------- ### Cosmos SDK Application CLI Setup (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/learn/beginner/00-app-anatomy.md Illustrates the setup of a Cosmos SDK application's command-line interface (CLI) within its main.go file. This includes defining the main function, adding generic commands, and integrating query and transaction commands from various modules. It's crucial for enabling user interaction with the full-node client. ```go package main import ( "fmt" "os" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/pruning" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/gaia/v7/app" "github.com/spf13/cobra" ) func main() { encodingConfig := app.MakeEncodingConfig() rootCmd := &cobra.Command{ Use: "gaiad", Short: "All-in-one daemon for Gaia Hub", PersistentPreRunE: server.PersistentPreRunEFn(encodingConfig), } rootCmd.AddCommand(version.Cmd) rootCmd.AddCommand(debug.Cmd()) rootCmd.AddCommand(pruning.Cmd(store.NewStoreLoader(app.NewGaiaApp(app.GetWasmEnabled())))) // Add --home' flag rootCmd.PersistentFlags().StringVar( &clientHome, "home", os.ExpandEnv("$HOME"), "directory for config and data", ) // Set config clientConfig.Cmd.Root = rootCmd // Build genesis file genesisCmd.Root = rootCmd // Build keys command keys.Cmd = keys.KeysCmd() // Add --home' flag to keys command keys.Cmd.PersistentFlags().StringVar( &clientHome, "home", os.ExpandEnv("$HOME"), "directory for config and data", ) rootCmd.AddCommand(keys.Cmd) // Build query command queryCmd := client.QueryCmd() queryCmd.AddCommand(cli.GetCommands(app.GetSubCmds()...)...) rootCmd.AddCommand(queryCmd) // Build tx command xCmd := tx.TxCmd() xCmd.AddCommand(cli.GetCommands(app.GetTxCommands()...)...) rootCmd.AddCommand(xCmd) // Build rest server command serverCmd := server.StartCmd(app.NewGaiaApp(app.GetWasmEnabled()), encodingConfig) serverCmd.AddCommand( config.Cmd(), flags.LineBreakLFlag(), flags.FlagBase64FilterFlag(), ) // Build grant-app-role command grantAppRoleCmd := cli.GrantAppRoleCmd() rootCmd.AddCommand(grantAppRoleCmd) if err := rootCmd.Execute(); err != nil { fmt.Fprintf(os.Stderr, "%+v\n", err) os.Exit(1) } } ``` -------------------------------- ### Parse JSON Responses with gjson in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Example of using the gjson library in Go to parse and assert values from a JSON response. It demonstrates how to extract array elements and specific values based on conditions, comparing them against expected values. ```go raw := cli.CustomQuery("q", "bank", "total-supply") exp := map[string]int64{ "stake": int64(500000000 * sut.nodesCount), "testtoken": int64(1000000000 * sut.nodesCount), } require.Len(t, gjson.Get(raw, "supply").Array(), len(exp), raw) for k, v := range exp { got := gjson.Get(raw, fmt.Sprintf("supply.#(denom==%q).amount", k)).Int() assert.Equal(t, v, got, raw) } ``` -------------------------------- ### Root Command Setup in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/learn/advanced/07-cli.md This Go code snippet demonstrates the setup of the root command for an application using the Cobra CLI framework. It includes adding persistent flags, a PreRun function, and essential subcommands for basic application functionality. It also shows how to initialize the application's configuration. ```go package main import ( "fmt" "os" "github.com/cosmos/cosmos-sdk/server" pruningtypes "github.com/cosmos/cosmos-sdk/server/pruning/types" cmm "github.com/cometbft/cometbft/cmd/cometbft/commands" cmdcfg "github.com/cometbft/cometbft/config" // ... other imports ) var ( rootCmd *cobra.Command ) func init() { rootCmd = &cobra.Command{ Use: "simd", Short: "The CometBFT SDK application", // If we are expecting a subcommand, then we don't need to run the pre run function. PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // Set client context // ... // Enable or disable metric flushing if err := server.InterceptFn(); err != nil { return err } server.SetCmd(cmd) // ... other initializations return nil }, } // ... add subcommands like status, keys, server, tx, query ... } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func initAppConfig() (appOpts server.AppCreateFn) { return func(app *runtime.App, baseappOptions ...func(*baseapp.BaseApp)) { // ... config initialization ... } } ``` -------------------------------- ### Initialize BaseApp and Store Keys in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/spec/store/README.md Illustrates the initialization of a `BaseApp` instance and the creation of various store keys (KV, Transient, Memory) within a Cosmos SDK application. It shows how to mount these stores to the application, enabling modules to access their respective KVStores. ```go func NewApp(...) Application { // ... bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) // ... keys := sdk.NewKVStoreKeys(...) transientKeys := sdk.NewTransientStoreKeys(...) memKeys := sdk.NewMemoryStoreKeys(...) // ... // initialize stores app.MountKVStores(keys) app.MountTransientStores(transientKeys) app.MountMemoryStores(memKeys) // ... } ``` -------------------------------- ### Example Module Registration (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-057-app-wiring.md An example demonstrating how to register a bank module using the `appmodule.Register` API. It shows how to provide protobuf types and dependency providers, including the module's configuration object and the necessary input/output structures for the provider function. ```go package main import ( "github.com/cosmos/cosmos-sdk/core/appmodule" "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/x/auth" bankmodulev1 "github.com/cosmos/cosmos-sdk/x/bank/types" types "path/to/your/generated/types" ) // Assuming appmodule and auth are imported elsewhere func init() { appmodule.Register("cosmos.bank.module.v1.Module", appmodule.Types( types.Types_tx_proto, types.Types_query_proto, types.Types_types_proto, ), appmodule.Provide( provideBankModule, ) ) } type Inputs struct { container.In AuthKeeper auth.Keeper DB ormdb.ModuleDB } type Outputs struct { Keeper bank.Keeper AppModule appmodule.AppModule } func ProvideBankModule(config *bankmodulev1.Module, inputs Inputs) (Outputs, error) { // Implementation details... return Outputs{}, nil } ``` -------------------------------- ### Cosmos SDK Application Setup (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-057-app-wiring.md Illustrates a simplified `app.go` file for a Cosmos SDK application using the new module system. It highlights the use of blank imports for module registration side-effects and the `app.Run` function to load the application configuration from YAML. ```go package main import ( // Each go package which registers a module must be imported just for side-effects // so that module implementations are registered. _ "github.com/cosmos/cosmos-sdk/x/auth/module" _ "github.com/cosmos/cosmos-sdk/x/bank/module" _ "github.com/cosmos/cosmos-sdk/x/staking/module" "github.com/cosmos/cosmos-sdk/core/app" ) // go:embed app.yaml var appConfigYAML []byte func main() { app.Run(app.LoadYAML(appConfigYAML)) } ``` -------------------------------- ### Start a Single Cosmos SDK Node Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/user/run-node/01-run-node.md This command starts a single node of the Cosmos SDK application. It's useful for initial setup and interaction with a node. Ensure the 'simd' binary is in your PATH. ```bash simd start ``` -------------------------------- ### Example: Smart Contract Address Construction (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-028-public-key-addresses.md Shows how to construct a smart contract address using multiple derivation components, including the module name, a namespace, and a specific key. It also provides an equivalent representation using a derived function. ```go smartContractAddr = Module("mySmartContractVM", smartContractsNamespace, smartContractKey}) // which equals to: smartContractAddr = Derived( Module("mySmartContractVM", smartContractsNamespace), []{smartContractKey}) ``` -------------------------------- ### Setup Hypothetical 'foo' v2 Module in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-063-core-module-api.md Demonstrates setting up a hypothetical 'foo' v2 module using ORM for state management and genesis. It defines a Keeper struct and registers services for message and query servers. The `ProvideApp` function initializes the Keeper and returns it as an `AppModule`. ```go type Keeper struct { db orm.ModuleDB evtSrv event.Service } func (k Keeper) RegisterServices(r grpc.ServiceRegistrar) { foov1.RegisterMsgServer(r, k) foov1.RegisterQueryServer(r, k) } func (k Keeper) BeginBlock(context.Context) error { return nil } func ProvideApp(config *foomodulev2.Module, evtSvc event.EventService, db orm.ModuleDB) (Keeper, appmodule.AppModule){ k := &Keeper{db: db, evtSvc: evtSvc} return k, k } ``` -------------------------------- ### Test Scenario Comment Block Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md A structured comment block used to describe the intention and flow of a test scenario, outlining the given, when, and then steps. ```go // scenario: // given a chain with a custom token on genesis // when an amount is burned // then this is reflected in the total supply ``` -------------------------------- ### Start Streaming Plugin Server (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-038-state-listening.md Launches a streaming plugin process using `plugin.NewClient`. It configures the client with handshake information, plugin map, command to execute, logger, and allowed protocols (NetRPC and GRPC). It then connects via RPC and dispenses the requested plugin. ```go func NewStreamingPlugin(name string, logLevel string) (interface{}, error) { logger := hclog.New(&hclog.LoggerOptions{ Output: hclog.DefaultOutput, Level: toHclogLevel(logLevel), Name: fmt.Sprintf("plugin.%s", name), }) // We're a host. Start by launching the streaming process. env := os.Getenv(GetPluginEnvKey(name)) client := plugin.NewClient(&plugin.ClientConfig{ HandshakeConfig: HandshakeMap[name], Plugins: PluginMap, Cmd: exec.Command("sh", "-c", env), Logger: logger, AllowedProtocols: []plugin.Protocol{ plugin.ProtocolNetRPC, plugin.ProtocolGRPC}, }) // Connect via RPC rpcClient, err := client.Client() if err != nil { return nil, err } // Request streaming plugin return rpcClient.Dispense(name) } ``` -------------------------------- ### Build and Copy System Test Binary (Shell) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Commands to build the system test binary from the current branch and copy it to the designated binaries folder. This ensures the latest code is used for testing. ```shell make test-system ``` ```shell make build mkdir -p ./tests/systemtests/binaries cp ./build/simd ./tests/systemtests/binaries/ ``` -------------------------------- ### Start Local Documentation Server Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/README.md Command to start a local development server for the documentation. This command also executes pre-build scripts to fetch necessary documentation files and post-build scripts for cleanup. ```shell npm start ``` -------------------------------- ### Unit Test Example for x/gov Keeper (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md A Go code snippet illustrating unit tests for the x/gov module's Keeper. It focuses on testing the Keeper's functionality in isolation by using mocked dependencies. ```Go package gov_test import ( "testing" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/require" ) func TestProposalMsgs(t *testing.T) { // Setup mocks and keeper instance k, ctx, _, _ := keeper.Setup(t) // Define test parameters t params := k.GetParams(ctx) proposer := testdata.AccAddress("proposer") // ... other test setup ... // Test proposal creation and processing // ... assertions ... } ``` -------------------------------- ### SimApp Chain Setup and Configuration Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/tools/cosmovisor/README.md This section demonstrates setting up a SimApp chain by checking out a specific version, building the binary, resetting the chain data, and configuring basic app settings like chain ID and keyring backend. It also includes initializing the node and modifying the genesis file. ```shell git checkout v0.47.4 make build ./build/simd tendermint unsafe-reset-all ./build/simd config chain-id test ./build/simd config keyring-backend test ./build/simd config broadcast-mode sync ./build/simd init test --chain-id test --overwrite cat <<< $(jq '.app_state.gov.params.voting_period = "20s"' $HOME/.simapp/config/genesis.json) > $HOME/.simapp/config/genesis.json ``` -------------------------------- ### Example: Concatenated Derivation Keys (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-028-public-key-addresses.md Illustrates how to create a module account address that depends on multiple derivation keys by concatenating them. This is useful for scenarios requiring combined key information. ```go btcAtomAMM := address.Module("amm", btc.Address() + atom.Address()}) ``` -------------------------------- ### Set Epochs Keeper Hooks in Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/UPGRADE_GUIDE.md Configures hooks for the epochs keeper, allowing other modules to react to epoch-related events. The example shows how to set up a multi-hook receiver, which can be extended to include hooks from other modules. ```go app.EpochsKeeper.SetHooks( epochstypes.NewMultiEpochHooks( // insert epoch hooks receivers here app.SomeOtherModule ), ) ``` -------------------------------- ### Burn Tokens via Bank TX with Go SDK Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Submits a bank burn transaction using the CLI wrapper to reduce the supply of a specific token. It requires a successful transaction hash for verification. ```go // and when txHash := cli.Run("tx", "bank", "burn", "node0", "400000mytoken") RequireTxSuccess(t, txHash) ``` -------------------------------- ### Example: Lending BTC Pool Address (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-028-public-key-addresses.md Demonstrates the creation of a specific module account address for a lending BTC pool. It utilizes the `address.Module` function with a module name and a specific BTC address derivation. ```go btcPool := address.Module("lending", btc.Address()}) ``` -------------------------------- ### Define Expected Token Balances with Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Defines a map to hold expected token balances, scaling certain token amounts based on the number of nodes in the chain. This is useful for setting up test assertions. ```go exp := map[string]int64{ "stake": int64(500000000 * sut.nodesCount), "testtoken": int64(1000000000 * sut.nodesCount), "mytoken": 1000000, } ``` -------------------------------- ### Deterministic Regression Test Example (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/build/building-modules/16-testing.md Illustrates how deterministic regression tests are written for Cosmos SDK queries annotated with `module_query_safe`. These tests ensure that query responses and gas consumption remain consistent across SDK versions. ```Go package bank_test import ( "testing" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/stretchr/testify/require" ) func TestDeterministicBalanceQuery(t *testing.T) { // Setup keeper and context k, ctx, _ := keeper.Setup(t) // Create accounts and fund them accs := testdata.CreateSimpleAccounts(2) addr1 := accs[0].Address addr2 := accs[1].Address // ... fund accounts ... // Define expected response and gas for 1000 queries expResponse := "..." expGas := uint64(10000) // Run regression test for Balance query k.Keeper.SetParams(ctx, banktypes.DefaultParams()) bankkeeper.TestBalance(t, k.Keeper, ctx, addr1, expResponse, expGas) // ... other query tests ... } ``` -------------------------------- ### gRPC Gateway Registration Example (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-063-core-module-api.md Illustrates how modules can provide gRPC gateway handler registration information. The `GrpcGatewayInfo` struct and `GrpcGatewayHandler` function type facilitate this, allowing modules to register their query services with the runtime module. ```go type GrpcGatewayInfo struct { Handlers []GrpcGatewayHandler } type GrpcGatewayHandler func(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error func ProvideGrpcGateway() GrpcGatewayInfo { return GrpcGatewayinfo { Handlers: []Handler {types.RegisterQueryHandlerClient} } } ``` -------------------------------- ### Verify Token Supply and Balance Changes with Go SDK Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Queries the total token supply and an account's balance after a transaction to verify state changes. It uses `gjson` for parsing query results and `assert` for comparisons. ```go exp["mytoken"] = 600_000 // update expected state raw = cli.CustomQuery("q", "bank", "total-supply") for k, v := range exp { got := gjson.Get(raw, fmt.Sprintf("supply.#(denom==%q).amount", k)).Int() assert.Equal(t, v, got, raw) } assert.Equal(t, int64(600_000), cli.QueryBalance(cli.GetKeyAddr("node0"), "mytoken")) ``` -------------------------------- ### Pack sdk.Msg as Any using anyutil Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/docs/learn/advanced/05-encoding.md Demonstrates how to pack an sdk.Msg into an anypb.Any using the 'cosmos-proto/anyutil' package. This method ensures compatibility with the Cosmos SDK's TypeURL conventions by omitting the 'type.googleapis.com' prefix, unlike the default 'anypb.New' function. It highlights the import change and the direct replacement of the function call. ```go import ( "fmt" "github.com/cosmos/cosmos-proto/anyutil" ) // Assuming internalMsg is an object that satisfies sdk.Msg interface // and has a Message() method returning a protobuf.Message // Example usage: // anyMsg, err := anyutil.New(internalMsg.Message().Interface()) // if err != nil { // // Handle error // } // fmt.Println(anyMsg.TypeURL) // Expected output: /cosmos.bank.v1beta1.MsgSend ``` -------------------------------- ### Run System Tests with Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Command to execute system tests using Go. It specifies read-only module mode, includes the `system_test` tag, enables verbose output, and allows specifying the number of nodes for the test. ```shell go test -mod=readonly -tags='system_test' -v ./... --run TestQueryTotalSupply --verbose --nodes-count=1 ``` -------------------------------- ### Run System Tests with Go Test Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/systemtests/GETTING_STARTED.md Command to execute system tests using the Go test runner. It specifies the read-only module mode, applies the 'system_test' build tag, enables verbose output, and targets a specific test function. ```shell go test -mod=readonly -tags='system_test' -v ./... --run TestQueryTotalSupply --verbose ``` -------------------------------- ### Cosmovisor Software Upgrade CLI Command with Auto-Download Info Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/tools/cosmovisor/README.md Example command to submit a software upgrade proposal using `gaiad`. It includes the `upgrade-info` flag, demonstrating how to embed the JSON structure for binary download configurations directly in the command. This allows cosmovisor to automatically fetch and install the specified binaries upon upgrade. ```shell > gaiad tx upgrade software-upgrade Vega \ --title Vega \ --deposit 100uatom \ --upgrade-height 7368420 \ --upgrade-info '{"binaries":{"linux/amd64":"https://github.com/cosmos/gaia/releases/download/v6.0.0-rc1/gaiad-v6.0.0-rc1-linux-amd64","linux/arm64":"https://github.com/cosmos/gaia/releases/download/v6.0.0-rc1/gaiad-v6.0.0-rc1-linux-arm64","darwin/amd64":"https://github.com/cosmos/gaia/releases/download/v6.0.0-rc1/gaiad-v6.0.0-rc1-darwin-amd64"}}' \ --summary "upgrade to Vega" \ --gas 400000 \ --from user \ --chain-id test \ --home test/val2 \ --node tcp://localhost:36657 \ --yes ``` -------------------------------- ### Initialize Cobra Root Command with Server Context Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/server/README.md Demonstrates how to set up the root Cobra command for an application, including essential pre-run handlers for initializing the client and server contexts. This ensures that all sub-commands have access to necessary configurations and utilities. ```go var ( initClientCtx = client.Context{...} rootCmd = &cobra.Command{ Use: "simd", Short: "simulation app", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { return err } return server.InterceptConfigsPreRunHandler(cmd) }, } // add root sub-commands ... ) ``` -------------------------------- ### Install Cosmovisor with Go Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/tools/cosmovisor/RELEASE_NOTES.md Installs the latest version of Cosmovisor using the Go installation command. This command fetches and installs the binary to your Go bin path, making it accessible from your terminal. ```go go install cosmossdk.io/tools/cosmovisor/cmd/cosmovisor@latest ``` -------------------------------- ### Example Query Implementation with sdk.Context Retrieval (Go) Source: https://github.com/symbioticfi/cosmos-relay-sdk/blob/main/docs/architecture/adr-021-protobuf-query-encoding.md This Go code snippet demonstrates an example implementation of the `QueryBalance` method for the bank module. It shows how to retrieve the `sdk.Context` from the incoming `context.Context` using `sdk.UnwrapSDKContext` and then use it to interact with the module's keeper. ```go type Querier struct { Keeper } func (q Querier) QueryBalance(ctx context.Context, params *types.QueryBalanceParams) (*sdk.Coin, error) { balance := q.GetBalance(sdk.UnwrapSDKContext(ctx), params.Address, params.Denom) return &balance, nil } ```