Skip to content

Commit

Permalink
chore: update encoding proto buf
Browse files Browse the repository at this point in the history
  • Loading branch information
kenta92115 committed Mar 22, 2024
1 parent 8dab2bb commit fede36a
Show file tree
Hide file tree
Showing 15 changed files with 286 additions and 80 deletions.
29 changes: 23 additions & 6 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,6 @@ import (
"swisstronik/docs"
"swisstronik/encoding"

simappparams "cosmossdk.io/simapp/params"

evmante "swisstronik/app/ante"
srvflags "swisstronik/server/flags"
evmcommontypes "swisstronik/types"
Expand Down Expand Up @@ -287,7 +285,8 @@ type App struct {
// this line is used by starport scaffolding # stargate/app/keeperDeclaration

// mm is the module manager
ModuleManager *module.Manager
ModuleManager *module.Manager
BasicModuleManager module.BasicManager

// sm is the simulation manager
sm *module.SimulationManager
Expand All @@ -303,10 +302,10 @@ func New(
skipUpgradeHeights map[int64]bool,
homePath string,
invCheckPeriod uint,
encodingConfig simappparams.EncodingConfig,
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *App {
encodingConfig := encoding.MakeConfig(ModuleBasics)
appCodec := encodingConfig.Codec
cdc := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
Expand Down Expand Up @@ -407,7 +406,7 @@ func New(
evmcommontypes.ProtoAccount,
maccPerms,
addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()),
sdk.Bech32PrefixAccAddr,
sdk.GetConfig().GetBech32AccountAddrPrefix(),
authAddr,
)

Expand Down Expand Up @@ -677,6 +676,24 @@ func New(
// this line is used by starport scaffolding # stargate/app/appModule
)

// BasicModuleManager defines the module BasicManager which is in charge of setting up basic,
// non-dependant module elements, such as codec registration and genesis verification.
// By default, it is composed of all the modules from the module manager.
// Additionally, app module basics can be overwritten by passing them as an argument.
app.BasicModuleManager = module.NewBasicManagerFromManager(
app.ModuleManager,
map[string]module.AppModuleBasic{
genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator),
govtypes.ModuleName: gov.NewAppModuleBasic(
[]govclient.ProposalHandler{
paramsclient.ProposalHandler,
},
),
},
)
app.BasicModuleManager.RegisterLegacyAminoCodec(cdc)
app.BasicModuleManager.RegisterInterfaces(interfaceRegistry)

app.ModuleManager.SetOrderPreBlockers(
upgradetypes.ModuleName,
)
Expand Down Expand Up @@ -1031,7 +1048,7 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig
nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)

// Register grpc-gateway routes for all modules.
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
app.BasicModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)

// register app's OpenAPI routes.
docs.RegisterOpenAPIService(Name, apiSvr.Router)
Expand Down
6 changes: 1 addition & 5 deletions app/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

"swisstronik/encoding"
"swisstronik/utils"

"cosmossdk.io/log"
Expand Down Expand Up @@ -90,7 +89,6 @@ func SetupWithDB(isCheckTx bool, patchGenesis func(*App, simapp.GenesisState) si
map[int64]bool{},
DefaultNodeHome,
5,
encoding.MakeConfig(ModuleBasics),
simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome),
baseapp.SetChainID(chainID),
)
Expand Down Expand Up @@ -215,8 +213,7 @@ func genesisStateWithValSet(codec codec.Codec, genesisState simapp.GenesisState,
// SetupTestingApp initializes the IBC-go testing application
func SetupTestingApp(chainID string) (ibctesting.TestingApp, map[string]json.RawMessage) {
db := dbm.NewMemDB()
cfg := encoding.MakeConfig(ModuleBasics)
app := New(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, 5, cfg, simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), baseapp.SetChainID(chainID))
app := New(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, 5, simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome), baseapp.SetChainID(chainID))
return app, NewDefaultGenesisState()
}

Expand Down Expand Up @@ -246,7 +243,6 @@ func SetupSwissApp(
log.NewNopLogger(),
db, nil, true, map[int64]bool{},
DefaultNodeHome, 5,
encoding.MakeConfig(ModuleBasics),
simtestutil.NewAppOptionsWithFlagHome(DefaultNodeHome),
baseapp.SetChainID(chainID),
)
Expand Down
156 changes: 131 additions & 25 deletions cmd/swisstronikd/cmd/genaccounts.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
package cmd

import (
"bufio"
"encoding/json"
"errors"
"fmt"
"swisstronik/crypto/hd"
evmtypes "swisstronik/x/evm/types"

"swisstronik/types"

address "cosmossdk.io/core/address"
"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"
"github.com/ethereum/go-ethereum/common"
"github.com/spf13/cobra"
)

Expand All @@ -34,57 +43,154 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
cdc := clientCtx.Codec
clientCtx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(hd.EthSecp256k1Option())
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}

serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config

config.SetRoot(clientCtx.HomeDir)

