Skip to content

Commit

Permalink
[CORE-538] Reduce usage of basic_manager.ModuleBasics in favor of usi…
Browse files Browse the repository at this point in the history
…ng module.NewBasicManagerFrom... (#984)
  • Loading branch information
lcwik authored Jan 18, 2024
1 parent 126a7e7 commit a9076e9
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 54 deletions.
15 changes: 11 additions & 4 deletions protocol/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package app
import (
"context"
"encoding/json"
custommodule "github.com/dydxprotocol/v4-chain/protocol/app/module"
"io"
"math/big"
"net/http"
Expand Down Expand Up @@ -91,7 +92,6 @@ import (
"google.golang.org/grpc"

// App
"github.com/dydxprotocol/v4-chain/protocol/app/basic_manager"
"github.com/dydxprotocol/v4-chain/protocol/app/flags"
"github.com/dydxprotocol/v4-chain/protocol/app/middleware"
"github.com/dydxprotocol/v4-chain/protocol/app/prepare"
Expand Down Expand Up @@ -282,6 +282,7 @@ type App struct {
// this line is used by starport scaffolding # stargate/app/keeperDeclaration

ModuleManager *module.Manager
ModuleBasics module.BasicManager

// module configurator
configurator module.Configurator
Expand Down Expand Up @@ -1204,6 +1205,12 @@ func New(
app.ModuleManager.RegisterInvariants(app.CrisisKeeper)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
err := app.ModuleManager.RegisterServices(app.configurator)
app.ModuleBasics = module.NewBasicManagerFromManager(
app.ModuleManager,
map[string]module.AppModuleBasic{
custommodule.SlashingModuleBasic{}.Name(): custommodule.SlashingModuleBasic{},
},
)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -1282,7 +1289,7 @@ func New(
// based on execution context such as the block proposer, the logger used by the logging middleware is
// stored in a global variable and can be overwritten as necessary.
middleware.Logger = logger
app.AddRunTxRecoveryHandler(middleware.NewRunTxPanicLoggingMiddleware())
app.AddRunTxRecoveryHandler(middleware.NewRunTxPanicLoggingMiddleware(app.ModuleBasics))

// Set handlers and store loaders for upgrades.
app.setupUpgradeHandlers()
Expand Down Expand Up @@ -1499,7 +1506,7 @@ func (app *App) TxConfig() client.TxConfig {

// DefaultGenesis returns a default genesis from the registered AppModuleBasic's.
func (app *App) DefaultGenesis() map[string]json.RawMessage {
return basic_manager.ModuleBasics.DefaultGenesis(app.appCodec)
return app.ModuleBasics.DefaultGenesis(app.appCodec)
}

// getSubspace returns a param subspace for a given module name.
Expand All @@ -1523,7 +1530,7 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig
nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)

// Register grpc-gateway routes for all modules.
module.NewBasicManagerFromManager(app.ModuleManager, nil).RegisterGRPCGatewayRoutes(
app.ModuleBasics.RegisterGRPCGatewayRoutes(
clientCtx,
apiSvr.GRPCGatewayRouter,
)
Expand Down
7 changes: 3 additions & 4 deletions protocol/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ import (
ica "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts"
"github.com/cosmos/ibc-go/v8/modules/apps/transfer"
ibc "github.com/cosmos/ibc-go/v8/modules/core"
ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint"
"github.com/dydxprotocol/v4-chain/protocol/app/basic_manager"
"github.com/dydxprotocol/v4-chain/protocol/app/flags"
custommodule "github.com/dydxprotocol/v4-chain/protocol/app/module"
"github.com/dydxprotocol/v4-chain/protocol/mocks"
Expand Down Expand Up @@ -196,7 +194,6 @@ func TestModuleBasics(t *testing.T) {
evidencemodule.AppModuleBasic{},
feegrantmodule.AppModuleBasic{},
ibc.AppModuleBasic{},
ibctm.AppModuleBasic{},
ica.AppModuleBasic{},
upgrade.AppModuleBasic{},
transfer.AppModuleBasic{},
Expand All @@ -219,8 +216,10 @@ func TestModuleBasics(t *testing.T) {
epochsmodule.AppModuleBasic{},
)

app := testapp.DefaultTestApp(nil)

expectedFieldTypes := getMapFieldsAndTypes(reflect.ValueOf(defaultAppModuleBasics))
actualFieldTypes := getMapFieldsAndTypes(reflect.ValueOf(basic_manager.ModuleBasics))
actualFieldTypes := getMapFieldsAndTypes(reflect.ValueOf(app.ModuleBasics))
require.Equal(t, expectedFieldTypes, actualFieldTypes, "Module basics does not match expected")
}

Expand Down
2 changes: 0 additions & 2 deletions protocol/app/basic_manager/basic_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import (
ica "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts"
"github.com/cosmos/ibc-go/v8/modules/apps/transfer"
ibc "github.com/cosmos/ibc-go/v8/modules/core"
ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint"
// Upgrades
)

Expand All @@ -65,7 +64,6 @@ var (
custommodule.SlashingModuleBasic{},
feegrantmodule.AppModuleBasic{},
ibc.AppModuleBasic{},
ibctm.AppModuleBasic{},
ica.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
Expand Down
8 changes: 0 additions & 8 deletions protocol/app/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ package app

import (
"encoding/json"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/dydxprotocol/v4-chain/protocol/app/basic_manager"
)

// The genesis state of the blockchain is represented here as a map of raw json
Expand All @@ -15,8 +12,3 @@ import (
// the ModuleBasicManager which populates json from each BasicModule
// object provided to it during init.
type GenesisState map[string]json.RawMessage

// NewDefaultGenesisState generates the default state for the application.
func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState {
return basic_manager.ModuleBasics.DefaultGenesis(cdc)
}
6 changes: 3 additions & 3 deletions protocol/app/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package app_test

import (
"encoding/json"
testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app"
"os"
"testing"

"github.com/dydxprotocol/v4-chain/protocol/app"
"github.com/stretchr/testify/require"
)

func TestDefaultGenesisState(t *testing.T) {
encodingConfig := app.GetEncodingConfig()
defaultGenesisState := app.NewDefaultGenesisState(encodingConfig.Codec)
app := testapp.DefaultTestApp(nil)
defaultGenesisState := app.DefaultGenesis()
humanReadableDefaultGenesisState, jsonUnmarshalErr := json.Marshal(&defaultGenesisState)

expectedDefaultGenesisState, fileReadErr := os.ReadFile("testdata/default_genesis_state.json")
Expand Down
6 changes: 3 additions & 3 deletions protocol/app/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ package middleware

import (
"fmt"
"github.com/cosmos/cosmos-sdk/types/module"
"os"
"runtime/debug"
"strings"

"cosmossdk.io/log"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/dydxprotocol/v4-chain/protocol/app/basic_manager"
kitlog "github.com/go-kit/log"
)

var (
Logger = log.NewLogger(kitlog.NewSyncWriter(os.Stdout))
)

func NewRunTxPanicLoggingMiddleware() baseapp.RecoveryHandler {
func NewRunTxPanicLoggingMiddleware(moduleBasics module.BasicManager) baseapp.RecoveryHandler {
return func(recoveryObj interface{}) error {
stack := string(debug.Stack())

var keyvals []interface{}

for _, module := range basic_manager.ModuleBasics {
for _, module := range moduleBasics {
fullModuleName := "/x/" + module.Name()
if strings.Contains(stack, fullModuleName) {
keyvals = append(keyvals, fullModuleName, "true")
Expand Down
4 changes: 3 additions & 1 deletion protocol/app/middleware/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package middleware_test
import (
"bytes"
"fmt"
testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app"
"github.com/dydxprotocol/v4-chain/protocol/testutil/logger"
"testing"

Expand Down Expand Up @@ -42,6 +43,7 @@ func TestRunTxPanicLoggingMiddleware(t *testing.T) {

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
app := testapp.DefaultTestApp(nil)
// Restore the old logger after the test runs since middleware.Logger is a global variable.
oldLogger := middleware.Logger
defer func() { middleware.Logger = oldLogger }()
Expand All @@ -52,7 +54,7 @@ func TestRunTxPanicLoggingMiddleware(t *testing.T) {
func() {
defer func() {
if r := recover(); r != nil {
handler := middleware.NewRunTxPanicLoggingMiddleware()
handler := middleware.NewRunTxPanicLoggingMiddleware(app.ModuleBasics)
err := handler(r)
require.Nil(t, err)
}
Expand Down
3 changes: 2 additions & 1 deletion protocol/app/testdata/default_genesis_state.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"07-tendermint": null,
"assets": {
"assets": [
{
Expand Down Expand Up @@ -93,6 +92,7 @@
"stateful_order_equity_tiers": []
}
},
"consensus": null,
"crisis": {
"constant_fee": {
"denom": "stake",
Expand Down Expand Up @@ -333,6 +333,7 @@
"port": "icahost"
}
},
"params": null,
"perpetuals": {
"perpetuals": [],
"liquidity_tiers": [],
Expand Down
57 changes: 29 additions & 28 deletions protocol/cmd/dydxprotocold/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
dydxapp "github.com/dydxprotocol/v4-chain/protocol/app"
"github.com/dydxprotocol/v4-chain/protocol/app/basic_manager"
protocolflags "github.com/dydxprotocol/v4-chain/protocol/app/flags"

"github.com/spf13/cast"
Expand All @@ -57,8 +55,8 @@ const (
flagIAVLCacheSize = "iavl-cache-size"
)

// TODO(DEC-1097): improve `cmd/` by adding tests, custom app configs, custom init cmd, and etc.
// NewRootCmd creates a new root command for `dydxprotocold`. It is called once in the main function.
// TODO(DEC-1097): improve `cmd/` by adding tests, custom app configs, custom init cmd, and etc.
func NewRootCmd(
option *RootCmdOption,
homeDir string,
Expand All @@ -85,12 +83,24 @@ func NewRootCmdWithInterceptors(
appConfigInterceptor func(string, *DydxAppConfig) (string, *DydxAppConfig),
appInterceptor func(app *dydxapp.App) *dydxapp.App,
) *cobra.Command {
encodingConfig := dydxapp.GetEncodingConfig()
tempApp := dydxapp.New(
log.NewNopLogger(),
dbm.NewMemDB(),
nil,
true,
viper.New(),
)
defer func() {
if err := tempApp.Close(); err != nil {
panic(err)
}
}()

initClientCtx := client.Context{}.
WithCodec(encodingConfig.Codec).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithCodec(tempApp.AppCodec()).
WithInterfaceRegistry(tempApp.InterfaceRegistry()).
WithTxConfig(tempApp.TxConfig()).
WithLegacyAmino(tempApp.LegacyAmino()).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastSync).
Expand Down Expand Up @@ -147,12 +157,12 @@ func NewRootCmdWithInterceptors(
SilenceUsage: true,
}

initRootCmd(rootCmd, option, encodingConfig, appInterceptor)
initRootCmd(tempApp, rootCmd, option, appInterceptor)
initClientCtx, err := config.ReadFromClientConfig(initClientCtx)
if err != nil {
panic(err)
}
if err := autoCliOpts(encodingConfig, initClientCtx).EnhanceRootCommand(rootCmd); err != nil {
if err := autoCliOpts(tempApp, initClientCtx).EnhanceRootCommand(rootCmd); err != nil {
panic(err)
}

Expand All @@ -161,30 +171,29 @@ func NewRootCmdWithInterceptors(

// initRootCmd initializes the app's root command with useful commands.
func initRootCmd(
tempApp *dydxapp.App,
rootCmd *cobra.Command,
option *RootCmdOption,
encodingConfig dydxapp.EncodingConfig,
appInterceptor func(app *dydxapp.App) *dydxapp.App,
) {
gentxModule := basic_manager.ModuleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic)
valOperAddressCodec := address.NewBech32Codec(sdktypes.GetConfig().GetBech32ValidatorAddrPrefix())
rootCmd.AddCommand(
genutilcli.InitCmd(basic_manager.ModuleBasics, dydxapp.DefaultNodeHome),
genutilcli.InitCmd(tempApp.ModuleBasics, dydxapp.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(
banktypes.GenesisBalancesIterator{},
dydxapp.DefaultNodeHome,
gentxModule.GenTxValidator,
genutiltypes.DefaultMessageValidator,
valOperAddressCodec,
),
genutilcli.MigrateGenesisCmd(genutilcli.MigrationMap),
genutilcli.GenTxCmd(
basic_manager.ModuleBasics,
encodingConfig.TxConfig,
tempApp.ModuleBasics,
tempApp.TxConfig(),
banktypes.GenesisBalancesIterator{},
dydxapp.DefaultNodeHome,
valOperAddressCodec,
),
genutilcli.ValidateGenesisCmd(basic_manager.ModuleBasics),
genutilcli.ValidateGenesisCmd(tempApp.ModuleBasics),
AddGenesisAccountCmd(dydxapp.DefaultNodeHome),
tmcli.NewCompletionCmd(rootCmd, true),
debug.Cmd(),
Expand Down Expand Up @@ -222,17 +231,9 @@ func initRootCmd(
// autoCliOpts returns options based upon the modules in the dYdX v4 app.
//
// Creates an instance of the application that is discarded to enumerate the modules.
func autoCliOpts(encodingCfg dydxapp.EncodingConfig, initClientCtx client.Context) autocli.AppOptions {
app := dydxapp.New(
log.NewNopLogger(),
dbm.NewMemDB(),
nil,
true,
viper.New(),
)

func autoCliOpts(tempApp *dydxapp.App, initClientCtx client.Context) autocli.AppOptions {
modules := make(map[string]appmodule.AppModule, 0)
for _, m := range app.ModuleManager.Modules {
for _, m := range tempApp.ModuleManager.Modules {
if moduleWithName, ok := m.(module.HasName); ok {
moduleName := moduleWithName.Name()
if appModule, ok := moduleWithName.(appmodule.AppModule); ok {
Expand All @@ -248,7 +249,7 @@ func autoCliOpts(encodingCfg dydxapp.EncodingConfig, initClientCtx client.Contex

return autocli.AppOptions{
Modules: modules,
ModuleOptions: runtimeservices.ExtractAutoCLIOptions(app.ModuleManager.Modules),
ModuleOptions: runtimeservices.ExtractAutoCLIOptions(tempApp.ModuleManager.Modules),
AddressCodec: authcodec.NewBech32Codec(sdktypes.GetConfig().GetBech32AccountAddrPrefix()),
ValidatorAddressCodec: authcodec.NewBech32Codec(sdktypes.GetConfig().GetBech32ValidatorAddrPrefix()),
ConsensusAddressCodec: authcodec.NewBech32Codec(sdktypes.GetConfig().GetBech32ConsensusAddrPrefix()),
Expand Down

0 comments on commit a9076e9

Please sign in to comment.