From 40f37f27e7eaf5a76cfbaae2eaffcc4a9655cfab Mon Sep 17 00:00:00 2001 From: philipsu522 Date: Tue, 31 May 2022 16:07:48 -0700 Subject: [PATCH 1/6] [WIP] Remove ignite/starport cli from codebase --- app/app.go | 53 +++++++--- app/encoding.go | 16 +++ app/params/amino.go | 24 +++++ app/params/config.go | 75 ++++++++++++++ app/params/doc.go | 19 ++++ app/params/encoding.go | 16 +++ app/params/proto.go | 25 +++++ cmd/seid/cmd/genaccounts.go | 179 ++++++++++++++++++++++++++++++++ cmd/seid/cmd/init.go | 165 ++++++++++++++++++++++++++++++ cmd/seid/{ => cmd}/root.go | 198 ++++++++---------------------------- cmd/seid/main.go | 13 +-- go.mod | 1 - 12 files changed, 606 insertions(+), 178 deletions(-) create mode 100644 app/encoding.go create mode 100644 app/params/amino.go create mode 100644 app/params/config.go create mode 100644 app/params/doc.go create mode 100644 app/params/encoding.go create mode 100644 app/params/proto.go create mode 100644 cmd/seid/cmd/genaccounts.go create mode 100644 cmd/seid/cmd/init.go rename cmd/seid/{ => cmd}/root.go (70%) diff --git a/app/app.go b/app/app.go index 3e94f42eaf..3e8ad22fc9 100644 --- a/app/app.go +++ b/app/app.go @@ -3,10 +3,11 @@ package app import ( "context" "fmt" + appparams "github.com/sei-protocol/sei-chain/app/params" "io" - "net/http" "os" "path/filepath" + "strings" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -92,10 +93,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/tendermint/starport/starport/pkg/cosmoscmd" - "github.com/tendermint/starport/starport/pkg/openapiconsole" - - "github.com/sei-protocol/sei-chain/docs" "github.com/sei-protocol/sei-chain/utils/tracing" dexmodule "github.com/sei-protocol/sei-chain/x/dex" @@ -184,10 +181,24 @@ var ( allowedReceivingModAcc = map[string]bool{ oracletypes.ModuleName: true, } + + // WasmProposalsEnabled enables all x/wasm proposals when it's value is "true" + // and EnableSpecificWasmProposals is empty. Otherwise, all x/wasm proposals + // are disabled. + WasmProposalsEnabled = "true" + + // EnableSpecificWasmProposals, if set, must be comma-separated list of values + // that are all a subset of "EnableAllProposals", which takes precedence over + // WasmProposalsEnabled. + // + // See: https://github.com/CosmWasm/wasmd/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34 + EnableSpecificWasmProposals = "" + + // EmptyWasmOpts defines a type alias for a list of wasm options. + EmptyWasmOpts []wasm.Option ) var ( - _ cosmoscmd.App = (*App)(nil) _ servertypes.Application = (*App)(nil) _ simapp.App = (*App)(nil) ) @@ -201,6 +212,28 @@ func init() { DefaultNodeHome = filepath.Join(userHomeDir, "."+AppName) } +// GetWasmEnabledProposals parses the WasmProposalsEnabled and +// EnableSpecificWasmProposals values to produce a list of enabled proposals to +// pass into the application. +func GetWasmEnabledProposals() []wasm.ProposalType { + if EnableSpecificWasmProposals == "" { + if WasmProposalsEnabled == "true" { + return wasm.EnableAllProposals + } + + return wasm.DisableAllProposals + } + + chunks := strings.Split(EnableSpecificWasmProposals, ",") + + proposals, err := wasm.ConvertToProposals(chunks) + if err != nil { + panic(err) + } + + return proposals +} + // App extends an ABCI application, but with most of its parameters exported. // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. @@ -266,12 +299,12 @@ func New( skipUpgradeHeights map[int64]bool, homePath string, invCheckPeriod uint, - encodingConfig cosmoscmd.EncodingConfig, + encodingConfig appparams.EncodingConfig, enabledProposals []wasm.ProposalType, appOpts servertypes.AppOptions, wasmOpts []wasm.Option, baseAppOptions ...func(*baseapp.BaseApp), -) cosmoscmd.App { +) *App { appCodec := encodingConfig.Marshaler cdc := encodingConfig.Amino interfaceRegistry := encodingConfig.InterfaceRegistry @@ -789,10 +822,6 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig // Register legacy and grpc-gateway routes for all modules. ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - - // register app's OpenAPI routes. - apiSvr.Router.Handle("/static/openapi.yml", http.FileServer(http.FS(docs.Docs))) - apiSvr.Router.HandleFunc("/", openapiconsole.Handler(AppName, "/static/openapi.yml")) } // RegisterTxService implements the Application.RegisterTxService method. diff --git a/app/encoding.go b/app/encoding.go new file mode 100644 index 0000000000..4724cb3a9a --- /dev/null +++ b/app/encoding.go @@ -0,0 +1,16 @@ +package app + +import ( + "github.com/cosmos/cosmos-sdk/std" + "github.com/sei-protocol/sei-chain/app/params" +) + +// MakeEncodingConfig creates an EncodingConfig for testing. +func MakeEncodingConfig() params.EncodingConfig { + encodingConfig := params.MakeEncodingConfig() + std.RegisterLegacyAminoCodec(encodingConfig.Amino) + std.RegisterInterfaces(encodingConfig.InterfaceRegistry) + ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) + ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) + return encodingConfig +} diff --git a/app/params/amino.go b/app/params/amino.go new file mode 100644 index 0000000000..e727d62cd9 --- /dev/null +++ b/app/params/amino.go @@ -0,0 +1,24 @@ +//go:build test_amino +// +build test_amino + +package params + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig() EncodingConfig { + cdc := codec.New() + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewAminoCodec(cdc) + + return EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxConfig: authtypes.StdTxConfig{Cdc: cdc}, + Amino: cdc, + } +} diff --git a/app/params/config.go b/app/params/config.go new file mode 100644 index 0000000000..adb375e012 --- /dev/null +++ b/app/params/config.go @@ -0,0 +1,75 @@ +package params + +import ( + "github.com/cosmos/cosmos-sdk/types/address" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +const ( + HumanCoinUnit = "sei" + BaseCoinUnit = "usei" + UseiExponent = 6 + + DefaultBondDenom = BaseCoinUnit + + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address. + Bech32PrefixAccAddr = "sei" +) + +var ( + // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key. + Bech32PrefixAccPub = Bech32PrefixAccAddr + "pub" + // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address. + Bech32PrefixValAddr = Bech32PrefixAccAddr + "valoper" + // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key. + Bech32PrefixValPub = Bech32PrefixAccAddr + "valoperpub" + // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address. + Bech32PrefixConsAddr = Bech32PrefixAccAddr + "valcons" + // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key. + Bech32PrefixConsPub = Bech32PrefixAccAddr + "valconspub" +) + +func init() { + SetAddressPrefixes() + RegisterDenoms() +} + +func RegisterDenoms() { + err := sdk.RegisterDenom(HumanCoinUnit, sdk.OneDec()) + if err != nil { + panic(err) + } + err = sdk.RegisterDenom(BaseCoinUnit, sdk.NewDecWithPrec(1, UseiExponent)) + if err != nil { + panic(err) + } +} + +func SetAddressPrefixes() { + println("-------set") + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) + + // This is copied from the cosmos sdk v0.43.0-beta1 + // source: https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/types/address.go#L141 + config.SetAddressVerifier(func(bytes []byte) error { + if len(bytes) == 0 { + return sdkerrors.Wrap(sdkerrors.ErrUnknownAddress, "addresses cannot be empty") + } + + if len(bytes) > address.MaxAddrLen { + return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "address max length is %d, got %d", address.MaxAddrLen, len(bytes)) + } + + // TODO: Do we want to allow addresses of lengths other than 20 and 32 bytes? + if len(bytes) != 20 && len(bytes) != 32 { + return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "address length must be 20 or 32 bytes, got %d", len(bytes)) + } + + return nil + }) +} diff --git a/app/params/doc.go b/app/params/doc.go new file mode 100644 index 0000000000..1c721342a9 --- /dev/null +++ b/app/params/doc.go @@ -0,0 +1,19 @@ +/* +Package params defines the simulation parameters in the simapp. + +It contains the default weights used for each transaction used on the module's +simulation. These weights define the chance for a transaction to be simulated at +any gived operation. + +You can repace the default values for the weights by providing a params.json +file with the weights defined for each of the transaction operations: + + { + "op_weight_msg_send": 60, + "op_weight_msg_delegate": 100, + } + +In the example above, the `MsgSend` has 60% chance to be simulated, while the +`MsgDelegate` will always be simulated. +*/ +package params diff --git a/app/params/encoding.go b/app/params/encoding.go new file mode 100644 index 0000000000..3d634abf16 --- /dev/null +++ b/app/params/encoding.go @@ -0,0 +1,16 @@ +package params + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" +) + +// EncodingConfig specifies the concrete encoding types to use for a given app. +// This is provided for compatibility between protobuf and amino implementations. +type EncodingConfig struct { + InterfaceRegistry types.InterfaceRegistry + Marshaler codec.Codec + TxConfig client.TxConfig + Amino *codec.LegacyAmino +} diff --git a/app/params/proto.go b/app/params/proto.go new file mode 100644 index 0000000000..7effc32976 --- /dev/null +++ b/app/params/proto.go @@ -0,0 +1,25 @@ +//go:build !test_amino +// +build !test_amino + +package params + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/x/auth/tx" +) + +// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration. +func MakeEncodingConfig() EncodingConfig { + amino := codec.NewLegacyAmino() + interfaceRegistry := types.NewInterfaceRegistry() + marshaler := codec.NewProtoCodec(interfaceRegistry) + txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes) + + return EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxConfig: txCfg, + Amino: amino, + } +} diff --git a/cmd/seid/cmd/genaccounts.go b/cmd/seid/cmd/genaccounts.go new file mode 100644 index 0000000000..13a55b6e8c --- /dev/null +++ b/cmd/seid/cmd/genaccounts.go @@ -0,0 +1,179 @@ +package cmd + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +const ( + flagVestingStart = "vesting-start-time" + flagVestingEnd = "vesting-end-time" + flagVestingAmt = "vesting-amount" +) + +// AddGenesisAccountCmd returns add-genesis-account cobra Command. +func AddGenesisAccountCmd(defaultNodeHome string) *cobra.Command { + cmd := &cobra.Command{ + Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", + Short: "Add a genesis account to genesis.json", + Long: `Add a genesis account to genesis.json. The provided account must specify +the account address or key name and a list of initial coins. If a key name is given, +the address will be looked up in the local Keybase. The list of initial tokens must +contain valid denominations. Accounts may optionally be supplied with vesting parameters. +`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + depCdc := clientCtx.Codec + cdc := depCdc + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + addr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + inBuf := bufio.NewReader(cmd.InOrStdin()) + keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + + // attempt to lookup address from Keybase if no address was provided + kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf) + if err != nil { + return err + } + + info, err := kb.Key(args[0]) + if err != nil { + return fmt.Errorf("failed to get address from Keybase: %w", err) + } + + addr = info.GetAddress() + } + + coins, err := sdk.ParseCoinsNormalized(args[1]) + if err != nil { + return fmt.Errorf("failed to parse coins: %w", err) + } + + vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart) + vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd) + vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt) + + vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr) + if err != nil { + return fmt.Errorf("failed to parse vesting amount: %w", err) + } + + // create concrete account type based on input parameters + var genAccount authtypes.GenesisAccount + + balances := banktypes.Balance{Address: addr.String(), Coins: coins.Sort()} + baseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0) + + if !vestingAmt.IsZero() { + baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) + + if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) || + baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) { + return errors.New("vesting amount cannot be greater than total amount") + } + + switch { + case vestingStart != 0 && vestingEnd != 0: + genAccount = authvesting.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart) + + case vestingEnd != 0: + genAccount = authvesting.NewDelayedVestingAccountRaw(baseVestingAccount) + + default: + return errors.New("invalid vesting parameters; must supply start and end time or end time") + } + } else { + genAccount = baseAccount + } + + if err := genAccount.Validate(); err != nil { + return fmt.Errorf("failed to validate new genesis account: %w", err) + } + + genFile := config.GenesisFile() + appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) + if err != nil { + return fmt.Errorf("failed to unmarshal genesis state: %w", err) + } + + authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState) + + accs, err := authtypes.UnpackAccounts(authGenState.Accounts) + if err != nil { + return fmt.Errorf("failed to get accounts from any: %w", err) + } + + if accs.Contains(addr) { + return fmt.Errorf("cannot add account at existing address %s", addr) + } + + // Add the new account to the set of genesis accounts and sanitize the + // accounts afterwards. + accs = append(accs, genAccount) + accs = authtypes.SanitizeGenesisAccounts(accs) + + genAccs, err := authtypes.PackAccounts(accs) + if err != nil { + return fmt.Errorf("failed to convert accounts into any's: %w", err) + } + authGenState.Accounts = genAccs + + authGenStateBz, err := cdc.MarshalJSON(&authGenState) + if err != nil { + return fmt.Errorf("failed to marshal auth genesis state: %w", err) + } + + appState[authtypes.ModuleName] = authGenStateBz + + bankGenState := banktypes.GetGenesisStateFromAppState(depCdc, appState) + bankGenState.Balances = append(bankGenState.Balances, balances) + bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances) + + bankGenStateBz, err := cdc.MarshalJSON(bankGenState) + if err != nil { + return fmt.Errorf("failed to marshal bank genesis state: %w", err) + } + + appState[banktypes.ModuleName] = bankGenStateBz + + appStateJSON, err := json.Marshal(appState) + if err != nil { + return fmt.Errorf("failed to marshal application genesis state: %w", err) + } + + genDoc.AppState = appStateJSON + return genutil.ExportGenesisFile(genDoc, genFile) + }, + } + + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") + cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") + cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/cmd/seid/cmd/init.go b/cmd/seid/cmd/init.go new file mode 100644 index 0000000000..d966d46089 --- /dev/null +++ b/cmd/seid/cmd/init.go @@ -0,0 +1,165 @@ +package cmd + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/cosmos/go-bip39" + "github.com/pkg/errors" + "github.com/spf13/cobra" + + tmcfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/libs/cli" + tmos "github.com/tendermint/tendermint/libs/os" + "github.com/tendermint/tendermint/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/input" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/genutil" +) + +const ( + // FlagOverwrite defines a flag to overwrite an existing genesis JSON file. + FlagOverwrite = "overwrite" + + // FlagSeed defines a flag to initialize the private validator key from a specific seed. + FlagRecover = "recover" +) + +type printInfo struct { + Moniker string `json:"moniker" yaml:"moniker"` + ChainID string `json:"chain_id" yaml:"chain_id"` + NodeID string `json:"node_id" yaml:"node_id"` + GenTxsDir string `json:"gentxs_dir" yaml:"gentxs_dir"` + AppMessage json.RawMessage `json:"app_message" yaml:"app_message"` +} + +func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, appMessage json.RawMessage) printInfo { + return printInfo{ + Moniker: moniker, + ChainID: chainID, + NodeID: nodeID, + GenTxsDir: genTxsDir, + AppMessage: appMessage, + } +} + +func displayInfo(info printInfo) error { + out, err := json.MarshalIndent(info, "", " ") + if err != nil { + return err + } + + _, err = fmt.Fprintf(os.Stderr, "%s\n", string(sdk.MustSortJSON(out))) + + return err +} + +// InitCmd returns a command that initializes all files needed for Tendermint +// and the respective application. +func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { + cmd := &cobra.Command{ + Use: "init [moniker]", + Short: "Initialize private validator, p2p, genesis, and application configuration files", + Long: `Initialize validators's and node's configuration files.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + cdc := clientCtx.Codec + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + // An easy way to run a lightweight seed node is to use tenderseed: github.com/binaryholdings/tenderseed + // TODO(psu) Add seeds for mainnet + seeds := []string{} + config.P2P.Seeds = strings.Join(seeds, ",") + config.P2P.MaxNumInboundPeers = 40 + config.P2P.MaxNumOutboundPeers = 10 + config.Mempool.Size = 500 + config.StateSync.TrustPeriod = 168 * time.Hour + config.FastSync.Version = "v0" + + config.SetRoot(clientCtx.HomeDir) + + chainID, _ := cmd.Flags().GetString(flags.FlagChainID) + if chainID == "" { + chainID = "sei" + } + + // Get bip39 mnemonic + var mnemonic string + recover, _ := cmd.Flags().GetBool(FlagRecover) + if recover { + inBuf := bufio.NewReader(cmd.InOrStdin()) + mnemonic, err := input.GetString("Enter your bip39 mnemonic", inBuf) + if err != nil { + return err + } + + if !bip39.IsMnemonicValid(mnemonic) { + return errors.New("invalid mnemonic") + } + } + + nodeID, _, err := genutil.InitializeNodeValidatorFilesFromMnemonic(config, mnemonic) + if err != nil { + return err + } + + config.Moniker = args[0] + + genFile := config.GenesisFile() + overwrite, _ := cmd.Flags().GetBool(FlagOverwrite) + + if !overwrite && tmos.FileExists(genFile) { + return fmt.Errorf("genesis.json file already exists: %v", genFile) + } + appState, err := json.MarshalIndent(mbm.DefaultGenesis(cdc), "", " ") + if err != nil { + return errors.Wrap(err, "Failed to marshall default genesis state") + } + + genDoc := &types.GenesisDoc{} + if _, err := os.Stat(genFile); err != nil { + if !os.IsNotExist(err) { + return err + } + } else { + genDoc, err = types.GenesisDocFromFile(genFile) + if err != nil { + return errors.Wrap(err, "Failed to read genesis doc from file") + } + } + + genDoc.ChainID = chainID + genDoc.Validators = nil + genDoc.AppState = appState + if err = genutil.ExportGenesisFile(genDoc, genFile); err != nil { + return errors.Wrap(err, "Failed to export genesis file") + } + + toPrint := newPrintInfo(config.Moniker, chainID, nodeID, "", appState) + + tmcfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config) + + return displayInfo(toPrint) + }, + } + + cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") + cmd.Flags().BoolP(FlagOverwrite, "o", false, "overwrite the genesis.json file") + cmd.Flags().Bool(FlagRecover, false, "provide seed phrase to recover existing key instead of creating") + cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will use sei") + + return cmd +} diff --git a/cmd/seid/root.go b/cmd/seid/cmd/root.go similarity index 70% rename from cmd/seid/root.go rename to cmd/seid/cmd/root.go index 980d9e460a..292eba66c0 100644 --- a/cmd/seid/root.go +++ b/cmd/seid/cmd/root.go @@ -1,7 +1,10 @@ -package main +package cmd import ( "errors" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/sei-protocol/sei-chain/app" + "github.com/sei-protocol/sei-chain/app/params" "io" "os" "path/filepath" @@ -21,7 +24,6 @@ import ( "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -29,37 +31,11 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" "github.com/spf13/cast" "github.com/spf13/cobra" - "github.com/spf13/pflag" - "github.com/tendermint/starport/starport/pkg/cosmoscmd" tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" ) -type ( - // AppBuilder is a method that allows to build an app - AppBuilder func( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - loadLatest bool, - skipUpgradeHeights map[int64]bool, - homePath string, - invCheckPeriod uint, - encodingConfig cosmoscmd.EncodingConfig, - enabledProposals []wasm.ProposalType, - appOpts servertypes.AppOptions, - wasmOpts []wasm.Option, - baseAppOptions ...func(*baseapp.BaseApp), - ) cosmoscmd.App - - // appCreator is an app creator - appCreator struct { - encodingConfig cosmoscmd.EncodingConfig - buildApp AppBuilder - } -) - // Option configures root command option. type Option func(*rootOptions) @@ -70,55 +46,15 @@ type rootOptions struct { envPrefix string } -func newRootOptions(options ...Option) rootOptions { - opts := rootOptions{} - opts.apply(options...) - return opts -} - func (s *rootOptions) apply(options ...Option) { for _, o := range options { o(s) } } -// AddSubCmd adds sub commands. -func AddSubCmd(cmd ...*cobra.Command) Option { - return func(o *rootOptions) { - o.addSubCmds = append(o.addSubCmds, cmd...) - } -} - -// CustomizeStartCmd accepts a handler to customize the start command. -func CustomizeStartCmd(h func(startCmd *cobra.Command)) Option { - return func(o *rootOptions) { - o.startCmdCustomizer = h - } -} - -// WithEnvPrefix accepts a new prefix for environment variables. -func WithEnvPrefix(envPrefix string) Option { - return func(o *rootOptions) { - o.envPrefix = envPrefix - } -} - // NewRootCmd creates a new root command for a Cosmos SDK application -func NewRootCmd( - appName, - accountAddressPrefix, - defaultNodeHome, - defaultChainID string, - moduleBasics module.BasicManager, - buildApp AppBuilder, - options ...Option, -) (*cobra.Command, cosmoscmd.EncodingConfig) { - rootOptions := newRootOptions(options...) - - // Set config for prefixes - cosmoscmd.SetPrefixes(accountAddressPrefix) - - encodingConfig := cosmoscmd.MakeEncodingConfig(moduleBasics) +func NewRootCmd() (*cobra.Command, params.EncodingConfig) { + encodingConfig := app.MakeEncodingConfig() initClientCtx := client.Context{}. WithCodec(encodingConfig.Marshaler). WithInterfaceRegistry(encodingConfig.InterfaceRegistry). @@ -127,12 +63,12 @@ func NewRootCmd( WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithBroadcastMode(flags.BroadcastBlock). - WithHomeDir(defaultNodeHome). - WithViper(rootOptions.envPrefix) + WithHomeDir(app.DefaultNodeHome). + WithViper("SEI") rootCmd := &cobra.Command{ - Use: appName + "d", - Short: "Stargate Sei App", + Use: "seid", + Short: "Start sei app", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) @@ -159,80 +95,54 @@ func NewRootCmd( initRootCmd( rootCmd, encodingConfig, - defaultNodeHome, - moduleBasics, - buildApp, - rootOptions, ) - overwriteFlagDefaults(rootCmd, map[string]string{ - flags.FlagChainID: defaultChainID, - flags.FlagKeyringBackend: "test", - }) - return rootCmd, encodingConfig } func initRootCmd( rootCmd *cobra.Command, - encodingConfig cosmoscmd.EncodingConfig, - defaultNodeHome string, - moduleBasics module.BasicManager, - buildApp AppBuilder, - options rootOptions, + encodingConfig params.EncodingConfig, ) { + cfg := sdk.GetConfig() + cfg.Seal() + rootCmd.AddCommand( - genutilcli.InitCmd(moduleBasics, defaultNodeHome), - genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, defaultNodeHome), + InitCmd(app.ModuleBasics, app.DefaultNodeHome), + genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), genutilcli.MigrateGenesisCmd(), genutilcli.GenTxCmd( - moduleBasics, + app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, - defaultNodeHome, + app.DefaultNodeHome, ), - genutilcli.ValidateGenesisCmd(moduleBasics), - cosmoscmd.AddGenesisAccountCmd(defaultNodeHome), + genutilcli.ValidateGenesisCmd(app.ModuleBasics), + AddGenesisAccountCmd(app.DefaultNodeHome), tmcli.NewCompletionCmd(rootCmd, true), debug.Cmd(), config.Cmd(), ) - a := appCreator{ - encodingConfig, - buildApp, - } - // add server commands server.AddCommands( rootCmd, - defaultNodeHome, - a.newApp, - a.appExport, - func(cmd *cobra.Command) { - addModuleInitFlags(cmd) - - if options.startCmdCustomizer != nil { - options.startCmdCustomizer(cmd) - } - }, + app.DefaultNodeHome, + newApp, + appExport, + addModuleInitFlags, ) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( rpc.StatusCommand(), - queryCommand(moduleBasics), - txCommand(moduleBasics), - keys.Commands(defaultNodeHome), + queryCommand(), + txCommand(), + keys.Commands(app.DefaultNodeHome), ) - - // add user given sub commands. - for _, cmd := range options.addSubCmds { - rootCmd.AddCommand(cmd) - } } // queryCommand returns the sub-command to send queries to the app -func queryCommand(moduleBasics module.BasicManager) *cobra.Command { +func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, @@ -250,14 +160,14 @@ func queryCommand(moduleBasics module.BasicManager) *cobra.Command { authcmd.QueryTxCmd(), ) - moduleBasics.AddQueryCommands(cmd) + app.ModuleBasics.AddQueryCommands(cmd) cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } // txCommand returns the sub-command to send transactions to the app -func txCommand(moduleBasics module.BasicManager) *cobra.Command { +func txCommand() *cobra.Command { cmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", @@ -277,7 +187,7 @@ func txCommand(moduleBasics module.BasicManager) *cobra.Command { authcmd.GetDecodeCommand(), ) - moduleBasics.AddTxCommands(cmd) + app.ModuleBasics.AddTxCommands(cmd) cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd @@ -287,24 +197,8 @@ func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) } -func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) { - set := func(s *pflag.FlagSet, key, val string) { - if f := s.Lookup(key); f != nil { - f.DefValue = val - f.Value.Set(val) - } - } - for key, val := range defaults { - set(c.Flags(), key, val) - set(c.PersistentFlags(), key, val) - } - for _, c := range c.Commands() { - overwriteFlagDefaults(c, defaults) - } -} - // newApp creates a new Cosmos SDK app -func (a appCreator) newApp( +func newApp( logger log.Logger, db dbm.DB, traceStore io.Writer, @@ -338,7 +232,7 @@ func (a appCreator) newApp( wasmopts := []wasm.Option{wasmkeeper.WithMessageEncoders(&wasmkeeper.MessageEncoders{})} - return a.buildApp( + return app.New( logger, db, traceStore, @@ -346,7 +240,7 @@ func (a appCreator) newApp( skipUpgradeHeights, cast.ToString(appOpts.Get(flags.FlagHome)), cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), - a.encodingConfig, + app.MakeEncodingConfig(), wasm.EnableAllProposals, appOpts, wasmopts, @@ -365,7 +259,7 @@ func (a appCreator) newApp( } // appExport creates a new simapp (optionally at a given height) -func (a appCreator) appExport( +func appExport( logger log.Logger, db dbm.DB, traceStore io.Writer, @@ -374,31 +268,23 @@ func (a appCreator) appExport( jailAllowedAddrs []string, appOpts servertypes.AppOptions, ) (servertypes.ExportedApp, error) { - var exportableApp cosmoscmd.ExportableApp + encCfg := app.MakeEncodingConfig() + encCfg.Marshaler = codec.NewProtoCodec(encCfg.InterfaceRegistry) + + var exportableApp *app.App homePath, ok := appOpts.Get(flags.FlagHome).(string) if !ok || homePath == "" { return servertypes.ExportedApp{}, errors.New("application home not set") } - exportableApp = a.buildApp( - logger, - db, - traceStore, - height == -1, // -1: no height provided - map[int64]bool{}, - homePath, - uint(1), - a.encodingConfig, - wasm.EnableAllProposals, - appOpts, - nil, - ) - if height != -1 { + exportableApp = app.New(logger, db, traceStore, false, map[int64]bool{}, "", uint(1), encCfg, app.GetWasmEnabledProposals(), appOpts, app.EmptyWasmOpts) if err := exportableApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } + } else { + exportableApp = app.New(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), encCfg, app.GetWasmEnabledProposals(), appOpts, app.EmptyWasmOpts) } return exportableApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) diff --git a/cmd/seid/main.go b/cmd/seid/main.go index 1b52ffbafd..f8ff134b76 100644 --- a/cmd/seid/main.go +++ b/cmd/seid/main.go @@ -1,6 +1,8 @@ package main import ( + "github.com/sei-protocol/sei-chain/app/params" + "github.com/sei-protocol/sei-chain/cmd/seid/cmd" "os" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" @@ -8,15 +10,8 @@ import ( ) func main() { - rootCmd, _ := NewRootCmd( - app.AppName, - app.AccountAddressPrefix, - app.DefaultNodeHome, - app.AppName, - app.ModuleBasics, - app.New, - // this line is used by starport scaffolding # root/arguments - ) + params.SetAddressPrefixes() + rootCmd, _ := cmd.NewRootCmd() if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil { os.Exit(1) } diff --git a/go.mod b/go.mod index 7d83adb9ca..689b436c34 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/spf13/cobra v1.4.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.7.1 - github.com/tendermint/starport v0.19.2 github.com/tendermint/tendermint v0.34.19 github.com/tendermint/tm-db v0.6.8-0.20220519162814-e24b96538a12 go.opentelemetry.io/otel v1.6.3 From f73cc2b7211d17c19c4c5d1b7db4f558b06eb883 Mon Sep 17 00:00:00 2001 From: philipsu522 Date: Tue, 31 May 2022 19:33:39 -0700 Subject: [PATCH 2/6] Finish --- app/params/config.go | 1 - 1 file changed, 1 deletion(-) diff --git a/app/params/config.go b/app/params/config.go index adb375e012..3ae0501c46 100644 --- a/app/params/config.go +++ b/app/params/config.go @@ -48,7 +48,6 @@ func RegisterDenoms() { } func SetAddressPrefixes() { - println("-------set") config := sdk.GetConfig() config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) From e18bf46adb42be8d503d865e9926857cdfd428db Mon Sep 17 00:00:00 2001 From: philipsu522 Date: Tue, 31 May 2022 21:10:15 -0700 Subject: [PATCH 3/6] fix tests --- testutil/network/network.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/testutil/network/network.go b/testutil/network/network.go index 6a28e234e6..080c75cac9 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/tendermint/starport/starport/pkg/cosmoscmd" tmrand "github.com/tendermint/tendermint/libs/rand" tmdb "github.com/tendermint/tm-db" @@ -47,7 +46,7 @@ func New(t *testing.T, configs ...network.Config) *network.Network { // DefaultConfig will initialize config for the network with custom application, // genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig func DefaultConfig() network.Config { - encoding := cosmoscmd.MakeEncodingConfig(app.ModuleBasics) + encoding := app.MakeEncodingConfig() return network.Config{ Codec: encoding.Marshaler, TxConfig: encoding.TxConfig, From 6a0c151c4e31047890a5012872bbb38d14ae8eae Mon Sep 17 00:00:00 2001 From: Joesph Chalabi Date: Thu, 2 Jun 2022 17:03:15 -0700 Subject: [PATCH 4/6] Added gas price to init --- cmd/seid/cmd/init.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/seid/cmd/init.go b/cmd/seid/cmd/init.go index d966d46089..f2350c7825 100644 --- a/cmd/seid/cmd/init.go +++ b/cmd/seid/cmd/init.go @@ -88,6 +88,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { config.Mempool.Size = 500 config.StateSync.TrustPeriod = 168 * time.Hour config.FastSync.Version = "v0" + app.Minimum.Gas.Prices = "0.01usei" config.SetRoot(clientCtx.HomeDir) From d84be8e05604c0d0c7802c56c282c97a22b31f11 Mon Sep 17 00:00:00 2001 From: Joesph Chalabi Date: Thu, 2 Jun 2022 21:56:38 -0700 Subject: [PATCH 5/6] Removed broken edit to init.go, add minimum gas prices to root.go --- cmd/seid/cmd/init.go | 1 - cmd/seid/cmd/root.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cmd/seid/cmd/init.go b/cmd/seid/cmd/init.go index f2350c7825..d966d46089 100644 --- a/cmd/seid/cmd/init.go +++ b/cmd/seid/cmd/init.go @@ -88,7 +88,6 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { config.Mempool.Size = 500 config.StateSync.TrustPeriod = 168 * time.Hour config.FastSync.Version = "v0" - app.Minimum.Gas.Prices = "0.01usei" config.SetRoot(clientCtx.HomeDir) diff --git a/cmd/seid/cmd/root.go b/cmd/seid/cmd/root.go index 292eba66c0..4709604200 100644 --- a/cmd/seid/cmd/root.go +++ b/cmd/seid/cmd/root.go @@ -325,7 +325,7 @@ func initAppConfig() (string, interface{}) { // own app.toml to override, or use this default value. // // In simapp, we set the min gas prices to 0. - srvCfg.MinGasPrices = "0stake" + srvCfg.MinGasPrices = "0.01ustake" srvCfg.API.Enable = true customAppConfig := CustomAppConfig{ From 8278f2b0eaf0e1d2d18974a58000a47c95ad7421 Mon Sep 17 00:00:00 2001 From: philipsu522 Date: Fri, 3 Jun 2022 08:48:54 -0700 Subject: [PATCH 6/6] change min gas price to usei --- cmd/seid/cmd/root.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/seid/cmd/root.go b/cmd/seid/cmd/root.go index 292eba66c0..2f3e4c18b4 100644 --- a/cmd/seid/cmd/root.go +++ b/cmd/seid/cmd/root.go @@ -325,7 +325,7 @@ func initAppConfig() (string, interface{}) { // own app.toml to override, or use this default value. // // In simapp, we set the min gas prices to 0. - srvCfg.MinGasPrices = "0stake" + srvCfg.MinGasPrices = "0.01usei" srvCfg.API.Enable = true customAppConfig := CustomAppConfig{