addr, err := addressCodec.StringToBytes(args[0])
kr := clientCtx.Keyring
addr, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend)
info, err := kr.Key(args[0])
if err != nil {
return err
return fmt.Errorf("failed to get address from Keyring: %w", err)
}

// attempt to lookup address from Keybase if no address was provided
kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf, cdc)
addr, err = info.GetAddress()
if err != nil {
return err
}
}

coins, err := sdk.ParseCoinsNormalized(args[1])
if err != nil {
return fmt.Errorf("failed to parse coins: %w", err)
}

vestingStart, err := cmd.Flags().GetInt64(flagVestingStart)
if err != nil {
return err
}
vestingEnd, err := cmd.Flags().GetInt64(flagVestingEnd)
if err != nil {
return err
}
vestingAmtStr, err := cmd.Flags().GetString(flagVestingAmt)
if err != nil {
return err
}

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)

info, err := kb.Key(args[0])
if !vestingAmt.IsZero() {
baseVestingAccount, err := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd)
if err != nil {
return fmt.Errorf("failed to get address from Keybase: %w", err)
return fmt.Errorf("failed to create base vesting account: %w", err)
}

addr, err = info.GetAddress()
if err != nil {
return fmt.Errorf("failed to get address from Keybase: %w", err)
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 = &types.EthAccount{
BaseAccount: baseAccount,
CodeHash: common.BytesToHash(evmtypes.EmptyCodeHash).Hex(),
}
}

appendflag, _ := cmd.Flags().GetBool(flagAppendMode)
vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart)
vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd)
vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt)
moduleNameStr, _ := cmd.Flags().GetString(flagModuleName)
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(clientCtx.Codec, 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

return genutil.AddGenesisAccount(clientCtx.Codec, addr, appendflag, config.GenesisFile(), args[1], vestingAmtStr, vestingStart, vestingEnd, moduleNameStr)
authGenStateBz, err := clientCtx.Codec.MarshalJSON(&authGenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}

appState[authtypes.ModuleName] = authGenStateBz

bankGenState := banktypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)
bankGenState.Balances = append(bankGenState.Balances, balances)
bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances)
bankGenState.Supply = bankGenState.Supply.Add(balances.Coins...)

bankGenStateBz, err := clientCtx.Codec.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, keyring.BackendTest, "Select keyring's backend (os|file|kwallet|pass|test)")
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")
cmd.Flags().Bool(flagAppendMode, false, "append the coins to an account already in the genesis.json file")
cmd.Flags().String(flagModuleName, "", "module account name")

flags.AddQueryFlagsToCmd(cmd)

return cmd
Expand Down
12 changes: 5 additions & 7 deletions cmd/swisstronikd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"github.com/cosmos/cosmos-sdk/types/module"

"cosmossdk.io/log"
simappparams "cosmossdk.io/simapp/params"
"cosmossdk.io/store"
"cosmossdk.io/store/snapshots"
snapshottypes "cosmossdk.io/store/snapshots/types"
Expand Down Expand Up @@ -60,6 +59,8 @@ import (

"swisstronik/utils"

ethermint "swisstronik/types"

"github.com/cosmos/cosmos-sdk/client/snapshot"
"github.com/cosmos/cosmos-sdk/codec"
runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services"
Expand All @@ -73,7 +74,7 @@ import (
const ShortBlockWindow uint32 = 20

// NewRootCmd creates a new root command for a Cosmos SDK application
func NewRootCmd() (*cobra.Command, simappparams.EncodingConfig) {
func NewRootCmd() (*cobra.Command, ethermint.EncodingConfig) {
// Initialize the SDK config the first before doing anything else.
InitSDKConfig()

Expand Down Expand Up @@ -189,7 +190,6 @@ func NewRootCmd() (*cobra.Command, simappparams.EncodingConfig) {
map[int64]bool{},
app.DefaultNodeHome,
5,
encoding.MakeConfig(app.ModuleBasics),
simutils.NewAppOptionsWithFlagHome(app.DefaultNodeHome),
baseapp.SetChainID(chainID),
)
Expand Down Expand Up @@ -290,7 +290,7 @@ func addModuleInitFlags(startCmd *cobra.Command) {
}

type appCreator struct {
encodingConfig simappparams.EncodingConfig
encodingConfig ethermint.EncodingConfig
}

// newApp creates a new Cosmos SDK app
Expand Down Expand Up @@ -357,7 +357,6 @@ func (a appCreator) newApp(
skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
cast.ToUint(appOpts.Get(sdkserver.FlagInvCheckPeriod)),
a.encodingConfig,
appOpts,
baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(sdkserver.FlagMinGasPrices))),
Expand Down Expand Up @@ -402,11 +401,10 @@ func (a appCreator) appExport(
map[int64]bool{},
homePath,
uint(1),
a.encodingConfig,
appOpts,
)
} else {
swissApp = app.New(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), a.encodingConfig, appOpts)
swissApp = app.New(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), appOpts)

}

Expand Down
Loading

0 comments on commit fede36a

Please sign in to comment.