Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(tests): migrate vesting module tests #2408

Merged
merged 23 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions client/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ func initGenFiles(
clientCtx.Codec.MustUnmarshalJSON(appGenState[govtypes.ModuleName], &govGenState)

govGenState.Params.MinDeposit[0].Denom = coinDenom
govGenState.Params.ExpeditedMinDeposit[0].Denom = coinDenom
appGenState[govtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&govGenState)

var mintGenState mintypes.GenesisState
Expand Down
3 changes: 3 additions & 0 deletions cmd/evmosd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import (
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"

"github.com/evmos/evmos/v16/utils"
)

type printInfo struct {
Expand Down Expand Up @@ -175,6 +177,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command {
cmd.Flags().BoolP(genutilcli.FlagOverwrite, "o", false, "overwrite the genesis.json file")
cmd.Flags().Bool(genutilcli.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 be randomly created")
cmd.Flags().String(genutilcli.FlagDefaultBondDenom, utils.BaseDenom, "defines the default denom to use in genesis file")

return cmd
}
1 change: 1 addition & 0 deletions cmd/evmosd/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ func initGenFiles(
clientCtx.Codec.MustUnmarshalJSON(appGenState[govtypes.ModuleName], &govGenState)

govGenState.Params.MinDeposit[0].Denom = coinDenom
govGenState.Params.ExpeditedMinDeposit[0].Denom = coinDenom
appGenState[govtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&govGenState)

var evmGenState evmtypes.GenesisState
Expand Down
9 changes: 0 additions & 9 deletions local_node.sh
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,6 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then
# Set moniker and chain-id for Evmos (Moniker can be anything, chain-id must be an integer)
evmosd init $MONIKER -o --chain-id "$CHAINID" --home "$HOMEDIR"

# Change parameter token denominations to aevmos
jq '.app_state["staking"]["params"]["bond_denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"
jq '.app_state["crisis"]["constant_fee"]["denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"
jq '.app_state["gov"]["deposit_params"]["min_deposit"][0]["denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"
# When upgrade to cosmos-sdk v0.47, use gov.params to edit the deposit params
jq '.app_state["gov"]["params"]["min_deposit"][0]["denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"
jq '.app_state["evm"]["params"]["evm_denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"
jq '.app_state["inflation"]["params"]["mint_denom"]="aevmos"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"

# Set gas limit in genesis
jq '.consensus_params["block"]["max_gas"]="10000000"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS"

Expand Down
6 changes: 6 additions & 0 deletions testutil/integration/common/grpc/bank.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,9 @@ func (gqh *IntegrationHandler) GetTotalSupply() (*banktypes.QueryTotalSupplyResp
bankClient := gqh.network.GetBankClient()
return bankClient.TotalSupply(context.Background(), &banktypes.QueryTotalSupplyRequest{})
}

// GetSpendableBalance returns the spendable balance for the given denomination.
func (gqh *IntegrationHandler) GetSpendableBalance(address sdktypes.AccAddress, denom string) (*banktypes.QuerySpendableBalanceByDenomResponse, error) {
bankClient := gqh.network.GetBankClient()
return bankClient.SpendableBalanceByDenom(context.Background(), &banktypes.QuerySpendableBalanceByDenomRequest{Address: address.String(), Denom: denom})
}
1 change: 1 addition & 0 deletions testutil/integration/common/grpc/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Handler interface {

// Bank methods
GetBalance(address sdktypes.AccAddress, denom string) (*banktypes.QueryBalanceResponse, error)
GetSpendableBalance(address sdktypes.AccAddress, denom string) (*banktypes.QuerySpendableBalanceByDenomResponse, error)
GetAllBalances(address sdktypes.AccAddress) (*banktypes.QueryAllBalancesResponse, error)
GetTotalSupply() (*banktypes.QueryTotalSupplyResponse, error)

Expand Down
19 changes: 12 additions & 7 deletions testutil/integration/evmos/factory/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,9 @@ func (tf *IntegrationTxFactory) EstimateGasLimit(from *common.Address, txArgs *e

// GenerateSignedEthTx generates an Ethereum tx with the provided private key and txArgs but does not broadcast it.
func (tf *IntegrationTxFactory) GenerateSignedEthTx(privKey cryptotypes.PrivKey, txArgs evmtypes.EvmTxArgs) (signing.Tx, error) {
msgEthereumTx, err := tf.GenerateMsgEthereumTx(privKey, txArgs)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to create ethereum tx")
}

signedMsg, err := tf.SignMsgEthereumTx(privKey, msgEthereumTx)
signedMsg, err := tf.GenerateSignedMsgEthereumTx(privKey, txArgs)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to sign ethereum tx")
return nil, errorsmod.Wrap(err, "failed to generate signed MsgEthereumTx")
}

// Validate the transaction to avoid unrealistic behavior
Expand All @@ -78,6 +73,16 @@ func (tf *IntegrationTxFactory) GenerateSignedEthTx(privKey cryptotypes.PrivKey,
return tf.buildSignedTx(signedMsg)
}

// GenerateSignedMsgEthereumTx generates an MsgEthereumTx signed with the provided private key and txArgs.
func (tf *IntegrationTxFactory) GenerateSignedMsgEthereumTx(privKey cryptotypes.PrivKey, txArgs evmtypes.EvmTxArgs) (evmtypes.MsgEthereumTx, error) {
msgEthereumTx, err := tf.GenerateMsgEthereumTx(privKey, txArgs)
if err != nil {
return evmtypes.MsgEthereumTx{}, errorsmod.Wrap(err, "failed to create ethereum tx")
}

return tf.SignMsgEthereumTx(privKey, msgEthereumTx)
}

// GenerateMsgEthereumTx creates a new MsgEthereumTx with the provided arguments.
// If any of the arguments are not provided, they will be populated with default values.
func (tf *IntegrationTxFactory) GenerateMsgEthereumTx(
Expand Down
2 changes: 2 additions & 0 deletions testutil/integration/evmos/factory/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ type TxFactory interface {
GenerateDefaultTxTypeArgs(sender common.Address, txType int) (evmtypes.EvmTxArgs, error)
// GenerateSignedEthTx generates an Ethereum tx with the provided private key and txArgs but does not broadcast it.
GenerateSignedEthTx(privKey cryptotypes.PrivKey, txArgs evmtypes.EvmTxArgs) (signing.Tx, error)
// GenerateSignedMsgEthereumTx generates an MsgEthereumTx signed with the provided private key and txArgs.
GenerateSignedMsgEthereumTx(privKey cryptotypes.PrivKey, txArgs evmtypes.EvmTxArgs) (evmtypes.MsgEthereumTx, error)

// SignMsgEthereumTx signs a MsgEthereumTx with the provided private key.
SignMsgEthereumTx(privKey cryptotypes.PrivKey, msgEthereumTx evmtypes.MsgEthereumTx) (evmtypes.MsgEthereumTx, error)
Expand Down
7 changes: 7 additions & 0 deletions testutil/integration/evmos/keyring/keyring.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ type Keyring interface {
GetAllAccAddrs() []sdktypes.AccAddress
// GetKey returns the key at the given keyring index
GetKey(index int) Key
// GetKeys returns all the keys
GetKeys() []Key

// AddKey adds a new account to the keyring
AddKey() int
Expand Down Expand Up @@ -94,6 +96,11 @@ func (kr *IntegrationKeyring) GetKey(index int) Key {
return kr.keys[index]
}

// GetKey returns the key specified by index
func (kr *IntegrationKeyring) GetKeys() []Key {
return kr.keys
}

// AddKey adds a new account to the keyring. It returns the index for the key
func (kr *IntegrationKeyring) AddKey() int {
acc := NewKey()
Expand Down
30 changes: 18 additions & 12 deletions testutil/integration/evmos/network/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,8 @@ func (n *IntegrationNetwork) NextBlockAfter(duration time.Duration) error {
newBlockTime := header.Time.Add(duration)
header.Time = newBlockTime

// add validator's commit info to allocate corresponding tokens to validators
ci := getCommitInfo(n.valSet.Validators)

// FinalizeBlock to run endBlock, deliverTx & beginBlock logic
req := &abcitypes.RequestFinalizeBlock{
Height: n.app.LastBlockHeight() + 1,
DecidedLastCommit: ci,
Hash: header.AppHash,
NextValidatorsHash: n.valSet.Hash(),
ProposerAddress: n.valSet.Proposer.Address,
Time: newBlockTime,
}
req := buildFinalizeBlockReq(header, n.valSet.Validators)

if _, err := n.app.FinalizeBlock(req); err != nil {
return err
Expand All @@ -55,7 +45,7 @@ func (n *IntegrationNetwork) NextBlockAfter(duration time.Duration) error {
newCtx = newCtx.WithConsensusParams(n.ctx.ConsensusParams())
// This might have to be changed with time if we want to test gas limits
newCtx = newCtx.WithBlockGasMeter(storetypes.NewInfiniteGasMeter())
newCtx = newCtx.WithVoteInfos(ci.GetVotes())
newCtx = newCtx.WithVoteInfos(req.DecidedLastCommit.GetVotes())
n.ctx = newCtx

// commit changes
Expand All @@ -64,6 +54,22 @@ func (n *IntegrationNetwork) NextBlockAfter(duration time.Duration) error {
return err
}

// buildFinalizeBlockReq is a helper function to build
// properly the FinalizeBlock request
func buildFinalizeBlockReq(header cmtproto.Header, validators []*cmttypes.Validator, txs ...[]byte) *abcitypes.RequestFinalizeBlock {
// add validator's commit info to allocate corresponding tokens to validators
ci := getCommitInfo(validators)
return &abcitypes.RequestFinalizeBlock{
Height: header.Height,
DecidedLastCommit: ci,
Hash: header.AppHash,
NextValidatorsHash: header.ValidatorsHash,
ProposerAddress: header.ProposerAddress,
Time: header.Time,
Txs: txs,
}
}

func getCommitInfo(validators []*cmttypes.Validator) abcitypes.CommitInfo {
voteInfos := make([]abcitypes.VoteInfo, len(validators))
for i, val := range validators {
Expand Down
7 changes: 7 additions & 0 deletions testutil/integration/evmos/network/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
feemarkettypes "github.com/evmos/evmos/v16/x/feemarket/types"
infltypes "github.com/evmos/evmos/v16/x/inflation/v1/types"
revtypes "github.com/evmos/evmos/v16/x/revenue/v1/types"
vestingtypes "github.com/evmos/evmos/v16/x/vesting/types"
)

func getQueryHelper(ctx sdktypes.Context) *baseapp.QueryServiceTestHelper {
Expand Down Expand Up @@ -106,3 +107,9 @@ func (n *IntegrationNetwork) GetEpochsClient() epochstypes.QueryClient {
epochstypes.RegisterQueryServer(queryHelper, n.app.EpochsKeeper)
return epochstypes.NewQueryClient(queryHelper)
}

func (n *IntegrationNetwork) GetVestingClient() vestingtypes.QueryClient {
queryHelper := getQueryHelper(n.GetContext())
vestingtypes.RegisterQueryServer(queryHelper, n.app.VestingKeeper)
return vestingtypes.NewQueryClient(queryHelper)
}
45 changes: 21 additions & 24 deletions testutil/integration/evmos/network/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
feemarkettypes "github.com/evmos/evmos/v16/x/feemarket/types"
infltypes "github.com/evmos/evmos/v16/x/inflation/v1/types"
revtypes "github.com/evmos/evmos/v16/x/revenue/v1/types"
vestingtypes "github.com/evmos/evmos/v16/x/vesting/types"
)

// Network is the interface that wraps the methods to interact with integration test network.
Expand All @@ -51,6 +52,7 @@ type Network interface {
GetRevenueClient() revtypes.QueryClient
GetInflationClient() infltypes.QueryClient
GetFeeMarketClient() feemarkettypes.QueryClient
GetVestingClient() vestingtypes.QueryClient
}

var _ Network = (*IntegrationNetwork)(nil)
Expand Down Expand Up @@ -192,30 +194,24 @@ func (n *IntegrationNetwork) configureAndInitChain() error {
return err
}

req := &abcitypes.RequestFinalizeBlock{
header := cmtproto.Header{
ChainID: n.cfg.chainID,
Height: evmosApp.LastBlockHeight() + 1,
Hash: evmosApp.LastCommitID().Hash,
AppHash: evmosApp.LastCommitID().Hash,
Time: now,
ValidatorsHash: valSet.Hash(),
NextValidatorsHash: valSet.Hash(),
ProposerAddress: valSet.Proposer.Address,
Time: now,
Version: tmversion.Consensus{
Block: version.BlockProtocol,
},
}

req := buildFinalizeBlockReq(header, valSet.Validators)
if _, err := evmosApp.FinalizeBlock(req); err != nil {
return err
}

header := cmtproto.Header{
ChainID: n.cfg.chainID,
Height: req.Height,
AppHash: req.Hash,
Time: now,
ValidatorsHash: req.NextValidatorsHash,
NextValidatorsHash: req.NextValidatorsHash,
ProposerAddress: req.ProposerAddress,
Version: tmversion.Consensus{
Block: version.BlockProtocol,
},
}
// TODO - this might not be the best way to initilize the context
n.ctx = evmosApp.BaseApp.NewContextLegacy(false, header)

Expand Down Expand Up @@ -286,15 +282,16 @@ func (n *IntegrationNetwork) GetValidators() []stakingtypes.Validator {
// BroadcastTxSync broadcasts the given txBytes to the network and returns the response.
// TODO - this should be change to gRPC
func (n *IntegrationNetwork) BroadcastTxSync(txBytes []byte) (abcitypes.ExecTxResult, error) {
req := abcitypes.RequestFinalizeBlock{
Time: n.ctx.BlockTime(),
Height: n.app.LastBlockHeight() + 1,
Hash: n.app.LastCommitID().Hash,
NextValidatorsHash: n.valSet.Hash(),
ProposerAddress: n.valSet.Proposer.Address,
Txs: [][]byte{txBytes},
}
blockRes, err := n.app.BaseApp.FinalizeBlock(&req)
header := n.ctx.BlockHeader()
// Update block header and BeginBlock
header.Height++
header.AppHash = n.app.LastCommitID().Hash
// Calculate new block time after duration
newBlockTime := header.Time.Add(time.Second)
header.Time = newBlockTime

req := buildFinalizeBlockReq(header, n.valSet.Validators, txBytes)
blockRes, err := n.app.BaseApp.FinalizeBlock(req)
if err != nil {
return abcitypes.ExecTxResult{}, err
}
Expand Down
4 changes: 3 additions & 1 deletion testutil/integration/evmos/network/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,9 @@ func setDefaultGovGenesisState(evmosApp *app.Evmos, genesisState types.GenesisSt
govGen := govtypesv1.DefaultGenesisState()
updatedParams := govGen.Params
// set 'aevmos' as deposit denom
updatedParams.MinDeposit = sdktypes.NewCoins(sdktypes.NewCoin(evmosutil.BaseDenom, sdkmath.NewInt(1e18)))
minDepositAmt := sdkmath.NewInt(1e18)
updatedParams.MinDeposit = sdktypes.NewCoins(sdktypes.NewCoin(evmosutil.BaseDenom, minDepositAmt))
updatedParams.ExpeditedMinDeposit = sdktypes.NewCoins(sdktypes.NewCoin(evmosutil.BaseDenom, minDepositAmt))
govGen.Params = updatedParams
genesisState[govtypes.ModuleName] = evmosApp.AppCodec().MustMarshalJSON(govGen)
return genesisState
Expand Down
47 changes: 43 additions & 4 deletions testutil/integration/evmos/utils/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,53 @@
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package utils

import sdktypes "github.com/cosmos/cosmos-sdk/types"
import (
"errors"
"fmt"

abcitypes "github.com/cometbft/cometbft/abci/types"
sdktypes "github.com/cosmos/cosmos-sdk/types"
)

// ContainsEventType returns true if the given events contain the given eventType.
func ContainsEventType(events sdktypes.Events, eventType string) bool {
func ContainsEventType(events []abcitypes.Event, eventType string) bool {
event := GetEventType(events, eventType)
return event != nil
}

// GetEventType returns the given events if found
// Otherwise returns nil
func GetEventType(events []abcitypes.Event, eventType string) *abcitypes.Event {
for _, event := range events {
if event.Type == eventType {
return true
return &event
}
}
return false
return nil
}

// GetEventAttributeValue returns the value for the required
// attribute key
func GetEventAttributeValue(event abcitypes.Event, attrKey string) string {
for _, attr := range event.Attributes {
if attr.Key == attrKey {
return attr.Value
}
}
return ""
}

// GetEventAttributeValue returns the value for the required
GAtom22 marked this conversation as resolved.
Show resolved Hide resolved
// attribute key
func GetFeesFromEvents(events []abcitypes.Event) (sdktypes.DecCoins, error) {
event := GetEventType(events, sdktypes.EventTypeTx)
if event == nil {
return sdktypes.DecCoins{}, errors.New("tx event not found")
}
feeStr := GetEventAttributeValue(*event, sdktypes.AttributeKeyFee)
feeCoins, err := sdktypes.ParseDecCoins(feeStr)
if err != nil {
return sdktypes.DecCoins{}, fmt.Errorf("invalid fees: %v. got %s", err, feeStr)
}
return feeCoins, nil
}
11 changes: 5 additions & 6 deletions testutil/integration/evmos/utils/gov.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func SubmitLegacyProposal(tf factory.TxFactory, network network.Network, propose

// VoteOnProposal is a helper function to vote on a governance proposal given the private key of the voter and
// the option to vote.
func VoteOnProposal(tf factory.TxFactory, voterPriv cryptotypes.PrivKey, proposalID uint64, option govv1.VoteOption) error {
func VoteOnProposal(tf factory.TxFactory, voterPriv cryptotypes.PrivKey, proposalID uint64, option govv1.VoteOption) (abcitypes.ExecTxResult, error) {
voterAccAddr := sdk.AccAddress(voterPriv.PubKey().Address())

msgVote := govv1.NewMsgVote(
Expand All @@ -78,19 +78,18 @@ func VoteOnProposal(tf factory.TxFactory, voterPriv cryptotypes.PrivKey, proposa
"",
)

_, err := tf.ExecuteCosmosTx(voterPriv, commonfactory.CosmosTxArgs{
res, err := tf.ExecuteCosmosTx(voterPriv, commonfactory.CosmosTxArgs{
Msgs: []sdk.Msg{msgVote},
})

return err
return res, err
}

// ApproveLegacyProposal is a helper function to vote 'yes'
// ApproveProposal is a helper function to vote 'yes'
// for it and wait till it passes.
func ApproveProposal(tf factory.TxFactory, network network.Network, proposerPriv cryptotypes.PrivKey, proposalID uint64) error {
// Vote on proposal
err := VoteOnProposal(tf, proposerPriv, proposalID, govv1.OptionYes)
if err != nil {
if _, err := VoteOnProposal(tf, proposerPriv, proposalID, govv1.OptionYes); err != nil {
return errorsmod.Wrap(err, "failed to vote on proposal")
}

Expand Down
1 change: 1 addition & 0 deletions testutil/network/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance
cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[govtypes.ModuleName], &govGenState)

govGenState.Params.MinDeposit[0].Denom = cfg.BondDenom
govGenState.Params.ExpeditedMinDeposit[0].Denom = cfg.BondDenom
cfg.GenesisState[govtypes.ModuleName] = cfg.Codec.MustMarshalJSON(&govGenState)

var inflationGenState inflationtypes.GenesisState
Expand Down