diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index fdf7e8e2c..fe4167754 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -18,7 +18,7 @@ permissions: read-all jobs: analyze: name: Analyze - runs-on: depot-ubuntu-24.04-8 + runs-on: depot-ubuntu-24.04-4 permissions: actions: read contents: read diff --git a/.github/workflows/system-test.yml b/.github/workflows/system-test.yml index 1704bac9b..077fc6eeb 100644 --- a/.github/workflows/system-test.yml +++ b/.github/workflows/system-test.yml @@ -10,7 +10,7 @@ permissions: read-all jobs: cleanup-runs: - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04-4 steps: - uses: rokroskar/workflow-run-cleanup-action@master env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 59e7dd1ab..d23d01b0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ - [\#511](https://github.com/cosmos/evm/pull/511) Minor code cleanup for `AddPrecompileFn`. - [\#544](https://github.com/cosmos/evm/pull/544) Parse logs from the txResult.Data and avoid emitting EVM events to cosmos-sdk events. - [\#582](https://github.com/cosmos/evm/pull/582) Add block max-gas (from genesis.json) and new min-tip (from app.toml/flags) ingestion into mempool config +- [\#436](https://github.com/cosmos/evm/pull/436) Refactor and consolidate chain config helpers and constants for test suites ### FEATURES diff --git a/Makefile b/Makefile index 5bd994ea3..f001377b0 100644 --- a/Makefile +++ b/Makefile @@ -145,9 +145,16 @@ test-race: ARGS=-race test-race: TEST_PACKAGES=$(PACKAGES_UNIT) test-race: run-tests +# Chain configuration environment variables +CHAIN_ENV_VARS = $(if $(CHAIN_ID),CHAIN_ID="$(CHAIN_ID)") \ + $(if $(EVM_CHAIN_ID),EVM_CHAIN_ID="$(EVM_CHAIN_ID)") \ + $(if $(DISPLAY_DENOM),DISPLAY_DENOM="$(DISPLAY_DENOM)") \ + $(if $(DECIMALS),DECIMALS="$(DECIMALS)") \ + $(if $(EXTENDED_DECIMALS),EXTENDED_DECIMALS="$(EXTENDED_DECIMALS)") + test-evmd: ARGS=-timeout=15m test-evmd: - @cd evmd && go test -tags=test -mod=readonly $(ARGS) $(EXTRA_ARGS) $(PACKAGES_EVMD) + @cd evmd && $(CHAIN_ENV_VARS) go test -tags=test -mod=readonly $(ARGS) $(EXTRA_ARGS) $(PACKAGES_EVMD) test-unit-cover: ARGS=-timeout=15m -coverprofile=coverage.txt -covermode=atomic test-unit-cover: TEST_PACKAGES=$(PACKAGES_UNIT) @@ -196,7 +203,7 @@ test-scripts: test-solidity: @echo "Beginning solidity tests..." - ./scripts/run-solidity-tests.sh + @$(CHAIN_ENV_VARS) ./scripts/run-solidity-tests.sh .PHONY: run-tests test test-all $(TEST_TARGETS) diff --git a/ante/cosmos/authz_test.go b/ante/cosmos/authz_test.go index aee72f910..010ba2653 100644 --- a/ante/cosmos/authz_test.go +++ b/ante/cosmos/authz_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/evm/ante/cosmos" "github.com/cosmos/evm/encoding" "github.com/cosmos/evm/testutil" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -21,17 +21,16 @@ import ( ) func TestAuthzLimiterDecorator(t *testing.T) { - evmConfigurator := evmtypes.NewEVMConfigurator(). - WithEVMCoinInfo(constants.ExampleChainCoinInfo[constants.ExampleChainID]) - err := evmConfigurator.Configure() - require.NoError(t, err) + chainConfig := testconfig.DefaultChainConfig + evmChainID := chainConfig.EvmConfig.ChainConfig.ChainId + evmCoinInfo := chainConfig.EvmConfig.CoinInfo + evmDenom := evmCoinInfo.GetDenom() - encodingCfg := encoding.MakeConfig(constants.ExampleChainID.EVMChainID) + encodingCfg := encoding.MakeConfig(evmChainID) txCfg := encodingCfg.TxConfig testPrivKeys, testAddresses, err := testutil.GeneratePrivKeyAddressPairs(5) require.NoError(t, err) - evmDenom := evmtypes.GetEVMCoinDenom() distantFuture := time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) validator := sdk.ValAddress(testAddresses[4]) diff --git a/ante/evm/fee_checker_test.go b/ante/evm/fee_checker_test.go index a5cbc3734..f850cac0b 100644 --- a/ante/evm/fee_checker_test.go +++ b/ante/evm/fee_checker_test.go @@ -11,8 +11,7 @@ import ( "github.com/cosmos/evm/ante/evm" anteinterfaces "github.com/cosmos/evm/ante/interfaces" "github.com/cosmos/evm/encoding" - "github.com/cosmos/evm/testutil/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/types" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -57,9 +56,15 @@ func TestSDKTxFeeChecker(t *testing.T) { // with extension option // without extension option // london hardfork enableness - chainID := uint64(config.EighteenDecimalsChainID) + chainConfig := testconfig.DefaultChainConfig + chainID := chainConfig.EvmConfig.ChainConfig.EthereumConfig().ChainID + chainDenomAtto := chainConfig.EvmConfig.CoinInfo.GetDenom() encodingConfig := encoding.MakeConfig(chainID) - err := config.EvmAppOptions(chainID) + + // Configure EVM with test configuration + configurator := typesutil.NewEVMConfigurator() + configurator.ResetTestConfig() + err := configurator.WithEVMCoinInfo(chainConfig.EvmConfig).Configure() require.NoError(t, err) evmDenom := evmtypes.GetEVMCoinDenom() @@ -110,7 +115,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10)))) return txBuilder.GetTx() }, false, @@ -155,7 +160,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10)))) return txBuilder.GetTx() }, true, @@ -172,7 +177,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder() txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) return txBuilder.GetTx() }, true, @@ -189,7 +194,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction)))) option, err := codectypes.NewAnyWithValue(&types.ExtensionOptionDynamicFeeTx{}) require.NoError(t, err) @@ -210,7 +215,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) option, err := codectypes.NewAnyWithValue(&types.ExtensionOptionDynamicFeeTx{ MaxPriorityPrice: math.LegacyNewDec(5).MulInt(evmtypes.DefaultPriorityReduction), @@ -233,7 +238,7 @@ func TestSDKTxFeeChecker(t *testing.T) { func() sdk.FeeTx { txBuilder := encodingConfig.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) txBuilder.SetGasLimit(1) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(chainDenomAtto, math.NewInt(10).Mul(evmtypes.DefaultPriorityReduction).Add(math.NewInt(10))))) // set negative priority fee option, err := codectypes.NewAnyWithValue(&types.ExtensionOptionDynamicFeeTx{ diff --git a/ante/evm/mono_decorator_test.go b/ante/evm/mono_decorator_test.go index 295415734..6bf421822 100644 --- a/ante/evm/mono_decorator_test.go +++ b/ante/evm/mono_decorator_test.go @@ -19,7 +19,7 @@ import ( "github.com/cosmos/evm/ante/evm" "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/encoding" - "github.com/cosmos/evm/testutil/config" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" "github.com/cosmos/evm/x/vm/statedb" @@ -119,7 +119,9 @@ func signMsgEthereumTx(t *testing.T, privKey *ethsecp256k1.PrivKey, args *evmsdk msg := evmsdktypes.NewTx(args) fromAddr := common.BytesToAddress(privKey.PubKey().Address().Bytes()) msg.From = fromAddr.Bytes() - ethSigner := ethtypes.LatestSignerForChainID(evmsdktypes.GetEthChainConfig().ChainID) + // Use the configured chain ID instead of the default one + chainID := new(big.Int).SetUint64(testconfig.DefaultChainConfig.EvmConfig.ChainConfig.ChainId) + ethSigner := ethtypes.LatestSignerForChainID(chainID) require.NoError(t, msg.Sign(ethSigner, utiltx.NewSigner(privKey))) return msg } @@ -144,8 +146,9 @@ func toMsgSlice(msgs []*evmsdktypes.MsgEthereumTx) []sdk.Msg { } func TestMonoDecorator(t *testing.T) { - chainID := uint64(config.EighteenDecimalsChainID) - require.NoError(t, config.EvmAppOptions(chainID)) + chainConfig := testconfig.DefaultChainConfig + chainID := chainConfig.EvmConfig.ChainConfig.ChainId + cfg := encoding.MakeConfig(chainID) testCases := []struct { diff --git a/ante/sigverify_test.go b/ante/sigverify_test.go index dce22274c..d0ec86172 100644 --- a/ante/sigverify_test.go +++ b/ante/sigverify_test.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/evm/ante" "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/encoding" - "github.com/cosmos/evm/server/config" + testconfig "github.com/cosmos/evm/testutil/config" storetypes "cosmossdk.io/store/types" @@ -27,7 +27,7 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { params := authtypes.DefaultParams() msg := []byte{1, 2, 3, 4} - encodingConfig := encoding.MakeConfig(config.DefaultEVMChainID) + encodingConfig := encoding.MakeConfig(testconfig.DefaultChainConfig.ChainInfo.EVMChainID) cdc := encodingConfig.Amino p := authtypes.DefaultParams() diff --git a/config/evm_app_options.go b/config/app_options.go similarity index 76% rename from config/evm_app_options.go rename to config/app_options.go index 63b06dbc6..cb1c2af7e 100644 --- a/config/evm_app_options.go +++ b/config/app_options.go @@ -1,8 +1,6 @@ package config import ( - "fmt" - "github.com/ethereum/go-ethereum/core/vm" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -19,16 +17,17 @@ type EVMOptionsFn func(uint64) error var sealed = false +// EvmAppOptionsWithConfig sets up EVM configuration with the provided coin info and activators. func EvmAppOptionsWithConfig( chainID uint64, - chainsCoinInfo map[uint64]evmtypes.EvmCoinInfo, - cosmosEVMActivators map[int]func(*vm.JumpTable), + coinInfo evmtypes.EvmCoinInfo, + activators map[int]func(*vm.JumpTable), ) error { if sealed { return nil } - if err := EvmAppOptionsWithConfigWithReset(chainID, chainsCoinInfo, cosmosEVMActivators, false); err != nil { + if err := EvmAppOptionsWithConfigWithReset(chainID, coinInfo, activators, false); err != nil { return err } @@ -36,32 +35,28 @@ func EvmAppOptionsWithConfig( return nil } +// EvmAppOptionsWithConfigWithReset sets up EVM configuration with an optional reset flag +// to allow reconfiguration during testing. func EvmAppOptionsWithConfigWithReset( chainID uint64, - chainsCoinInfo map[uint64]evmtypes.EvmCoinInfo, - cosmosEVMActivators map[int]func(*vm.JumpTable), + coinInfo evmtypes.EvmCoinInfo, + activators map[int]func(*vm.JumpTable), withReset bool, ) error { - coinInfo, found := chainsCoinInfo[chainID] - if !found { - return fmt.Errorf("unknown chain id: %d", chainID) - } - // set the denom info for the chain if err := setBaseDenom(coinInfo); err != nil { return err } ethCfg := evmtypes.DefaultChainConfig(chainID) - configurator := evmtypes.NewEVMConfigurator() + configurator := evmtypes.NewEvmConfig() if withReset { // reset configuration to set the new one configurator.ResetTestConfig() } err := configurator. - WithExtendedEips(cosmosEVMActivators). + WithExtendedEips(activators). WithChainConfig(ethCfg). - // NOTE: we're using the 18 decimals default for the example chain WithEVMCoinInfo(coinInfo). Configure() if err != nil { diff --git a/ethereum/eip712/preprocess_test.go b/ethereum/eip712/preprocess_test.go index c0376fda0..a638a7ddc 100644 --- a/ethereum/eip712/preprocess_test.go +++ b/ethereum/eip712/preprocess_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/evm/encoding" "github.com/cosmos/evm/ethereum/eip712" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -30,7 +30,7 @@ import ( // Testing Constants var ( // chainID is used in EIP-712 tests. - chainID = uint64(constants.ExampleEIP155ChainID) + chainID = testconfig.DefaultChainConfig.ChainInfo.EVMChainID ctx = client.Context{}.WithTxConfig( encoding.MakeConfig(chainID).TxConfig, @@ -39,7 +39,7 @@ var ( // feePayerAddress is the address of the fee payer used in EIP-712 tests. feePayerAddress = fmt.Sprintf( "%s17xpfvakm2amg962yls6f84z3kell8c5lserqta", - constants.ExampleBech32Prefix, + sdk.GetConfig().GetBech32AccountAddrPrefix(), ) ) @@ -54,10 +54,8 @@ type TestCaseStruct struct { } func TestLedgerPreprocessing(t *testing.T) { - // Update bech32 prefix - sdk.GetConfig().SetBech32PrefixForAccount(constants.ExampleBech32Prefix, "") - evmConfigurator := evmtypes.NewEVMConfigurator(). - WithEVMCoinInfo(constants.ExampleChainCoinInfo[constants.ExampleChainID]) + coinInfo := testconfig.DefaultChainConfig.EvmConfig + evmConfigurator := evmtypes.NewEvmConfig().WithEVMCoinInfo(coinInfo) err := evmConfigurator.Configure() require.NoError(t, err) diff --git a/evmd/cmd/evmd/cmd/creator.go b/evmd/cmd/evmd/cmd/creator.go index c6238998d..2effac635 100644 --- a/evmd/cmd/evmd/cmd/creator.go +++ b/evmd/cmd/evmd/cmd/creator.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "fmt" "io" "path/filepath" @@ -10,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" servertypes "github.com/cosmos/cosmos-sdk/server/types" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/cosmos/evm/evmd" evmdconfig "github.com/cosmos/evm/evmd/cmd/evmd/config" @@ -88,14 +88,20 @@ func (a appCreator) newApp( baseapp.SetIAVLCacheSize(cast.ToInt(appOpts.Get(server.FlagIAVLCacheSize))), } + // Load chain configuration from app options + chainConfig, err := evmdconfig.LoadChainConfig(appOpts) + if err != nil { + panic(fmt.Errorf("failed to load chain configuration: %w", err)) + } + return evmd.NewExampleApp( logger, db, traceStore, true, - simtestutil.EmptyAppOptions{}, - evmdconfig.EVMChainID, - evmdconfig.EvmAppOptions, + appOpts, + chainConfig.ChainInfo.EVMChainID, + evmdconfig.EvmAppOptionsFromConfig(chainConfig), baseappOptions..., ) } @@ -131,14 +137,20 @@ func (a appCreator) appExport( loadLatest = true } + // Load chain configuration from app options + chainConfig, err := evmdconfig.LoadChainConfig(appOpts) + if err != nil { + return servertypes.ExportedApp{}, fmt.Errorf("failed to load chain configuration: %w", err) + } + evmApp = evmd.NewExampleApp( logger, db, traceStore, loadLatest, appOpts, - evmdconfig.EVMChainID, - evmdconfig.EvmAppOptions, + chainConfig.ChainInfo.EVMChainID, + evmdconfig.EvmAppOptionsFromConfig(chainConfig), ) if height != -1 { diff --git a/evmd/cmd/evmd/cmd/testnet.go b/evmd/cmd/evmd/cmd/testnet.go index c90690cb0..e6c40c842 100644 --- a/evmd/cmd/evmd/cmd/testnet.go +++ b/evmd/cmd/evmd/cmd/testnet.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/evm/evmd" evmdconfig "github.com/cosmos/evm/evmd/cmd/evmd/config" cosmosevmserverconfig "github.com/cosmos/evm/server/config" + evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -65,7 +66,10 @@ var ( unsafeStartValidatorFn UnsafeStartValidatorCmdCreator ) -const TEST_DENOM = "atest" +const ( + TEST_DENOM = "atest" + TEST_EVM_CHAIN_ID = 9000 // Test EVM chain ID, different from mainnet +) var mnemonics = []string{ "copper push brief egg scan entry inform record adjust fossil boss egg comic alien upon aspect dry avoid interest fury window hint race symptom", @@ -108,7 +112,7 @@ func addTestnetFlagsToCmd(cmd *cobra.Command) { cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with") cmd.Flags().StringP(flagOutputDir, "o", "./.testnets", "Directory to store initialization data for the testnet") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") - cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") + cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", TEST_DENOM), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") cmd.Flags().String(flags.FlagKeyType, string(cosmosevmhd.EthSecp256k1Type), "Key signing algorithm to generate keys for") // support old flags name for backwards compatibility @@ -268,12 +272,13 @@ func initTestnetFiles( appConfig.Telemetry.EnableHostnameLabel = false appConfig.Telemetry.GlobalLabels = [][]string{{"chain_id", args.chainID}} evm := cosmosevmserverconfig.DefaultEVMConfig() - evm.EVMChainID = evmdconfig.EVMChainID + evm.EVMChainID = TEST_EVM_CHAIN_ID evmCfg := evmdconfig.EVMAppConfig{ Config: *appConfig, EVM: *evm, JSONRPC: *cosmosevmserverconfig.DefaultJSONRPCConfig(), TLS: *cosmosevmserverconfig.DefaultTLSConfig(), + Coin: *cosmosevmserverconfig.DefaultEvmCoinInfo(), } var ( @@ -669,6 +674,22 @@ func startTestnet(cmd *cobra.Command, args startArgs) error { return nil } +// createTestChainConfig creates a chain configuration suitable for testing. +func createTestChainConfig() evmdconfig.ChainConfig { + return evmdconfig.ChainConfig{ + ChainInfo: evmdconfig.ChainInfo{ + ChainID: "test-chain", + EVMChainID: TEST_EVM_CHAIN_ID, + }, + CoinInfo: evmtypes.EvmCoinInfo{ + Denom: TEST_DENOM, + ExtendedDenom: TEST_DENOM, + DisplayDenom: "test", + Decimals: 18, + }, + } +} + // NewTestNetworkFixture returns a new evmd AppConstructor for network simulation tests func NewTestNetworkFixture() network.TestFixture { dir, err := os.MkdirTemp("", "evm") @@ -677,14 +698,16 @@ func NewTestNetworkFixture() network.TestFixture { } defer os.RemoveAll(dir) + testConfig := createTestChainConfig() + app := evmd.NewExampleApp( log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.EmptyAppOptions{}, - evmdconfig.EVMChainID, - evmdconfig.EvmAppOptions, + testConfig.ChainInfo.EVMChainID, + evmdconfig.EvmAppOptionsFromConfig(testConfig), ) appCtr := func(val network.ValidatorI) servertypes.Application { @@ -694,8 +717,8 @@ func NewTestNetworkFixture() network.TestFixture { nil, true, simtestutil.EmptyAppOptions{}, - evmdconfig.EVMChainID, - evmdconfig.EvmAppOptions, + testConfig.ChainInfo.EVMChainID, + evmdconfig.EvmAppOptionsFromConfig(testConfig), ) } diff --git a/evmd/cmd/evmd/config/config.go b/evmd/cmd/evmd/config/config.go index 2699ca0b6..85e43f341 100644 --- a/evmd/cmd/evmd/config/config.go +++ b/evmd/cmd/evmd/config/config.go @@ -1,68 +1,24 @@ package config import ( + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/evm/types" evmtypes "github.com/cosmos/evm/x/vm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" ) -// ChainsCoinInfo is a map of the chain id and its corresponding EvmCoinInfo -// that allows initializing the app with different coin info based on the -// chain id -var ChainsCoinInfo = map[uint64]evmtypes.EvmCoinInfo{ - EighteenDecimalsChainID: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, - // SixDecimalsChainID provides a chain ID which is being set up with 6 decimals - SixDecimalsChainID: { - Denom: "utest", - ExtendedDenom: "atest", - DisplayDenom: "test", - Decimals: evmtypes.SixDecimals, - }, - // EVMChainID provides a chain ID used for internal testing - EVMChainID: { - Denom: "atest", - ExtendedDenom: "atest", - DisplayDenom: "test", - Decimals: evmtypes.EighteenDecimals, - }, -} - const ( - // Bech32Prefix defines the Bech32 prefix used for accounts on the exemplary Cosmos EVM blockchain. - Bech32Prefix = "cosmos" - // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address. - Bech32PrefixAccAddr = Bech32Prefix - // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key. - Bech32PrefixAccPub = Bech32Prefix + sdk.PrefixPublic - // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address. - Bech32PrefixValAddr = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator - // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key. - Bech32PrefixValPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator + sdk.PrefixPublic - // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address. - Bech32PrefixConsAddr = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus - // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key. - Bech32PrefixConsPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic - // DisplayDenom defines the denomination displayed to users in client applications. - DisplayDenom = "atom" - // BaseDenom defines to the default denomination used in the Cosmos EVM example chain. - BaseDenom = "aatom" - // BaseDenomUnit defines the precision of the base denomination. - BaseDenomUnit = 18 - // EVMChainID defines the EIP-155 replay-protection chain id for the current ethereum chain config. - EVMChainID = 262144 + // WEVMOSContractMainnet is the WEVMOS contract address for mainnet + WEVMOSContractMainnet = "0xD4949664cD82660AaE99bEdc034a0deA8A0bd517" ) -// SetBech32Prefixes sets the global prefixes to be used when serializing addresses and public keys to Bech32 strings. -func SetBech32Prefixes(config *sdk.Config) { - config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) +type ChainConfig struct { + ChainInfo ChainInfo + CoinInfo evmtypes.EvmCoinInfo +} + +type ChainInfo struct { + ChainID string + EVMChainID uint64 } // SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets. diff --git a/evmd/cmd/evmd/config/config_testing.go b/evmd/cmd/evmd/config/config_testing.go deleted file mode 100644 index 504d57427..000000000 --- a/evmd/cmd/evmd/config/config_testing.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build test -// +build test - -package config - -import ( - evmconfig "github.com/cosmos/evm/config" - testconfig "github.com/cosmos/evm/testutil/config" -) - -// EvmAppOptions allows to setup the global configuration -// for the Cosmos EVM chain. -func EvmAppOptions(chainID uint64) error { - return evmconfig.EvmAppOptionsWithConfigWithReset(chainID, testconfig.TestChainsCoinInfo, cosmosEVMActivators, true) -} diff --git a/evmd/cmd/evmd/config/constants.go b/evmd/cmd/evmd/config/constants.go deleted file mode 100644 index fb9bdbe4b..000000000 --- a/evmd/cmd/evmd/config/constants.go +++ /dev/null @@ -1,31 +0,0 @@ -package config - -const ( - // ExampleChainDenom is the denomination of the Cosmos EVM example chain's base coin. - ExampleChainDenom = "aatom" - - // ExampleDisplayDenom is the display denomination of the Cosmos EVM example chain's base coin. - ExampleDisplayDenom = "atom" - - // EighteenDecimalsChainID is the chain ID for the 18 decimals chain. - EighteenDecimalsChainID = 9001 - - // SixDecimalsChainID is the chain ID for the 6 decimals chain. - SixDecimalsChainID = 9002 - - // TwelveDecimalsChainID is the chain ID for the 12 decimals chain. - TwelveDecimalsChainID = 9003 - - // TwoDecimalsChainID is the chain ID for the 2 decimals chain. - TwoDecimalsChainID = 9004 - - CosmosChainID = 262144 - - // TestChainID1 is test chain IDs for IBC E2E test - TestChainID1 = 9005 - // TestChainID2 is test chain IDs for IBC E2E test - TestChainID2 = 9006 - - // WEVMOSContractMainnet is the WEVMOS contract address for mainnet - WEVMOSContractMainnet = "0xD4949664cD82660AaE99bEdc034a0deA8A0bd517" -) diff --git a/evmd/cmd/evmd/config/evm_app_options.go b/evmd/cmd/evmd/config/evm_app_options.go index 07e73107d..855a8d339 100644 --- a/evmd/cmd/evmd/config/evm_app_options.go +++ b/evmd/cmd/evmd/config/evm_app_options.go @@ -1,14 +1,26 @@ -//go:build !test -// +build !test - package config import ( evmconfig "github.com/cosmos/evm/config" + evmtypes "github.com/cosmos/evm/x/vm/types" ) // EvmAppOptions allows to setup the global configuration -// for the Cosmos EVM chain. -func EvmAppOptions(chainID uint64) error { - return evmconfig.EvmAppOptionsWithConfig(chainID, ChainsCoinInfo, cosmosEVMActivators) +// for the Cosmos EVM chain using the provided chain configuration. +func EvmAppOptions(chainConfig ChainConfig) error { + return evmconfig.EvmAppOptionsWithConfig(chainConfig.ChainInfo.EVMChainID, chainConfig.CoinInfo, cosmosEVMActivators) +} + +// EvmAppOptionsFromConfig creates an EVM options function that uses the provided chain configuration. +func EvmAppOptionsFromConfig(chainConfig ChainConfig) evmconfig.EVMOptionsFn { + return func(chainID uint64) error { + // Use the chainID from the config, not the parameter (for consistency) + return evmconfig.EvmAppOptionsWithConfig(chainConfig.ChainInfo.EVMChainID, chainConfig.CoinInfo, cosmosEVMActivators) + } +} + +// LegacyEvmAppOptions provides backward compatibility with the old interface. +// Deprecated: Use EvmAppOptionsFromConfig instead. +func LegacyEvmAppOptions(chainID uint64, coinInfo evmtypes.EvmCoinInfo) error { + return evmconfig.EvmAppOptionsWithConfig(chainID, coinInfo, cosmosEVMActivators) } diff --git a/evmd/cmd/evmd/config/evmd_config.go b/evmd/cmd/evmd/config/evmd_config.go index 2f9303699..52cbb0f69 100644 --- a/evmd/cmd/evmd/config/evmd_config.go +++ b/evmd/cmd/evmd/config/evmd_config.go @@ -24,6 +24,8 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +const EVMAppTemplate = serverconfig.DefaultConfigTemplate + cosmosevmserverconfig.DefaultEVMConfigTemplate + func MustGetDefaultNodeHome() string { defaultNodeHome, err := clienthelpers.GetNodeHomeDirectory(".evmd") if err != nil { @@ -92,11 +94,12 @@ type EVMAppConfig struct { EVM cosmosevmserverconfig.EVMConfig JSONRPC cosmosevmserverconfig.JSONRPCConfig TLS cosmosevmserverconfig.TLSConfig + Coin evmtypes.EvmCoinInfo } -// InitAppConfig helps to override default appConfig template and configs. -// return "", nil if no custom configuration is required for the application. -func InitAppConfig(denom string, evmChainID uint64) (string, interface{}) { +// InitAppConfig returns application's default configuration using the provided chain configuration. +// It overrides the server config to use chain-specific values instead of hardcoded defaults. +func InitAppConfig(chainConfig ChainConfig) (string, interface{}) { // Optionally allow the chain developer to overwrite the SDK's default // server config. srvCfg := serverconfig.DefaultConfig() @@ -112,19 +115,18 @@ func InitAppConfig(denom string, evmChainID uint64) (string, interface{}) { // own app.toml to override, or use this default value. // // In this example application, we set the min gas prices to 0. - srvCfg.MinGasPrices = "0" + denom + srvCfg.MinGasPrices = "0" + chainConfig.CoinInfo.GetDenom() evmCfg := cosmosevmserverconfig.DefaultEVMConfig() - evmCfg.EVMChainID = evmChainID + evmCfg.EVMChainID = chainConfig.ChainInfo.EVMChainID customAppConfig := EVMAppConfig{ Config: *srvCfg, EVM: *evmCfg, JSONRPC: *cosmosevmserverconfig.DefaultJSONRPCConfig(), TLS: *cosmosevmserverconfig.DefaultTLSConfig(), + Coin: chainConfig.CoinInfo, } return EVMAppTemplate, customAppConfig } - -const EVMAppTemplate = serverconfig.DefaultConfigTemplate + cosmosevmserverconfig.DefaultEVMConfigTemplate diff --git a/evmd/cmd/evmd/config/loader.go b/evmd/cmd/evmd/config/loader.go new file mode 100644 index 000000000..f89ddf9e9 --- /dev/null +++ b/evmd/cmd/evmd/config/loader.go @@ -0,0 +1,174 @@ +package config + +import ( + "fmt" + "strconv" + + "github.com/spf13/cast" + + evmtypes "github.com/cosmos/evm/x/vm/types" + + "github.com/cosmos/cosmos-sdk/client/flags" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + srvflags "github.com/cosmos/evm/server/flags" +) + +// LoadChainConfig loads chain configuration from CLI flags and configuration files. +// It follows this priority order: +// 1. CLI flags (highest priority) +// 2. TOML configuration file +// 3. Default values (lowest priority) +func LoadChainConfig(appOpts servertypes.AppOptions) (ChainConfig, error) { + // Load Chain ID + chainID, err := loadChainID(appOpts) + if err != nil { + return ChainConfig{}, fmt.Errorf("failed to load chain ID: %w", err) + } + + // Load EVM Chain ID with defaults + evmChainID, err := loadEVMChainID(appOpts) + if err != nil { + return ChainConfig{}, fmt.Errorf("failed to load EVM chain ID: %w", err) + } + + // Load Coin Info with defaults + coinInfo, err := loadCoinInfoWithDefaults(appOpts) + if err != nil { + return ChainConfig{}, fmt.Errorf("failed to load coin info: %w", err) + } + + // Build ChainConfig using existing structure + chainConfig := ChainConfig{ + ChainInfo: ChainInfo{ + ChainID: chainID, + EVMChainID: evmChainID, + }, + CoinInfo: coinInfo, + } + + return chainConfig, nil +} + +// loadChainID loads the Cosmos chain ID from appOpts, following this priority: +// 1. --chain-id flag +// 2. Home directory client config +// 3. Empty string (will need to be set elsewhere) +func loadChainID(appOpts servertypes.AppOptions) (string, error) { + // Try to get from CLI flag first + chainID := cast.ToString(appOpts.Get(flags.FlagChainID)) + if chainID != "" { + return chainID, nil + } + + // If not available, try to load from home directory + homeDir := cast.ToString(appOpts.Get(flags.FlagHome)) + if homeDir != "" { + chainID, err := GetChainIDFromHome(homeDir) + if err == nil && chainID != "" { + return chainID, nil + } + // Don't error if we can't read from home - just continue with empty + } + + return "", nil +} + +// loadEVMChainID loads the EVM chain ID from appOpts, following this priority: +// 1. --evm.evm-chain-id flag +// 2. TOML configuration [evm] evm-chain-id +// 3. Default value (9001) as fallback +func loadEVMChainID(appOpts servertypes.AppOptions) (uint64, error) { + // Try EVM-specific flag first + if evmFlag := appOpts.Get(srvflags.EVMChainID); evmFlag != nil { + if evmFlagStr := cast.ToString(evmFlag); evmFlagStr != "" { + evmChainID, err := strconv.ParseUint(evmFlagStr, 10, 64) + if err == nil { + return evmChainID, nil + } + // If we have a flag value but can't parse it, that's an error + return 0, fmt.Errorf("failed to parse EVM chain ID from flag: %w", err) + } + } + + // Try TOML configuration + if tomlValue := appOpts.Get("evm.evm-chain-id"); tomlValue != nil { + if tomlStr := cast.ToString(tomlValue); tomlStr != "" { + evmChainID, err := strconv.ParseUint(tomlStr, 10, 64) + if err == nil { + return evmChainID, nil + } + } + } + + // Fall back to default value (matches local_node.sh CHAINID default) + return 9001, nil +} + +// loadCoinInfo loads coin configuration from appOpts. +// All coin configuration must be explicitly specified in TOML configuration [chain] section. +// Returns error if any required values are missing. +func loadCoinInfo(appOpts servertypes.AppOptions) (evmtypes.EvmCoinInfo, error) { + coinInfo := evmtypes.EvmCoinInfo{} + + // All fields are required + denom := cast.ToString(appOpts.Get("coin.denom")) + if denom == "" { + return coinInfo, fmt.Errorf("coin.denom must be specified in [coin] section of app.toml") + } + coinInfo.Denom = denom + + extendedDenom := cast.ToString(appOpts.Get("coin.extended-denom")) + if extendedDenom == "" { + return coinInfo, fmt.Errorf("coin.extended-denom must be specified in [coin] section of app.toml") + } + coinInfo.ExtendedDenom = extendedDenom + + displayDenom := cast.ToString(appOpts.Get("coin.display-denom")) + if displayDenom == "" { + return coinInfo, fmt.Errorf("coin.display-denom must be specified in [coin] section of app.toml") + } + coinInfo.DisplayDenom = displayDenom + + decimals := cast.ToUint64(appOpts.Get("coin.decimals")) + if decimals == 0 { + return coinInfo, fmt.Errorf("coin.decimals must be specified and non-zero in [coin] section of app.toml") + } + coinInfo.Decimals = evmtypes.Decimals(decimals) + + return coinInfo, nil +} + +// loadCoinInfoWithDefaults loads coin configuration with fallback to default values +func loadCoinInfoWithDefaults(appOpts servertypes.AppOptions) (evmtypes.EvmCoinInfo, error) { + // Try to load from configuration first + coinInfo, err := loadCoinInfo(appOpts) + if err == nil { + return coinInfo, nil + } + + // If loading from config fails, provide sensible defaults + // These match the values from local_node.sh environment variables + defaultDenom := "atest" + defaultDisplayDenom := "test" + defaultDecimals := evmtypes.Decimals(18) + + // Create extended denom (atto version for 18-decimal representation) + extendedDenom := evmtypes.CreateDenomStr(defaultDecimals, defaultDisplayDenom) + + // If the base denom has different decimals, we need to create it properly + denom := evmtypes.CreateDenomStr(defaultDecimals, defaultDisplayDenom) + if defaultDecimals == evmtypes.EighteenDecimals { + // For 18 decimals, base and extended are the same + denom = defaultDenom + extendedDenom = defaultDenom + } + + coinInfo = evmtypes.EvmCoinInfo{ + Denom: denom, + ExtendedDenom: extendedDenom, + DisplayDenom: defaultDisplayDenom, + Decimals: defaultDecimals, + } + + return coinInfo, nil +} diff --git a/evmd/cmd/evmd/main.go b/evmd/cmd/evmd/main.go index 0669a5891..cd63910e1 100644 --- a/evmd/cmd/evmd/main.go +++ b/evmd/cmd/evmd/main.go @@ -8,21 +8,12 @@ import ( evmdconfig "github.com/cosmos/evm/evmd/cmd/evmd/config" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - sdk "github.com/cosmos/cosmos-sdk/types" ) func main() { - setupSDKConfig() - rootCmd := cmd.NewRootCmd() if err := svrcmd.Execute(rootCmd, "evmd", evmdconfig.MustGetDefaultNodeHome()); err != nil { fmt.Fprintln(rootCmd.OutOrStderr(), err) os.Exit(1) } } - -func setupSDKConfig() { - config := sdk.GetConfig() - evmdconfig.SetBech32Prefixes(config) - config.Seal() -} diff --git a/evmd/config/client.toml b/evmd/config/client.toml index 2a8569c81..0aa41d768 100644 --- a/evmd/config/client.toml +++ b/evmd/config/client.toml @@ -15,3 +15,5 @@ output = "text" node = "tcp://localhost:26657" # Transaction broadcasting mode (sync|async) broadcast-mode = "sync" +# Denom to use when sending transactions +base-denom = "aatom" \ No newline at end of file diff --git a/evmd/genesis.go b/evmd/genesis.go index 7d656730b..37009c4aa 100644 --- a/evmd/genesis.go +++ b/evmd/genesis.go @@ -3,8 +3,7 @@ package evmd import ( "encoding/json" - "github.com/cosmos/evm/evmd/cmd/evmd/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" erc20types "github.com/cosmos/evm/x/erc20/types" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -39,8 +38,8 @@ func NewEVMGenesisState() *evmtypes.GenesisState { // which is the base denomination of the chain (i.e. the WEVMOS contract). func NewErc20GenesisState() *erc20types.GenesisState { erc20GenState := erc20types.DefaultGenesisState() - erc20GenState.TokenPairs = testconstants.ExampleTokenPairs - erc20GenState.NativePrecompiles = []string{testconstants.WEVMOSContractMainnet} + erc20GenState.TokenPairs = testconfig.DefaultTokenPairs + erc20GenState.NativePrecompiles = []string{testconfig.DefaultWevmosContractMainnet} return erc20GenState } @@ -50,7 +49,7 @@ func NewErc20GenesisState() *erc20types.GenesisState { // NOTE: for the example chain implementation we are also adding a default minter. func NewMintGenesisState() *minttypes.GenesisState { mintGenState := minttypes.DefaultGenesisState() - mintGenState.Params.MintDenom = config.ExampleChainDenom + mintGenState.Params.MintDenom = testconfig.DefaultChainConfig.CoinInfo.Denom return mintGenState } diff --git a/evmd/test_helpers.go b/evmd/test_helpers.go index b7e77d9b3..8b870955a 100644 --- a/evmd/test_helpers.go +++ b/evmd/test_helpers.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/evm/evmd/cmd/evmd/config" testconfig "github.com/cosmos/evm/testutil/config" + evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/stretchr/testify/require" abci "github.com/cometbft/cometbft/abci/types" @@ -44,8 +45,17 @@ func init() { // Set the global SDK config for the tests cfg := sdk.GetConfig() - config.SetBech32Prefixes(cfg) config.SetBip44CoinType(cfg) + // Note: Bech32 prefixes are now managed by the configuration system +} + +// testEvmAppOptions creates an EvmAppOptions function for testing +func testEvmAppOptions(evmChainID uint64) error { + // Use default chain configuration for testing + chainConfig := testconfig.DefaultChainConfig + configurator := evmtypes.NewEVMConfigurator() + configurator.ResetTestConfig() + return configurator.WithEVMCoinInfo(chainConfig.CoinInfo).Configure() } func setup(withGenesis bool, invCheckPeriod uint, chainID string, evmChainID uint64) (*EVMD, GenesisState) { @@ -55,7 +65,7 @@ func setup(withGenesis bool, invCheckPeriod uint, chainID string, evmChainID uin appOptions[flags.FlagHome] = defaultNodeHome appOptions[server.FlagInvCheckPeriod] = invCheckPeriod - app := NewExampleApp(log.NewNopLogger(), db, nil, true, appOptions, evmChainID, testconfig.EvmAppOptions, baseapp.SetChainID(chainID)) + app := NewExampleApp(log.NewNopLogger(), db, nil, true, appOptions, evmChainID, testEvmAppOptions, baseapp.SetChainID(chainID)) if withGenesis { return app, app.DefaultGenesis() } @@ -132,7 +142,7 @@ func SetupTestingApp(chainID string, evmChainID uint64) func() (ibctesting.Testi db, nil, true, simtestutil.NewAppOptionsWithFlagHome(defaultNodeHome), evmChainID, - testconfig.EvmAppOptions, + testEvmAppOptions, baseapp.SetChainID(chainID), ) return app, app.DefaultGenesis() diff --git a/evmd/tests/integration/create_app.go b/evmd/tests/integration/create_app.go index fd05c278f..2b9866ce3 100644 --- a/evmd/tests/integration/create_app.go +++ b/evmd/tests/integration/create_app.go @@ -6,10 +6,9 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/evm" "github.com/cosmos/evm/evmd" - "github.com/cosmos/evm/evmd/cmd/evmd/config" testconfig "github.com/cosmos/evm/testutil/config" - "github.com/cosmos/evm/testutil/constants" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" + evmtypes "github.com/cosmos/evm/x/vm/types" ibctesting "github.com/cosmos/ibc-go/v10/testing" clienthelpers "cosmossdk.io/client/v2/helpers" @@ -21,6 +20,15 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// testEvmAppOptionsWithReset creates an EvmAppOptions function for testing with reset +func testEvmAppOptionsWithReset(evmChainID uint64) error { + // Use default chain configuration for testing + chainConfig := testconfig.DefaultChainConfig + configurator := evmtypes.NewEVMConfigurator() + configurator.ResetTestConfig() + return configurator.WithEVMCoinInfo(chainConfig.CoinInfo).Configure() +} + // CreateEvmd creates an evm app for regular integration tests (non-mempool) // This version uses a noop mempool to avoid state issues during transaction processing func CreateEvmd(chainID string, evmChainID uint64, customBaseAppOptions ...func(*baseapp.BaseApp)) evm.EvmApp { @@ -43,7 +51,7 @@ func CreateEvmd(chainID string, evmChainID uint64, customBaseAppOptions ...func( loadLatest, appOptions, evmChainID, - testconfig.EvmAppOptions, + testEvmAppOptionsWithReset, baseAppOptions..., ) } @@ -51,14 +59,15 @@ func CreateEvmd(chainID string, evmChainID uint64, customBaseAppOptions ...func( // SetupEvmd initializes a new evmd app with default genesis state. // It is used in IBC integration tests to create a new evmd app instance. func SetupEvmd() (ibctesting.TestingApp, map[string]json.RawMessage) { + chainID := testconfig.DefaultChainConfig.ChainInfo.EVMChainID app := evmd.NewExampleApp( log.NewNopLogger(), dbm.NewMemDB(), nil, true, simutils.EmptyAppOptions{}, - constants.ExampleEIP155ChainID, - testconfig.EvmAppOptions, + chainID, + testEvmAppOptionsWithReset, ) // disable base fee for testing genesisState := app.DefaultGenesis() @@ -66,10 +75,10 @@ func SetupEvmd() (ibctesting.TestingApp, map[string]json.RawMessage) { fmGen.Params.NoBaseFee = true genesisState[feemarkettypes.ModuleName] = app.AppCodec().MustMarshalJSON(fmGen) stakingGen := stakingtypes.DefaultGenesisState() - stakingGen.Params.BondDenom = config.ExampleChainDenom + stakingGen.Params.BondDenom = testconfig.DefaultChainConfig.CoinInfo.Denom genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGen) mintGen := minttypes.DefaultGenesisState() - mintGen.Params.MintDenom = config.ExampleChainDenom + mintGen.Params.MintDenom = testconfig.DefaultChainConfig.CoinInfo.Denom genesisState[minttypes.ModuleName] = app.AppCodec().MustMarshalJSON(mintGen) return app, genesisState diff --git a/evmd/tests/integration/x_vm_test.go b/evmd/tests/integration/x_vm_test.go index c1aec6e9f..971c9a0f9 100644 --- a/evmd/tests/integration/x_vm_test.go +++ b/evmd/tests/integration/x_vm_test.go @@ -6,6 +6,7 @@ import ( "github.com/cosmos/evm/server/config" "github.com/cosmos/evm/tests/integration/x/vm" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/testutil/keyring" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" @@ -32,26 +33,12 @@ func BenchmarkGasEstimation(b *testing.B) { // gh := grpc.NewIntegrationHandler(nw) // tf := factory.New(nw, gh) - chainConfig := types.DefaultChainConfig(nw.GetEIP155ChainID().Uint64()) // get the denom and decimals set on chain initialization // because we'll need to set them again when resetting the chain config - denom := types.GetEVMCoinDenom() - extendedDenom := types.GetEVMCoinExtendedDenom() - displayDenom := types.GetEVMCoinDisplayDenom() - decimals := types.GetEVMCoinDecimals() - - configurator := types.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator. - WithChainConfig(chainConfig). - WithEVMCoinInfo(types.EvmCoinInfo{ - Denom: denom, - ExtendedDenom: extendedDenom, - DisplayDenom: displayDenom, - Decimals: decimals, - }). - Configure() - require.NoError(b, err) + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := types.DefaultChainConfig(nw.GetEIP155ChainID().Uint64(), *coinInfo) + evmConfig := types.NewEvmConfig().WithChainConfig(chainConfig).WithEVMCoinInfo(coinInfo) + nw.App.GetEVMKeeper().SetEvmConfig(evmConfig) // Use simple transaction args for consistent benchmarking args := types.TransactionArgs{ diff --git a/evmd/tests/ledger/evmosd_suite_test.go b/evmd/tests/ledger/evmosd_suite_test.go index 200a8a5da..1ad850735 100644 --- a/evmd/tests/ledger/evmosd_suite_test.go +++ b/evmd/tests/ledger/evmosd_suite_test.go @@ -29,7 +29,7 @@ import ( "github.com/cosmos/evm/encoding" "github.com/cosmos/evm/evmd" "github.com/cosmos/evm/evmd/tests/ledger/mocks" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/cosmos-sdk/client" @@ -87,11 +87,11 @@ func (suite *LedgerTestSuite) SetupEvmosApp() { consAddress := sdk.ConsAddress(utiltx.GenerateAddress().Bytes()) // init app - chainID := constants.ExampleChainID - suite.app = evmd.Setup(suite.T(), chainID.ChainID, chainID.EVMChainID) + chainInfo := testconfig.DefaultChainConfig.ChainInfo + suite.app = evmd.Setup(suite.T(), chainInfo.ChainID, chainInfo.EVMChainID) suite.ctx = suite.app.NewContextLegacy(false, tmproto.Header{ Height: 1, - ChainID: chainID.ChainID, + ChainID: chainInfo.ChainID, Time: time.Now().UTC(), ProposerAddress: consAddress.Bytes(), @@ -136,7 +136,7 @@ func (suite *LedgerTestSuite) NewKeyringAndCtxs(krHome string, input io.Reader, WithUseLedger(true). WithKeyring(kr). WithClient(mocks.MockCometRPC{Client: rpcclientmock.Client{}}). - WithChainID(constants.ExampleChainIDPrefix + "-13"). + WithChainID(testconfig.DefaultChainIDPrefix + "-13"). WithSignModeStr(flags.SignModeLegacyAminoJSON) srvCtx := server.NewDefaultContext() diff --git a/evmd/tests/ledger/ledger_test.go b/evmd/tests/ledger/ledger_test.go index 8de8823b3..61d745bfc 100644 --- a/evmd/tests/ledger/ledger_test.go +++ b/evmd/tests/ledger/ledger_test.go @@ -12,8 +12,8 @@ import ( "github.com/cosmos/evm/crypto/hd" "github.com/cosmos/evm/encoding" "github.com/cosmos/evm/evmd/tests/ledger/mocks" - "github.com/cosmos/evm/server/config" "github.com/cosmos/evm/testutil" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "cosmossdk.io/math" @@ -60,7 +60,7 @@ var _ = Describe("Ledger CLI and keyring functionality: ", func() { Describe("Adding a key from ledger using the CLI", func() { BeforeEach(func() { krHome = s.T().TempDir() - encCfg = encoding.MakeConfig(config.DefaultEVMChainID) + encCfg = encoding.MakeConfig(testconfig.DefaultChainConfig.ChainInfo.EVMChainID) cmd = s.cosmosEVMAddKeyCmd() @@ -109,7 +109,7 @@ var _ = Describe("Ledger CLI and keyring functionality: ", func() { Describe("Singing a transactions", func() { BeforeEach(func() { krHome = s.T().TempDir() - encCfg = encoding.MakeConfig(config.DefaultEVMChainID) + encCfg = encoding.MakeConfig(testconfig.DefaultChainConfig.ChainInfo.EVMChainID) var err error diff --git a/evmd/tests/network/network.go b/evmd/tests/network/network.go index 51fb9133f..3e5411f51 100644 --- a/evmd/tests/network/network.go +++ b/evmd/tests/network/network.go @@ -32,8 +32,8 @@ import ( evmdconfig "github.com/cosmos/evm/evmd/cmd/evmd/config" "github.com/cosmos/evm/server/config" testconfig "github.com/cosmos/evm/testutil/config" - testconstants "github.com/cosmos/evm/testutil/constants" cosmosevmtypes "github.com/cosmos/evm/types" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/log" "cosmossdk.io/math" @@ -100,6 +100,15 @@ type Config struct { PrintMnemonic bool // print the mnemonic of first validator as log output for testing } +// testEvmAppOptions creates an EvmAppOptions function for testing +func testEvmAppOptions(evmChainID uint64) error { + // Use default chain configuration for testing + chainConfig := testconfig.DefaultChainConfig + configurator := evmtypes.NewEVMConfigurator() + configurator.ResetTestConfig() + return configurator.WithEVMCoinInfo(chainConfig.CoinInfo).Configure() +} + // DefaultConfig returns a sane default configuration suitable for nearly all // testing requirements. func DefaultConfig() Config { @@ -110,8 +119,9 @@ func DefaultConfig() Config { panic(fmt.Sprintf("failed creating temporary directory: %v", err)) } defer os.RemoveAll(dir) - tempApp := evmd.NewExampleApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simutils.NewAppOptionsWithFlagHome(dir), evmChainID, testconfig.EvmAppOptions, baseapp.SetChainID(chainID)) + tempApp := evmd.NewExampleApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simutils.NewAppOptionsWithFlagHome(dir), evmChainID, testEvmAppOptions, baseapp.SetChainID(chainID)) + baseDenom := testconfig.DefaultChainConfig.CoinInfo.Denom cfg := Config{ Codec: tempApp.AppCodec(), TxConfig: tempApp.TxConfig(), @@ -123,8 +133,8 @@ func DefaultConfig() Config { TimeoutCommit: 3 * time.Second, ChainID: chainID, NumValidators: 4, - BondDenom: testconstants.ExampleAttoDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", testconstants.ExampleAttoDenom), + BondDenom: baseDenom, + MinGasPrices: fmt.Sprintf("0.000006%s", baseDenom), AccountTokens: sdk.TokensFromConsensusPower(1000000000000000000, cosmosevmtypes.AttoPowerReduction), StakingTokens: sdk.TokensFromConsensusPower(500000000000000000, cosmosevmtypes.AttoPowerReduction), BondedTokens: sdk.TokensFromConsensusPower(100000000000000000, cosmosevmtypes.AttoPowerReduction), @@ -144,7 +154,7 @@ func NewAppConstructor(chainID string, evmChainID uint64) AppConstructor { val.Ctx.Logger, dbm.NewMemDB(), nil, true, simutils.NewAppOptionsWithFlagHome(val.Ctx.Config.RootDir), evmChainID, - testconfig.EvmAppOptions, + testEvmAppOptions, baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), baseapp.SetChainID(chainID), @@ -476,7 +486,16 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { return nil, err } - customAppTemplate, _ := evmdconfig.InitAppConfig(testconstants.ExampleAttoDenom, testconstants.ExampleEIP155ChainID) + testChainConfig := testconfig.DefaultChainConfig + // Convert testutil.ChainConfig to evmdconfig.ChainConfig + chainConfig := evmdconfig.ChainConfig{ + ChainInfo: evmdconfig.ChainInfo{ + ChainID: testChainConfig.ChainInfo.ChainID, + EVMChainID: testChainConfig.ChainInfo.EVMChainID, + }, + CoinInfo: testChainConfig.CoinInfo, + } + customAppTemplate, _ := evmdconfig.InitAppConfig(chainConfig) srvconfig.SetConfigTemplate(customAppTemplate) srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), appCfg) diff --git a/ibc/utils_test.go b/ibc/utils_test.go index 586ecd259..0332627e1 100644 --- a/ibc/utils_test.go +++ b/ibc/utils_test.go @@ -7,7 +7,7 @@ import ( cosmosevmibc "github.com/cosmos/evm/ibc" precompilestestutil "github.com/cosmos/evm/precompiles/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" transfertypes "github.com/cosmos/ibc-go/v10/modules/apps/transfer/types" channeltypes "github.com/cosmos/ibc-go/v10/modules/core/04-channel/types" ibctesting "github.com/cosmos/ibc-go/v10/testing" @@ -297,7 +297,7 @@ func TestGetReceivedCoin(t *testing.T) { } func TestGetSentCoin(t *testing.T) { - baseDenom := testconstants.ExampleAttoDenom + baseDenom := testconfig.DefaultChainConfig.EvmConfig.Denom testCases := []struct { name string diff --git a/local_node.sh b/local_node.sh index c04c16382..a387fb61c 100755 --- a/local_node.sh +++ b/local_node.sh @@ -1,6 +1,9 @@ #!/bin/bash CHAINID="${CHAIN_ID:-9001}" +DENOM="${DENOM:-atest}" +DISPLAY_DENOM="${DISPLAY_DENOM:-test}" +DECIMALS="${DECIMALS:-18}" MONIKER="localtestnet" # Remember to change to other types of keyring like 'file' in-case exposing to outside world, # otherwise your balance will be wiped quickly @@ -164,7 +167,7 @@ write_mnemonics_yaml() { # ---------- Add funded account ---------- add_genesis_funds() { local keyname="$1" - evmd genesis add-genesis-account "$keyname" 1000000000000000000000atest --keyring-backend "$KEYRING" --home "$CHAINDIR" + evmd genesis add-genesis-account "$keyname" 1000000000000000000000${DENOM} --keyring-backend "$KEYRING" --home "$CHAINDIR" } # Setup local node if overwrite is set to Yes, otherwise skip setup @@ -231,21 +234,23 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then echo "$VAL_MNEMONIC" | evmd init $MONIKER -o --chain-id "$CHAINID" --home "$CHAINDIR" --recover # ---------- Genesis customizations ---------- - jq '.app_state["staking"]["params"]["bond_denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["gov"]["deposit_params"]["min_deposit"][0]["denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["gov"]["params"]["min_deposit"][0]["denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["gov"]["params"]["expedited_min_deposit"][0]["denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["evm"]["params"]["evm_denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["mint"]["params"]["mint_denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - - jq '.app_state["bank"]["denom_metadata"]=[{"description":"The native staking token for evmd.","denom_units":[{"denom":"atest","exponent":0,"aliases":["attotest"]},{"denom":"test","exponent":18,"aliases":[]}],"base":"atest","display":"test","name":"Test Token","symbol":"TEST","uri":"","uri_hash":""}]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["staking"]["params"]["bond_denom"]="'"$DENOM"'"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["gov"]["deposit_params"]["min_deposit"][0]["denom"]="'"$DENOM"'"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["gov"]["params"]["min_deposit"][0]["denom"]="'"$DENOM"'"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["gov"]["params"]["expedited_min_deposit"][0]["denom"]="'"$DENOM"'"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["evm"]["params"]["evm_denom"]="'"$DENOM"'"' "$GENESISF" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state["mint"]["params"]["mint_denom"]="'"$DENOM"'"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + + # Create dynamic denom metadata with proper exponents and display denom + # Convert first letter to uppercase, rest to lowercase for proper title case + DISPLAY_TITLE="$(echo "$DISPLAY_DENOM" | cut -c1 | tr '[:lower:]' '[:upper:]')$(echo "$DISPLAY_DENOM" | cut -c2- | tr '[:upper:]' '[:lower:]')" + DISPLAY_SYMBOL=$(echo "$DISPLAY_DENOM" | tr '[:lower:]' '[:upper:]') + jq '.app_state["bank"]["denom_metadata"]=[{"description":"The native staking token for evmd.","denom_units":[{"denom":"'"$DENOM"'","exponent":0,"aliases":[]},{"denom":"'"$DISPLAY_DENOM"'","exponent":'"$DECIMALS"',"aliases":[]}],"base":"'"$DENOM"'","display":"'"$DISPLAY_DENOM"'","name":"'"$DISPLAY_TITLE"' Token","symbol":"'"$DISPLAY_SYMBOL"'","uri":"","uri_hash":""}]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" jq '.app_state["evm"]["params"]["active_static_precompiles"]=["0x0000000000000000000000000000000000000100","0x0000000000000000000000000000000000000400","0x0000000000000000000000000000000000000800","0x0000000000000000000000000000000000000801","0x0000000000000000000000000000000000000802","0x0000000000000000000000000000000000000803","0x0000000000000000000000000000000000000804","0x0000000000000000000000000000000000000805", "0x0000000000000000000000000000000000000806", "0x0000000000000000000000000000000000000807"]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state["evm"]["params"]["evm_denom"]="atest"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state.erc20.native_precompiles=["0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" - jq '.app_state.erc20.token_pairs=[{contract_owner:1,erc20_address:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",denom:"atest",enabled:true}]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + jq '.app_state.erc20.token_pairs=[{contract_owner:1,erc20_address:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",denom:"'"$DENOM"'",enabled:true}]' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" jq '.consensus.params.block.max_gas="10000000"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" @@ -288,7 +293,7 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then sed -i.bak 's/"expedited_voting_period": "86400s"/"expedited_voting_period": "15s"/g' "$GENESIS" # fund validator (devs already funded in the loop) - evmd genesis add-genesis-account "$VAL_KEY" 100000000000000000000000000atest --keyring-backend "$KEYRING" --home "$CHAINDIR" + evmd genesis add-genesis-account "$VAL_KEY" 100000000000000000000000000${DENOM} --keyring-backend "$KEYRING" --home "$CHAINDIR" # --------- maybe generate additional users --------- # start with provided/default list @@ -340,7 +345,7 @@ if [[ $overwrite == "y" || $overwrite == "Y" ]]; then fi # --------- Finalize genesis --------- - evmd genesis gentx "$VAL_KEY" 1000000000000000000000atest --gas-prices ${BASEFEE}atest --keyring-backend "$KEYRING" --chain-id "$CHAINID" --home "$CHAINDIR" + evmd genesis gentx "$VAL_KEY" 1000000000000000000000${DENOM} --gas-prices ${BASEFEE}${DENOM} --keyring-backend "$KEYRING" --chain-id "$CHAINID" --home "$CHAINDIR" evmd genesis collect-gentxs --home "$CHAINDIR" evmd genesis validate-genesis --home "$CHAINDIR" diff --git a/mempool/mempool.go b/mempool/mempool.go index 24c3687a4..f38a44439 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/evm/mempool/txpool" "github.com/cosmos/evm/mempool/txpool/legacypool" "github.com/cosmos/evm/rpc/stream" - "github.com/cosmos/evm/x/precisebank/types" evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/log" @@ -85,14 +84,23 @@ type EVMMempoolConfig struct { // It initializes both EVM and Cosmos transaction pools, sets up blockchain interfaces, // and configures fee-based prioritization. The config parameter allows customization // of pools and verification functions, with sensible defaults created if not provided. -func NewExperimentalEVMMempool(getCtxCallback func(height int64, prove bool) (sdk.Context, error), logger log.Logger, vmKeeper VMKeeperI, feeMarketKeeper FeeMarketKeeperI, txConfig client.TxConfig, clientCtx client.Context, config *EVMMempoolConfig) *ExperimentalEVMMempool { +func NewExperimentalEVMMempool( + getCtxCallback func(height int64, prove bool) (sdk.Context, error), + logger log.Logger, + vmKeeper VMKeeperI, + feeMarketKeeper FeeMarketKeeperI, + txConfig client.TxConfig, + clientCtx client.Context, + config *EVMMempoolConfig, + evmCoinInfo *evmtypes.EvmCoinInfo, +) *ExperimentalEVMMempool { var ( cosmosPool sdkmempool.ExtMempool blockchain *Blockchain ) - bondDenom := evmtypes.GetEVMCoinDenom() - evmDenom := types.ExtendedCoinDenom() + bondDenom := evmCoinInfo.GetDenom() + evmDenom := evmCoinInfo.GetExtendedDenom() // add the mempool name to the logger logger = logger.With(log.ModuleKey, "ExperimentalEVMMempool") diff --git a/precompiles/common/balance_handler_test.go b/precompiles/common/balance_handler_test.go index c0ea5fe0b..0417103f0 100644 --- a/precompiles/common/balance_handler_test.go +++ b/precompiles/common/balance_handler_test.go @@ -12,10 +12,9 @@ import ( cmn "github.com/cosmos/evm/precompiles/common" cmnmocks "github.com/cosmos/evm/precompiles/common/mocks" testutil "github.com/cosmos/evm/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" precisebanktypes "github.com/cosmos/evm/x/precisebank/types" "github.com/cosmos/evm/x/vm/statedb" - evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/cosmos/evm/x/vm/types/mocks" storetypes "cosmossdk.io/store/types" @@ -26,15 +25,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) -func setupBalanceHandlerTest(t *testing.T) { - t.Helper() - - sdk.GetConfig().SetBech32PrefixForAccount(testconstants.ExampleBech32Prefix, "") - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - require.NoError(t, configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]).Configure()) -} - func TestParseAddress(t *testing.T) { testCases := []struct { name string @@ -80,8 +70,6 @@ func TestParseAddress(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - setupBalanceHandlerTest(t) - ethAddr, event := tc.maleate() addr, err := cmn.ParseAddress(event, tc.key) @@ -96,6 +84,8 @@ func TestParseAddress(t *testing.T) { } func TestParseAmount(t *testing.T) { + evmCoinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + testCases := []struct { name string maleate func() sdk.Event @@ -105,7 +95,7 @@ func TestParseAmount(t *testing.T) { { name: "valid amount", maleate: func() sdk.Event { - coinStr := sdk.NewCoins(sdk.NewInt64Coin(evmtypes.GetEVMCoinDenom(), 5)).String() + coinStr := sdk.NewCoins(sdk.NewInt64Coin(evmCoinInfo.GetDenom(), 5)).String() return sdk.NewEvent("bank", sdk.NewAttribute(sdk.AttributeKeyAmount, coinStr)) }, expAmt: uint256.NewInt(5), @@ -128,9 +118,7 @@ func TestParseAmount(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - setupBalanceHandlerTest(t) - - amt, err := cmn.ParseAmount(tc.maleate()) + amt, err := cmn.ParseAmount(tc.maleate(), *evmCoinInfo) if tc.expError { require.Error(t, err) return @@ -143,8 +131,6 @@ func TestParseAmount(t *testing.T) { } func TestAfterBalanceChange(t *testing.T) { - setupBalanceHandlerTest(t) - storeKey := storetypes.NewKVStoreKey("test") tKey := storetypes.NewTransientStoreKey("test_t") ctx := sdktestutil.DefaultContext(storeKey, tKey) @@ -172,7 +158,8 @@ func TestAfterBalanceChange(t *testing.T) { bh := cmn.NewBalanceHandler(bankKeeper) bh.BeforeBalanceChange(ctx) - coins := sdk.NewCoins(sdk.NewInt64Coin(evmtypes.GetEVMCoinDenom(), 3)) + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + coins := sdk.NewCoins(sdk.NewInt64Coin(coinInfo.GetDenom(), 3)) ctx.EventManager().EmitEvents(sdk.Events{ banktypes.NewCoinSpentEvent(spenderAcc, coins), banktypes.NewCoinReceivedEvent(receiverAcc, coins), @@ -186,8 +173,6 @@ func TestAfterBalanceChange(t *testing.T) { } func TestAfterBalanceChangeErrors(t *testing.T) { - setupBalanceHandlerTest(t) - storeKey := storetypes.NewKVStoreKey("test") tKey := storetypes.NewTransientStoreKey("test_t") ctx := sdktestutil.DefaultContext(storeKey, tKey) @@ -209,7 +194,8 @@ func TestAfterBalanceChangeErrors(t *testing.T) { bh.BeforeBalanceChange(ctx) // invalid address in event - coins := sdk.NewCoins(sdk.NewInt64Coin(evmtypes.GetEVMCoinDenom(), 1)) + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + coins := sdk.NewCoins(sdk.NewInt64Coin(coinInfo.GetDenom(), 1)) ctx.EventManager().EmitEvent(banktypes.NewCoinSpentEvent(addr, coins)) ctx.EventManager().Events()[len(ctx.EventManager().Events())-1].Attributes[0].Value = "invalid" err = bh.AfterBalanceChange(ctx, stateDB) diff --git a/precompiles/common/types_test.go b/precompiles/common/types_test.go index 2ccbf868e..b7ca4555f 100644 --- a/precompiles/common/types_test.go +++ b/precompiles/common/types_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/evm/precompiles/common" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "cosmossdk.io/math" @@ -24,7 +24,8 @@ func TestNewCoinsResponse(t *testing.T) { } for _, tc := range testCases { - coin := sdk.NewCoin(constants.ExampleAttoDenom, tc.amount) + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + coin := sdk.NewCoin(denom, tc.amount) coins := sdk.NewCoins(coin) res := common.NewCoinsResponse(coins) require.Equal(t, 1, len(res)) @@ -41,7 +42,8 @@ func TestNewDecCoinsResponse(t *testing.T) { } for _, tc := range testCases { - coin := sdk.NewDecCoin(constants.ExampleAttoDenom, tc.amount) + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + coin := sdk.NewDecCoin(denom, tc.amount) coins := sdk.NewDecCoins(coin) res := common.NewDecCoinsResponse(coins) require.Equal(t, 1, len(res)) diff --git a/precompiles/common/utils.go b/precompiles/common/utils.go index 520dc5e09..910bbdef6 100644 --- a/precompiles/common/utils.go +++ b/precompiles/common/utils.go @@ -31,7 +31,7 @@ func ParseAddress(event sdk.Event, key string) (sdk.AccAddress, error) { return accAddr, nil } -func ParseAmount(event sdk.Event) (*uint256.Int, error) { +func ParseAmount(event sdk.Event, evmCoinInfo evmtypes.EvmCoinInfo) (*uint256.Int, error) { amountAttr, ok := event.GetAttribute(sdk.AttributeKeyAmount) if !ok { return nil, fmt.Errorf("event %q missing attribute %q", banktypes.EventTypeCoinSpent, sdk.AttributeKeyAmount) @@ -42,8 +42,8 @@ func ParseAmount(event sdk.Event) (*uint256.Int, error) { return nil, fmt.Errorf("failed to parse coins from %q: %w", amountAttr.Value, err) } - amountBigInt := amountCoins.AmountOf(evmtypes.GetEVMCoinDenom()).BigInt() - amount, err := utils.Uint256FromBigInt(evmtypes.ConvertAmountTo18DecimalsBigInt(amountBigInt)) + amountBigInt := amountCoins.AmountOf(evmCoinInfo.GetDenom()).BigInt() + amount, err := utils.Uint256FromBigInt(evmtypes.ConvertAmountTo18DecimalsBigInt(amountBigInt, evmCoinInfo.Decimals)) if err != nil { return nil, fmt.Errorf("failed to convert coin amount to Uint256: %w", err) } diff --git a/rpc/backend/node_info.go b/rpc/backend/node_info.go index dcdf28a68..5fb388bc5 100644 --- a/rpc/backend/node_info.go +++ b/rpc/backend/node_info.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/evm/crypto/ethsecp256k1" rpctypes "github.com/cosmos/evm/rpc/types" "github.com/cosmos/evm/server/config" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" errorsmod "cosmossdk.io/errors" @@ -345,7 +345,7 @@ func (b *Backend) RPCMinGasPrice() *big.Int { minGasPrice := b.Cfg.GetMinGasPrices() amt := minGasPrice.AmountOf(baseDenom) if amt.IsNil() || amt.IsZero() { - return big.NewInt(constants.DefaultGasPrice) + return big.NewInt(testconfig.DefaultGasPrice) } return evmtypes.ConvertAmountTo18DecimalsLegacy(amt).TruncateInt().BigInt() diff --git a/rpc/backend/tx_info_test.go b/rpc/backend/tx_info_test.go index 834b6f2ca..76c96bb9e 100644 --- a/rpc/backend/tx_info_test.go +++ b/rpc/backend/tx_info_test.go @@ -22,7 +22,7 @@ import ( "github.com/cosmos/evm/indexer" "github.com/cosmos/evm/rpc/backend/mocks" rpctypes "github.com/cosmos/evm/rpc/types" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -36,7 +36,7 @@ func setupMockBackend(t *testing.T) *Backend { t.Helper() ctx := server.NewDefaultContext() ctx.Viper.Set("telemetry.global-labels", []interface{}{}) - ctx.Viper.Set("evm.evm-chain-id", constants.ExampleChainID.EVMChainID) + ctx.Viper.Set("evm.evm-chain-id", testconfig.DefaultEvmChainID) baseDir := t.TempDir() nodeDirName := "node" @@ -52,8 +52,10 @@ func setupMockBackend(t *testing.T) *Backend { Seq: uint64(1), } - encodingConfig := encoding.MakeConfig(constants.ExampleChainID.EVMChainID) - clientCtx := client.Context{}.WithChainID(constants.ExampleChainID.ChainID). + chainID := testconfig.DefaultChainConfig.ChainID + evmChainConfig := testconfig.DefaultChainConfig.EvmConfig.ChainConfig + encodingConfig := encoding.MakeConfig(evmChainConfig.ChainId) + clientCtx := client.Context{}.WithChainID(chainID). WithHeight(1). WithTxConfig(encodingConfig.TxConfig). WithKeyringDir(clientDir). @@ -69,7 +71,7 @@ func setupMockBackend(t *testing.T) *Backend { backend.Cfg.JSONRPC.GasCap = 25000000 backend.Cfg.JSONRPC.EVMTimeout = 0 backend.Cfg.JSONRPC.AllowInsecureUnlock = true - backend.Cfg.EVM.EVMChainID = constants.ExampleChainID.EVMChainID + backend.Cfg.EVM.EVMChainID = evmChainConfig.ChainId mockEVMQueryClient := mocks.NewEVMQueryClient(t) mockFeeMarketQueryClient := mocks.NewFeeMarketQueryClient(t) backend.QueryClient.QueryClient = mockEVMQueryClient @@ -86,7 +88,7 @@ func setupMockBackend(t *testing.T) *Backend { mockHeader := &tmtypes.Header{ Height: 1, Time: time.Now(), - ChainID: constants.ExampleChainID.ChainID, + ChainID: chainID, } mockBlock := &tmtypes.Block{ Header: *mockHeader, diff --git a/scripts/run-solidity-tests.sh b/scripts/run-solidity-tests.sh index 1aecd33c7..1f370cb72 100755 --- a/scripts/run-solidity-tests.sh +++ b/scripts/run-solidity-tests.sh @@ -3,6 +3,14 @@ export GOPATH="$HOME"/go export PATH="$PATH":"$GOPATH"/bin +# Preserve chain configuration environment variables +export CHAIN_ID="${CHAIN_ID:-}" +export EVM_CHAIN_ID="${EVM_CHAIN_ID:-}" +export DENOM="${DENOM:-}" +export EXTENDED_DENOM="${EXTENDED_DENOM:-}" +export DISPLAY_DENOM="${DISPLAY_DENOM:-}" +export DECIMALS="${DECIMALS:-}" + # remove existing data rm -rf "$HOME"/.tmp-evmd-solidity-tests diff --git a/server/config/config.go b/server/config/config.go index cabd79181..9626a2a45 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -10,6 +10,8 @@ import ( "github.com/cometbft/cometbft/libs/strings" + evmtypes "github.com/cosmos/evm/x/vm/types" + errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/server/config" @@ -130,9 +132,10 @@ var evmTracers = []string{"json", "markdown", "struct", "access_list"} type Config struct { config.Config `mapstructure:",squash"` - EVM EVMConfig `mapstructure:"evm"` - JSONRPC JSONRPCConfig `mapstructure:"json-rpc"` - TLS TLSConfig `mapstructure:"tls"` + EVM EVMConfig `mapstructure:"evm"` + JSONRPC JSONRPCConfig `mapstructure:"json-rpc"` + TLS TLSConfig `mapstructure:"tls"` + Coin evmtypes.EvmCoinInfo `mapstructure:"chain"` } // EVMConfig defines the application configuration values for the EVM. @@ -341,6 +344,15 @@ func DefaultTLSConfig() *TLSConfig { } } +// DefaultEvmCoinInfo returns the default chain configuration +func DefaultEvmCoinInfo() *evmtypes.EvmCoinInfo { + return &evmtypes.EvmCoinInfo{ + DisplayDenom: "test", + Decimals: evmtypes.EighteenDecimals, + ExtendedDecimals: evmtypes.EighteenDecimals, + } +} + // Validate returns an error if the TLS certificate and key file extensions are invalid. func (c TLSConfig) Validate() error { certExt := path.Ext(c.CertificatePath) @@ -371,6 +383,7 @@ func DefaultConfig() *Config { EVM: *DefaultEVMConfig(), JSONRPC: *DefaultJSONRPCConfig(), TLS: *DefaultTLSConfig(), + Coin: *DefaultEvmCoinInfo(), } } @@ -397,5 +410,9 @@ func (c Config) ValidateBasic() error { return errorsmod.Wrapf(errortypes.ErrAppConfig, "invalid tls config value: %s", err.Error()) } + if err := c.Coin.Validate(); err != nil { + return errorsmod.Wrapf(errortypes.ErrAppConfig, "invalid chain config value: %s", err.Error()) + } + return c.Config.ValidateBasic() } diff --git a/server/config/config_test.go b/server/config/config_test.go index e5920a986..7e99e8b99 100644 --- a/server/config/config_test.go +++ b/server/config/config_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" serverconfig "github.com/cosmos/evm/server/config" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" ) func TestDefaultConfig(t *testing.T) { @@ -20,6 +20,8 @@ func TestDefaultConfig(t *testing.T) { } func TestGetConfig(t *testing.T) { + denom := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetDenom() + tests := []struct { name string args func() *viper.Viper @@ -30,12 +32,12 @@ func TestGetConfig(t *testing.T) { "test unmarshal embedded structs", func() *viper.Viper { v := viper.New() - v.Set("minimum-gas-prices", fmt.Sprintf("100%s", constants.ExampleAttoDenom)) + v.Set("minimum-gas-prices", fmt.Sprintf("100%s", denom)) return v }, func() serverconfig.Config { cfg := serverconfig.DefaultConfig() - cfg.MinGasPrices = fmt.Sprintf("100%s", constants.ExampleAttoDenom) + cfg.MinGasPrices = fmt.Sprintf("100%s", denom) return *cfg }, false, diff --git a/server/config/toml.go b/server/config/toml.go index 1e9d4689a..045f563fc 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -116,4 +116,19 @@ certificate-path = "{{ .TLS.CertificatePath }}" # Key path defines the key.pem file path for the TLS configuration. key-path = "{{ .TLS.KeyPath }}" + +############################################################################### +### Coin Configuration ### +############################################################################### + +[coin] + +# DisplayDenom defines the display denomination shown to users +display-denom = "{{ .Coin.DisplayDenom }}" + +# Decimals defines the precision/decimals for the base denomination (1-18) +decimals = {{ .Coin.Decimals }} + +# ExtendedDecimals defines the precision/decimals for the extended denomination (typically 18 decimals for atto-denom) +extended-decimals = {{ .Coin.ExtendedDecimals }} ` diff --git a/server/start.go b/server/start.go index 85ba9dad6..6a89a6636 100644 --- a/server/start.go +++ b/server/start.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "fmt" "io" "net" @@ -269,7 +270,7 @@ func startStandAlone(svrCtx *server.Context, clientCtx client.Context, opts Star }() evmApp, ok := app.(Application) if !ok { - svrCtx.Logger.Error("failed to get server config", "error", err.Error()) + return errors.New("failed to get server config, app type assertion failed") } evmApp.SetClientCtx(clientCtx) diff --git a/tests/integration/ante/ante_test_suite.go b/tests/integration/ante/ante_test_suite.go index d6a72cfa3..21c7443a1 100644 --- a/tests/integration/ante/ante_test_suite.go +++ b/tests/integration/ante/ante_test_suite.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/suite" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" @@ -99,7 +100,12 @@ func (s *AnteTestSuite) SetupTest() { s.Require().NotNil(s.network.App.AppCodec()) - chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64()) + // get the denom and decimals set when initialized the chain + // to set them again + // when resetting the chain config + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) if !s.enableLondonHF { maxInt := sdkmath.NewInt(math.MaxInt64) chainConfig.LondonBlock = &maxInt @@ -110,27 +116,9 @@ func (s *AnteTestSuite) SetupTest() { chainConfig.CancunTime = &maxInt chainConfig.PragueTime = &maxInt } + evmConfig := evmtypes.NewEvmConfig().WithChainConfig(chainConfig).WithEVMCoinInfo(coinInfo) + s.network.App.GetEVMKeeper().SetEvmConfig(evmConfig) - // get the denom and decimals set when initialized the chain - // to set them again - // when resetting the chain config - denom := evmtypes.GetEVMCoinDenom() - extendedDenom := evmtypes.GetEVMCoinExtendedDenom() - displayDenom := evmtypes.GetEVMCoinDisplayDenom() - decimals := evmtypes.GetEVMCoinDecimals() - - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator. - WithChainConfig(chainConfig). - WithEVMCoinInfo(evmtypes.EvmCoinInfo{ - Denom: denom, - ExtendedDenom: extendedDenom, - DisplayDenom: displayDenom, - Decimals: decimals, - }). - Configure() - s.Require().NoError(err) } func (s *AnteTestSuite) WithFeemarketEnabled(enabled bool) { diff --git a/tests/integration/ante/evm_ante_test_suite.go b/tests/integration/ante/evm_ante_test_suite.go index 361071447..052229c6d 100644 --- a/tests/integration/ante/evm_ante_test_suite.go +++ b/tests/integration/ante/evm_ante_test_suite.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/ethereum/eip712" "github.com/cosmos/evm/testutil" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -140,7 +140,8 @@ func (s *EvmAnteTestSuite) CreateTestEIP712MsgCreateValidator(from sdk.AccAddres // Build MsgCreateValidator valAddr := sdk.ValAddress(from.Bytes()) privEd := ed25519.GenPrivKey() - evmDenom := evmtypes.GetEVMCoinDenom() + coinInfo := s.network.App.GetEVMKeeper().GetEvmConfig().CoinInfo + evmDenom := coinInfo.GetDenom() msgCreate, err := stakingtypes.NewMsgCreateValidator( valAddr.String(), privEd.PubKey(), @@ -644,7 +645,8 @@ func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app evm. // set distribution module account balance which pays out the rewards distrAcc := distrKeeper.GetDistributionAccount(ctx) - err := testutil.FundModuleAccount(ctx, bankKeeper, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, totalRewards))) + attoDenom := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetDenom() + err := testutil.FundModuleAccount(ctx, bankKeeper, distrAcc.GetName(), sdk.NewCoins(sdk.NewCoin(attoDenom, totalRewards))) if err != nil { return sdk.Context{}, fmt.Errorf("failed to fund distribution module account: %s", err.Error()) } @@ -668,14 +670,14 @@ func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app evm. if err != nil { return sdk.Context{}, fmt.Errorf("failed to get staking params: %s", err.Error()) } - stakingParams.BondDenom = constants.ExampleAttoDenom + stakingParams.BondDenom = attoDenom stakingParams.MinCommissionRate = zeroDec err = stakingKeeper.SetParams(ctx, stakingParams) require.NoError(t, err) stakingHelper := teststaking.NewHelper(t, ctx, stakingKeeper) stakingHelper.Commission = stakingtypes.NewCommissionRates(zeroDec, zeroDec, zeroDec) - stakingHelper.Denom = constants.ExampleAttoDenom + stakingHelper.Denom = attoDenom valAddr := sdk.ValAddress(addr2.Bytes()) // self-delegate the same amount of tokens as the delegate address also stakes @@ -693,7 +695,7 @@ func PrepareAccountsForDelegationRewards(t *testing.T, ctx sdk.Context, app evm. if err != nil { return sdk.Context{}, fmt.Errorf("failed to get validator: %s", err.Error()) } - allocatedRewards := sdk.NewDecCoins(sdk.NewDecCoin(constants.ExampleAttoDenom, reward.Mul(sdkmath.NewInt(2)))) + allocatedRewards := sdk.NewDecCoins(sdk.NewDecCoin(attoDenom, reward.Mul(sdkmath.NewInt(2)))) if err = distrKeeper.AllocateTokensToValidator(ctx, validator, allocatedRewards); err != nil { return sdk.Context{}, fmt.Errorf("failed to allocate tokens to validator: %s", err.Error()) } diff --git a/tests/integration/ante/evm_unit_ante_test_suite.go b/tests/integration/ante/evm_unit_ante_test_suite.go index 3fd1597bb..1299f86b5 100644 --- a/tests/integration/ante/evm_unit_ante_test_suite.go +++ b/tests/integration/ante/evm_unit_ante_test_suite.go @@ -3,7 +3,7 @@ package ante import ( "github.com/stretchr/testify/suite" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" ) @@ -26,7 +26,7 @@ func NewEvmUnitAnteTestSuite( ) *EvmUnitAnteTestSuite { return &EvmUnitAnteTestSuite{ create: create, - ChainID: constants.ExampleChainID.ChainID, - EvmChainID: constants.ExampleChainID.EVMChainID, + ChainID: testconfig.DefaultChainConfig.ChainID, + EvmChainID: testconfig.DefaultChainConfig.EvmConfig.ChainConfig.ChainId, } } diff --git a/tests/integration/ante/test_authz.go b/tests/integration/ante/test_authz.go index 2bb2097d5..e26d890b5 100644 --- a/tests/integration/ante/test_authz.go +++ b/tests/integration/ante/test_authz.go @@ -31,7 +31,9 @@ func (suite *AnteTestSuite) TestRejectMsgsInAuthz() { distantFuture := time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) nw := suite.GetNetwork() - evmDenom := evmtypes.GetEVMCoinDenom() + + coinInfo := nw.App.GetEVMKeeper().GetEvmConfig().CoinInfo + evmDenom := coinInfo.GetDenom() baseFeeRes, err := nw.GetEvmClient().BaseFee(nw.GetContext(), &evmtypes.QueryBaseFeeRequest{}) suite.Require().NoError(err, "failed to get base fee") diff --git a/tests/integration/ante/test_bench_evm_ante.go b/tests/integration/ante/test_bench_evm_ante.go index fc7919d6d..1008d0e34 100644 --- a/tests/integration/ante/test_bench_evm_ante.go +++ b/tests/integration/ante/test_bench_evm_ante.go @@ -26,8 +26,13 @@ func RunBenchmarkEthGasConsumeDecorator(b *testing.B, create network.CreateEvmAp s.SetT(&testing.T{}) s.SetupTest() ctx := s.network.GetContext() + + chainConfig := s.network.App.GetEVMKeeper().GetEvmConfig().ChainConfig + coinInfo := s.network.App.GetEVMKeeper().GetEvmConfig().CoinInfo + ethConfig := chainConfig.EthereumConfig() + args := &evmtypes.EvmTxArgs{ - ChainID: evmtypes.GetEthChainConfig().ChainID, + ChainID: ethConfig.ChainID, Nonce: 1, Amount: big.NewInt(10), GasLimit: uint64(1_000_000), @@ -67,7 +72,7 @@ func RunBenchmarkEthGasConsumeDecorator(b *testing.B, create network.CreateEvmAp baseFee := s.GetNetwork().App.GetFeeMarketKeeper().GetParams(ctx).BaseFee fee := tx.GetEffectiveFee(baseFee.BigInt()) - denom := evmtypes.GetEVMCoinDenom() + denom := coinInfo.GetDenom() fees := sdk.NewCoins(sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(fee))) bechAddr := sdk.AccAddress(addr.Bytes()) diff --git a/tests/integration/ante/test_evm_01_setup_ctx.go b/tests/integration/ante/test_evm_01_setup_ctx.go index 259e601f5..5fa6a2307 100644 --- a/tests/integration/ante/test_evm_01_setup_ctx.go +++ b/tests/integration/ante/test_evm_01_setup_ctx.go @@ -15,8 +15,10 @@ import ( func (s *EvmAnteTestSuite) TestEthSetupContextDecorator() { dec := evmante.NewEthSetUpContextDecorator(s.GetNetwork().App.GetEVMKeeper()) + chainConfig := s.GetNetwork().App.GetEVMKeeper().GetEvmConfig().ChainConfig + ethConfig := chainConfig.EthereumConfig() ethContractCreationTxParams := &evmtypes.EvmTxArgs{ - ChainID: evmtypes.GetEthChainConfig().ChainID, + ChainID: ethConfig.ChainID, Nonce: 1, Amount: big.NewInt(10), GasLimit: 1000, diff --git a/tests/integration/ante/test_evm_ante.go b/tests/integration/ante/test_evm_ante.go index be0fec752..e46faaf9d 100644 --- a/tests/integration/ante/test_evm_ante.go +++ b/tests/integration/ante/test_evm_ante.go @@ -13,7 +13,7 @@ import ( ethante "github.com/cosmos/evm/ante/evm" "github.com/cosmos/evm/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -35,6 +35,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { privKey cryptotypes.PrivKey ) to := utiltx.GenerateAddress() + attoDenom := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() setup := func() { s.WithFeemarketEnabled(false) @@ -48,7 +49,10 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { ctx = s.GetNetwork().GetContext() } - ethCfg := evmtypes.GetEthChainConfig() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) + ethCfg := chainConfig.EthereumConfig() + ethContractCreationTxParams := evmtypes.EvmTxArgs{ ChainID: ethCfg.ChainID, Nonce: 0, @@ -289,7 +293,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) s.Require().NoError(err) return txBuilder.GetTx() @@ -300,7 +304,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas))) //#nosec G115 + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas))) //#nosec G115 amount := sdk.NewCoins(coinAmount) txBuilder, err := s.CreateTestEIP712TxBuilderMsgDelegate(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) s.Require().NoError(err) @@ -311,7 +315,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 create validator", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgCreateValidator(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -323,7 +327,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 create validator (with blank fields)", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgCreateValidator2(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -335,7 +339,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgSubmitProposal", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) // reusing the gasAmount for deposit @@ -350,7 +354,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) grantee := sdk.AccAddress("_______grantee______") - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) blockTime := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC) @@ -370,7 +374,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgGrantAllowance", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) gasAmount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712GrantAllowance(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, gasAmount) @@ -383,7 +387,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 edit validator", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgEditValidator(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -395,7 +399,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 submit evidence", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgSubmitEvidence(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -407,7 +411,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 submit proposal v1", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712SubmitProposalV1(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -419,7 +423,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgExec", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgExec(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -431,7 +435,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgVoteV1", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgVoteV1(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -443,7 +447,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Multiple MsgSend", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MultipleMsgSend(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -455,7 +459,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Multiple Different Msgs", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MultipleDifferentMsgs(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -467,7 +471,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Same Msgs, Different Schemas", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712SameMsgDifferentSchemas(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -479,7 +483,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Zero Value Array (Should Not Omit Field)", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712ZeroValueArray(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -491,7 +495,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 Zero Value Number (Should Not Omit Field)", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712ZeroValueNumber(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -503,7 +507,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgTransfer", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgTransfer(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -515,7 +519,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "success- DeliverTx EIP712 MsgTransfer Without Memo", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MsgTransferWithoutMemo(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -527,7 +531,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { "fails - DeliverTx EIP712 Multiple Signers", func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) - coinAmount := sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20)) + coinAmount := sdk.NewCoin(attoDenom, sdkmath.NewInt(20)) amount := sdk.NewCoins(coinAmount) gas := uint64(200000) txBuilder, err := s.CreateTestEIP712MultipleSignerMsgs(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) @@ -540,7 +544,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, "cosmos-1", 9002, gas, amount) s.Require().NoError(err) return txBuilder.GetTx() @@ -551,11 +555,11 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) s.Require().NoError(err) txBuilder.SetGasLimit(uint64(300000)) - txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(30)))) + txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(30)))) return txBuilder.GetTx() }, false, false, false, }, @@ -564,7 +568,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, "cosmos-1", 9005, gas, amount) s.Require().NoError(err) return txBuilder.GetTx() @@ -575,7 +579,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) s.Require().NoError(err) nonce, err := s.GetNetwork().App.GetAccountKeeper().GetSequence(ctx, s.GetKeyring().GetAccAddr(0)) @@ -598,7 +602,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { func() sdk.Tx { from := s.GetKeyring().GetAccAddr(0) gas := uint64(200000) - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(100*int64(gas)))) //#nosec G115 txBuilder, err := s.CreateTestEIP712TxBuilderMsgSend(from, privKey, ctx.ChainID(), ethCfg.ChainID.Uint64(), gas, amount) s.Require().NoError(err) nonce, err := s.GetNetwork().App.GetAccountKeeper().GetSequence(ctx, s.GetKeyring().GetAccAddr(0)) @@ -628,7 +632,7 @@ func (s *EvmAnteTestSuite) TestAnteHandler() { { "passes - Single-signer EIP-712", func() sdk.Tx { - evmDenom := evmtypes.GetEVMCoinDenom() + evmDenom := coinInfo.GetDenom() msg := banktypes.NewMsgSend( sdk.AccAddress(privKey.PubKey().Address()), addr[:], @@ -947,10 +951,12 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithDynamicTxFee() { addr, privKey := utiltx.NewAddrKey() to := utiltx.GenerateAddress() - evmChainID := evmtypes.GetEthChainConfig().ChainID + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) + ethCfg := chainConfig.EthereumConfig() ethContractCreationTxParams := evmtypes.EvmTxArgs{ - ChainID: evmChainID, + ChainID: ethCfg.ChainID, Nonce: 0, Amount: big.NewInt(10), GasLimit: 100000, @@ -960,7 +966,7 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithDynamicTxFee() { } ethTxParams := evmtypes.EvmTxArgs{ - ChainID: evmChainID, + ChainID: ethCfg.ChainID, Nonce: 0, Amount: big.NewInt(10), GasLimit: 100000, @@ -1112,7 +1118,9 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { addr, privKey := utiltx.NewAddrKey() to := utiltx.GenerateAddress() - ethCfg := evmtypes.GetEthChainConfig() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) + ethCfg := chainConfig.EthereumConfig() ethContractCreationTxParams := evmtypes.EvmTxArgs{ ChainID: ethCfg.ChainID, @@ -1153,11 +1161,11 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { evmtypes.AccessControl{ Create: evmtypes.AccessControlType{ AccessType: evmtypes.AccessTypeRestricted, - AccessControlList: evmtypes.DefaultCreateAllowlistAddresses, + AccessControlList: nil, }, Call: evmtypes.AccessControlType{ AccessType: evmtypes.AccessTypePermissionless, - AccessControlList: evmtypes.DefaultCreateAllowlistAddresses, + AccessControlList: nil, }, }, evmtypes.ErrCreateDisabled, @@ -1169,7 +1177,7 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { s.Require().NoError(err) return tx }, - evmtypes.DefaultAccessControl, + evmtypes.DefaultAccessControl(), nil, }, { @@ -1182,11 +1190,11 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { evmtypes.AccessControl{ Create: evmtypes.AccessControlType{ AccessType: evmtypes.AccessTypePermissionless, - AccessControlList: evmtypes.DefaultCreateAllowlistAddresses, + AccessControlList: nil, }, Call: evmtypes.AccessControlType{ AccessType: evmtypes.AccessTypeRestricted, - AccessControlList: evmtypes.DefaultCreateAllowlistAddresses, + AccessControlList: nil, }, }, evmtypes.ErrCallDisabled, @@ -1198,7 +1206,7 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { s.Require().NoError(err) return tx }, - evmtypes.DefaultAccessControl, + evmtypes.DefaultAccessControl(), nil, }, } @@ -1237,7 +1245,9 @@ func (s *EvmAnteTestSuite) TestAnteHandlerWithParams() { func (s *EvmAnteTestSuite) TestEthSigVerificationDecorator() { addr, privKey := utiltx.NewAddrKey() - ethCfg := evmtypes.GetEthChainConfig() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) + ethCfg := chainConfig.EthereumConfig() ethSigner := types.LatestSignerForChainID(ethCfg.ChainID) ethContractCreationTxParams := &evmtypes.EvmTxArgs{ @@ -1310,8 +1320,12 @@ func (s *EvmAnteTestSuite) TestSignatures() { privKey := s.GetKeyring().GetPrivKey(0) to := utiltx.GenerateAddress() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.network.GetEIP155ChainID().Uint64(), *coinInfo) + ethCfg := chainConfig.EthereumConfig() + txArgs := evmtypes.EvmTxArgs{ - ChainID: evmtypes.GetEthChainConfig().ChainID, + ChainID: ethCfg.ChainID, Nonce: 0, To: &to, Amount: big.NewInt(10), diff --git a/tests/integration/ante/test_evm_fee_market.go b/tests/integration/ante/test_evm_fee_market.go index 5008f0c9d..1f090bf6e 100644 --- a/tests/integration/ante/test_evm_fee_market.go +++ b/tests/integration/ante/test_evm_fee_market.go @@ -6,9 +6,8 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/cosmos/evm/ante/evm" - "github.com/cosmos/evm/server/config" "github.com/cosmos/evm/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -26,7 +25,9 @@ func (s *EvmAnteTestSuite) TestGasWantedDecorator() { dec := evm.NewGasWantedDecorator(s.GetNetwork().App.GetEVMKeeper(), s.GetNetwork().App.GetFeeMarketKeeper()) from, fromPrivKey := utiltx.NewAddrKey() to := utiltx.GenerateAddress() - denom := evmtypes.GetEVMCoinDenom() + + denom := s.GetNetwork().App.GetEVMKeeper().GetEvmConfig().CoinInfo.GetDenom() + attoDenom := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetDenom() testCases := []struct { name string @@ -97,12 +98,12 @@ func (s *EvmAnteTestSuite) TestGasWantedDecorator() { "EIP712 message", 200000, func() sdk.Tx { - amount := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(20))) + amount := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(20))) gas := uint64(200000) acc := s.GetNetwork().App.GetAccountKeeper().NewAccountWithAddress(ctx, from.Bytes()) s.Require().NoError(acc.SetSequence(1)) s.GetNetwork().App.GetAccountKeeper().SetAccount(ctx, acc) - builder, err := s.CreateTestEIP712TxBuilderMsgSend(acc.GetAddress(), fromPrivKey, ctx.ChainID(), config.DefaultEVMChainID, gas, amount) + builder, err := s.CreateTestEIP712TxBuilderMsgSend(acc.GetAddress(), fromPrivKey, ctx.ChainID(), testconfig.DefaultChainConfig.EvmConfig.ChainConfig.ChainId, gas, amount) s.Require().NoError(err) return builder.GetTx() }, @@ -112,13 +113,13 @@ func (s *EvmAnteTestSuite) TestGasWantedDecorator() { "Cosmos Tx - gasWanted > max block gas", TestGasLimit, func() sdk.Tx { - denom := testconstants.ExampleAttoDenom + denom := attoDenom testMsg := banktypes.MsgSend{ FromAddress: "cosmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp", ToAddress: "cosmos1dx67l23hz9l0k9hcher8xz04uj7wf3yu26l2yn", Amount: sdk.Coins{sdk.Coin{Amount: sdkmath.NewInt(10), Denom: denom}}, } - txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), testconstants.ExampleAttoDenom, &testMsg) + txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), attoDenom, &testMsg) limit := types.BlockGasLimit(ctx) txBuilder.SetGasLimit(limit + 5) return txBuilder.GetTx() diff --git a/tests/integration/ante/test_evm_unit_04_validate.go b/tests/integration/ante/test_evm_unit_04_validate.go index 8e87308cd..a210fe95c 100644 --- a/tests/integration/ante/test_evm_unit_04_validate.go +++ b/tests/integration/ante/test_evm_unit_04_validate.go @@ -8,7 +8,7 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/cosmos/evm/ante/evm" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" testkeyring "github.com/cosmos/evm/testutil/keyring" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -236,21 +236,16 @@ func (s *EvmUnitAnteTestSuite) TestCheckTxFee() { }, } - for _, chainID := range []testconstants.ChainID{ - testconstants.ExampleChainID, - testconstants.SixDecimalsChainID, + for _, chainConfig := range []testconfig.ChainConfig{ + testconfig.DefaultChainConfig, + testconfig.SixDecimalsChainConfig, } { for _, tc := range testCases { - s.Run(fmt.Sprintf("%s, %s", chainID.ChainID, tc.name), func() { - // Call the configurator to set the EVM coin required for the - // function to be tested. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - s.Require().NoError(configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[chainID]).Configure()) + s.Run(fmt.Sprintf("%s, %s", chainConfig.ChainID, tc.name), func() { // If decimals is not 18 decimals, we have to convert txFeeInfo to original // decimals representation. - evmExtendedDenom := evmtypes.GetEVMCoinExtendedDenom() + evmExtendedDenom := chainConfig.EvmConfig.CoinInfo.GetExtendedDenom() coins := sdktypes.Coins{sdktypes.Coin{Denom: evmExtendedDenom, Amount: amount}} diff --git a/tests/integration/ante/test_evm_unit_06_account_verification.go b/tests/integration/ante/test_evm_unit_06_account_verification.go index b9e248afd..c1cd0f03a 100644 --- a/tests/integration/ante/test_evm_unit_06_account_verification.go +++ b/tests/integration/ante/test_evm_unit_06_account_verification.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/cosmos/evm/ante/evm" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -27,13 +27,17 @@ import ( func (s *EvmUnitAnteTestSuite) TestVerifyAccountBalance() { // Setup keyring := testkeyring.New(2) + chainConfig := testconfig.ChainConfig{ + ChainInfo: testconfig.ChainInfo{ + ChainID: s.ChainID, + EVMChainID: s.EvmChainID, + }, + EvmConfig: testconfig.DefaultChainConfig.EvmConfig, + } unitNetwork := network.NewUnitTestNetwork( s.create, network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), - network.WithChainID(testconstants.ChainID{ - ChainID: s.ChainID, - EVMChainID: s.EvmChainID, - }), + network.WithChainConfig(chainConfig), ) grpcHandler := grpc.NewIntegrationHandler(unitNetwork) txFactory := factory.New(unitNetwork, grpcHandler) diff --git a/tests/integration/ante/test_evm_unit_08_gas_consume.go b/tests/integration/ante/test_evm_unit_08_gas_consume.go index 605221891..e8fa8157f 100644 --- a/tests/integration/ante/test_evm_unit_08_gas_consume.go +++ b/tests/integration/ante/test_evm_unit_08_gas_consume.go @@ -4,7 +4,7 @@ import ( "fmt" evmante "github.com/cosmos/evm/ante/evm" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" commonfactory "github.com/cosmos/evm/testutil/integration/base/factory" testfactory "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" @@ -20,12 +20,16 @@ import ( func (s *EvmUnitAnteTestSuite) TestUpdateCumulativeGasWanted() { keyring := testkeyring.New(1) - unitNetwork := network.NewUnitTestNetwork( - s.create, - network.WithChainID(testconstants.ChainID{ + chainConfig := testconfig.ChainConfig{ + ChainInfo: testconfig.ChainInfo{ ChainID: s.ChainID, EVMChainID: s.EvmChainID, - }), + }, + EvmConfig: testconfig.DefaultChainConfig.EvmConfig, + } + unitNetwork := network.NewUnitTestNetwork( + s.create, + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), ) @@ -97,12 +101,16 @@ func (s *EvmUnitAnteTestSuite) TestUpdateCumulativeGasWanted() { // NOTE: claim rewards are not tested since there is an independent suite to test just that func (s *EvmUnitAnteTestSuite) TestConsumeGasAndEmitEvent() { keyring := testkeyring.New(1) - unitNetwork := network.NewUnitTestNetwork( - s.create, - network.WithChainID(testconstants.ChainID{ + chainConfig := testconfig.ChainConfig{ + ChainInfo: testconfig.ChainInfo{ ChainID: s.ChainID, EVMChainID: s.EvmChainID, - }), + }, + EvmConfig: testconfig.DefaultChainConfig.EvmConfig, + } + unitNetwork := network.NewUnitTestNetwork( + s.create, + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), ) grpcHandler := grpc.NewIntegrationHandler(unitNetwork) diff --git a/tests/integration/ante/test_evm_unit_09_increment_sequence.go b/tests/integration/ante/test_evm_unit_09_increment_sequence.go index d2b3e0b64..cfddb482f 100644 --- a/tests/integration/ante/test_evm_unit_09_increment_sequence.go +++ b/tests/integration/ante/test_evm_unit_09_increment_sequence.go @@ -3,7 +3,7 @@ package ante import ( "github.com/cosmos/evm/ante/evm" "github.com/cosmos/evm/mempool" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" @@ -14,12 +14,17 @@ import ( func (s *EvmUnitAnteTestSuite) TestIncrementSequence() { keyring := testkeyring.New(1) - unitNetwork := network.NewUnitTestNetwork( - s.create, - network.WithChainID(testconstants.ChainID{ + chainConfig := testconfig.ChainConfig{ + ChainInfo: testconfig.ChainInfo{ ChainID: s.ChainID, EVMChainID: s.EvmChainID, - }), + }, + EvmConfig: testconfig.DefaultChainConfig.EvmConfig, + } + + unitNetwork := network.NewUnitTestNetwork( + s.create, + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), ) grpcHandler := grpc.NewIntegrationHandler(unitNetwork) diff --git a/tests/integration/ante/test_evm_unit_10_gas_wanted.go b/tests/integration/ante/test_evm_unit_10_gas_wanted.go index 5c30816bc..570da86d7 100644 --- a/tests/integration/ante/test_evm_unit_10_gas_wanted.go +++ b/tests/integration/ante/test_evm_unit_10_gas_wanted.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/cosmos/evm/ante/evm" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -20,12 +20,16 @@ import ( func (s *EvmUnitAnteTestSuite) TestCheckGasWanted() { keyring := testkeyring.New(1) - unitNetwork := network.NewUnitTestNetwork( - s.create, - network.WithChainID(testconstants.ChainID{ + chainConfig := testconfig.ChainConfig{ + ChainInfo: testconfig.ChainInfo{ ChainID: s.ChainID, EVMChainID: s.EvmChainID, - }), + }, + EvmConfig: testconfig.DefaultChainConfig.EvmConfig, + } + unitNetwork := network.NewUnitTestNetwork( + s.create, + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), ) grpcHandler := grpc.NewIntegrationHandler(unitNetwork) diff --git a/tests/integration/ante/test_integration.go b/tests/integration/ante/test_integration.go index 3bf348aff..16c6b18e8 100644 --- a/tests/integration/ante/test_integration.go +++ b/tests/integration/ante/test_integration.go @@ -10,7 +10,7 @@ import ( //nolint:revive // dot imports are fine for Ginkgo . "github.com/onsi/gomega" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" commonfactory "github.com/cosmos/evm/testutil/integration/base/factory" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" @@ -18,6 +18,7 @@ import ( "github.com/cosmos/evm/testutil/integration/evm/utils" testkeyring "github.com/cosmos/evm/testutil/keyring" testutiltx "github.com/cosmos/evm/testutil/tx" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -56,8 +57,9 @@ func (s *IntegrationTestSuite) SetupTest() { customGen[distrtypes.ModuleName] = distrGen // set non-zero inflation for rewards to accrue (use defaults from SDK for values) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) mintGen := minttypes.DefaultGenesisState() - mintGen.Params.MintDenom = testconstants.ExampleAttoDenom + mintGen.Params.MintDenom = attoDenom customGen[minttypes.ModuleName] = mintGen operatorsAddr := make([]sdk.AccAddress, 3) diff --git a/tests/integration/ante/test_min_gas_price.go b/tests/integration/ante/test_min_gas_price.go index 2c06894d1..34aecd806 100644 --- a/tests/integration/ante/test_min_gas_price.go +++ b/tests/integration/ante/test_min_gas_price.go @@ -5,8 +5,9 @@ import ( cosmosante "github.com/cosmos/evm/ante/cosmos" "github.com/cosmos/evm/testutil" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" testutiltx "github.com/cosmos/evm/testutil/tx" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -24,7 +25,7 @@ var execTypes = []struct { } func (s *AnteTestSuite) TestMinGasPriceDecorator() { - denom := constants.ExampleAttoDenom + denom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) testMsg := banktypes.MsgSend{ FromAddress: "cosmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp", ToAddress: "cosmos1dx67l23hz9l0k9hcher8xz04uj7wf3yu26l2yn", diff --git a/tests/integration/eip712/test_eip712.go b/tests/integration/eip712/test_eip712.go index 92b498139..ba512be0c 100644 --- a/tests/integration/eip712/test_eip712.go +++ b/tests/integration/eip712/test_eip712.go @@ -12,8 +12,6 @@ import ( "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/ethereum/eip712" - "github.com/cosmos/evm/testutil/config" - "github.com/cosmos/evm/testutil/constants" "github.com/cosmos/evm/testutil/integration/evm/network" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -72,8 +70,6 @@ func (s *TestSuite) SetupTest() { s.config = nw.GetEncodingConfig() s.clientCtx = client.Context{}.WithTxConfig(s.config.TxConfig) s.denom = evmtypes.GetEVMCoinDenom() - - sdk.GetConfig().SetBech32PrefixForAccount(config.Bech32Prefix, "") } // createTestAddress creates random test addresses for messages @@ -117,6 +113,7 @@ func (s *TestSuite) TestEIP712() { signing.SignMode_SIGN_MODE_DIRECT, signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, } + cfg := sdk.GetConfig() params := TestParams{ fee: txtypes.Fee{ @@ -333,7 +330,7 @@ func (s *TestSuite) TestEIP712() { err = txBuilder.SetSignatures([]signing.SignatureV2{txSig}...) s.Require().NoError(err) - chainID := constants.ExampleChainID.ChainID + chainID := "cosmos-1" // Test chain ID - matches network default if tc.chainID != "" { chainID = tc.chainID } @@ -347,7 +344,7 @@ func (s *TestSuite) TestEIP712() { AccountNumber: params.accountNumber, Sequence: params.sequence, PubKey: pubKey, - Address: sdk.MustBech32ifyAddressBytes(constants.ExampleBech32Prefix, pubKey.Bytes()), + Address: sdk.MustBech32ifyAddressBytes(cfg.GetBech32AccountAddrPrefix(), pubKey.Bytes()), } bz, err := authsigning.GetSignBytesAdapter( diff --git a/tests/integration/indexer/test_kv_indexer.go b/tests/integration/indexer/test_kv_indexer.go index 93a62d8db..fa7783130 100644 --- a/tests/integration/indexer/test_kv_indexer.go +++ b/tests/integration/indexer/test_kv_indexer.go @@ -14,7 +14,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/indexer" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/vm/types" @@ -48,7 +48,8 @@ func TestKVIndexer(t *testing.T, create network.CreateEvmApp, options ...network clientCtx := client.Context{}.WithTxConfig(encodingConfig.TxConfig).WithCodec(encodingConfig.Codec) // build cosmos-sdk wrapper tx - tmTx, err := tx.BuildTx(clientCtx.TxConfig.NewTxBuilder(), constants.ExampleAttoDenom) + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + tmTx, err := tx.BuildTx(clientCtx.TxConfig.NewTxBuilder(), denom) require.NoError(t, err) txBz, err := clientCtx.TxConfig.TxEncoder()(tmTx) require.NoError(t, err) diff --git a/tests/integration/mempool/test_setup.go b/tests/integration/mempool/test_setup.go index ae80aaee4..941f993cd 100644 --- a/tests/integration/mempool/test_setup.go +++ b/tests/integration/mempool/test_setup.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/suite" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -39,15 +39,15 @@ func NewMempoolIntegrationTestSuite(create network.CreateEvmApp, options ...netw // SetupTest initializes the test environment with default settings. func (s *IntegrationTestSuite) SetupTest() { - s.SetupTestWithChainID(testconstants.ExampleChainID) + s.SetupTestWithChainConfig(testconfig.DefaultChainConfig) } -// SetupTestWithChainID initializes the test environment with a specific chain ID. -func (s *IntegrationTestSuite) SetupTestWithChainID(chainID testconstants.ChainID) { +// SetupTestWithChainConfig initializes the test environment with a specific chain ID. +func (s *IntegrationTestSuite) SetupTestWithChainConfig(chainConfig testconfig.ChainConfig) { s.keyring = keyring.New(20) options := []network.ConfigOption{ - network.WithChainID(chainID), + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(s.keyring.GetAllAccAddrs()...), } options = append(options, s.options...) diff --git a/tests/integration/precompiles/bech32/test_bech32.go b/tests/integration/precompiles/bech32/test_bech32.go index ef6f258b9..23a730142 100644 --- a/tests/integration/precompiles/bech32/test_bech32.go +++ b/tests/integration/precompiles/bech32/test_bech32.go @@ -6,7 +6,6 @@ import ( "github.com/holiman/uint256" "github.com/cosmos/evm/precompiles/bech32" - "github.com/cosmos/evm/testutil/config" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -59,6 +58,8 @@ func (s *PrecompileTestSuite) TestRun() { uint64(1000000), ) + cfg := sdk.GetConfig() + testCases := []struct { name string malleate func() *vm.Contract @@ -111,7 +112,7 @@ func (s *PrecompileTestSuite) TestRun() { input, err := s.precompile.Pack( bech32.HexToBech32Method, s.keyring.GetAddr(0), - config.Bech32Prefix, + cfg.GetBech32AccountAddrPrefix(), ) s.Require().NoError(err, "failed to pack input") contract.Input = input @@ -137,7 +138,7 @@ func (s *PrecompileTestSuite) TestRun() { input, err := s.precompile.Pack( bech32.HexToBech32Method, common.BytesToAddress(valAddrBz), - config.Bech32PrefixValAddr, + cfg.GetBech32ValidatorAddrPrefix(), ) s.Require().NoError(err, "failed to pack input") contract.Input = input @@ -160,7 +161,7 @@ func (s *PrecompileTestSuite) TestRun() { input, err := s.precompile.Pack( bech32.HexToBech32Method, s.keyring.GetAddr(0), - config.Bech32PrefixConsAddr, + cfg.GetBech32ConsensusAddrPrefix(), ) s.Require().NoError(err, "failed to pack input") contract.Input = input diff --git a/tests/integration/precompiles/bech32/test_methods.go b/tests/integration/precompiles/bech32/test_methods.go index 592554cd6..553ceaa83 100644 --- a/tests/integration/precompiles/bech32/test_methods.go +++ b/tests/integration/precompiles/bech32/test_methods.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/evm/precompiles/bech32" cmn "github.com/cosmos/evm/precompiles/common" - "github.com/cosmos/evm/testutil/config" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -17,6 +16,7 @@ func (s *PrecompileTestSuite) TestHexToBech32() { s.SetupTest() method := s.precompile.Methods[bech32.HexToBech32Method] + cfg := sdk.GetConfig() testCases := []struct { name string @@ -63,7 +63,7 @@ func (s *PrecompileTestSuite) TestHexToBech32() { func() []interface{} { return []interface{}{ s.keyring.GetAddr(0), - config.Bech32Prefix, + cfg.GetBech32AccountAddrPrefix(), } }, func(data []byte) { @@ -103,6 +103,7 @@ func (s *PrecompileTestSuite) TestBech32ToHex() { s.SetupTest() method := s.precompile.Methods[bech32.Bech32ToHexMethod] + cfg := sdk.GetConfig() testCases := []struct { name string @@ -135,18 +136,18 @@ func (s *PrecompileTestSuite) TestBech32ToHex() { "fail - invalid bech32 address", func() []interface{} { return []interface{}{ - config.Bech32Prefix, + cfg.GetBech32AccountAddrPrefix(), } }, func([]byte) {}, true, - fmt.Sprintf("invalid bech32 address: %s", config.Bech32Prefix), + fmt.Sprintf("invalid bech32 address: %s", cfg.GetBech32AccountAddrPrefix()), }, { "fail - decoding bech32 failed", func() []interface{} { return []interface{}{ - config.Bech32Prefix + "1", + cfg.GetBech32AccountAddrPrefix() + "1", } }, func([]byte) {}, diff --git a/tests/integration/precompiles/distribution/test_distribution.go b/tests/integration/precompiles/distribution/test_distribution.go index c749828b5..2b0901a76 100644 --- a/tests/integration/precompiles/distribution/test_distribution.go +++ b/tests/integration/precompiles/distribution/test_distribution.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/evm/precompiles/distribution" "github.com/cosmos/evm/precompiles/testutil" chainutil "github.com/cosmos/evm/testutil" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -73,6 +73,9 @@ func (s *PrecompileTestSuite) TestRun() { ctx sdk.Context err error ) + + attoDenom := testconfig.DefaultChainConfig.EvmConfig.Denom + testcases := []struct { name string malleate func() (common.Address, []byte) @@ -86,7 +89,8 @@ func (s *PrecompileTestSuite) TestRun() { valAddr, err := sdk.ValAddressFromBech32(s.network.GetValidators()[0].OperatorAddress) s.Require().NoError(err) val, _ := s.network.App.GetStakingKeeper().GetValidator(ctx, valAddr) - coins := sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, math.NewInt(1e18))) + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + coins := sdk.NewCoins(sdk.NewCoin(denom, math.NewInt(1e18))) s.Require().NoError(s.network.App.GetDistrKeeper().AllocateTokensToValidator(ctx, val, sdk.NewDecCoinsFromCoins(coins...))) input, err := s.precompile.Pack( @@ -109,7 +113,8 @@ func (s *PrecompileTestSuite) TestRun() { caller := common.BytesToAddress(valAddr) commAmt := math.LegacyNewDecWithPrec(1000000000000000000, 1) - valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(constants.ExampleAttoDenom, commAmt)} + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(denom, commAmt)} // set outstanding rewards s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission})) // set commission @@ -189,7 +194,7 @@ func (s *PrecompileTestSuite) TestRun() { s.keyring.GetAddr(0), []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -209,7 +214,7 @@ func (s *PrecompileTestSuite) TestRun() { s.keyring.GetAddr(0), []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, { @@ -300,6 +305,8 @@ func (s *PrecompileTestSuite) TestCMS() { ctx sdk.Context err error ) + attoDenom := testconfig.DefaultChainConfig.EvmConfig.Denom + testcases := []struct { name string malleate func() (common.Address, []byte) @@ -312,7 +319,7 @@ func (s *PrecompileTestSuite) TestCMS() { valAddr, err := sdk.ValAddressFromBech32(s.network.GetValidators()[0].OperatorAddress) s.Require().NoError(err) val, _ := s.network.App.GetStakingKeeper().GetValidator(ctx, valAddr) - coins := sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, math.NewInt(1e18))) + coins := sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(1e18))) s.Require().NoError(s.network.App.GetDistrKeeper().AllocateTokensToValidator(ctx, val, sdk.NewDecCoinsFromCoins(coins...))) input, err := s.precompile.Pack( @@ -334,7 +341,7 @@ func (s *PrecompileTestSuite) TestCMS() { caller := common.BytesToAddress(valAddr) commAmt := math.LegacyNewDecWithPrec(1000000000000000000, 1) - valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(constants.ExampleAttoDenom, commAmt)} + valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(attoDenom, commAmt)} // set outstanding rewards s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission})) // set commission @@ -411,7 +418,7 @@ func (s *PrecompileTestSuite) TestCMS() { s.keyring.GetAddr(0), []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -430,7 +437,7 @@ func (s *PrecompileTestSuite) TestCMS() { s.keyring.GetAddr(0), []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, { diff --git a/tests/integration/precompiles/distribution/test_event.go b/tests/integration/precompiles/distribution/test_event.go index c83178113..e66594994 100644 --- a/tests/integration/precompiles/distribution/test_event.go +++ b/tests/integration/precompiles/distribution/test_event.go @@ -11,8 +11,7 @@ import ( cmn "github.com/cosmos/evm/precompiles/common" "github.com/cosmos/evm/precompiles/distribution" "github.com/cosmos/evm/precompiles/testutil" - "github.com/cosmos/evm/testutil/config" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/vm/statedb" "cosmossdk.io/math" @@ -59,7 +58,7 @@ func (s *PrecompileTestSuite) TestSetWithdrawAddressEvent() { err := cmn.UnpackLog(s.precompile.ABI, &setWithdrawerAddrEvent, distribution.EventTypeSetWithdrawAddress, *log) s.Require().NoError(err) s.Require().Equal(s.keyring.GetAddr(0), setWithdrawerAddrEvent.Caller) - s.Require().Equal(sdk.MustBech32ifyAddressBytes(config.Bech32Prefix, s.keyring.GetAddr(0).Bytes()), setWithdrawerAddrEvent.WithdrawerAddress) + s.Require().Equal(sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), s.keyring.GetAddr(0).Bytes()), setWithdrawerAddrEvent.WithdrawerAddress) }, 20000, false, @@ -188,13 +187,14 @@ func (s *PrecompileTestSuite) TestWithdrawValidatorCommissionEvent() { func(operatorAddress string) []interface{} { valAddr, err := sdk.ValAddressFromBech32(operatorAddress) s.Require().NoError(err) - valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(constants.ExampleAttoDenom, math.LegacyNewDecFromInt(amt))} + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(denom, math.LegacyNewDecFromInt(amt))} // set outstanding rewards s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission})) // set commission s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: valCommission})) // set funds to distr mod to pay for commission - coins := sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, amt)) + coins := sdk.NewCoins(sdk.NewCoin(denom, amt)) err = s.mintCoinsForDistrMod(ctx, coins) s.Require().NoError(err) return []interface{}{ @@ -253,6 +253,8 @@ func (s *PrecompileTestSuite) TestClaimRewardsEvent() { ctx sdk.Context stDB *statedb.StateDB ) + denom := testconfig.DefaultChainConfig.EvmConfig.Denom + testCases := []struct { name string coins sdk.Coins @@ -260,7 +262,7 @@ func (s *PrecompileTestSuite) TestClaimRewardsEvent() { }{ { "success", - sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, math.NewInt(1e18))), + sdk.NewCoins(sdk.NewCoin(denom, math.NewInt(1e18))), func() { log := stDB.Logs()[0] s.Require().Equal(log.Address, s.precompile.Address()) @@ -295,6 +297,8 @@ func (s *PrecompileTestSuite) TestFundCommunityPoolEvent() { ctx sdk.Context stDB *statedb.StateDB ) + attoDenom := testconfig.DefaultChainConfig.EvmConfig.Denom + testCases := []struct { name string coins sdk.Coins @@ -302,7 +306,7 @@ func (s *PrecompileTestSuite) TestFundCommunityPoolEvent() { }{ { "success - the correct event is emitted", - sdk.NewCoins(sdk.NewCoin(constants.ExampleAttoDenom, math.NewInt(1e18))), + sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(1e18))), func(coins sdk.Coins) { log := stDB.Logs()[0] s.Require().Equal(log.Address, s.precompile.Address()) @@ -315,7 +319,7 @@ func (s *PrecompileTestSuite) TestFundCommunityPoolEvent() { err := cmn.UnpackLog(s.precompile.ABI, &fundCommunityPoolEvent, distribution.EventTypeFundCommunityPool, *log) s.Require().NoError(err) s.Require().Equal(s.keyring.GetAddr(0), fundCommunityPoolEvent.Depositor) - s.Require().Equal(constants.ExampleAttoDenom, fundCommunityPoolEvent.Denom) + s.Require().Equal(attoDenom, fundCommunityPoolEvent.Denom) s.Require().Equal(big.NewInt(1e18), fundCommunityPoolEvent.Amount) }, }, @@ -323,9 +327,9 @@ func (s *PrecompileTestSuite) TestFundCommunityPoolEvent() { // New multi-coin deposit test case name: "success - multiple coins => multiple events emitted", coins: sdk.NewCoins( - sdk.NewCoin(constants.ExampleAttoDenom, math.NewInt(10)), // coin #1 - sdk.NewCoin(constants.OtherCoinDenoms[0], math.NewInt(20)), // coin #2 - sdk.NewCoin(constants.OtherCoinDenoms[1], math.NewInt(30)), // coin #3 + sdk.NewCoin(attoDenom, math.NewInt(10)), // coin #1 + sdk.NewCoin(testFooDenom, math.NewInt(20)), // coin #2 + sdk.NewCoin(testBarDenom, math.NewInt(30)), // coin #3 ).Sort(), postCheck: func(coins sdk.Coins) { logs := stDB.Logs() @@ -380,6 +384,9 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolEvent() { stDB *statedb.StateDB amt = math.NewInt(1e18) ) + attoDenom := testconfig.DefaultChainConfig.EvmConfig.Denom + fooDenom, barDenom := "foo", "bar" + method := s.precompile.Methods[distribution.DepositValidatorRewardsPoolMethod] testCases := []struct { name string @@ -394,7 +401,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolEvent() { func(operatorAddress string) ([]interface{}, sdk.Coins) { coins := []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, } @@ -425,7 +432,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolEvent() { s.Require().NoError(err) s.Require().Equal(depositValidatorRewardsPool.Depositor, s.keyring.GetAddr(0)) s.Require().Equal(depositValidatorRewardsPool.ValidatorAddress, common.BytesToAddress(valAddr.Bytes())) - s.Require().Equal(depositValidatorRewardsPool.Denom, constants.ExampleAttoDenom) + s.Require().Equal(depositValidatorRewardsPool.Denom, attoDenom) s.Require().Equal(depositValidatorRewardsPool.Amount, amt.BigInt()) }, 20000, @@ -437,15 +444,15 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolEvent() { func(operatorAddress string) ([]interface{}, sdk.Coins) { coins := []cmn.Coin{ { - Denom: constants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, { - Denom: s.otherDenoms[0], + Denom: fooDenom, Amount: big.NewInt(2e18), }, { - Denom: s.otherDenoms[1], + Denom: barDenom, Amount: big.NewInt(3e18), }, } diff --git a/tests/integration/precompiles/distribution/test_integration.go b/tests/integration/precompiles/distribution/test_integration.go index 53500a6b6..00e757a7c 100644 --- a/tests/integration/precompiles/distribution/test_integration.go +++ b/tests/integration/precompiles/distribution/test_integration.go @@ -18,7 +18,7 @@ import ( "github.com/cosmos/evm/precompiles/staking" "github.com/cosmos/evm/precompiles/testutil" "github.com/cosmos/evm/precompiles/testutil/contracts" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/testutil/integration/evm/utils" testutiltx "github.com/cosmos/evm/testutil/tx" @@ -52,7 +52,13 @@ var ( txArgs evmtypes.EvmTxArgs // minExpRewardOrCommission is the minimun coins expected for validator's rewards or commission // required for the tests - minExpRewardOrCommission = sdk.NewDecCoins(sdk.NewDecCoin(testconstants.ExampleAttoDenom, testRewardsAmt)) + minExpRewardOrCommission = sdk.NewDecCoins(sdk.NewDecCoin(testconfig.DefaultChainConfig.EvmConfig.Denom, testRewardsAmt)) +) + +// Test denomination constants to avoid goconst lint warnings +const ( + testFooDenom = "foo" + testBarDenom = "bar" ) func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmApp, options ...network.ConfigOption) { @@ -905,8 +911,8 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp fundAmt := math.NewInt(10) sendAmt := []cmn.Coin{ {Denom: s.bondDenom, Amount: fundAmt.BigInt()}, - {Denom: testconstants.OtherCoinDenoms[0], Amount: fundAmt.BigInt()}, - {Denom: testconstants.OtherCoinDenoms[1], Amount: fundAmt.BigInt()}, + {Denom: testFooDenom, Amount: fundAmt.BigInt()}, + {Denom: testBarDenom, Amount: fundAmt.BigInt()}, } sendSdkCoins, err := cmn.NewSdkCoinsFromCoins(sendAmt) Expect(err).To(BeNil()) diff --git a/tests/integration/precompiles/distribution/test_setup.go b/tests/integration/precompiles/distribution/test_setup.go index 57b15cb85..b7cb4ddc9 100644 --- a/tests/integration/precompiles/distribution/test_setup.go +++ b/tests/integration/precompiles/distribution/test_setup.go @@ -4,12 +4,11 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/evm/precompiles/distribution" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" - evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" sdkmath "cosmossdk.io/math" @@ -57,7 +56,9 @@ func (s *PrecompileTestSuite) SetupTest() { customGen := network.CustomGenesisState{} // mint some coin to fee collector - coins := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(1000000000000000000))) + attoDenom := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetDenom() + fooDenom, barDenom := "foo", "bar" + coins := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(1000000000000000000))) balances := []banktypes.Balance{ { Address: authtypes.NewModuleAddress(authtypes.FeeCollectorName).String(), @@ -90,7 +91,7 @@ func (s *PrecompileTestSuite) SetupTest() { // set non-zero inflation for rewards to accrue (use defaults from SDK for values) mintGen := minttypes.DefaultGenesisState() - mintGen.Params.MintDenom = testconstants.ExampleAttoDenom + mintGen.Params.MintDenom = attoDenom customGen[minttypes.ModuleName] = mintGen operatorsAddr := make([]sdk.AccAddress, 3) @@ -99,12 +100,12 @@ func (s *PrecompileTestSuite) SetupTest() { } s.otherDenoms = []string{ - testconstants.OtherCoinDenoms[0], - testconstants.OtherCoinDenoms[1], + fooDenom, + barDenom, } options := []network.ConfigOption{ - network.WithOtherDenoms(testconstants.OtherCoinDenoms), + network.WithOtherDenoms(s.otherDenoms), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), network.WithOtherDenoms(s.otherDenoms), network.WithCustomGenesis(customGen), @@ -124,7 +125,7 @@ func (s *PrecompileTestSuite) SetupTest() { s.bondDenom = bondDenom // TODO: check if this is correct? - s.baseDenom = evmtypes.GetEVMCoinDenom() + s.baseDenom = s.network.App.GetEVMKeeper().GetEvmConfig().CoinInfo.GetDenom() s.factory = txFactory s.grpcHandler = grpcHandler diff --git a/tests/integration/precompiles/distribution/test_tx.go b/tests/integration/precompiles/distribution/test_tx.go index 33db8c8b1..741983699 100644 --- a/tests/integration/precompiles/distribution/test_tx.go +++ b/tests/integration/precompiles/distribution/test_tx.go @@ -10,9 +10,10 @@ import ( cmn "github.com/cosmos/evm/precompiles/common" "github.com/cosmos/evm/precompiles/distribution" "github.com/cosmos/evm/precompiles/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" utiltx "github.com/cosmos/evm/testutil/tx" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -22,6 +23,8 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +var attoDenom = evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + func (s *PrecompileTestSuite) TestSetWithdrawAddress() { var ctx sdk.Context method := s.precompile.Methods[distribution.SetWithdrawAddressMethod] @@ -199,10 +202,10 @@ func (s *PrecompileTestSuite) TestWithdrawDelegatorReward() { var coins []cmn.Coin err := s.precompile.UnpackIntoInterface(&coins, distribution.WithdrawDelegatorRewardMethod, data) s.Require().NoError(err, "failed to unpack output") - s.Require().Equal(coins[0].Denom, testconstants.ExampleAttoDenom) + s.Require().Equal(coins[0].Denom, attoDenom) s.Require().Equal(coins[0].Amount.Int64(), expRewardsAmt.Int64()) // Check bank balance after the withdrawal of rewards - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), attoDenom) s.Require().True(balance.Amount.GT(network.PrefundedAccountInitialBalance)) }, 20000, @@ -275,14 +278,14 @@ func (s *PrecompileTestSuite) TestWithdrawValidatorCommission() { valAddr, err := sdk.ValAddressFromBech32(operatorAddress) s.Require().NoError(err) amt := math.LegacyNewDecWithPrec(1000000000000000000, 1) - valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(testconstants.ExampleAttoDenom, amt)} + valCommission := sdk.DecCoins{sdk.NewDecCoinFromDec(attoDenom, amt)} // set outstanding rewards s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorOutstandingRewards(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: valCommission})) // set commission s.Require().NoError(s.network.App.GetDistrKeeper().SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: valCommission})) // fund distr mod to pay for rewards + commission - coins := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, amt.Mul(math.LegacyNewDec(2)).RoundInt())) + coins := sdk.NewCoins(sdk.NewCoin(attoDenom, amt.Mul(math.LegacyNewDec(2)).RoundInt())) err = s.mintCoinsForDistrMod(ctx, coins) s.Require().NoError(err) return []interface{}{ @@ -294,15 +297,15 @@ func (s *PrecompileTestSuite) TestWithdrawValidatorCommission() { amt := math.NewInt(100000000000000000) err := s.precompile.UnpackIntoInterface(&coins, distribution.WithdrawValidatorCommissionMethod, data) s.Require().NoError(err, "failed to unpack output") - s.Require().Equal(coins[0].Denom, testconstants.ExampleAttoDenom) + s.Require().Equal(coins[0].Denom, attoDenom) s.Require().Equal(coins[0].Amount, amt.BigInt()) // Check bank balance after the withdrawal of commission valAddr, err := sdk.ValAddressFromBech32(s.network.GetValidators()[0].GetOperator()) s.Require().NoError(err) - balance := s.network.App.GetBankKeeper().GetBalance(ctx, valAddr.Bytes(), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, valAddr.Bytes(), attoDenom) s.Require().Equal(balance.Amount, prevBalance.Amount.Add(amt)) - s.Require().Equal(balance.Denom, testconstants.ExampleAttoDenom) + s.Require().Equal(balance.Denom, attoDenom) }, 20000, false, @@ -318,7 +321,7 @@ func (s *PrecompileTestSuite) TestWithdrawValidatorCommission() { valAddr, err := sdk.ValAddressFromBech32(s.network.GetValidators()[0].GetOperator()) s.Require().NoError(err) - prevBalance = s.network.App.GetBankKeeper().GetBalance(ctx, valAddr.Bytes(), testconstants.ExampleAttoDenom) + prevBalance = s.network.App.GetBankKeeper().GetBalance(ctx, valAddr.Bytes(), attoDenom) validatorAddress := common.BytesToAddress(valAddr.Bytes()) var contract *vm.Contract @@ -409,7 +412,7 @@ func (s *PrecompileTestSuite) TestClaimRewards() { } }, func(_ []byte) { - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), attoDenom) // rewards from 3 validators - 5% commission expRewards := expRewardsAmt.Mul(math.NewInt(3)) s.Require().Equal(balance.Amount, prevBalance.Amount.Add(expRewards)) @@ -427,7 +430,7 @@ func (s *PrecompileTestSuite) TestClaimRewards() { } }, func([]byte) { - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), attoDenom) // rewards from 3 validators - 5% commission expRewards := expRewardsAmt.Mul(math.NewInt(3)) s.Require().Equal(balance.Amount, prevBalance.Amount.Add(expRewards)) @@ -445,7 +448,7 @@ func (s *PrecompileTestSuite) TestClaimRewards() { } }, func([]byte) { - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAccAddr(0), attoDenom) s.Require().Equal(balance.Amount, prevBalance.Amount.Add(expRewardsAmt)) }, 20000, @@ -480,7 +483,7 @@ func (s *PrecompileTestSuite) TestClaimRewards() { s.Require().NoError(err) // get previous balance to compare final balance in the postCheck func - prevBalance = s.network.App.GetBankKeeper().GetBalance(ctx, addr.Bytes(), testconstants.ExampleAttoDenom) + prevBalance = s.network.App.GetBankKeeper().GetBalance(ctx, addr.Bytes(), attoDenom) bz, err := s.precompile.ClaimRewards(ctx, contract, s.network.GetStateDB(), &method, tc.malleate()) @@ -536,7 +539,7 @@ func (s *PrecompileTestSuite) TestFundCommunityPool() { s.keyring.GetAddr(0), []cmn.Coin{ { - Denom: testconstants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -547,8 +550,8 @@ func (s *PrecompileTestSuite) TestFundCommunityPool() { s.Require().NoError(err) coins := pool.CommunityPool expectedAmount := new(big.Int).Mul(big.NewInt(1e18), new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(math.LegacyPrecision)), nil)) - s.Require().Equal(expectedAmount, coins.AmountOf(testconstants.ExampleAttoDenom).BigInt()) - userBalance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), testconstants.ExampleAttoDenom) + s.Require().Equal(expectedAmount, coins.AmountOf(attoDenom).BigInt()) + userBalance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), attoDenom) s.Require().Equal(network.PrefundedAccountInitialBalance.Sub(math.NewInt(1e18)), userBalance.Amount) }, 20000, @@ -566,7 +569,7 @@ func (s *PrecompileTestSuite) TestFundCommunityPool() { contract, ctx = testutil.NewPrecompileContract(s.T(), ctx, s.keyring.GetAddr(0), s.precompile.Address(), tc.gas) // Sanity check to make sure the starting balance is always 100k ATOM - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), attoDenom) s.Require().Equal(balance.Amount, network.PrefundedAccountInitialBalance) bz, err := s.precompile.FundCommunityPool(ctx, contract, s.network.GetStateDB(), &method, tc.malleate()) @@ -611,7 +614,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolMethod() { val.OperatorAddress, []cmn.Coin{ { - Denom: testconstants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -630,7 +633,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolMethod() { "", []cmn.Coin{ { - Denom: testconstants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -663,7 +666,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolMethod() { val.OperatorAddress, []cmn.Coin{ { - Denom: testconstants.ExampleAttoDenom, + Denom: attoDenom, Amount: big.NewInt(1e18), }, }, @@ -682,7 +685,7 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolMethod() { s.Require().NoError(err) depositCoins := sdk.DecCoins{ - {Denom: testconstants.ExampleAttoDenom, Amount: math.LegacyNewDecFromBigInt(big.NewInt(1e18))}, + {Denom: attoDenom, Amount: math.LegacyNewDecFromBigInt(big.NewInt(1e18))}, } expectedValCommission := depositCoins.MulDec(val.GetCommission()) expectedCurrentRewards := depositCoins.Sub(expectedValCommission) @@ -704,9 +707,9 @@ func (s *PrecompileTestSuite) TestDepositValidatorRewardsPoolMethod() { s.Require().Equal(expectedOutstandingRewards, outstandingRewards.Rewards) // check bank balance after the deposit - balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), testconstants.ExampleAttoDenom) + balance := s.network.App.GetBankKeeper().GetBalance(ctx, s.keyring.GetAddr(0).Bytes(), attoDenom) s.Require().Equal(balance.Amount, network.PrefundedAccountInitialBalance.Sub(math.NewInt(1e18))) - s.Require().Equal(balance.Denom, testconstants.ExampleAttoDenom) + s.Require().Equal(balance.Denom, attoDenom) }, 20000, false, diff --git a/tests/integration/precompiles/erc20/test_integration.go b/tests/integration/precompiles/erc20/test_integration.go index 20869e598..ad7b0e51b 100644 --- a/tests/integration/precompiles/erc20/test_integration.go +++ b/tests/integration/precompiles/erc20/test_integration.go @@ -19,7 +19,7 @@ import ( "github.com/cosmos/evm/precompiles/erc20" "github.com/cosmos/evm/precompiles/erc20/testdata" "github.com/cosmos/evm/precompiles/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -251,7 +251,7 @@ func TestIntegrationTestSuite(t *testing.T, create network.CreateEvmApp, options passCheck = failCheck.WithExpPass(true) erc20Keeper := is.network.App.GetErc20Keeper() - available := erc20Keeper.IsNativePrecompileAvailable(is.network.GetContext(), common.HexToAddress(testconstants.WEVMOSContractMainnet)) + available := erc20Keeper.IsNativePrecompileAvailable(is.network.GetContext(), common.HexToAddress(testconfig.DefaultWevmosContractMainnet)) Expect(available).To(BeTrue()) revertContractAddr, err = is.factory.DeployContract( @@ -261,7 +261,7 @@ func TestIntegrationTestSuite(t *testing.T, create network.CreateEvmApp, options Contract: revertCallerContract, // NOTE: we're passing the precompile address to the constructor because that initiates the contract // to make calls to the correct ERC20 precompile. - ConstructorArgs: []interface{}{common.HexToAddress(testconstants.WEVMOSContractMainnet)}, + ConstructorArgs: []interface{}{common.HexToAddress(testconfig.DefaultWevmosContractMainnet)}, }, ) Expect(err).ToNot(HaveOccurred(), "failed to deploy reverter contract") diff --git a/tests/integration/precompiles/gov/test_query.go b/tests/integration/precompiles/gov/test_query.go index 3e57f40a9..adb1fe0b1 100644 --- a/tests/integration/precompiles/gov/test_query.go +++ b/tests/integration/precompiles/gov/test_query.go @@ -10,7 +10,7 @@ import ( cmn "github.com/cosmos/evm/precompiles/common" "github.com/cosmos/evm/precompiles/gov" "github.com/cosmos/evm/precompiles/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "cosmossdk.io/math" @@ -29,7 +29,7 @@ var ( govAcct = authtypes.NewModuleAddress(govtypes.ModuleName) // TestProposalMsgs are msgs used on a proposal. TestProposalMsgs = []sdk.Msg{ - banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(1000)))), + banktypes.NewMsgSend(govAcct, addr, sdk.NewCoins(sdk.NewCoin(testconfig.DefaultChainConfig.EvmConfig.Denom, math.NewInt(1000)))), } ) diff --git a/tests/integration/precompiles/gov/test_setup.go b/tests/integration/precompiles/gov/test_setup.go index 312f91b47..25a001507 100644 --- a/tests/integration/precompiles/gov/test_setup.go +++ b/tests/integration/precompiles/gov/test_setup.go @@ -6,11 +6,12 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/evm/precompiles/gov" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -51,6 +52,7 @@ func (s *PrecompileTestSuite) SetupTest() { customGen := network.CustomGenesisState{} now := time.Now().UTC() inOneHour := now.Add(time.Hour) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) var err error anyMessage, err := types.NewAnyWithValue(TestProposalMsgs[0]) @@ -100,7 +102,7 @@ func (s *PrecompileTestSuite) SetupTest() { bankGen := banktypes.DefaultGenesisState() bankGen.Balances = []banktypes.Balance{{ Address: authtypes.NewModuleAddress(govtypes.ModuleName).String(), - Coins: sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(200))), + Coins: sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(200))), }} govGen := govv1.DefaultGenesisState() govGen.StartingProposalId = 3 @@ -108,15 +110,15 @@ func (s *PrecompileTestSuite) SetupTest() { { ProposalId: 1, Depositor: keyring.GetAccAddr(0).String(), - Amount: sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(100))), + Amount: sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(100))), }, { ProposalId: 2, Depositor: keyring.GetAccAddr(1).String(), - Amount: sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(100))), + Amount: sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(100))), }, } - govGen.Params.MinDeposit = sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(100))) + govGen.Params.MinDeposit = sdk.NewCoins(sdk.NewCoin(attoDenom, math.NewInt(100))) govGen.Params.ProposalCancelDest = keyring.GetAccAddr(2).String() govGen.Proposals = append(govGen.Proposals, prop) govGen.Proposals = append(govGen.Proposals, prop2) diff --git a/tests/integration/precompiles/staking/test_integration.go b/tests/integration/precompiles/staking/test_integration.go index 7d49f82df..c09ec64d6 100644 --- a/tests/integration/precompiles/staking/test_integration.go +++ b/tests/integration/precompiles/staking/test_integration.go @@ -21,7 +21,7 @@ import ( "github.com/cosmos/evm/precompiles/staking/testdata" "github.com/cosmos/evm/precompiles/testutil" "github.com/cosmos/evm/precompiles/testutil/contracts" - cosmosevmutil "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/testutil/integration/evm/utils" testutiltx "github.com/cosmos/evm/testutil/tx" @@ -2600,6 +2600,7 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp }) Context("querying delegation", func() { + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) BeforeEach(func() { callArgs.MethodName = "getDelegation" }) @@ -2621,7 +2622,7 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp err = s.precompile.UnpackIntoInterface(&delOut, staking.DelegationMethod, ethRes.Ret) Expect(err).To(BeNil(), "error while unpacking the delegation output: %v", err) Expect(delOut.Balance.Amount.Int64()).To(Equal(int64(0)), "expected a different delegation balance") - Expect(delOut.Balance.Denom).To(Equal(cosmosevmutil.ExampleAttoDenom), "expected a different delegation balance") + Expect(delOut.Balance.Denom).To(Equal(attoDenom), "expected a different delegation balance") }) It("which exists should return the delegation", func() { @@ -2642,7 +2643,7 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp err = s.precompile.UnpackIntoInterface(&delOut, staking.DelegationMethod, ethRes.Ret) Expect(err).To(BeNil(), "error while unpacking the delegation output: %v", err) Expect(delOut.Balance).To(Equal( - cmn.Coin{Denom: cosmosevmutil.ExampleAttoDenom, Amount: big.NewInt(1e18)}), + cmn.Coin{Denom: attoDenom, Amount: big.NewInt(1e18)}), "expected a different delegation balance", ) }) diff --git a/tests/integration/precompiles/staking/test_setup.go b/tests/integration/precompiles/staking/test_setup.go index cb4e04d63..3abf6b27b 100644 --- a/tests/integration/precompiles/staking/test_setup.go +++ b/tests/integration/precompiles/staking/test_setup.go @@ -4,11 +4,12 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/evm/precompiles/staking" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" + evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -47,7 +48,8 @@ func (s *PrecompileTestSuite) SetupTest() { keyring := testkeyring.New(2) customGenesis := network.CustomGenesisState{} // mint some coin to fee collector - coins := sdk.NewCoins(sdk.NewCoin(testconstants.ExampleAttoDenom, sdkmath.NewInt(InitialTestBalance))) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + coins := sdk.NewCoins(sdk.NewCoin(attoDenom, sdkmath.NewInt(InitialTestBalance))) balances := []banktypes.Balance{ { Address: authtypes.NewModuleAddress(authtypes.FeeCollectorName).String(), diff --git a/tests/integration/precompiles/staking/test_staking.go b/tests/integration/precompiles/staking/test_staking.go index d8b5149dc..eb34fbe8e 100644 --- a/tests/integration/precompiles/staking/test_staking.go +++ b/tests/integration/precompiles/staking/test_staking.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/evm/precompiles/staking" "github.com/cosmos/evm/precompiles/testutil" chainutil "github.com/cosmos/evm/testutil" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/keyring" "github.com/cosmos/evm/x/vm/statedb" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -224,7 +224,8 @@ func (s *PrecompileTestSuite) TestRun() { // Needs to be called after setting unbonding delegation // In order to mimic the coins being added to the unboding pool - coin := sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(1000)) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + coin := sdk.NewCoin(attoDenom, math.NewInt(1000)) err = s.network.App.GetBankKeeper().SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, sdk.Coins{coin}) s.Require().NoError(err, "failed to send coins from module to module") @@ -352,7 +353,8 @@ func (s *PrecompileTestSuite) TestRun() { // Needs to be called after setting unbonding delegation // In order to mimic the coins being added to the unboding pool - coin := sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(1000)) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + coin := sdk.NewCoin(attoDenom, math.NewInt(1000)) err = s.network.App.GetBankKeeper().SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, sdk.Coins{coin}) s.Require().NoError(err, "failed to send coins from module to module") @@ -572,7 +574,8 @@ func (s *PrecompileTestSuite) TestCMS() { // Needs to be called after setting unbonding delegation // In order to mimic the coins being added to the unboding pool - coin := sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(1000)) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + coin := sdk.NewCoin(attoDenom, math.NewInt(1000)) err = s.network.App.GetBankKeeper().SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, sdk.Coins{coin}) s.Require().NoError(err, "failed to send coins from module to module") @@ -700,7 +703,8 @@ func (s *PrecompileTestSuite) TestCMS() { // Needs to be called after setting unbonding delegation // In order to mimic the coins being added to the unboding pool - coin := sdk.NewCoin(testconstants.ExampleAttoDenom, math.NewInt(1000)) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + coin := sdk.NewCoin(attoDenom, math.NewInt(1000)) err = s.network.App.GetBankKeeper().SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, sdk.Coins{coin}) s.Require().NoError(err, "failed to send coins from module to module") diff --git a/tests/integration/precompiles/werc20/test_events.go b/tests/integration/precompiles/werc20/test_events.go index e4734754d..3fbcd8af5 100644 --- a/tests/integration/precompiles/werc20/test_events.go +++ b/tests/integration/precompiles/werc20/test_events.go @@ -9,7 +9,7 @@ import ( cmn "github.com/cosmos/evm/precompiles/common" "github.com/cosmos/evm/precompiles/werc20" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -44,11 +44,11 @@ func NewPrecompileUnitTestSuite( // SetupTest allows to configure the testing suite embedding a network with a // custom chainID. This is important to check that the correct address is used // for the precompile. -func (s *PrecompileUnitTestSuite) SetupTest(chainID testconstants.ChainID) { +func (s *PrecompileUnitTestSuite) SetupTest(chainConfig testconfig.ChainConfig) { keyring := keyring.New(2) options := []network.ConfigOption{ - network.WithChainID(chainID), + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), } options = append(options, s.options...) @@ -61,7 +61,7 @@ func (s *PrecompileUnitTestSuite) SetupTest(chainID testconstants.ChainID) { s.grpcHandler = grpcHandler s.keyring = keyring - s.precompileAddrHex = network.GetWEVMOSContractHex(chainID) + s.precompileAddrHex = network.GetWEVMOSContractHex(chainConfig.ChainInfo) ctx := integrationNetwork.GetContext() @@ -96,21 +96,21 @@ type WithdrawalEvent struct { //nolint:dupl func (s *PrecompileUnitTestSuite) TestEmitDepositEvent() { testCases := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "mainnet", - chainID: testconstants.ExampleChainID, + name: "mainnet", + chainConfig: testconfig.DefaultChainConfig, }, { - name: "six decimals", - chainID: testconstants.SixDecimalsChainID, + name: "six decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, } for _, tc := range testCases { s.Run(tc.name, func() { - s.SetupTest(tc.chainID) + s.SetupTest(tc.chainConfig) caller := s.keyring.GetAddr(0) amount := new(big.Int).SetInt64(1_000) @@ -155,21 +155,21 @@ func (s *PrecompileUnitTestSuite) TestEmitDepositEvent() { //nolint:dupl func (s *PrecompileUnitTestSuite) TestEmitWithdrawalEvent() { testCases := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "mainnet", - chainID: testconstants.ExampleChainID, + name: "mainnet", + chainConfig: testconfig.DefaultChainConfig, }, { - name: "six decimals", - chainID: testconstants.SixDecimalsChainID, + name: "six decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, } for _, tc := range testCases { s.Run(tc.name, func() { - s.SetupTest(tc.chainID) + s.SetupTest(tc.chainConfig) caller := s.keyring.GetAddr(0) amount := new(big.Int).SetInt64(1_000) diff --git a/tests/integration/precompiles/werc20/test_integration.go b/tests/integration/precompiles/werc20/test_integration.go index 686bdb65f..33fceb284 100644 --- a/tests/integration/precompiles/werc20/test_integration.go +++ b/tests/integration/precompiles/werc20/test_integration.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/evm/precompiles/testutil" "github.com/cosmos/evm/precompiles/werc20" "github.com/cosmos/evm/precompiles/werc20/testdata" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -50,7 +50,7 @@ type PrecompileIntegrationTestSuite struct { } func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmApp, options ...network.ConfigOption) { - _ = DescribeTableSubtree("a user interact with the WEVMOS precompiled contract", func(chainId testconstants.ChainID) { + _ = DescribeTableSubtree("a user interact with the WEVMOS precompiled contract", func(chainConfig testconfig.ChainConfig) { var ( is *PrecompileIntegrationTestSuite passCheck, failCheck testutil.LogCheckArgs @@ -70,10 +70,10 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp // Configure deposit amounts with integer and fractional components to test // precise balance handling across different decimal configurations var conversionFactor *big.Int - switch chainId { - case testconstants.SixDecimalsChainID: + switch chainConfig { + case testconfig.SixDecimalsChainConfig: conversionFactor = big.NewInt(1e12) // For 6-decimal chains - case testconstants.TwelveDecimalsChainID: + case testconfig.TwelveDecimalsChainConfig: conversionFactor = big.NewInt(1e6) // For 12-decimal chains default: conversionFactor = big.NewInt(1) // For 18-decimal chains @@ -107,15 +107,8 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp feemarketGenesis.Params.NoBaseFee = true customGenesis[feemarkettypes.ModuleName] = feemarketGenesis - // Reset evm config here for the standard case - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - Expect(configurator. - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[chainId]). - Configure()).To(BeNil(), "expected no error setting the evm configurator") - opts := []network.ConfigOption{ - network.WithChainID(chainId), + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), network.WithCustomGenesis(customGenesis), } @@ -129,10 +122,11 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp is.grpcHandler = grpcHandler is.keyring = keyring - is.wrappedCoinDenom = evmtypes.GetEVMCoinDenom() - is.precompileAddrHex = network.GetWEVMOSContractHex(testconstants.ChainID{ - ChainID: is.network.GetChainID(), - EVMChainID: is.network.GetEIP155ChainID().Uint64(), + coinInfo := chainConfig.EvmConfig.CoinInfo + is.wrappedCoinDenom = coinInfo.GetDenom() + is.precompileAddrHex = network.GetWEVMOSContractHex(testconfig.ChainConfig{ + ChainID: is.network.GetChainID(), + EvmConfig: chainConfig.EvmConfig, }) ctx := integrationNetwork.GetContext() @@ -145,7 +139,7 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp BeTrue(), "expected wevmos to be in the native precompiles", ) - _, found := is.network.App.GetBankKeeper().GetDenomMetaData(ctx, evmtypes.GetEVMCoinDenom()) + _, found := is.network.App.GetBankKeeper().GetDenomMetaData(ctx, coinInfo.GetDenom()) Expect(found).To(BeTrue(), "expected native token metadata to be registered") // Check that WEVMOS is registered in the token pairs map. @@ -157,7 +151,7 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp precompileAddr := common.HexToAddress(is.precompileAddrHex) tokenPair = erc20types.NewTokenPair( precompileAddr, - evmtypes.GetEVMCoinDenom(), + coinInfo.GetDenom(), erc20types.OWNER_MODULE, ) precompile, err := werc20.NewPrecompile( @@ -320,10 +314,11 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp Context("and funds are NOT part of the transaction", func() { When("the method is withdraw", func() { It("it should fail if user doesn't have enough funds", func() { + coinInfo := chainConfig.EvmConfig.CoinInfo newUserAcc, newUserPriv := utiltx.NewAccAddressAndKey() newUserBalance := sdk.Coins{sdk.Coin{ - Denom: evmtypes.GetEVMCoinDenom(), - Amount: math.NewIntFromBigInt(withdrawAmount).Quo(precisebanktypes.ConversionFactor()).SubRaw(1), + Denom: coinInfo.GetDenom(), + Amount: math.NewIntFromBigInt(withdrawAmount).Quo(precisebanktypes.ConversionFactor(coinInfo.ExtendedDecimals)).SubRaw(1), }} err := is.network.App.GetBankKeeper().SendCoins(is.network.GetContext(), user.AccAddr, newUserAcc, newUserBalance) Expect(err).ToNot(HaveOccurred(), "expected no error sending tokens") @@ -552,19 +547,16 @@ func TestPrecompileIntegrationTestSuite(t *testing.T, create network.CreateEvmAp err = is.precompile.UnpackIntoInterface(&decimals, erc20.DecimalsMethod, ethRes.Ret) Expect(err).ToNot(HaveOccurred(), "failed to unpack result") - coinInfo := testconstants.ExampleChainCoinInfo[testconstants.ChainID{ - ChainID: is.network.GetChainID(), - EVMChainID: is.network.GetEIP155ChainID().Uint64(), - }] - Expect(decimals).To(Equal(uint8(coinInfo.Decimals)), "expected different decimals") + evmDecimals := is.network.GetEVMDecimals() + Expect(decimals).To(Equal(uint8(evmDecimals)), "expected different decimals") }, ) }) }) }, - Entry("6 decimals chain", testconstants.SixDecimalsChainID), - Entry("12 decimals chain", testconstants.TwelveDecimalsChainID), - Entry("18 decimals chain", testconstants.ExampleChainID), + Entry("6 decimals chain", testconfig.SixDecimalsChainConfig), + Entry("12 decimals chain", testconfig.TwelveDecimalsChainConfig), + Entry("18 decimals chain", testconfig.DefaultChainConfig), ) // Run Ginkgo integration tests diff --git a/tests/integration/rpc/backend/test_backend_suite.go b/tests/integration/rpc/backend/test_backend_suite.go index c464d673b..717f74a85 100644 --- a/tests/integration/rpc/backend/test_backend_suite.go +++ b/tests/integration/rpc/backend/test_backend_suite.go @@ -19,7 +19,7 @@ import ( rpcbackend "github.com/cosmos/evm/rpc/backend" "github.com/cosmos/evm/rpc/backend/mocks" rpctypes "github.com/cosmos/evm/rpc/types" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -48,7 +48,7 @@ func NewTestSuite(create network.CreateEvmApp, options ...network.ConfigOption) } } -var ChainID = constants.ExampleChainID +var ChainID = testconfig.DefaultChainConfig.ChainInfo // SetupTest is executed before every TestSuite test func (s *TestSuite) SetupTest() { diff --git a/tests/integration/rpc/backend/test_call_tx.go b/tests/integration/rpc/backend/test_call_tx.go index a35eaba75..99a0b3f41 100644 --- a/tests/integration/rpc/backend/test_call_tx.go +++ b/tests/integration/rpc/backend/test_call_tx.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/evm/rpc/backend/mocks" rpctypes "github.com/cosmos/evm/rpc/types" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -337,7 +337,7 @@ func (s *TestSuite) TestSendRawTransaction() { return bytes }, common.Hash{}, - fmt.Errorf("incorrect chain-id; expected %d, got %d", constants.ExampleChainID.EVMChainID, invalidChainID).Error(), + fmt.Errorf("incorrect chain-id; expected %d, got %d", testconfig.DefaultChainConfig.ChainInfo.EVMChainID, invalidChainID).Error(), false, }, { diff --git a/tests/integration/rpc/backend/test_chain_info.go b/tests/integration/rpc/backend/test_chain_info.go index 514132476..aec3e64c0 100644 --- a/tests/integration/rpc/backend/test_chain_info.go +++ b/tests/integration/rpc/backend/test_chain_info.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/evm/rpc/backend/mocks" rpc "github.com/cosmos/evm/rpc/types" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -156,7 +156,7 @@ func (s *TestSuite) TestBaseFee() { } func (s *TestSuite) TestChainID() { - expChainID := (*hexutil.Big)(big.NewInt(int64(constants.ExampleChainID.EVMChainID))) //nolint:gosec // G115 + expChainID := (*hexutil.Big)(big.NewInt(int64(testconfig.DefaultEvmChainID))) testCases := []struct { name string registerMock func() diff --git a/tests/integration/rpc/backend/test_evm_query_client.go b/tests/integration/rpc/backend/test_evm_query_client.go index cbeed91e9..34fffa040 100644 --- a/tests/integration/rpc/backend/test_evm_query_client.go +++ b/tests/integration/rpc/backend/test_evm_query_client.go @@ -18,7 +18,7 @@ import ( "github.com/cosmos/evm/rpc/backend/mocks" rpc "github.com/cosmos/evm/rpc/types" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" proto "github.com/cosmos/gogoproto/proto" @@ -56,26 +56,26 @@ var _ evmtypes.QueryClient = &mocks.EVMQueryClient{} func RegisterTraceTransactionWithPredecessors(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx, predecessors []*evmtypes.MsgEthereumTx) { data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} queryClient.On("TraceTx", rpc.ContextWithHeight(1), - MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, Predecessors: predecessors, ChainId: int64(constants.ExampleChainID.EVMChainID), BlockMaxGas: -1})). //nolint:gosec // G115 + MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, Predecessors: predecessors, ChainId: int64(testconfig.DefaultEvmChainID), BlockMaxGas: -1})). Return(&evmtypes.QueryTraceTxResponse{Data: data}, nil) } func RegisterTraceTransaction(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx) { data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} - queryClient.On("TraceTx", rpc.ContextWithHeight(1), MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, ChainId: int64(constants.ExampleChainID.EVMChainID), BlockMaxGas: -1})). //nolint:gosec // G115 - Return(&evmtypes.QueryTraceTxResponse{Data: data}, nil) + queryClient.On("TraceTx", rpc.ContextWithHeight(1), MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, ChainId: int64(testconfig.DefaultEvmChainID), BlockMaxGas: -1})). + Return(&evmtypes.QueryTraceTxResponse{Data: data}, nil) } func RegisterTraceTransactionError(queryClient *mocks.EVMQueryClient, msgEthTx *evmtypes.MsgEthereumTx) { - queryClient.On("TraceTx", rpc.ContextWithHeight(1), MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, ChainId: int64(constants.ExampleChainID.EVMChainID)})). //nolint:gosec // G115 - Return(nil, errortypes.ErrInvalidRequest) + queryClient.On("TraceTx", rpc.ContextWithHeight(1), MatchByProto(&evmtypes.QueryTraceTxRequest{Msg: msgEthTx, BlockNumber: 1, ChainId: int64(testconfig.DefaultEvmChainID)})). + Return(nil, errortypes.ErrInvalidRequest) } // TraceBlock func RegisterTraceBlock(queryClient *mocks.EVMQueryClient, txs []*evmtypes.MsgEthereumTx) { data := []byte{0x7b, 0x22, 0x74, 0x65, 0x73, 0x74, 0x22, 0x3a, 0x20, 0x22, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x22, 0x7d} queryClient.On("TraceBlock", rpc.ContextWithHeight(1), - MatchByProto(&evmtypes.QueryTraceBlockRequest{Txs: txs, BlockNumber: 1, TraceConfig: &evmtypes.TraceConfig{}, ChainId: int64(constants.ExampleChainID.EVMChainID), BlockMaxGas: -1})). //nolint:gosec // G115 + MatchByProto(&evmtypes.QueryTraceBlockRequest{Txs: txs, BlockNumber: 1, TraceConfig: &evmtypes.TraceConfig{}, ChainId: int64(testconfig.DefaultEvmChainID), BlockMaxGas: -1})). Return(&evmtypes.QueryTraceBlockResponse{Data: data}, nil) } diff --git a/tests/integration/rpc/backend/test_node_info.go b/tests/integration/rpc/backend/test_node_info.go index 270a3c8a1..9d2e231ba 100644 --- a/tests/integration/rpc/backend/test_node_info.go +++ b/tests/integration/rpc/backend/test_node_info.go @@ -14,7 +14,7 @@ import ( "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/rpc/backend/mocks" "github.com/cosmos/evm/server/config" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -33,13 +33,13 @@ func (s *TestSuite) TestRPCMinGasPrice() { { "pass - default gas price", func() {}, - big.NewInt(constants.DefaultGasPrice), + big.NewInt(testconfig.DefaultGasPrice), true, }, { "pass - min gas price is 0", func() {}, - big.NewInt(constants.DefaultGasPrice), + big.NewInt(testconfig.DefaultGasPrice), true, }, } @@ -260,7 +260,8 @@ func (s *TestSuite) TestSetEtherbase() { RegisterStatus(client) RegisterValidatorAccount(QueryClient, s.acc) RegisterParams(QueryClient, &header, 1) - c := sdk.NewDecCoin(constants.ExampleAttoDenom, math.NewIntFromBigInt(big.NewInt(1))) + attoDenom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + c := sdk.NewDecCoin(attoDenom, math.NewIntFromBigInt(big.NewInt(1))) s.backend.Cfg.SetMinGasPrices(sdk.DecCoins{c}) delAddr, _ := s.backend.GetCoinbase() // account, _ := s.backend.ClientCtx.AccountRetriever.GetAccount(s.backend.ClientCtx, delAddr) diff --git a/tests/integration/testutil/test_bank.go b/tests/integration/testutil/test_bank.go index 0f3c90b17..836023db2 100644 --- a/tests/integration/testutil/test_bank.go +++ b/tests/integration/testutil/test_bank.go @@ -14,6 +14,8 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) +// Note: TestSuite is defined in test_config.go + func (s *TestSuite) TestCheckBalances() { testDenom := "atest" keyring := testkeyring.New(1) diff --git a/tests/integration/testutil/test_config.go b/tests/integration/testutil/test_config.go index dac835b44..6a1c036a3 100644 --- a/tests/integration/testutil/test_config.go +++ b/tests/integration/testutil/test_config.go @@ -3,7 +3,7 @@ package testutil import ( - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" grpchandler "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" @@ -15,13 +15,15 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) +// Note: TestSuite is defined in test_suite.go + func (s *TestSuite) TestWithChainID() { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsConfig := testconfig.DefaultChainConfig + sixDecimalsConfig := testconfig.SixDecimalsChainConfig testCases := []struct { name string - chainID testconstants.ChainID + chainID string evmChainID uint64 coinInfo evmtypes.EvmCoinInfo expBaseFee math.LegacyDec @@ -29,15 +31,15 @@ func (s *TestSuite) TestWithChainID() { }{ { name: "18 decimals", - chainID: testconstants.ExampleChainID, - coinInfo: eighteenDecimalsCoinInfo, + chainID: eighteenDecimalsConfig.ChainID, + coinInfo: *eighteenDecimalsConfig.EvmConfig.CoinInfo, expBaseFee: math.LegacyNewDec(875_000_000), expCosmosAmount: network.GetInitialAmount(evmtypes.EighteenDecimals), }, { name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, - coinInfo: sixDecimalsCoinInfo, + chainID: sixDecimalsConfig.ChainID, + coinInfo: *sixDecimalsConfig.EvmConfig.CoinInfo, expBaseFee: math.LegacyNewDecWithPrec(875, 6), expCosmosAmount: network.GetInitialAmount(evmtypes.SixDecimals), }, @@ -47,8 +49,10 @@ func (s *TestSuite) TestWithChainID() { // create a new network with 2 pre-funded accounts keyring := testkeyring.New(1) + // Create chain config for the test case + chainConfig := testconfig.CreateChainConfig(tc.chainID, tc.evmChainID, nil, "test", tc.coinInfo.Decimals, tc.coinInfo.ExtendedDecimals) options := []network.ConfigOption{ - network.WithChainID(tc.chainID), + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(keyring.GetAllAccAddrs()...), } options = append(options, s.options...) @@ -74,7 +78,7 @@ func (s *TestSuite) TestWithChainID() { ) // Bank balance should always be in the original amount. - cReq, err := handler.GetBalanceFromBank(keyring.GetAccAddr(0), tc.coinInfo.Denom) + cReq, err := handler.GetBalanceFromBank(keyring.GetAccAddr(0), tc.coinInfo.GetDenom()) s.NoError(err, "error getting balances") s.Equal( tc.expCosmosAmount.String(), @@ -98,9 +102,9 @@ func (s *TestSuite) TestWithChainID() { } func (s *TestSuite) TestWithBalances() { - key1Balance := sdk.NewCoins(sdk.NewInt64Coin(testconstants.ExampleAttoDenom, 1e18)) + key1Balance := sdk.NewCoins(sdk.NewInt64Coin(testconfig.DefaultChainConfig.EvmConfig.CoinInfo.GetDenom(), 1e18)) key2Balance := sdk.NewCoins( - sdk.NewInt64Coin(testconstants.ExampleAttoDenom, 2e18), + sdk.NewInt64Coin(testconfig.DefaultChainConfig.EvmConfig.Denom, 2e18), sdk.NewInt64Coin("other", 3e18), ) diff --git a/tests/integration/wallets/test_ledger_suite.go b/tests/integration/wallets/test_ledger_suite.go index a9f166c19..eaf4645d2 100644 --- a/tests/integration/wallets/test_ledger_suite.go +++ b/tests/integration/wallets/test_ledger_suite.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/suite" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/wallets/ledger" "github.com/cosmos/evm/wallets/ledger/mocks" @@ -51,7 +51,7 @@ func (suite *LedgerTestSuite) SetupTest() { // We use the testutil network to load the encoding config network.New(suite.create, suite.options...) - suite.hrp = "cosmos" + suite.hrp = sdk.GetConfig().GetBech32AccountAddrPrefix() suite.txAmino = suite.getMockTxAmino() suite.txProtobuf = suite.getMockTxProtobuf() @@ -93,7 +93,7 @@ func (suite *LedgerTestSuite) getMockTxAmino() []byte { } }], "sequence":"6" - }`, constants.ExampleChainID.ChainID), + }`, testconfig.DefaultChainID), "", ) @@ -157,7 +157,7 @@ func (suite *LedgerTestSuite) getMockTxProtobuf() []byte { signBytes, err := tx.DirectSignBytes( bodyBytes, authInfoBytes, - constants.ExampleChainID.ChainID, + testconfig.DefaultChainID, 0, ) suite.Require().NoError(err) diff --git a/tests/integration/wallets/test_legder.go b/tests/integration/wallets/test_legder.go index 8f8a915c6..3a9ef1229 100644 --- a/tests/integration/wallets/test_legder.go +++ b/tests/integration/wallets/test_legder.go @@ -205,7 +205,7 @@ func (suite *LedgerTestSuite) TestGetAddressPubKeySECP256K1() { suite.Require().NoError(err) addr := crypto.PubkeyToAddress(privKey.PublicKey) - expAddr, err := sdk.Bech32ifyAddressBytes("cosmos", common.HexToAddress(addr.String()).Bytes()) + expAddr, err := sdk.Bech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), common.HexToAddress(addr.String()).Bytes()) suite.Require().NoError(err) testCases := []struct { diff --git a/tests/integration/x/erc20/test_grpc_query.go b/tests/integration/x/erc20/test_grpc_query.go index 138614b4b..cfa2f3708 100644 --- a/tests/integration/x/erc20/test_grpc_query.go +++ b/tests/integration/x/erc20/test_grpc_query.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/cosmos/evm/testutil/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/erc20/types" @@ -32,7 +32,7 @@ func (s *KeeperTestSuite) TestTokenPairs() { Pagination: &query.PageResponse{ Total: 1, }, - TokenPairs: testconstants.ExampleTokenPairs, + TokenPairs: testconfig.DefaultTokenPairs, } }, true, @@ -43,7 +43,7 @@ func (s *KeeperTestSuite) TestTokenPairs() { req = &types.QueryTokenPairsRequest{ Pagination: &query.PageRequest{Limit: 10, CountTotal: true}, } - pairs := testconstants.ExampleTokenPairs + pairs := testconfig.DefaultTokenPairs pair := types.NewTokenPair(utiltx.GenerateAddress(), "coin", types.OWNER_MODULE) s.network.App.GetErc20Keeper().SetTokenPair(ctx, pair) pairs = append(pairs, pair) @@ -59,7 +59,7 @@ func (s *KeeperTestSuite) TestTokenPairs() { "2 pairs registered wo/pagination", func() { req = &types.QueryTokenPairsRequest{} - pairs := testconstants.ExampleTokenPairs + pairs := testconfig.DefaultTokenPairs pair := types.NewTokenPair(utiltx.GenerateAddress(), "coin", types.OWNER_MODULE) pair2 := types.NewTokenPair(utiltx.GenerateAddress(), "coin2", types.OWNER_MODULE) diff --git a/tests/integration/x/erc20/test_precompiles.go b/tests/integration/x/erc20/test_precompiles.go index 502fce96d..6744b6812 100644 --- a/tests/integration/x/erc20/test_precompiles.go +++ b/tests/integration/x/erc20/test_precompiles.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/erc20/types" @@ -96,7 +96,7 @@ func (s *KeeperTestSuite) TestGetERC20PrecompileInstance() { func (s *KeeperTestSuite) TestGetNativePrecompiles() { var ctx sdk.Context testAddr := utiltx.GenerateAddress() - defaultWEVMOSAddr := common.HexToAddress(testconstants.WEVMOSContractMainnet) + defaultWEVMOSAddr := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) testCases := []struct { name string @@ -139,7 +139,7 @@ func (s *KeeperTestSuite) TestGetNativePrecompiles() { func (s *KeeperTestSuite) TestSetNativePrecompile() { var ctx sdk.Context testAddr := utiltx.GenerateAddress() - defaultWEVMOSAddr := common.HexToAddress(testconstants.WEVMOSContractMainnet) + defaultWEVMOSAddr := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) testCases := []struct { name string @@ -192,7 +192,7 @@ func (s *KeeperTestSuite) TestSetNativePrecompile() { func (s *KeeperTestSuite) TestDeleteNativePrecompile() { var ctx sdk.Context testAddr := utiltx.GenerateAddress() - defaultWEVMOSAddr := common.HexToAddress(testconstants.WEVMOSContractMainnet) + defaultWEVMOSAddr := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) unavailableAddr := common.HexToAddress("unavailable") testCases := []struct { @@ -285,7 +285,7 @@ func (s *KeeperTestSuite) TestDeleteNativePrecompile() { func (s *KeeperTestSuite) TestIsNativePrecompileAvailable() { var ctx sdk.Context testAddr := utiltx.GenerateAddress() - defaultWEVMOSAddr := common.HexToAddress(testconstants.WEVMOSContractMainnet) + defaultWEVMOSAddr := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) unavailableAddr := common.HexToAddress("unavailable") testCases := []struct { diff --git a/tests/integration/x/erc20/test_token_pairs.go b/tests/integration/x/erc20/test_token_pairs.go index fc63348e0..ee8ac113a 100644 --- a/tests/integration/x/erc20/test_token_pairs.go +++ b/tests/integration/x/erc20/test_token_pairs.go @@ -5,7 +5,7 @@ import ( "github.com/ethereum/go-ethereum/common" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/erc20/types" @@ -23,14 +23,14 @@ func (s *KeeperTestSuite) TestGetTokenPairs() { malleate func() }{ { - "no pair registered", func() { expRes = testconstants.ExampleTokenPairs }, + "no pair registered", func() { expRes = testconfig.DefaultTokenPairs }, }, { "1 pair registered", func() { pair := types.NewTokenPair(utiltx.GenerateAddress(), "coin", types.OWNER_MODULE) s.network.App.GetErc20Keeper().SetTokenPair(ctx, pair) - expRes = testconstants.ExampleTokenPairs + expRes = testconfig.DefaultTokenPairs expRes = append(expRes, pair) }, }, @@ -41,7 +41,7 @@ func (s *KeeperTestSuite) TestGetTokenPairs() { pair2 := types.NewTokenPair(utiltx.GenerateAddress(), "coin2", types.OWNER_MODULE) s.network.App.GetErc20Keeper().SetTokenPair(ctx, pair) s.network.App.GetErc20Keeper().SetTokenPair(ctx, pair2) - expRes = testconstants.ExampleTokenPairs + expRes = testconfig.DefaultTokenPairs expRes = append(expRes, []types.TokenPair{pair, pair2}...) }, }, diff --git a/tests/integration/x/precisebank/test_burn_integration.go b/tests/integration/x/precisebank/test_burn_integration.go index 65b57f5da..324e49b92 100644 --- a/tests/integration/x/precisebank/test_burn_integration.go +++ b/tests/integration/x/precisebank/test_burn_integration.go @@ -6,9 +6,7 @@ import ( "math/rand" "testing" - "github.com/stretchr/testify/require" - - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -23,6 +21,8 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsMatchingErrors() { // consumers. This test ensures that the panics & errors returned by // x/precisebank are identical to x/bank. + integerDenom := s.network.GetEVMDenom() + tests := []struct { name string recipientModule string @@ -35,7 +35,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsMatchingErrors() { "invalid module", "notamodule", func() {}, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", "module account notamodule does not exist: unknown address", }, @@ -44,7 +44,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsMatchingErrors() { // Check app.go to ensure this module has no burn permissions authtypes.FeeCollectorName, func() {}, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", "module account fee_collector does not have permissions to burn tokens: unauthorized", }, @@ -53,16 +53,16 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsMatchingErrors() { // Has burn permissions so it goes to the amt check evmtypes.ModuleName, func() {}, - sdk.Coins{sdk.Coin{Denom: types.IntegerCoinDenom(), Amount: sdkmath.NewInt(-100)}}, - fmt.Sprintf("-100%s: invalid coins", types.IntegerCoinDenom()), + sdk.Coins{sdk.Coin{Denom: integerDenom, Amount: sdkmath.NewInt(-100)}}, + fmt.Sprintf("-100%s: invalid coins", integerDenom), "", }, { "insufficient balance - empty", evmtypes.ModuleName, func() {}, - cs(c(types.IntegerCoinDenom(), 1000)), - fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", types.IntegerCoinDenom(), types.IntegerCoinDenom()), + cs(c(integerDenom, 1000)), + fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", integerDenom, integerDenom), "", }, } @@ -109,6 +109,10 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsMatchingErrors() { } func (s *KeeperIntegrationTestSuite) TestBurnCoins() { + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string startBalance sdk.Coins @@ -125,42 +129,42 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoins() { }, { "passthrough - integer denom", - cs(c(types.IntegerCoinDenom(), 2000)), - cs(c(types.IntegerCoinDenom(), 1000)), - cs(c(types.ExtendedCoinDenom(), 1000000000000000)), + cs(c(integerDenom, 2000)), + cs(c(integerDenom, 1000)), + cs(c(extendedDenom, 1000000000000000)), "", }, { "fractional only - no borrow", - cs(c(types.ExtendedCoinDenom(), 1000)), - cs(c(types.ExtendedCoinDenom(), 500)), - cs(c(types.ExtendedCoinDenom(), 500)), + cs(c(extendedDenom, 1000)), + cs(c(extendedDenom, 500)), + cs(c(extendedDenom, 500)), "", }, { "fractional burn - borrows", - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().AddRaw(100))), - cs(c(types.ExtendedCoinDenom(), 500)), - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(400))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).AddRaw(100))), + cs(c(extendedDenom, 500)), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(400))), "", }, { "error - insufficient integer balance", - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(2))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(2))), cs(), // Returns correct error with aatom balance (rewrites Bank BurnCoins err) fmt.Sprintf("spendable balance 1000000000000%s is smaller than 2000000000000%s: insufficient funds", - types.ExtendedCoinDenom(), types.ExtendedCoinDenom()), + extendedDenom, extendedDenom), }, { "error - insufficient fractional, borrow", - cs(c(types.ExtendedCoinDenom(), 1000)), - cs(c(types.ExtendedCoinDenom(), 2000)), + cs(c(extendedDenom, 1000)), + cs(c(extendedDenom, 2000)), cs(), // Error from SendCoins to reserve fmt.Sprintf("spendable balance 1000%s is smaller than 2000%s: insufficient funds", - types.ExtendedCoinDenom(), types.ExtendedCoinDenom()), + extendedDenom, extendedDenom), }, } @@ -224,7 +228,11 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRemainder() { moduleName := evmtypes.ModuleName moduleAddr := s.network.App.GetAccountKeeper().GetModuleAddress(moduleName) - startCoins := cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5))) + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + + startCoins := cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5))) // Start balance err := s.network.App.GetPreciseBankKeeper().MintCoins( @@ -234,21 +242,21 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRemainder() { ) s.Require().NoError(err) - burnAmt := types.ConversionFactor().QuoRaw(10) - burnCoins := cs(ci(types.ExtendedCoinDenom(), burnAmt)) + burnAmt := types.ConversionFactor(extendedDecimals).QuoRaw(10) + burnCoins := cs(ci(extendedDenom, burnAmt)) // Burn 0.1 until balance is 0 for { reserveBalBefore := s.network.App.GetBankKeeper().GetBalance( s.network.GetContext(), reserveAddr, - types.IntegerCoinDenom(), + integerDenom, ) balBefore := s.network.App.GetPreciseBankKeeper().GetBalance( s.network.GetContext(), moduleAddr, - types.ExtendedCoinDenom(), + extendedDenom, ) remainderBefore := s.network.App.GetPreciseBankKeeper().GetRemainderAmount(s.network.GetContext()) @@ -267,12 +275,12 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRemainder() { balAfter := s.network.App.GetPreciseBankKeeper().GetBalance( s.network.GetContext(), moduleAddr, - types.ExtendedCoinDenom(), + extendedDenom, ) reserveBalAfter := s.network.App.GetBankKeeper().GetBalance( s.network.GetContext(), reserveAddr, - types.IntegerCoinDenom(), + integerDenom, ) s.Require().Equal( @@ -283,7 +291,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRemainder() { // Remainder should be updated correctly s.Require().Equal( - remainderBefore.Add(burnAmt).Mod(types.ConversionFactor()), + remainderBefore.Add(burnAmt).Mod(types.ConversionFactor(extendedDecimals)), remainderAfter, ) @@ -313,8 +321,12 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { burnerModuleName := evmtypes.ModuleName burnerAddr := s.network.App.GetAccountKeeper().GetModuleAddress(burnerModuleName) + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + accCount := 20 - startCoins := cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5))) + startCoins := cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5))) addrs := []sdk.AccAddress{} @@ -325,21 +337,21 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { addrs = append(addrs, addr) } - burnAmt := types.ConversionFactor().QuoRaw(10) - burnCoins := cs(ci(types.ExtendedCoinDenom(), burnAmt)) + burnAmt := types.ConversionFactor(extendedDecimals).QuoRaw(10) + burnCoins := cs(ci(extendedDenom, burnAmt)) // Burn 0.1 from each account for _, addr := range addrs { reserveBalBefore := s.network.App.GetBankKeeper().GetBalance( s.network.GetContext(), reserveAddr, - types.IntegerCoinDenom(), + integerDenom, ) balBefore := s.network.App.GetPreciseBankKeeper().GetBalance( s.network.GetContext(), addr, - types.ExtendedCoinDenom(), + extendedDenom, ) remainderBefore := s.network.App.GetPreciseBankKeeper().GetRemainderAmount(s.network.GetContext()) @@ -366,12 +378,12 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { balAfter := s.network.App.GetPreciseBankKeeper().GetBalance( s.network.GetContext(), addr, - types.ExtendedCoinDenom(), + extendedDenom, ) reserveBalAfter := s.network.App.GetBankKeeper().GetBalance( s.network.GetContext(), reserveAddr, - types.IntegerCoinDenom(), + integerDenom, ) s.Require().Equal( @@ -382,7 +394,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { // Remainder should be updated correctly s.Require().Equal( - remainderBefore.Add(burnAmt).Mod(types.ConversionFactor()), + remainderBefore.Add(burnAmt).Mod(types.ConversionFactor(extendedDecimals)), remainderAfter, ) @@ -397,12 +409,12 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { reserveIncrease := sdkmath.ZeroInt() // Does account need to borrow from integer? - if balBefore.Amount.Mod(types.ConversionFactor()).LT(burnAmt) { + if balBefore.Amount.Mod(types.ConversionFactor(extendedDecimals)).LT(burnAmt) { reserveIncrease = reserveIncrease.AddRaw(1) } // If remainder has exceeded (then rolled over), burn additional 1 - if remainderBefore.Add(burnAmt).GTE(types.ConversionFactor()) { + if remainderBefore.Add(burnAmt).GTE(types.ConversionFactor(extendedDecimals)) { reserveIncrease = reserveIncrease.SubRaw(1) } @@ -415,42 +427,45 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsSpreadRemainder() { } func (s *KeeperIntegrationTestSuite) TestBurnCoinsRandomValueMultiDecimals() { + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) // Has burn permissions burnerModuleName := evmtypes.ModuleName burner := sdk.AccAddress([]byte{1}) // Initial balance large enough to cover many small burns - initialBalance := types.ConversionFactor().MulRaw(100) - initialCoin := cs(ci(types.ExtendedCoinDenom(), initialBalance)) + initialBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) + initialCoin := cs(ci(extendedDenom, initialBalance)) err := s.network.App.GetPreciseBankKeeper().MintCoins(s.network.GetContext(), burnerModuleName, initialCoin) s.Require().NoError(err) err = s.network.App.GetPreciseBankKeeper().SendCoinsFromModuleToAccount(s.network.GetContext(), burnerModuleName, burner, initialCoin) s.Require().NoError(err) // Setup test parameters - maxBurnUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxBurnUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) totalBurned := sdkmath.ZeroInt() @@ -459,7 +474,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRandomValueMultiDecimals() { // Continue burns as long as burner has balance remaining for { // Check current burner balance - burnerAmount := s.GetAllBalances(burner).AmountOf(types.ExtendedCoinDenom()) + burnerAmount := s.GetAllBalances(burner).AmountOf(extendedDenom) if burnerAmount.IsZero() { break } @@ -472,7 +487,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRandomValueMultiDecimals() { randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, maxPossibleBurn.BigInt())).AddRaw(1) // 1. send to burner module - burnCoins := cs(ci(types.ExtendedCoinDenom(), randAmount)) + burnCoins := cs(ci(extendedDenom, randAmount)) err := s.network.App.GetPreciseBankKeeper().SendCoinsFromAccountToModule(s.network.GetContext(), burner, burnerModuleName, burnCoins) s.Require().NoError(err) @@ -487,7 +502,7 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRandomValueMultiDecimals() { s.T().Logf("Completed %d random burns, total burned: %s", burnCount, totalBurned) // Check burner balance - burnerBal := s.GetAllBalances(burner).AmountOf(types.ExtendedCoinDenom()) + burnerBal := s.GetAllBalances(burner).AmountOf(extendedDenom) s.Equal(burnerBal.BigInt().Cmp(big.NewInt(0)), 0, "burner balance mismatch (expected: %s, actual: %s)", big.NewInt(0), burnerBal) // Check remainder @@ -498,17 +513,14 @@ func (s *KeeperIntegrationTestSuite) TestBurnCoinsRandomValueMultiDecimals() { } func FuzzBurnCoins(f *testing.F) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID]) - err := configurator.Configure() - require.NoError(f, err) + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals f.Add(int64(0)) f.Add(int64(100)) - f.Add(types.ConversionFactor().Int64()) - f.Add(types.ConversionFactor().MulRaw(5).Int64()) - f.Add(types.ConversionFactor().MulRaw(2).AddRaw(123948723).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).MulRaw(5).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(123948723).Int64()) f.Fuzz(func(t *testing.T, amount int64) { // No negative amounts @@ -532,7 +544,7 @@ func FuzzBurnCoins(f *testing.F) { err := suite.network.App.GetPreciseBankKeeper().MintCoins( suite.network.GetContext(), moduleName, - cs(ci(types.ExtendedCoinDenom(), sdkmath.NewInt(amount).MulRaw(burnCount))), + cs(ci(extendedDenom, sdkmath.NewInt(amount).MulRaw(burnCount))), ) suite.Require().NoError(err) @@ -541,13 +553,13 @@ func FuzzBurnCoins(f *testing.F) { err := suite.network.App.GetPreciseBankKeeper().BurnCoins( suite.network.GetContext(), moduleName, - cs(c(types.ExtendedCoinDenom(), amount)), + cs(c(extendedDenom, amount)), ) suite.Require().NoError(err) } // Check full balances - balAfter := suite.network.App.GetPreciseBankKeeper().GetBalance(suite.network.GetContext(), moduleAddr, types.ExtendedCoinDenom()) + balAfter := suite.network.App.GetPreciseBankKeeper().GetBalance(suite.network.GetContext(), moduleAddr, extendedDenom) suite.Require().Equalf( int64(0), diff --git a/tests/integration/x/precisebank/test_genesis.go b/tests/integration/x/precisebank/test_genesis.go index 02f01e130..6f1c11f85 100644 --- a/tests/integration/x/precisebank/test_genesis.go +++ b/tests/integration/x/precisebank/test_genesis.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/suite" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/x/precisebank" "github.com/cosmos/evm/x/precisebank/types" @@ -31,12 +31,12 @@ func NewGenesisTestSuite(create network.CreateEvmApp, options ...network.ConfigO } func (s *GenesisTestSuite) SetupTest() { - s.SetupTestWithChainID(testconstants.SixDecimalsChainID) + s.SetupTestWithChainID(testconfig.SixDecimalsChainConfig) } -func (s *GenesisTestSuite) SetupTestWithChainID(chainID testconstants.ChainID) { +func (s *GenesisTestSuite) SetupTestWithChainID(chainConfig testconfig.ChainConfig) { options := []network.ConfigOption{ - network.WithChainID(chainID), + network.WithChainConfig(chainConfig), } options = append(options, s.options...) s.network = network.NewUnitTestNetwork(s.create, options...) @@ -49,6 +49,10 @@ func (s *GenesisTestSuite) SetupTestWithChainID(chainID testconstants.ChainID) { } func (s *GenesisTestSuite) TestInitGenesis() { + integerCoinDenom := s.network.GetEVMDenom() + extendedCoinDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string setupFn func() @@ -75,14 +79,14 @@ func (s *GenesisTestSuite) TestInitGenesis() { err := s.network.App.GetBankKeeper().MintCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) }, types.NewGenesisState( types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().SubRaw(1)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), }, // 2 leftover from 0.999... + 0.999... sdkmath.NewInt(2), @@ -110,20 +114,20 @@ func (s *GenesisTestSuite) TestInitGenesis() { err := s.network.App.GetBankKeeper().BurnCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) }, types.NewGenesisState( types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().SubRaw(1)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), }, // 2 leftover from 0.999... + 0.999... sdkmath.NewInt(2), ), fmt.Sprintf("module account balance does not match sum of fractional balances and remainder, balance is 0%s but expected 2000000000000%s (2%s)", - types.IntegerCoinDenom(), types.ExtendedCoinDenom(), types.IntegerCoinDenom()), + integerCoinDenom, extendedCoinDenom, integerCoinDenom), }, { "invalid - module balance excessive", @@ -133,19 +137,19 @@ func (s *GenesisTestSuite) TestInitGenesis() { err := s.network.App.GetBankKeeper().MintCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(99))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(99))), ) s.Require().NoError(err) }, types.NewGenesisState( types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().SubRaw(1)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).SubRaw(1)), }, sdkmath.NewInt(2), ), fmt.Sprintf("module account balance does not match sum of fractional balances and remainder, balance is 100%s but expected 2000000000000%s (2%s)", - types.IntegerCoinDenom(), types.ExtendedCoinDenom(), types.IntegerCoinDenom()), + integerCoinDenom, extendedCoinDenom, integerCoinDenom), }, { "sets module account", @@ -222,6 +226,8 @@ func (s *GenesisTestSuite) TestInitGenesis() { func (s *GenesisTestSuite) TestExportGenesis() { // ExportGenesis(InitGenesis(genesisState)) == genesisState // Must also be valid. + integerCoinDenom := s.network.GetEVMDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals tests := []struct { name string @@ -238,21 +244,21 @@ func (s *GenesisTestSuite) TestExportGenesis() { err := s.network.App.GetBankKeeper().BurnCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) err = s.network.App.GetBankKeeper().MintCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) return types.NewGenesisState( types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().QuoRaw(2)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), }, sdkmath.ZeroInt(), ) @@ -265,21 +271,21 @@ func (s *GenesisTestSuite) TestExportGenesis() { err := s.network.App.GetBankKeeper().BurnCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) err = s.network.App.GetBankKeeper().MintCoins( s.network.GetContext(), types.ModuleName, - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1))), + sdk.NewCoins(sdk.NewCoin(integerCoinDenom, sdkmath.NewInt(1))), ) s.Require().NoError(err) return types.NewGenesisState( types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().QuoRaw(2)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().QuoRaw(2).SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2).SubRaw(1)), }, sdkmath.OneInt(), ) diff --git a/tests/integration/x/precisebank/test_grpc_query.go b/tests/integration/x/precisebank/test_grpc_query.go index 317c21add..8e8ae0f29 100644 --- a/tests/integration/x/precisebank/test_grpc_query.go +++ b/tests/integration/x/precisebank/test_grpc_query.go @@ -3,6 +3,7 @@ package precisebank import ( "context" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -18,14 +19,17 @@ func (s *KeeperIntegrationTestSuite) TestQueryRemainder() { ) s.Require().NoError(err) - expRemainder := sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.ZeroInt()) + extendedCoinDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + + expRemainder := sdk.NewCoin(extendedCoinDenom, sdkmath.ZeroInt()) s.Require().Equal(expRemainder, res.Remainder) // Mint fractional coins to create non-zero remainder pbk := s.network.App.GetPreciseBankKeeper() - coin := sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.OneInt()) + coin := sdk.NewCoin(extendedCoinDenom, sdkmath.OneInt()) err = pbk.MintCoins( s.network.GetContext(), minttypes.ModuleName, @@ -39,11 +43,14 @@ func (s *KeeperIntegrationTestSuite) TestQueryRemainder() { ) s.Require().NoError(err) - expRemainder.Amount = types.ConversionFactor().Sub(coin.Amount) + expRemainder.Amount = types.ConversionFactor(extendedDecimals).Sub(coin.Amount) s.Require().Equal(expRemainder, res.Remainder) } func (s *KeeperIntegrationTestSuite) TestQueryFractionalBalance() { + extendedCoinDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + testCases := []struct { name string giveBalance sdkmath.Int @@ -58,15 +65,15 @@ func (s *KeeperIntegrationTestSuite) TestQueryFractionalBalance() { }, { "max amount", - types.ConversionFactor().SubRaw(1), + types.ConversionFactor(extendedDecimals).SubRaw(1), }, { "multiple integer amounts, 0 fractional", - types.ConversionFactor().MulRaw(5), + types.ConversionFactor(extendedDecimals).MulRaw(5), }, { "multiple integer amounts, non-zero fractional", - types.ConversionFactor().MulRaw(5).Add(types.ConversionFactor().QuoRaw(2)), + types.ConversionFactor(extendedDecimals).MulRaw(5).Add(types.ConversionFactor(extendedDecimals).QuoRaw(2)), }, } @@ -76,7 +83,7 @@ func (s *KeeperIntegrationTestSuite) TestQueryFractionalBalance() { addr := sdk.AccAddress([]byte("test")) - coin := sdk.NewCoin(types.ExtendedCoinDenom(), tc.giveBalance) + coin := sdk.NewCoin(extendedCoinDenom, tc.giveBalance) s.MintToAccount(addr, sdk.NewCoins(coin)) res, err := s.network.GetPreciseBankClient().FractionalBalance( @@ -88,8 +95,8 @@ func (s *KeeperIntegrationTestSuite) TestQueryFractionalBalance() { s.Require().NoError(err) // Only fractional amount, even if minted more than conversion factor - expAmount := tc.giveBalance.Mod(types.ConversionFactor()) - expFractionalBalance := sdk.NewCoin(types.ExtendedCoinDenom(), expAmount) + expAmount := tc.giveBalance.Mod(types.ConversionFactor(extendedDecimals)) + expFractionalBalance := sdk.NewCoin(extendedCoinDenom, expAmount) s.Require().Equal(expFractionalBalance, res.FractionalBalance) }) } diff --git a/tests/integration/x/precisebank/test_integration.go b/tests/integration/x/precisebank/test_integration.go index 9b568d2af..cb1cd4519 100644 --- a/tests/integration/x/precisebank/test_integration.go +++ b/tests/integration/x/precisebank/test_integration.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/cosmos/evm/contracts" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/utils" testutiltypes "github.com/cosmos/evm/testutil/types" "github.com/cosmos/evm/x/precisebank/types" @@ -19,39 +19,42 @@ import ( ) func (s *KeeperIntegrationTestSuite) TestMintBurnSendCoinsRandomValueMultiDecimals() { + extendedCoinDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) moduleName := evmtypes.ModuleName sender := sdk.AccAddress([]byte{1}) recipient := sdk.AccAddress([]byte{2}) // Mint initial balance to sender - initialBalance := types.ConversionFactor().MulRaw(100) - initialCoins := cs(ci(types.ExtendedCoinDenom(), initialBalance)) + initialBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) + initialCoins := cs(ci(extendedCoinDenom, initialBalance)) s.Require().NoError(s.network.App.GetPreciseBankKeeper().MintCoins(s.network.GetContext(), moduleName, initialCoins)) s.Require().NoError(s.network.App.GetPreciseBankKeeper().SendCoinsFromModuleToAccount(s.network.GetContext(), moduleName, sender, initialCoins)) - maxUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) // Expected balances tracking @@ -69,7 +72,7 @@ func (s *KeeperIntegrationTestSuite) TestMintBurnSendCoinsRandomValueMultiDecima switch op { case 0: // Mint to sender via module randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, maxUnit.BigInt())).AddRaw(1) - mintCoins := cs(ci(types.ExtendedCoinDenom(), randAmount)) + mintCoins := cs(ci(extendedCoinDenom, randAmount)) if err := s.network.App.GetPreciseBankKeeper().MintCoins(s.network.GetContext(), moduleName, mintCoins); err != nil { continue } @@ -81,13 +84,13 @@ func (s *KeeperIntegrationTestSuite) TestMintBurnSendCoinsRandomValueMultiDecima mintCount++ case 1: // Burn from sender via module - senderBal := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderBal := s.GetAllBalances(sender).AmountOf(extendedCoinDenom) if senderBal.IsZero() { continue } burnable := sdkmath.MinInt(senderBal, maxUnit) randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, burnable.BigInt())).AddRaw(1) - burnCoins := cs(ci(types.ExtendedCoinDenom(), randAmount)) + burnCoins := cs(ci(extendedCoinDenom, randAmount)) if err := s.network.App.GetPreciseBankKeeper().SendCoinsFromAccountToModule(s.network.GetContext(), sender, moduleName, burnCoins); err != nil { continue } @@ -99,13 +102,13 @@ func (s *KeeperIntegrationTestSuite) TestMintBurnSendCoinsRandomValueMultiDecima burnCount++ case 2: // Send from sender to recipient - senderBal := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderBal := s.GetAllBalances(sender).AmountOf(extendedCoinDenom) if senderBal.IsZero() { continue } sendable := sdkmath.MinInt(senderBal, maxUnit) randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, sendable.BigInt())).AddRaw(1) - sendCoins := cs(ci(types.ExtendedCoinDenom(), randAmount)) + sendCoins := cs(ci(extendedCoinDenom, randAmount)) if err := s.network.App.GetPreciseBankKeeper().SendCoins(s.network.GetContext(), sender, recipient, sendCoins); err != nil { continue } @@ -118,13 +121,13 @@ func (s *KeeperIntegrationTestSuite) TestMintBurnSendCoinsRandomValueMultiDecima s.T().Logf("Executed operations: %d mints, %d burns, %d sends", mintCount, burnCount, sendCount) // Check balances - actualSenderBal := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) - actualRecipientBal := s.GetAllBalances(recipient).AmountOf(types.ExtendedCoinDenom()) + actualSenderBal := s.GetAllBalances(sender).AmountOf(extendedCoinDenom) + actualRecipientBal := s.GetAllBalances(recipient).AmountOf(extendedCoinDenom) s.Require().Equal(expectedSenderBal.BigInt().Cmp(actualSenderBal.BigInt()), 0, "Sender balance mismatch (expected: %s, actual: %s)", expectedSenderBal, actualSenderBal) s.Require().Equal(expectedRecipientBal.BigInt().Cmp(actualRecipientBal.BigInt()), 0, "Recipient balance mismatch (expected: %s, actual: %s)", expectedRecipientBal, actualRecipientBal) // Check remainder - expectedRemainder := burnAmount.Sub(mintAmount).Mod(types.ConversionFactor()) + expectedRemainder := burnAmount.Sub(mintAmount).Mod(types.ConversionFactor(extendedDecimals)) actualRemainder := s.network.App.GetPreciseBankKeeper().GetRemainderAmount(s.network.GetContext()) s.Require().Equal(expectedRemainder.BigInt().Cmp(actualRemainder.BigInt()), 0, "Remainder mismatch (expected: %s, actual: %s)", expectedRemainder, actualRemainder) }) @@ -135,27 +138,30 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { maxGasLimit := int64(500000) defaultEVMCoinTransferGasLimit := int64(21000) + extendedCoinDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) sender := s.keyring.GetKey(0) recipient := s.keyring.GetKey(1) @@ -167,8 +173,8 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { gasFee := gasPrice.Mul(sdkmath.NewInt(defaultEVMCoinTransferGasLimit)) // Burn balance from sender except for initial balance - initialBalance := types.ConversionFactor().MulRaw(100) - senderBal := s.GetAllBalances(sender.AccAddr).AmountOf(types.ExtendedCoinDenom()).Sub(gasFee).Sub(initialBalance) + initialBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) + senderBal := s.GetAllBalances(sender.AccAddr).AmountOf(extendedCoinDenom).Sub(gasFee).Sub(initialBalance) _, err = s.factory.ExecuteEthTx(sender.Priv, evmtypes.EvmTxArgs{ To: &burnerAddr, Amount: senderBal.BigInt(), @@ -178,7 +184,7 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { s.Require().NoError(err) // Burn balance from recipient - recipientBal := s.GetAllBalances(recipient.AccAddr).AmountOf(types.ExtendedCoinDenom()).Sub(gasFee) + recipientBal := s.GetAllBalances(recipient.AccAddr).AmountOf(extendedCoinDenom).Sub(gasFee) _, err = s.factory.ExecuteEthTx(recipient.Priv, evmtypes.EvmTxArgs{ To: &burnerAddr, Amount: recipientBal.BigInt(), @@ -190,7 +196,7 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { err = s.network.NextBlock() s.Require().NoError(err) - maxSendUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxSendUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) expectedSenderBal := initialBalance @@ -235,12 +241,12 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { s.T().Logf("Completed %d random evm sends", sentCount) // Check sender balance - actualSenderBal := s.GetAllBalances(sender.AccAddr).AmountOf(types.ExtendedCoinDenom()) + actualSenderBal := s.GetAllBalances(sender.AccAddr).AmountOf(extendedCoinDenom) s.Require().Equal(expectedSenderBal.BigInt().Cmp(actualSenderBal.BigInt()), 0, "Sender balance mismatch (expected: %s, actual: %s)", expectedSenderBal, actualSenderBal) // Check recipient balance - actualRecipientBal := s.GetAllBalances(recipient.AccAddr).AmountOf(types.ExtendedCoinDenom()) + actualRecipientBal := s.GetAllBalances(recipient.AccAddr).AmountOf(extendedCoinDenom) s.Require().Equal(expectedRecipientBal.BigInt().Cmp(actualRecipientBal.BigInt()), 0, "Recipient balance mismatch (expected: %s, actual: %s)", expectedRecipientBal, actualRecipientBal) }) @@ -249,26 +255,26 @@ func (s *KeeperIntegrationTestSuite) TestSendEvmTxRandomValueMultiDecimals() { func (s *KeeperIntegrationTestSuite) TestWATOMWrapUnwrapMultiDecimal() { tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) sender := s.keyring.GetKey(0) amount := big.NewInt(1) diff --git a/tests/integration/x/precisebank/test_mint_integration.go b/tests/integration/x/precisebank/test_mint_integration.go index 0458f1299..5abcf247e 100644 --- a/tests/integration/x/precisebank/test_mint_integration.go +++ b/tests/integration/x/precisebank/test_mint_integration.go @@ -6,9 +6,7 @@ import ( "math/rand" "testing" - "github.com/stretchr/testify/require" - - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -30,7 +28,8 @@ func (s *KeeperIntegrationTestSuite) TestBlockedRecipient() { // To x/precisebank toAddr := s.network.App.GetAccountKeeper().GetModuleAddress(types.ModuleName) - amount := cs(c(types.IntegerCoinDenom(), 1000)) + integerDenom := s.network.GetEVMDenom() + amount := cs(c(integerDenom, 1000)) msg := banktypes.NewMsgSend(fromAddr, toAddr, amount) @@ -48,6 +47,8 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsMatchingErrors() { // consumers. This test ensures that the panics & errors returned by // x/precisebank are identical to x/bank. + integerDenom := s.network.GetEVMDenom() + tests := []struct { name string recipientModule string @@ -58,7 +59,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsMatchingErrors() { { "invalid module", "notamodule", - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", "module account notamodule does not exist: unknown address", }, @@ -66,15 +67,15 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsMatchingErrors() { "no mint permissions", // Check app.go to ensure this module has no mint permissions authtypes.FeeCollectorName, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", "module account fee_collector does not have permissions to mint tokens: unauthorized", }, { "invalid amount", evmtypes.ModuleName, - sdk.Coins{sdk.Coin{Denom: types.IntegerCoinDenom(), Amount: sdkmath.NewInt(-100)}}, - fmt.Sprintf("-100%s: invalid coins", types.IntegerCoinDenom()), + sdk.Coins{sdk.Coin{Denom: integerDenom, Amount: sdkmath.NewInt(-100)}}, + fmt.Sprintf("-100%s: invalid coins", integerDenom), "", }, } @@ -127,6 +128,10 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { wantBalance sdk.Coins } + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string recipientModule string @@ -149,8 +154,8 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { evmtypes.ModuleName, []mintTest{ { - mintAmount: cs(c(types.IntegerCoinDenom(), 1000)), - wantBalance: cs(c(types.ExtendedCoinDenom(), 1000000000000000)), + mintAmount: cs(c(integerDenom, 1000)), + wantBalance: cs(c(extendedDenom, 1000000000000000)), }, }, }, @@ -159,12 +164,12 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { evmtypes.ModuleName, []mintTest{ { - mintAmount: cs(c(types.ExtendedCoinDenom(), 1000)), - wantBalance: cs(c(types.ExtendedCoinDenom(), 1000)), + mintAmount: cs(c(extendedDenom, 1000)), + wantBalance: cs(c(extendedDenom, 1000)), }, { - mintAmount: cs(c(types.ExtendedCoinDenom(), 1000)), - wantBalance: cs(c(types.ExtendedCoinDenom(), 2000)), + mintAmount: cs(c(extendedDenom, 1000)), + wantBalance: cs(c(extendedDenom, 2000)), }, }, }, @@ -174,13 +179,13 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { []mintTest{ { // Start with (1/4 * 3) = 0.75 - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(4).MulRaw(3))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(4).MulRaw(3))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(4).MulRaw(3))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(4).MulRaw(3))), }, { // Add another 0.50 to incur carry to test reserve on carry - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(2))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(4).MulRaw(5))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(2))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(4).MulRaw(5))), }, }, }, @@ -190,14 +195,14 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { []mintTest{ // mint 0.5, acc = 0.5, reserve = 1 { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(2))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(2))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(2))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(2))), }, // mint another 0.5, acc = 1, reserve = 0 // Reserve actually goes down by 1 for integer carry { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().QuoRaw(2))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).QuoRaw(2))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), }, }, }, @@ -206,13 +211,13 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { evmtypes.ModuleName, []mintTest{ { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), }, // Carry again - exact amount { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(2))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(2))), }, }, }, @@ -222,13 +227,13 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { []mintTest{ // MintCoins(C + 100) { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().AddRaw(100))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().AddRaw(100))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).AddRaw(100))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).AddRaw(100))), }, // MintCoins(C + 5), total = 2C + 105 { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().AddRaw(5))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(2).AddRaw(105))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).AddRaw(5))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(105))), }, }, }, @@ -237,12 +242,12 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { evmtypes.ModuleName, []mintTest{ { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5).AddRaw(100))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5).AddRaw(100))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5).AddRaw(100))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5).AddRaw(100))), }, { - mintAmount: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(2).AddRaw(5))), - wantBalance: cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(7).AddRaw(105))), + mintAmount: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(5))), + wantBalance: cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(7).AddRaw(105))), }, }, }, @@ -252,21 +257,21 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { []mintTest{ { mintAmount: cs( - ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5).AddRaw(100)), + ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5).AddRaw(100)), c("busd", 1000), ), wantBalance: cs( - ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5).AddRaw(100)), + ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5).AddRaw(100)), c("busd", 1000), ), }, { mintAmount: cs( - ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(2).AddRaw(5)), + ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(5)), c("meow", 40), ), wantBalance: cs( - ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(7).AddRaw(105)), + ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(7).AddRaw(105)), c("busd", 1000), c("meow", 40), ), @@ -302,7 +307,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { var denoms []string for _, coin := range bankCoins { // Ignore integer coins, query the extended denom instead - if coin.Denom == types.IntegerCoinDenom() { + if coin.Denom == integerDenom { continue } @@ -312,7 +317,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { // Add the extended denom to the list of denoms to balance check // Will be included in balance check even if x/bank doesn't have // uatom. - denoms = append(denoms, types.ExtendedCoinDenom()) + denoms = append(denoms, extendedDenom) // All balance queries through x/precisebank afterBalance := sdk.NewCoins() @@ -339,37 +344,40 @@ func (s *KeeperIntegrationTestSuite) TestMintCoins() { } func (s *KeeperIntegrationTestSuite) TestMintCoinsRandomValueMultiDecimals() { + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) // Has mint permissions minterModuleName := evmtypes.ModuleName minter := sdk.AccAddress([]byte{1}) // Target balance - targetBalance := types.ConversionFactor().MulRaw(100) + targetBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) // Setup test parameters - maxMintUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxMintUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) totalMinted := sdkmath.ZeroInt() @@ -378,7 +386,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsRandomValueMultiDecimals() { // Continue mints as long as target balance is not reached for { // Check current minter balance - minterBal := s.GetAllBalances(minter).AmountOf(types.ExtendedCoinDenom()) + minterBal := s.GetAllBalances(minter).AmountOf(extendedDenom) if minterBal.GTE(targetBalance) { break } @@ -389,7 +397,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsRandomValueMultiDecimals() { randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, maxPossible.BigInt())).AddRaw(1) // 1. mint to evm module - mintCoins := cs(ci(types.ExtendedCoinDenom(), randAmount)) + mintCoins := cs(ci(extendedDenom, randAmount)) err := s.network.App.GetPreciseBankKeeper().MintCoins(s.network.GetContext(), minterModuleName, mintCoins) s.Require().NoError(err) @@ -404,7 +412,7 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsRandomValueMultiDecimals() { s.T().Logf("Completed %d random mints, total minted: %s", mintCount, totalMinted) // Check minter balance - minterBal := s.GetAllBalances(minter).AmountOf(types.ExtendedCoinDenom()) + minterBal := s.GetAllBalances(minter).AmountOf(extendedDenom) s.Equal(minterBal.BigInt().Cmp(targetBalance.BigInt()), 0, "minter balance mismatch (expected: %s, actual: %s)", targetBalance, minterBal) // Check remainder @@ -415,18 +423,15 @@ func (s *KeeperIntegrationTestSuite) TestMintCoinsRandomValueMultiDecimals() { } func FuzzMintCoins(f *testing.F) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID]) - err := configurator.Configure() - require.NoError(f, err) + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() f.Add(int64(0)) f.Add(int64(100)) - f.Add(types.ConversionFactor().Int64()) - f.Add(types.ConversionFactor().QuoRaw(2).Int64()) - f.Add(types.ConversionFactor().MulRaw(5).Int64()) - f.Add(types.ConversionFactor().MulRaw(2).AddRaw(123948723).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).QuoRaw(2).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).MulRaw(5).Int64()) + f.Add(types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(123948723).Int64()) f.Fuzz(func(t *testing.T, amount int64) { // No negative amounts @@ -449,14 +454,14 @@ func FuzzMintCoins(f *testing.F) { err := suite.network.App.GetPreciseBankKeeper().MintCoins( suite.network.GetContext(), evmtypes.ModuleName, - cs(c(types.ExtendedCoinDenom(), amount)), + cs(c(extendedDenom, amount)), ) suite.Require().NoError(err) } // Check full balances recipientAddr := suite.network.App.GetAccountKeeper().GetModuleAddress(evmtypes.ModuleName) - bal := suite.network.App.GetPreciseBankKeeper().GetBalance(suite.network.GetContext(), recipientAddr, types.ExtendedCoinDenom()) + bal := suite.network.App.GetPreciseBankKeeper().GetBalance(suite.network.GetContext(), recipientAddr, extendedDenom) suite.Require().Equalf( amount*mintCount, diff --git a/tests/integration/x/precisebank/test_send_integration.go b/tests/integration/x/precisebank/test_send_integration.go index d819bf650..63259f734 100644 --- a/tests/integration/x/precisebank/test_send_integration.go +++ b/tests/integration/x/precisebank/test_send_integration.go @@ -9,9 +9,8 @@ import ( "testing" corevm "github.com/ethereum/go-ethereum/core/vm" - "github.com/stretchr/testify/require" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" cosmosevmutils "github.com/cosmos/evm/utils" erc20types "github.com/cosmos/evm/x/erc20/types" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" @@ -35,6 +34,8 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModuleMatchingErr // No specific errors for SendCoinsFromAccountToModule, only 1 panic if // the module account does not exist + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + tests := []struct { name string sender sdk.AccAddress @@ -54,7 +55,7 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModuleMatchingErr "missing module account - extended", sdk.AccAddress([]byte{2}), "cat", - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), "module account cat does not exist: unknown address", }, } @@ -118,6 +119,9 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr s.Require().NotEmpty(blockedAddr, "no blocked addresses found") s.Require().NotEmpty(senderModuleName, "no sender module name found") + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + tests := []struct { name string senderModule string @@ -139,7 +143,7 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr "missing module account - extended", "cat", sdk.AccAddress([]byte{2}), - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), "", "module account cat does not exist: unknown address", }, @@ -155,7 +159,7 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr "blocked recipient address - extended", senderModuleName, blockedAddr, - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), fmt.Sprintf("%s is not allowed to receive funds: unauthorized", blockedAddr.String()), "", }, @@ -164,17 +168,17 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr "invalid coins", senderModuleName, sdk.AccAddress([]byte{2}), - sdk.Coins{sdk.Coin{Denom: types.IntegerCoinDenom(), Amount: sdkmath.NewInt(-1)}}, - fmt.Sprintf("-1%s: invalid coins", types.IntegerCoinDenom()), + sdk.Coins{sdk.Coin{Denom: integerDenom, Amount: sdkmath.NewInt(-1)}}, + fmt.Sprintf("-1%s: invalid coins", integerDenom), "", }, { "insufficient balance - passthrough", senderModuleName, sdk.AccAddress([]byte{2}), - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", - types.IntegerCoinDenom(), types.IntegerCoinDenom()), + integerDenom, integerDenom), "", }, { @@ -183,9 +187,9 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr sdk.AccAddress([]byte{2}), // We can still test insufficient bal errors with "aatom" since // we also expect it to not exist in x/bank - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", - types.ExtendedCoinDenom(), types.ExtendedCoinDenom()), + extendedDenom, extendedDenom), "", }, } @@ -232,8 +236,10 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccountMatchingErr } func (s *KeeperIntegrationTestSuite) TestSendCoinsMatchingErrors() { - // Ensure errors match x/bank errors + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + // Ensure errors match x/bank errors tests := []struct { name string initialAmount sdk.Coins @@ -243,32 +249,32 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsMatchingErrors() { { "invalid coins", cs(), - sdk.Coins{sdk.Coin{Denom: types.IntegerCoinDenom(), Amount: sdkmath.NewInt(-1)}}, + sdk.Coins{sdk.Coin{Denom: integerDenom, Amount: sdkmath.NewInt(-1)}}, fmt.Sprintf("-1%s: invalid coins", - types.IntegerCoinDenom()), + integerDenom), }, { "insufficient empty balance - passthrough", cs(), - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", - types.IntegerCoinDenom(), types.IntegerCoinDenom()), + integerDenom, integerDenom), }, { "insufficient empty balance - extended", cs(), // We can still test insufficient bal errors with "aatom" since // we also expect it to not exist in x/bank - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), fmt.Sprintf("spendable balance 0%s is smaller than 1000%s: insufficient funds", - types.ExtendedCoinDenom(), types.ExtendedCoinDenom()), + extendedDenom, extendedDenom), }, { "insufficient non-empty balance - passthrough", - cs(c(types.IntegerCoinDenom(), 100), c("usdc", 1000)), - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 100), c("usdc", 1000)), + cs(c(integerDenom, 1000)), fmt.Sprintf("spendable balance 100%s is smaller than 1000%s: insufficient funds", - types.IntegerCoinDenom(), types.IntegerCoinDenom()), + integerDenom, integerDenom), }, // non-empty aatom transfer error is tested in SendCoins, not here since // x/bank doesn't hold aatom @@ -306,6 +312,10 @@ func (s *KeeperIntegrationTestSuite) TestSendCoins() { // mocked BankKeeper overcomplicates expected keepers and makes initializing // balances very complex. + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string giveStartBalSender sdk.Coins @@ -315,11 +325,11 @@ func (s *KeeperIntegrationTestSuite) TestSendCoins() { }{ { "insufficient balance error denom matches", - cs(c(types.ExtendedCoinDenom(), 10), c("usdc", 1000)), + cs(c(extendedDenom, 10), c("usdc", 1000)), cs(), - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), fmt.Sprintf("spendable balance 10%s is smaller than 1000%s: insufficient funds", - types.ExtendedCoinDenom(), types.ExtendedCoinDenom()), + extendedDenom, extendedDenom), }, { "passthrough - unrelated", @@ -330,59 +340,59 @@ func (s *KeeperIntegrationTestSuite) TestSendCoins() { }, { "passthrough - integer denom", - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), cs(), - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", }, { "passthrough & extended", - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), cs(), - cs(c(types.IntegerCoinDenom(), 10), c(types.ExtendedCoinDenom(), 1)), + cs(c(integerDenom, 10), c(extendedDenom, 1)), "", }, { "aatom send - 1aatom to 0 balance", // Starting balances - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5))), cs(), // Send amount - cs(c(types.ExtendedCoinDenom(), 1)), // aatom + cs(c(extendedDenom, 1)), // aatom "", }, { "sender borrow from integer", // 1uatom, 0 fractional - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), cs(), // Send 1 with 0 fractional balance - cs(c(types.ExtendedCoinDenom(), 1)), + cs(c(extendedDenom, 1)), "", }, { "sender borrow from integer - max fractional amount", // 1uatom, 0 fractional - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor())), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals))), cs(), // Max fractional amount - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), "", }, { "receiver carry", - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), // max fractional amount, carries over to integer - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), - cs(c(types.ExtendedCoinDenom(), 1)), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), + cs(c(extendedDenom, 1)), "", }, { "receiver carry - max fractional amount", - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(5))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(5))), // max fractional amount, carries over to integer - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), "", }, } @@ -424,14 +434,14 @@ func (s *KeeperIntegrationTestSuite) TestSendCoins() { // includes uatom, convert it so that its the equivalent aatom // amount so its easier to compare. Compare extended coins only. sendAmountFullExtended := tt.giveAmt - sendAmountInteger := tt.giveAmt.AmountOf(types.IntegerCoinDenom()) + sendAmountInteger := tt.giveAmt.AmountOf(integerDenom) if !sendAmountInteger.IsZero() { - integerCoin := sdk.NewCoin(types.IntegerCoinDenom(), sendAmountInteger) + integerCoin := sdk.NewCoin(integerDenom, sendAmountInteger) sendAmountFullExtended = sendAmountFullExtended.Sub(integerCoin) // Add equivalent extended coin - extendedCoinAmount := sendAmountInteger.Mul(types.ConversionFactor()) - extendedCoin := sdk.NewCoin(types.ExtendedCoinDenom(), extendedCoinAmount) + extendedCoinAmount := sendAmountInteger.Mul(types.ConversionFactor(extendedDecimals)) + extendedCoin := sdk.NewCoin(extendedDenom, extendedCoinAmount) sendAmountFullExtended = sendAmountFullExtended.Add(extendedCoin) } @@ -476,6 +486,10 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsMatrix() { // mocked BankKeeper overcomplicates expected keepers and makes initializing // balances very complex. + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + type startBalance struct { name string bal sdk.Coins @@ -485,11 +499,11 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsMatrix() { // Test matrix fields: startBalances := []startBalance{ {"empty", cs()}, - {"integer only", cs(c(types.IntegerCoinDenom(), 1000))}, - {"extended only", cs(c(types.ExtendedCoinDenom(), 1000))}, - {"integer & extended", cs(c(types.IntegerCoinDenom(), 1000), c(types.ExtendedCoinDenom(), 1000))}, - {"integer & extended - max fractional", cs(c(types.IntegerCoinDenom(), 1000), ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1)))}, - {"integer & extended - min fractional", cs(c(types.IntegerCoinDenom(), 1000), c(types.ExtendedCoinDenom(), 1))}, + {"integer only", cs(c(integerDenom, 1000))}, + {"extended only", cs(c(extendedDenom, 1000))}, + {"integer & extended", cs(c(integerDenom, 1000), c(extendedDenom, 1000))}, + {"integer & extended - max fractional", cs(c(integerDenom, 1000), ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1)))}, + {"integer & extended - min fractional", cs(c(integerDenom, 1000), c(extendedDenom, 1))}, } sendAmts := []struct { @@ -502,23 +516,23 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsMatrix() { }, { "integer only", - cs(c(types.IntegerCoinDenom(), 10)), + cs(c(integerDenom, 10)), }, { "extended only", - cs(c(types.ExtendedCoinDenom(), 10)), + cs(c(extendedDenom, 10)), }, { "integer & extended", - cs(c(types.IntegerCoinDenom(), 10), c(types.ExtendedCoinDenom(), 1000)), + cs(c(integerDenom, 10), c(extendedDenom, 1000)), }, { "integer & extended - max fractional", - cs(c(types.IntegerCoinDenom(), 10), ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), + cs(c(integerDenom, 10), ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), }, { "integer & extended - min fractional", - cs(c(types.IntegerCoinDenom(), 10), c(types.ExtendedCoinDenom(), 1)), + cs(c(integerDenom, 10), c(extendedDenom, 1)), }, } @@ -593,7 +607,8 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModule() { recipientModule := minttypes.ModuleName recipientAddr := s.network.App.GetAccountKeeper().GetModuleAddress(recipientModule) - sendAmt := cs(c(types.ExtendedCoinDenom(), 1000)) + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + sendAmt := cs(c(extendedDenom, 1000)) s.MintToAccount(sender, sendAmt) @@ -623,11 +638,13 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModule() { func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModuleBlockedRecipientCarry() { // Carrying to module account balance. This tests that SendCoinsFromAccountToModule // does not fail when sending to a blocked module account. + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals sender := sdk.AccAddress([]byte{1}) - sendAmt := cs(c(types.ExtendedCoinDenom(), 1000)) - sendAmt2 := cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(10))) + sendAmt := cs(c(extendedDenom, 1000)) + sendAmt2 := cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(10))) s.MintToAccount(sender, sendAmt.Add(sendAmt2...)) @@ -652,10 +669,14 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromAccountToModuleBlockedReci func (s *KeeperIntegrationTestSuite) TestSendCoinsBlockedRecipientCarry() { // Same test as TestSendCoinsFromModuleToAccount_Blocked, but with SendCoins // which also should not fail when sending to a blocked module account. + + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + sender := sdk.AccAddress([]byte{1}) - sendAmt := cs(c(types.ExtendedCoinDenom(), 1000)) - sendAmt2 := cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(10))) + sendAmt := cs(c(extendedDenom, 1000)) + sendAmt2 := cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(10))) s.MintToAccount(sender, sendAmt.Add(sendAmt2...)) @@ -684,12 +705,14 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccount() { // of SendCoinsFromAccountToModule, so we are only checking the correct // addresses are being used. + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + senderModule := evmtypes.ModuleName senderAddr := s.network.App.GetAccountKeeper().GetModuleAddress(senderModule) recipient := sdk.AccAddress([]byte{1}) - sendAmt := cs(c(types.ExtendedCoinDenom(), 1000)) + sendAmt := cs(c(extendedDenom, 1000)) s.MintToModuleAccount(senderModule, sendAmt) @@ -717,37 +740,40 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsFromModuleToAccount() { } func (s *KeeperIntegrationTestSuite) TestSendCoinsRandomValueMultiDecimals() { + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) sender := sdk.AccAddress([]byte{1}) recipient := sdk.AccAddress([]byte{2}) // Initial balance large enough to cover many small sends - initialBalance := types.ConversionFactor().MulRaw(100) - s.MintToAccount(sender, cs(ci(types.ExtendedCoinDenom(), initialBalance))) + initialBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) + s.MintToAccount(sender, cs(ci(extendedDenom, initialBalance))) // Setup test parameters - maxSendUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxSendUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) totalSent := sdkmath.ZeroInt() @@ -756,7 +782,7 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsRandomValueMultiDecimals() { // Continue transfers as long as sender has balance remaining for { // Check current sender balance - senderAmount := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderAmount := s.GetAllBalances(sender).AmountOf(extendedDenom) if senderAmount.IsZero() { break } @@ -768,7 +794,7 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsRandomValueMultiDecimals() { } randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, maxPossibleSend.BigInt())).AddRaw(1) - sendAmount := cs(ci(types.ExtendedCoinDenom(), randAmount)) + sendAmount := cs(ci(extendedDenom, randAmount)) err := s.network.App.GetPreciseBankKeeper().SendCoins(s.network.GetContext(), sender, recipient, sendAmount) s.NoError(err) totalSent = totalSent.Add(randAmount) @@ -778,16 +804,16 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsRandomValueMultiDecimals() { s.T().Logf("Completed %d random sends, total sent: %s", sentCount, totalSent.String()) // Check sender balance - senderAmount := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderAmount := s.GetAllBalances(sender).AmountOf(extendedDenom) s.Equal(senderAmount.BigInt().Cmp(big.NewInt(0)), 0, "sender balance should be zero") // Check recipient balance recipientBal := s.GetAllBalances(recipient) - intReceived := recipientBal.AmountOf(types.ExtendedCoinDenom()).Quo(types.ConversionFactor()) + intReceived := recipientBal.AmountOf(extendedDenom).Quo(types.ConversionFactor(extendedDecimals)) fracReceived := s.network.App.GetPreciseBankKeeper().GetFractionalBalance(s.network.GetContext(), recipient) - expectedInt := totalSent.Quo(types.ConversionFactor()) - expectedFrac := totalSent.Mod(types.ConversionFactor()) + expectedInt := totalSent.Quo(types.ConversionFactor(extendedDecimals)) + expectedFrac := totalSent.Mod(types.ConversionFactor(extendedDecimals)) s.Equal(expectedInt.BigInt().Cmp(intReceived.BigInt()), 0, "integer carry mismatch (expected: %s, received: %s)", expectedInt, intReceived) s.Equal(expectedFrac.BigInt().Cmp(fracReceived.BigInt()), 0, "fractional balance mismatch (expected: %s, received: %s)", expectedFrac, fracReceived) @@ -796,19 +822,16 @@ func (s *KeeperIntegrationTestSuite) TestSendCoinsRandomValueMultiDecimals() { } func FuzzSendCoins(f *testing.F) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID]) - err := configurator.Configure() - require.NoError(f, err) + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals f.Add(uint64(100), uint64(0), uint64(2)) f.Add(uint64(100), uint64(100), uint64(5)) - f.Add(types.ConversionFactor().Uint64(), uint64(0), uint64(500)) + f.Add(types.ConversionFactor(extendedDecimals).Uint64(), uint64(0), uint64(500)) f.Add( - types.ConversionFactor().MulRaw(2).AddRaw(123948723).Uint64(), - types.ConversionFactor().MulRaw(2).Uint64(), - types.ConversionFactor().Uint64(), + types.ConversionFactor(extendedDecimals).MulRaw(2).AddRaw(123948723).Uint64(), + types.ConversionFactor(extendedDecimals).MulRaw(2).Uint64(), + types.ConversionFactor(extendedDecimals).Uint64(), ) f.Fuzz(func( @@ -827,11 +850,11 @@ func FuzzSendCoins(f *testing.F) { recipient := sdk.AccAddress([]byte{2}) // Initial balances - suite.MintToAccount(sender, cs(c(types.ExtendedCoinDenom(), int64(startBalSender)))) //nolint:gosec // G115 - suite.MintToAccount(recipient, cs(c(types.ExtendedCoinDenom(), int64(startBalReceiver)))) //nolint:gosec // G115 + suite.MintToAccount(sender, cs(c(extendedDenom, int64(startBalSender)))) //nolint:gosec // G115 + suite.MintToAccount(recipient, cs(c(extendedDenom, int64(startBalReceiver)))) //nolint:gosec // G115 // Send amount - sendCoins := cs(c(types.ExtendedCoinDenom(), int64(sendAmount))) //nolint:gosec // G115 + sendCoins := cs(c(extendedDenom, int64(sendAmount))) //nolint:gosec // G115 err := suite.network.App.GetPreciseBankKeeper().SendCoins(suite.network.GetContext(), sender, recipient, sendCoins) if startBalSender < sendAmount { suite.Require().Error(err, "expected insufficient funds error") @@ -846,47 +869,50 @@ func FuzzSendCoins(f *testing.F) { suite.Require().Equal( startBalSender-sendAmount, - balSender.AmountOf(types.ExtendedCoinDenom()).Uint64(), + balSender.AmountOf(extendedDenom).Uint64(), ) suite.Require().Equal( startBalReceiver+sendAmount, - balReceiver.AmountOf(types.ExtendedCoinDenom()).Uint64(), + balReceiver.AmountOf(extendedDenom).Uint64(), ) }) } func (s *KeeperIntegrationTestSuite) TestSendMsg_RandomValueMultiDecimals() { //nolint:revive // false positive due to file name + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { - name string - chainID testconstants.ChainID + name string + chainConfig testconfig.ChainConfig }{ { - name: "6 decimals", - chainID: testconstants.SixDecimalsChainID, + name: "6 decimals", + chainConfig: testconfig.SixDecimalsChainConfig, }, { - name: "12 decimals", - chainID: testconstants.TwelveDecimalsChainID, + name: "12 decimals", + chainConfig: testconfig.TwelveDecimalsChainConfig, }, { - name: "2 decimals", - chainID: testconstants.TwoDecimalsChainID, + name: "2 decimals", + chainConfig: testconfig.TwoDecimalsChainConfig, }, } for _, tt := range tests { s.Run(tt.name, func() { - s.SetupTestWithChainID(tt.chainID) + s.SetupTestWithChainConfig(tt.chainConfig) sender := sdk.AccAddress([]byte{1}) recipient := sdk.AccAddress([]byte{2}) // Initial balance large enough to cover many small sends - initialBalance := types.ConversionFactor().MulRaw(100) - s.MintToAccount(sender, cs(ci(types.ExtendedCoinDenom(), initialBalance))) + initialBalance := types.ConversionFactor(extendedDecimals).MulRaw(100) + s.MintToAccount(sender, cs(ci(extendedDenom, initialBalance))) // Setup test parameters - maxSendUnit := types.ConversionFactor().MulRaw(2).SubRaw(1) + maxSendUnit := types.ConversionFactor(extendedDecimals).MulRaw(2).SubRaw(1) r := rand.New(rand.NewSource(SEED)) totalSent := sdkmath.ZeroInt() @@ -895,7 +921,7 @@ func (s *KeeperIntegrationTestSuite) TestSendMsg_RandomValueMultiDecimals() { // // Continue transfers as long as sender has balance remaining for { // Check current sender balance - senderAmount := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderAmount := s.GetAllBalances(sender).AmountOf(extendedDenom) if senderAmount.IsZero() { break } @@ -907,7 +933,7 @@ func (s *KeeperIntegrationTestSuite) TestSendMsg_RandomValueMultiDecimals() { // } randAmount := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, maxPossibleSend.BigInt())).AddRaw(1) - sendAmount := cs(ci(types.ExtendedCoinDenom(), randAmount)) + sendAmount := cs(ci(extendedDenom, randAmount)) msgSend := banktypes.MsgSend{ FromAddress: sender.String(), ToAddress: recipient.String(), @@ -922,16 +948,16 @@ func (s *KeeperIntegrationTestSuite) TestSendMsg_RandomValueMultiDecimals() { // s.T().Logf("Completed %d random sends, total sent: %s", sentCount, totalSent.String()) // Check sender balance - senderAmount := s.GetAllBalances(sender).AmountOf(types.ExtendedCoinDenom()) + senderAmount := s.GetAllBalances(sender).AmountOf(extendedDenom) s.Equal(senderAmount.BigInt().Cmp(big.NewInt(0)), 0, "sender balance should be zero") // Check recipient balance recipientBal := s.GetAllBalances(recipient) - intReceived := recipientBal.AmountOf(types.ExtendedCoinDenom()).Quo(types.ConversionFactor()) + intReceived := recipientBal.AmountOf(extendedDenom).Quo(types.ConversionFactor(extendedDecimals)) fracReceived := s.network.App.GetPreciseBankKeeper().GetFractionalBalance(s.network.GetContext(), recipient) - expectedInt := totalSent.Quo(types.ConversionFactor()) - expectedFrac := totalSent.Mod(types.ConversionFactor()) + expectedInt := totalSent.Quo(types.ConversionFactor(extendedDecimals)) + expectedFrac := totalSent.Mod(types.ConversionFactor(extendedDecimals)) s.Equal(expectedInt.BigInt().Cmp(intReceived.BigInt()), 0, "integer carry mismatch (expected: %s, received: %s)", expectedInt, intReceived) s.Equal(expectedFrac.BigInt().Cmp(fracReceived.BigInt()), 0, "fractional balance mismatch (expected: %s, received: %s)", expectedFrac, fracReceived) diff --git a/tests/integration/x/precisebank/test_setup.go b/tests/integration/x/precisebank/test_setup.go index bab55b5f2..23458040f 100644 --- a/tests/integration/x/precisebank/test_setup.go +++ b/tests/integration/x/precisebank/test_setup.go @@ -3,7 +3,7 @@ package precisebank import ( "github.com/stretchr/testify/suite" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -34,14 +34,14 @@ func NewKeeperIntegrationTestSuite(create network.CreateEvmApp, options ...netwo } func (s *KeeperIntegrationTestSuite) SetupTest() { - s.SetupTestWithChainID(testconstants.SixDecimalsChainID) + s.SetupTestWithChainConfig(testconfig.SixDecimalsChainConfig) } -func (s *KeeperIntegrationTestSuite) SetupTestWithChainID(chainID testconstants.ChainID) { +func (s *KeeperIntegrationTestSuite) SetupTestWithChainConfig(chainConfig testconfig.ChainConfig) { s.keyring = keyring.New(2) options := []network.ConfigOption{ - network.WithChainID(chainID), + network.WithChainConfig(chainConfig), network.WithPreFundedAccounts(s.keyring.GetAllAccAddrs()...), } options = append(options, s.options...) diff --git a/tests/integration/x/precisebank/test_utils.go b/tests/integration/x/precisebank/test_utils.go index 2ac668c87..85e52748c 100644 --- a/tests/integration/x/precisebank/test_utils.go +++ b/tests/integration/x/precisebank/test_utils.go @@ -61,7 +61,7 @@ func (s *KeeperIntegrationTestSuite) GetAllBalances(addr sdk.AccAddress) sdk.Coi // Remove integer coins from the balance for _, coin := range bankBalances { - if coin.Denom == types.IntegerCoinDenom() { + if coin.Denom == s.network.GetEVMDenom() { bankBalances = bankBalances.Sub(coin) } } diff --git a/tests/integration/x/precisebank/test_view_integration.go b/tests/integration/x/precisebank/test_view_integration.go index 48c877ef2..f4ec6ea5e 100644 --- a/tests/integration/x/precisebank/test_view_integration.go +++ b/tests/integration/x/precisebank/test_view_integration.go @@ -1,6 +1,7 @@ package precisebank import ( + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -11,6 +12,10 @@ import ( ) func (s *KeeperIntegrationTestSuite) TestKeeperSpendableCoin() { + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string giveDenom string // queried denom for balance @@ -23,46 +28,46 @@ func (s *KeeperIntegrationTestSuite) TestKeeperSpendableCoin() { }{ { "extended denom, no fractional - locked coins", - types.ExtendedCoinDenom(), + extendedDenom, // queried bank balance in uatom when querying for aatom - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(10))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(10))), // (integer + fractional) - locked sdk.NewCoin( - types.ExtendedCoinDenom(), - types.ConversionFactor().MulRaw(1000-10), + extendedDenom, + types.ConversionFactor(extendedDecimals).MulRaw(1000-10), ), }, { "extended denom, with fractional - locked coins", - types.ExtendedCoinDenom(), + extendedDenom, // queried bank balance in uatom when querying for aatom - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.NewInt(5000), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(10))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(10))), sdk.NewCoin( - types.ExtendedCoinDenom(), + extendedDenom, // (integer - locked) + fractional - types.ConversionFactor().MulRaw(1000-10).AddRaw(5000), + types.ConversionFactor(extendedDecimals).MulRaw(1000-10).AddRaw(5000), ), }, { "non-extended denom - uatom returns uatom", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(10))), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(990)), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(10))), + sdk.NewCoin(integerDenom, sdkmath.NewInt(990)), }, { "non-extended denom, with fractional - uatom returns uatom", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), // does not affect balance sdkmath.NewInt(100), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(10))), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(990)), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(10))), + sdk.NewCoin(integerDenom, sdkmath.NewInt(990)), }, } @@ -120,13 +125,17 @@ func (s *KeeperIntegrationTestSuite) TestKeeperHiddenReserve() { // Reserve balances should not be shown to consumers of x/precisebank, as it // represents the fractional balances of accounts. + integerDenom := s.network.GetEVMDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + moduleAddr := authtypes.NewModuleAddress(types.ModuleName) addr1 := sdk.AccAddress{1} // Make the reserve hold a non-zero balance // Mint fractional coins to an account, which should cause a mint of 1 // integer coin to the reserve to back it. - extCoin := sdk.NewCoin(types.ExtendedCoinDenom(), types.ConversionFactor().AddRaw(1000)) + extCoin := sdk.NewCoin(extendedDenom, types.ConversionFactor(extendedDecimals).AddRaw(1000)) unrelatedCoin := sdk.NewCoin("unrelated", sdkmath.NewInt(1000)) s.MintToAccount( addr1, @@ -137,7 +146,7 @@ func (s *KeeperIntegrationTestSuite) TestKeeperHiddenReserve() { ) // Check underlying x/bank balance for reserve - reserveIntCoin := s.network.App.GetBankKeeper().GetBalance(s.network.GetContext(), moduleAddr, types.IntegerCoinDenom()) + reserveIntCoin := s.network.App.GetBankKeeper().GetBalance(s.network.GetContext(), moduleAddr, integerDenom) s.Require().Equal( sdkmath.NewInt(2), // Network setup creates 1, test mints 1 more = 2 total reserveIntCoin.Amount, @@ -153,26 +162,26 @@ func (s *KeeperIntegrationTestSuite) TestKeeperHiddenReserve() { { "reserve account - hidden extended denom", moduleAddr, - types.ExtendedCoinDenom(), + extendedDenom, sdkmath.ZeroInt(), }, { "reserve account - visible integer denom", moduleAddr, - types.IntegerCoinDenom(), + integerDenom, sdkmath.NewInt(2), // Network setup creates 1, test mints 1 more = 2 total }, { "user account - visible extended denom", addr1, - types.ExtendedCoinDenom(), + extendedDenom, extCoin.Amount, }, { "user account - visible integer denom", addr1, - types.IntegerCoinDenom(), - extCoin.Amount.Quo(types.ConversionFactor()), + integerDenom, + extCoin.Amount.Quo(types.ConversionFactor(extendedDecimals)), }, } diff --git a/tests/integration/x/vm/keeper_test_suite.go b/tests/integration/x/vm/keeper_test_suite.go index 8f3f3b39a..e865e3c06 100644 --- a/tests/integration/x/vm/keeper_test_suite.go +++ b/tests/integration/x/vm/keeper_test_suite.go @@ -59,7 +59,8 @@ func (s *KeeperTestSuite) SetupTest() { if s.MintFeeCollector { // mint some coin to fee collector - coins := sdk.NewCoins(sdk.NewCoin(evmtypes.GetEVMCoinDenom(), sdkmath.NewInt(int64(params.TxGas)-1))) + integerDenom := s.Network.GetEVMDenom() + coins := sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(int64(params.TxGas)-1))) balances := []banktypes.Balance{ { Address: authtypes.NewModuleAddress(authtypes.FeeCollectorName).String(), @@ -88,7 +89,10 @@ func (s *KeeperTestSuite) SetupTest() { s.Handler = gh s.Keyring = keys - chainConfig := evmtypes.DefaultChainConfig(s.Network.GetEIP155ChainID().Uint64()) + // get the denom and decimals set on chain initialization + // because we'll need to set them again when resetting the chain config + coinInfo := s.Network.App.GetEVMKeeper().GetEvmConfig().CoinInfo + chainConfig := evmtypes.DefaultChainConfig(s.Network.GetEIP155ChainID().Uint64(), *coinInfo) if !s.EnableLondonHF { maxInt := sdkmath.NewInt(math.MaxInt64) chainConfig.LondonBlock = &maxInt @@ -99,23 +103,6 @@ func (s *KeeperTestSuite) SetupTest() { chainConfig.CancunTime = &maxInt chainConfig.PragueTime = &maxInt } - // get the denom and decimals set on chain initialization - // because we'll need to set them again when resetting the chain config - denom := evmtypes.GetEVMCoinDenom() - extendedDenom := evmtypes.GetEVMCoinExtendedDenom() - displayDenom := evmtypes.GetEVMCoinDisplayDenom() - decimals := evmtypes.GetEVMCoinDecimals() - - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator. - WithChainConfig(chainConfig). - WithEVMCoinInfo(evmtypes.EvmCoinInfo{ - Denom: denom, - ExtendedDenom: extendedDenom, - DisplayDenom: displayDenom, - Decimals: decimals, - }). - Configure() - s.Require().NoError(err) + evmConfig := evmtypes.NewEvmConfig().WithChainConfig(chainConfig).WithEVMCoinInfo(coinInfo) + s.Network.App.GetEVMKeeper().SetEvmConfig(evmConfig) } diff --git a/tests/integration/x/vm/test_benchmark.go b/tests/integration/x/vm/test_benchmark.go index 77847f070..20474be71 100644 --- a/tests/integration/x/vm/test_benchmark.go +++ b/tests/integration/x/vm/test_benchmark.go @@ -8,10 +8,11 @@ import ( ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/require" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/vm/keeper/testdata" "github.com/cosmos/evm/x/vm/types" + evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -24,7 +25,8 @@ func SetupContract(b *testing.B) (*KeeperTestSuite, common.Address) { suite := KeeperTestSuite{} suite.SetupTest() - amt := sdk.Coins{sdk.NewInt64Coin(testconstants.ExampleAttoDenom, 1000000000000000000)} + denom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + amt := sdk.Coins{sdk.NewInt64Coin(denom, 1000000000000000000)} err := suite.Network.App.GetBankKeeper().MintCoins(suite.Network.GetContext(), types.ModuleName, amt) require.NoError(b, err) err = suite.Network.App.GetBankKeeper().SendCoinsFromModuleToAccount(suite.Network.GetContext(), types.ModuleName, suite.Keyring.GetAddr(0).Bytes(), amt) @@ -42,7 +44,8 @@ func SetupTestMessageCall(b *testing.B) (*KeeperTestSuite, common.Address) { suite := KeeperTestSuite{} suite.SetupTest() - amt := sdk.Coins{sdk.NewInt64Coin(testconstants.ExampleAttoDenom, 1000000000000000000)} + denom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + amt := sdk.Coins{sdk.NewInt64Coin(denom, 1000000000000000000)} err := suite.Network.App.GetBankKeeper().MintCoins(suite.Network.GetContext(), types.ModuleName, amt) require.NoError(b, err) err = suite.Network.App.GetBankKeeper().SendCoinsFromModuleToAccount(suite.Network.GetContext(), types.ModuleName, suite.Keyring.GetAddr(0).Bytes(), amt) @@ -64,7 +67,8 @@ func DoBenchmark(b *testing.B, txBuilder TxBuilder) { krSigner := utiltx.NewSigner(suite.Keyring.GetPrivKey(0)) msg := txBuilder(suite, contractAddr) msg.From = suite.Keyring.GetAddr(0).Bytes() - err := msg.Sign(ethtypes.LatestSignerForChainID(types.GetEthChainConfig().ChainID), krSigner) + chainID := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID + err := msg.Sign(ethtypes.LatestSignerForChainID(chainID), krSigner) require.NoError(b, err) b.ResetTimer() @@ -72,7 +76,8 @@ func DoBenchmark(b *testing.B, txBuilder TxBuilder) { for i := 0; i < b.N; i++ { ctx, _ := suite.Network.GetContext().CacheContext() - fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdkmath.NewIntFromBigInt(msg.GetFee()))} + denom := suite.Network.App.GetEVMKeeper().GetEvmConfig().CoinInfo.GetDenom() + fees := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(msg.GetFee()))} err = authante.DeductFees(suite.Network.App.GetBankKeeper(), suite.Network.GetContext(), suite.Network.App.GetAccountKeeper().GetAccount(ctx, msg.GetFrom()), fees) require.NoError(b, err) @@ -90,8 +95,9 @@ func BenchmarkTokenTransfer(b *testing.B) { input, err := erc20Contract.ABI.Pack("transfer", common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), big.NewInt(1000)) require.NoError(b, err) nonce := suite.Network.App.GetEVMKeeper().GetNonce(suite.Network.GetContext(), suite.Keyring.GetAddr(0)) + chainID := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID ethTxParams := &types.EvmTxArgs{ - ChainID: types.GetEthChainConfig().ChainID, + ChainID: chainID, Nonce: nonce, To: &contract, Amount: big.NewInt(0), @@ -111,8 +117,9 @@ func BenchmarkEmitLogs(b *testing.B) { input, err := erc20Contract.ABI.Pack("benchmarkLogs", big.NewInt(1000)) require.NoError(b, err) nonce := suite.Network.App.GetEVMKeeper().GetNonce(suite.Network.GetContext(), suite.Keyring.GetAddr(0)) + chainID := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID ethTxParams := &types.EvmTxArgs{ - ChainID: types.GetEthChainConfig().ChainID, + ChainID: chainID, Nonce: nonce, To: &contract, Amount: big.NewInt(0), @@ -132,8 +139,9 @@ func BenchmarkTokenTransferFrom(b *testing.B) { input, err := erc20Contract.ABI.Pack("transferFrom", suite.Keyring.GetAddr(0), common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), big.NewInt(0)) require.NoError(b, err) nonce := suite.Network.App.GetEVMKeeper().GetNonce(suite.Network.GetContext(), suite.Keyring.GetAddr(0)) + chainID := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID ethTxParams := &types.EvmTxArgs{ - ChainID: types.GetEthChainConfig().ChainID, + ChainID: chainID, Nonce: nonce, To: &contract, Amount: big.NewInt(0), @@ -153,8 +161,9 @@ func BenchmarkTokenMint(b *testing.B) { input, err := erc20Contract.ABI.Pack("mint", common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), big.NewInt(1000)) require.NoError(b, err) nonce := suite.Network.App.GetEVMKeeper().GetNonce(suite.Network.GetContext(), suite.Keyring.GetAddr(0)) + chainID := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID ethTxParams := &types.EvmTxArgs{ - ChainID: types.GetEthChainConfig().ChainID, + ChainID: chainID, Nonce: nonce, To: &contract, Amount: big.NewInt(0), @@ -175,7 +184,7 @@ func BenchmarkMessageCall(b *testing.B) { input, err := messageCallContract.ABI.Pack("benchmarkMessageCall", big.NewInt(10000)) require.NoError(b, err) nonce := suite.Network.App.GetEVMKeeper().GetNonce(suite.Network.GetContext(), suite.Keyring.GetAddr(0)) - ethCfg := types.GetEthChainConfig() + ethCfg := suite.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig() ethTxParams := &types.EvmTxArgs{ ChainID: ethCfg.ChainID, Nonce: nonce, @@ -197,7 +206,8 @@ func BenchmarkMessageCall(b *testing.B) { for i := 0; i < b.N; i++ { ctx, _ := suite.Network.GetContext().CacheContext() - fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdkmath.NewIntFromBigInt(msg.GetFee()))} + denom := suite.Network.App.GetEVMKeeper().GetEvmConfig().CoinInfo.GetDenom() + fees := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(msg.GetFee()))} err = authante.DeductFees(suite.Network.App.GetBankKeeper(), suite.Network.GetContext(), suite.Network.App.GetAccountKeeper().GetAccount(ctx, msg.GetFrom()), fees) require.NoError(b, err) diff --git a/tests/integration/x/vm/test_call_evm.go b/tests/integration/x/vm/test_call_evm.go index 013b200f2..8b806ff84 100644 --- a/tests/integration/x/vm/test_call_evm.go +++ b/tests/integration/x/vm/test_call_evm.go @@ -6,14 +6,14 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/cosmos/evm/contracts" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/erc20/types" evmtypes "github.com/cosmos/evm/x/vm/types" ) func (s *KeeperTestSuite) TestCallEVM() { - wcosmosEVMContract := common.HexToAddress(testconstants.WEVMOSContractMainnet) + wcosmosEVMContract := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) testCases := []struct { name string method string @@ -47,7 +47,7 @@ func (s *KeeperTestSuite) TestCallEVM() { func (s *KeeperTestSuite) TestCallEVMWithData() { erc20 := contracts.ERC20MinterBurnerDecimalsContract.ABI - wcosmosEVMContract := common.HexToAddress(testconstants.WEVMOSContractMainnet) + wcosmosEVMContract := common.HexToAddress(testconfig.DefaultWevmosContractMainnet) testCases := []struct { name string from common.Address diff --git a/tests/integration/x/vm/test_grpc_query.go b/tests/integration/x/vm/test_grpc_query.go index f9b55fac3..1fe8e6213 100644 --- a/tests/integration/x/vm/test_grpc_query.go +++ b/tests/integration/x/vm/test_grpc_query.go @@ -17,7 +17,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/evm/server/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/network" "github.com/cosmos/evm/testutil/keyring" @@ -40,7 +40,8 @@ import ( const invalidAddress = "0x0000" func (s *KeeperTestSuite) TestQueryAccount() { - baseDenom := types.GetEVMCoinDenom() + baseDenom := s.Network.GetEVMDenom() + testCases := []struct { msg string getReq func() *types.QueryAccountRequest @@ -198,7 +199,7 @@ func (s *KeeperTestSuite) TestQueryCosmosAccount() { } func (s *KeeperTestSuite) TestQueryBalance() { - baseDenom := types.GetEVMCoinDenom() + baseDenom := s.Network.GetEVMDenom() testCases := []struct { msg string @@ -557,6 +558,8 @@ func (s *KeeperTestSuite) TestEstimateGas() { erc20Contract, err := testdata.LoadERC20Contract() s.Require().NoError(err) + baseDenom := s.Network.GetEVMDenom() + testCases := []struct { msg string getArgs func() types.TransactionArgs @@ -622,7 +625,7 @@ func (s *KeeperTestSuite) TestEstimateGas() { func() types.TransactionArgs { addr := s.Keyring.GetAddr(0) hexBigInt := hexutil.Big(*big.NewInt(1)) - balance := s.Network.App.GetBankKeeper().GetBalance(s.Network.GetContext(), sdk.AccAddress(addr.Bytes()), types.GetEVMCoinDenom()) + balance := s.Network.App.GetBankKeeper().GetBalance(s.Network.GetContext(), sdk.AccAddress(addr.Bytes()), baseDenom) value := balance.Amount.Add(sdkmath.NewInt(1)) return types.TransactionArgs{ To: &common.Address{}, @@ -641,7 +644,7 @@ func (s *KeeperTestSuite) TestEstimateGas() { func() types.TransactionArgs { addr := s.Keyring.GetAddr(0) hexBigInt := hexutil.Big(*big.NewInt(1)) - balance := s.Network.App.GetBankKeeper().GetBalance(s.Network.GetContext(), sdk.AccAddress(addr.Bytes()), types.GetEVMCoinDenom()) + balance := s.Network.App.GetBankKeeper().GetBalance(s.Network.GetContext(), sdk.AccAddress(addr.Bytes()), baseDenom) value := balance.Amount.Sub(sdkmath.NewInt(1)) return types.TransactionArgs{ To: &common.Address{}, @@ -1561,6 +1564,9 @@ func (s *KeeperTestSuite) TestQueryBaseFee() { defer func() { s.EnableFeemarket = false }() s.SetupTest() + // Save initial configure to restore it between tests + initialEvmConfig := *s.Network.App.GetEVMKeeper().GetEvmConfig() + testCases := []struct { name string getExpResp func() *types.QueryBaseFeeResponse @@ -1592,7 +1598,7 @@ func (s *KeeperTestSuite) TestQueryBaseFee() { feemarketDefault := feemarkettypes.DefaultParams() s.Require().NoError(s.Network.App.GetFeeMarketKeeper().SetParams(s.Network.GetContext(), feemarketDefault)) - chainConfig := types.DefaultChainConfig(s.Network.GetEIP155ChainID().Uint64()) + chainConfig := types.DefaultChainConfig(s.Network.GetEIP155ChainID().Uint64(), *testconfig.DefaultChainConfig.EvmConfig.CoinInfo) maxInt := sdkmath.NewInt(math.MaxInt64) chainConfig.LondonBlock = &maxInt chainConfig.ArrowGlacierBlock = &maxInt @@ -1602,13 +1608,9 @@ func (s *KeeperTestSuite) TestQueryBaseFee() { chainConfig.CancunTime = &maxInt chainConfig.PragueTime = &maxInt - configurator := types.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator. - WithChainConfig(chainConfig). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - Configure() - s.Require().NoError(err) + evmConfig := *s.Network.App.GetEVMKeeper().GetEvmConfig() + evmConfig.ChainConfig = chainConfig + s.Network.App.GetEVMKeeper().SetEvmConfig(&evmConfig) }, true, }, @@ -1630,21 +1632,13 @@ func (s *KeeperTestSuite) TestQueryBaseFee() { }, } - // Save initial configure to restore it between tests - coinInfo := types.EvmCoinInfo{ - Denom: types.GetEVMCoinDenom(), - ExtendedDenom: types.GetEVMCoinExtendedDenom(), - DisplayDenom: types.GetEVMCoinDisplayDenom(), - Decimals: types.GetEVMCoinDecimals(), - } - chainConfig := types.DefaultChainConfig(s.Network.GetEIP155ChainID().Uint64()) - for _, tc := range testCases { s.Run(tc.name, func() { // Set necessary params tc.setParams() // Get the expected response expResp := tc.getExpResp() + // Function under test res, err := s.Network.GetEvmClient().BaseFee( s.Network.GetContext(), @@ -1658,13 +1652,9 @@ func (s *KeeperTestSuite) TestQueryBaseFee() { s.Require().Error(err) } s.Require().NoError(s.Network.NextBlock()) - configurator := types.NewEVMConfigurator() - configurator.ResetTestConfig() - err = configurator. - WithChainConfig(chainConfig). - WithEVMCoinInfo(coinInfo). - Configure() - s.Require().NoError(err) + + // Reset evm config + s.Network.App.GetEVMKeeper().SetEvmConfig(&initialEvmConfig) }) } } @@ -1779,6 +1769,8 @@ func (s *KeeperTestSuite) TestEthCall() { } func (s *KeeperTestSuite) TestBalance() { + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + testCases := []struct { name string returnedBal func() *uint256.Int @@ -1800,7 +1792,7 @@ func (s *KeeperTestSuite) TestBalance() { balance, ok := sdkmath.NewIntFromString(balanceResp.Balance) s.Require().True(ok) - balance = balance.Quo(types2.ConversionFactor()) + balance = balance.Quo(types2.ConversionFactor(extendedDecimals)) s.Require().NotEqual(balance.String(), "0") // replace with vesting account @@ -1847,7 +1839,7 @@ func (s *KeeperTestSuite) TestBalance() { balance, ok := sdkmath.NewIntFromString(balanceResp.Balance) s.Require().True(ok) - balance = balance.Quo(types2.ConversionFactor()) + balance = balance.Quo(types2.ConversionFactor(extendedDecimals)) s.Require().NotEqual(balance.String(), "0") // replace with vesting account diff --git a/tests/integration/x/vm/test_iterate_contracts.go b/tests/integration/x/vm/test_iterate_contracts.go index 3c6cd5497..fb9137977 100644 --- a/tests/integration/x/vm/test_iterate_contracts.go +++ b/tests/integration/x/vm/test_iterate_contracts.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/cosmos/evm/contracts" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/factory" "github.com/cosmos/evm/testutil/integration/evm/grpc" "github.com/cosmos/evm/testutil/integration/evm/network" @@ -57,7 +57,7 @@ func TestIterateContracts(t *testing.T, create network.CreateEvmApp, options ... network.App.GetEVMKeeper().IterateContracts(network.GetContext(), func(addr common.Address, codeHash common.Hash) bool { // NOTE: we only care about the 2 contracts deployed above, not the ERC20 native precompile for the aatom denomination - if bytes.Equal(addr.Bytes(), common.HexToAddress(testconstants.WEVMOSContractMainnet).Bytes()) { + if bytes.Equal(addr.Bytes(), common.HexToAddress(testconfig.DefaultWevmosContractMainnet).Bytes()) { return false } diff --git a/tests/integration/x/vm/test_statedb.go b/tests/integration/x/vm/test_statedb.go index b78480b90..bd12526b4 100644 --- a/tests/integration/x/vm/test_statedb.go +++ b/tests/integration/x/vm/test_statedb.go @@ -12,7 +12,7 @@ import ( ethparams "github.com/ethereum/go-ethereum/params" "github.com/holiman/uint256" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" utiltx "github.com/cosmos/evm/testutil/tx" @@ -684,8 +684,9 @@ func (s *KeeperTestSuite) TestAddLog() { msg2 := types.NewTx(ethTx2Params) msg2.From = addr.Bytes() + chainID := testconfig.DefaultChainConfig.ChainInfo.EVMChainID ethTx3Params := &types.EvmTxArgs{ - ChainID: big.NewInt(testconstants.ExampleEIP155ChainID), + ChainID: new(big.Int).SetUint64(chainID), Nonce: 0, To: &toAddr, Amount: common.Big1, diff --git a/tests/integration/x/vm/utils.go b/tests/integration/x/vm/utils.go index ab5b0b30a..5aa6338e9 100644 --- a/tests/integration/x/vm/utils.go +++ b/tests/integration/x/vm/utils.go @@ -19,17 +19,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (s *KeeperTestSuite) EvmDenom() string { - return evmtypes.GetEVMCoinDenom() -} - func (s *KeeperTestSuite) StateDB() *statedb.StateDB { return statedb.New(s.Network.GetContext(), s.Network.App.GetEVMKeeper(), statedb.NewEmptyTxConfig()) } // DeployTestContract deploy a test erc20 contract and returns the contract address func (s *KeeperTestSuite) DeployTestContract(t require.TestingT, ctx sdk.Context, owner common.Address, supply *big.Int) common.Address { - chainID := evmtypes.GetEthChainConfig().ChainID + chainID := s.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID erc20Contract, err := testdata.LoadERC20Contract() require.NoError(t, err, "failed to load contract") @@ -91,7 +87,7 @@ func (s *KeeperTestSuite) DeployTestContract(t require.TestingT, ctx sdk.Context func (s *KeeperTestSuite) TransferERC20Token(t require.TestingT, contractAddr, from, to common.Address, amount *big.Int) *evmtypes.MsgEthereumTx { ctx := s.Network.GetContext() - chainID := evmtypes.GetEthChainConfig().ChainID + chainID := s.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID erc20Contract, err := testdata.LoadERC20Contract() require.NoError(t, err, "failed to load contract") @@ -149,7 +145,7 @@ func (s *KeeperTestSuite) TransferERC20Token(t require.TestingT, contractAddr, f // DeployTestMessageCall deploy a test erc20 contract and returns the contract address func (s *KeeperTestSuite) DeployTestMessageCall(t require.TestingT) common.Address { ctx := s.Network.GetContext() - chainID := evmtypes.GetEthChainConfig().ChainID + chainID := s.Network.App.GetEVMKeeper().GetEvmConfig().ChainConfig.EthereumConfig().ChainID testMsgCall, err := testdata.LoadMessageCallContract() require.NoError(t, err) diff --git a/tests/solidity/test-helper.js b/tests/solidity/test-helper.js index 01c129177..c308fdf99 100644 --- a/tests/solidity/test-helper.js +++ b/tests/solidity/test-helper.js @@ -15,31 +15,18 @@ function panic (errMsg) { process.exit(-1) } -// Function to extract EVMChainID from Go config file -function extractChainIDFromGo(goFilePath) { - try { - if (!fs.existsSync(goFilePath)) { - logger.warn(`Go config file not found at ${goFilePath}, using default chain ID: 262144`) - return 262144 - } - - const goFileContent = fs.readFileSync(goFilePath, 'utf8') - - // Look for DefaultEVMChainID = number - const chainIdMatch = goFileContent.match(/DefaultEVMChainID\s*=\s*(\d+)/) - - if (chainIdMatch) { - const chainId = parseInt(chainIdMatch[1], 10) - logger.info(`Extracted DefaultEVMChainID from Go config: ${chainId}`) - return chainId - } - - logger.warn('DefaultEVMChainID not found in Go file, using default: 262144') - return 262144 - } catch (error) { - logger.warn(`Error reading Go config file: ${error.message}, using default: 262144`) - return 262144 +// Function to get EVM Chain ID from environment or use default +function getEVMChainID() { + // Use environment variable if set, otherwise default to 262144 + const envChainId = process.env.EVM_CHAIN_ID + if (envChainId && !isNaN(envChainId)) { + const chainId = parseInt(envChainId, 10) + logger.info(`Using EVM Chain ID from environment: ${chainId}`) + return chainId } + + logger.info('No EVM_CHAIN_ID environment variable set, using default: 262144') + return 262144 } // Function to update Hardhat config with the extracted chain ID @@ -113,18 +100,25 @@ function restoreHardhatConfig(hardhatConfigPath, backupPath) { } } -// Function to sync configuration from Go to Hardhat +// Function to sync configuration from environment variables to Hardhat function syncConfiguration() { - // Adjust these paths based on your project structure - const goConfigPath = path.join(__dirname, '../../server/config/config.go') const hardhatConfigPath = path.join(__dirname, './suites/precompiles/hardhat.config.js') - logger.info('Syncing configuration from Go to Hardhat...') + logger.info('Syncing configuration from environment variables to Hardhat...') + + // Log current environment variables for debugging + const envVars = ['CHAIN_ID', 'EVM_CHAIN_ID', 'DENOM', 'EXTENDED_DENOM', 'DISPLAY_DENOM', 'DECIMALS'] + envVars.forEach(varName => { + const value = process.env[varName] + if (value) { + logger.info(` ${varName}: ${value}`) + } + }) // Create backup before modifying const backupPath = backupHardhatConfig(hardhatConfigPath) - const chainId = extractChainIDFromGo(goConfigPath) + const chainId = getEVMChainID() updateHardhatConfig(chainId, hardhatConfigPath) return { hardhatConfigPath, backupPath } @@ -316,7 +310,16 @@ function setupNetwork ({ runConfig, timeout }) { const rootDir = path.resolve(__dirname, '..', '..'); // → ".../evm" const scriptPath = path.join(rootDir, 'local_node.sh'); // → ".../evm/local_node.sh" - const osdProc = spawn(scriptPath, ['-y'], { + // Build arguments from environment variables + const args = ['-y'] + if (process.env.CHAIN_ID) args.push('--chain-id', process.env.CHAIN_ID) + if (process.env.EVM_CHAIN_ID) args.push('--evm-chain-id', process.env.EVM_CHAIN_ID) + if (process.env.DENOM) args.push('--denom', process.env.DENOM) + if (process.env.EXTENDED_DENOM) args.push('--extended-denom', process.env.EXTENDED_DENOM) + if (process.env.DISPLAY_DENOM) args.push('--display-denom', process.env.DISPLAY_DENOM) + if (process.env.DECIMALS) args.push('--decimals', process.env.DECIMALS) + + const osdProc = spawn(scriptPath, args, { cwd: rootDir, stdio: ['ignore', 'pipe', 'pipe'], // <-- stdout/stderr streams }) @@ -360,7 +363,7 @@ function setupNetwork ({ runConfig, timeout }) { } async function main () { - // Sync configuration before running tests + // Configure Hardhat with environment variables before running tests const configPaths = syncConfiguration() let proc = null @@ -402,7 +405,7 @@ async function main () { process.on('unhandledRejection', (e) => { console.error(e) - // Try to restore config if possible + // Try to restore original Hardhat config if possible const hardhatConfigPath = path.join(__dirname, 'hardhat.config.js') const backupPath = hardhatConfigPath + '.backup' if (fs.existsSync(backupPath)) { diff --git a/testutil/config/config.go b/testutil/config/config.go index 7ea385bdb..c7c909ca5 100644 --- a/testutil/config/config.go +++ b/testutil/config/config.go @@ -1,65 +1,39 @@ package config import ( - "github.com/cosmos/evm/types" evmtypes "github.com/cosmos/evm/x/vm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" ) -// ChainsCoinInfo is a map of the chain id and its corresponding EvmCoinInfo -// that allows initializing the app with different coin info based on the -// chain id -var ChainsCoinInfo = map[uint64]evmtypes.EvmCoinInfo{ - EighteenDecimalsChainID: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, - EVMChainID: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, +type ChainConfig struct { + ChainID string + EvmConfig *evmtypes.EvmConfig } -const ( - // Bech32Prefix defines the Bech32 prefix used for accounts on the exemplary Cosmos EVM blockchain. - Bech32Prefix = "cosmos" - // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address. - Bech32PrefixAccAddr = Bech32Prefix - // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key. - Bech32PrefixAccPub = Bech32Prefix + sdk.PrefixPublic - // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address. - Bech32PrefixValAddr = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator - // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key. - Bech32PrefixValPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator + sdk.PrefixPublic - // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address. - Bech32PrefixConsAddr = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus - // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key. - Bech32PrefixConsPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic - // DisplayDenom defines the denomination displayed to users in client applications. - DisplayDenom = "atom" - // BaseDenom defines to the default denomination used in the Cosmos EVM example chain. - BaseDenom = "aatom" - // BaseDenomUnit defines the precision of the base denomination. - BaseDenomUnit = 18 - // EVMChainID defines the EIP-155 replay-protection chain id for the current ethereum chain config. - EVMChainID = 262144 -) +// CreateChainConfig allows creating a test chain with custom parameters +// extendedDecimals is always 18-decimals (atto) denom for EVM chains +func CreateChainConfig( + chainID string, + evmChainID uint64, + evmChainConfig *evmtypes.ChainConfig, + displayDenom string, + decimals evmtypes.Decimals, + extendedDecimals evmtypes.Decimals, +) ChainConfig { + coinInfo := evmtypes.EvmCoinInfo{ + DisplayDenom: displayDenom, + Decimals: decimals, + ExtendedDecimals: extendedDecimals, + } -// SetBech32Prefixes sets the global prefixes to be used when serializing addresses and public keys to Bech32 strings. -func SetBech32Prefixes(config *sdk.Config) { - config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) -} + if evmChainConfig == nil { + evmChainConfig = evmtypes.DefaultChainConfig(evmChainID, coinInfo) + } + evmConfig := evmtypes.NewEvmConfig(). + WithChainConfig(evmChainConfig). + WithEVMCoinInfo(&coinInfo) -// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets. -func SetBip44CoinType(config *sdk.Config) { - config.SetCoinType(types.Bip44CoinType) - config.SetPurpose(sdk.Purpose) // Shared - config.SetFullFundraiserPath(types.BIP44HDPath) //nolint: staticcheck + return ChainConfig{ + ChainID: chainID, + EvmConfig: evmConfig, + } } diff --git a/testutil/config/config_testing.go b/testutil/config/config_testing.go deleted file mode 100644 index e37568c2b..000000000 --- a/testutil/config/config_testing.go +++ /dev/null @@ -1,63 +0,0 @@ -//go:build test -// +build test - -package config - -import ( - evmconfig "github.com/cosmos/evm/config" - evmtypes "github.com/cosmos/evm/x/vm/types" -) - -// TestChainsCoinInfo is a map of the chain id and its corresponding EvmCoinInfo -// that allows initializing the app with different coin info based on the -// chain id -var TestChainsCoinInfo = map[uint64]evmtypes.EvmCoinInfo{ - EighteenDecimalsChainID: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, - SixDecimalsChainID: { - Denom: "utest", - ExtendedDenom: "atest", - DisplayDenom: "test", - Decimals: evmtypes.SixDecimals, - }, - TwelveDecimalsChainID: { - Denom: "ptest2", - ExtendedDenom: "atest2", - DisplayDenom: "test2", - Decimals: evmtypes.TwelveDecimals, - }, - TwoDecimalsChainID: { - Denom: "ctest3", - ExtendedDenom: "atest3", - DisplayDenom: "test3", - Decimals: evmtypes.TwoDecimals, - }, - TestChainID1: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleChainDenom, - Decimals: evmtypes.EighteenDecimals, - }, - TestChainID2: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleChainDenom, - Decimals: evmtypes.EighteenDecimals, - }, - EVMChainID: { - Denom: ExampleChainDenom, - ExtendedDenom: ExampleChainDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, -} - -// EvmAppOptions allows to setup the global configuration -// for the Cosmos EVM chain. -func EvmAppOptions(chainID uint64) error { - return evmconfig.EvmAppOptionsWithConfigWithReset(chainID, TestChainsCoinInfo, cosmosEVMActivators, true) -} diff --git a/testutil/config/constants.go b/testutil/config/constants.go index fb9bdbe4b..32a36e632 100644 --- a/testutil/config/constants.go +++ b/testutil/config/constants.go @@ -1,31 +1,66 @@ package config -const ( - // ExampleChainDenom is the denomination of the Cosmos EVM example chain's base coin. - ExampleChainDenom = "aatom" +import ( + erc20types "github.com/cosmos/evm/x/erc20/types" + evmtypes "github.com/cosmos/evm/x/vm/types" - // ExampleDisplayDenom is the display denomination of the Cosmos EVM example chain's base coin. - ExampleDisplayDenom = "atom" + "cosmossdk.io/math" +) - // EighteenDecimalsChainID is the chain ID for the 18 decimals chain. - EighteenDecimalsChainID = 9001 +const ( + // DefaultGasPrice is the default gas price used for testing transactions + DefaultGasPrice = 20 - // SixDecimalsChainID is the chain ID for the 6 decimals chain. - SixDecimalsChainID = 9002 + // DefaultChainIDPrefix defines the default chain ID prefix for tests + DefaultChainIDPrefix = "cosmos" + // DefaultChainID defines the default chain ID for tests + DefaultChainID = "cosmos-1" + // DefaultEvmChainID defines the default EVM chain ID for tests + DefaultEvmChainID = 9001 + // DefaultDisplayDenom defines the default display denom for use in tests + DefaultDisplayDenom = "atom" + // DefaultDecimals defines the default decimals used for creating denoms in tests + DefaultDecimals = evmtypes.EighteenDecimals - // TwelveDecimalsChainID is the chain ID for the 12 decimals chain. - TwelveDecimalsChainID = 9003 + // DefaultWevmosContractMainnet is the default WEVMOS contract address for mainnet + DefaultWevmosContractMainnet = "0xD4949664cD82660AaE99bEdc034a0deA8A0bd517" + // DefaultWevmosContractTestnet is the WEVMOS contract address for testnet + DefaultWevmosContractTestnet = "0xcc491f589b45d4a3c679016195b3fb87d7848210" - // TwoDecimalsChainID is the chain ID for the 2 decimals chain. - TwoDecimalsChainID = 9004 + // ExampleEvmAddressAlice is an example EVM address + EvmAddressAlice = "0x1e0DE5DB1a39F99cBc67B00fA3415181b3509e42" + // EvmAddressBob is an example EVM address + EvmAddressBob = "0x0AFc8e15F0A74E98d0AEC6C67389D2231384D4B2" +) - CosmosChainID = 262144 +// Common test configurations for reuse +var ( + // DefaultChainConfig provides a standard 18-decimal cosmos/atom test configuration + DefaultChainConfig = CreateChainConfig(DefaultChainID, DefaultEvmChainID, nil, DefaultDisplayDenom, DefaultDecimals, DefaultDecimals) + // TwoDecimalsChainConfig provides a 2-decimal test configuration + TwoDecimalsChainConfig = CreateChainConfig("ostwo-1", 9002, nil, "test2", evmtypes.TwoDecimals, evmtypes.EighteenDecimals) + // SixDecimalsChainConfig provides a 6-decimal test configuration + SixDecimalsChainConfig = CreateChainConfig("ossix-1", 9006, nil, "test6", evmtypes.SixDecimals, evmtypes.EighteenDecimals) + // TwelveDecimalsChainConfig provides a 12-decimal test configuration + TwelveDecimalsChainConfig = CreateChainConfig("ostwelve-1", 9012, nil, "test12", evmtypes.TwelveDecimals, evmtypes.EighteenDecimals) - // TestChainID1 is test chain IDs for IBC E2E test - TestChainID1 = 9005 - // TestChainID2 is test chain IDs for IBC E2E test - TestChainID2 = 9006 + // DefaultTokenPairs defines a slice containing a pair for the native denom of the default chain + DefaultTokenPairs = []erc20types.TokenPair{ + { + Erc20Address: DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(DefaultDecimals, DefaultDisplayDenom), + Enabled: true, + ContractOwner: erc20types.OWNER_MODULE, + }, + } - // WEVMOSContractMainnet is the WEVMOS contract address for mainnet - WEVMOSContractMainnet = "0xD4949664cD82660AaE99bEdc034a0deA8A0bd517" + // DefaultAllowances defines a slice containing an allowance for the native denom of the default chain + DefaultAllowances = []erc20types.Allowance{ + { + Erc20Address: DefaultWevmosContractMainnet, + Owner: EvmAddressAlice, + Spender: EvmAddressBob, + Value: math.NewInt(100), + }, + } ) diff --git a/testutil/config/evm_app_options.go b/testutil/config/evm_app_options.go deleted file mode 100644 index 07e73107d..000000000 --- a/testutil/config/evm_app_options.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !test -// +build !test - -package config - -import ( - evmconfig "github.com/cosmos/evm/config" -) - -// EvmAppOptions allows to setup the global configuration -// for the Cosmos EVM chain. -func EvmAppOptions(chainID uint64) error { - return evmconfig.EvmAppOptionsWithConfig(chainID, ChainsCoinInfo, cosmosEVMActivators) -} diff --git a/testutil/config/genesis.go b/testutil/config/genesis.go index 4dc55d415..255186649 100644 --- a/testutil/config/genesis.go +++ b/testutil/config/genesis.go @@ -3,7 +3,6 @@ package config import ( "encoding/json" - testconstants "github.com/cosmos/evm/testutil/constants" erc20types "github.com/cosmos/evm/x/erc20/types" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -37,8 +36,8 @@ func NewEVMGenesisState() *evmtypes.GenesisState { // which is the base denomination of the chain (i.e. the WEVMOS contract). func NewErc20GenesisState() *erc20types.GenesisState { erc20GenState := erc20types.DefaultGenesisState() - erc20GenState.TokenPairs = testconstants.ExampleTokenPairs - erc20GenState.NativePrecompiles = []string{testconstants.WEVMOSContractMainnet} + erc20GenState.TokenPairs = DefaultTokenPairs + erc20GenState.NativePrecompiles = []string{DefaultWevmosContractMainnet} return erc20GenState } @@ -48,7 +47,7 @@ func NewErc20GenesisState() *erc20types.GenesisState { // NOTE: for the example chain implementation we are also adding a default minter. func NewMintGenesisState() *minttypes.GenesisState { mintGenState := minttypes.DefaultGenesisState() - mintGenState.Params.MintDenom = ExampleChainDenom + mintGenState.Params.MintDenom = evmtypes.CreateDenomStr(DefaultDecimals, DefaultDisplayDenom) return mintGenState } diff --git a/testutil/constants/constants.go b/testutil/constants/constants.go deleted file mode 100644 index 1b2cf732a..000000000 --- a/testutil/constants/constants.go +++ /dev/null @@ -1,131 +0,0 @@ -package constants - -import ( - erc20types "github.com/cosmos/evm/x/erc20/types" - evmtypes "github.com/cosmos/evm/x/vm/types" - - "cosmossdk.io/math" -) - -const ( - // DefaultGasPrice is used in testing as the default to use for transactions - DefaultGasPrice = 20 - - // ExampleAttoDenom provides an example denom for use in tests - ExampleAttoDenom = "aatom" - - // ExampleMicroDenom provides an example denom for use in tests - ExampleMicroDenom = "uatom" - - // ExampleDisplayDenom provides an example display denom for use in tests - ExampleDisplayDenom = "atom" - - // ExampleBech32Prefix provides an example Bech32 prefix for use in tests - ExampleBech32Prefix = "cosmos" - - // ExampleEIP155ChainID provides an example EIP-155 chain ID for use in tests - ExampleEIP155ChainID = 9001 - - // WEVMOSContractMainnet is the WEVMOS contract address for mainnet - WEVMOSContractMainnet = "0xD4949664cD82660AaE99bEdc034a0deA8A0bd517" - // WEVMOSContractTestnet is the WEVMOS contract address for testnet - WEVMOSContractTestnet = "0xcc491f589b45d4a3c679016195b3fb87d7848210" - // ExampleEvmAddress1 is the example EVM address - ExampleEvmAddressAlice = "0x1e0DE5DB1a39F99cBc67B00fA3415181b3509e42" - // ExampleEvmAddress2 is the example EVM address - ExampleEvmAddressBob = "0x0AFc8e15F0A74E98d0AEC6C67389D2231384D4B2" -) - -type ChainID struct { - ChainID string `json:"chain_id"` - EVMChainID uint64 `json:"evm_chain_id"` -} - -var ( - // ExampleChainIDPrefix provides a chain ID prefix for EIP-155 that can be used in tests - ExampleChainIDPrefix = "cosmos" - - // ExampleChainID provides a chain ID that can be used in tests - ExampleChainID = ChainID{ - ChainID: ExampleChainIDPrefix + "-1", - EVMChainID: 9001, - } - - // SixDecimalsChainID provides a chain ID which is being set up with 6 decimals - SixDecimalsChainID = ChainID{ - ChainID: "ossix-2", - EVMChainID: 9002, - } - - // TwelveDecimalsChainID provides a chain ID which is being set up with 12 decimals - TwelveDecimalsChainID = ChainID{ - ChainID: "ostwelve-3", - EVMChainID: 9003, - } - - // TwoDecimalsChainID provides a chain ID which is being set up with 2 decimals - TwoDecimalsChainID = ChainID{ - ChainID: "ostwo-4", - EVMChainID: 9004, - } - - // ExampleChainCoinInfo provides the coin info for the example chain - // - // It is a map of the chain id and its corresponding EvmCoinInfo - // that allows initializing the app with different coin info based on the - // chain id - ExampleChainCoinInfo = map[ChainID]evmtypes.EvmCoinInfo{ - ExampleChainID: { - Denom: ExampleAttoDenom, - ExtendedDenom: ExampleAttoDenom, - DisplayDenom: ExampleDisplayDenom, - Decimals: evmtypes.EighteenDecimals, - }, - SixDecimalsChainID: { - Denom: "utest", - ExtendedDenom: "atest", - DisplayDenom: "test", - Decimals: evmtypes.SixDecimals, - }, - TwelveDecimalsChainID: { - Denom: "ptest2", - ExtendedDenom: "atest2", - DisplayDenom: "test2", - Decimals: evmtypes.TwelveDecimals, - }, - TwoDecimalsChainID: { - Denom: "ctest3", - ExtendedDenom: "atest3", - DisplayDenom: "test3", - Decimals: evmtypes.TwoDecimals, - }, - } - - // OtherCoinDenoms provides a list of other coin denoms that can be used in tests - OtherCoinDenoms = []string{ - "foo", - "bar", - } - - // ExampleTokenPairs creates a slice of token pairs, that contains a pair for the native denom of the example chain - // implementation. - ExampleTokenPairs = []erc20types.TokenPair{ - { - Erc20Address: WEVMOSContractMainnet, - Denom: ExampleAttoDenom, - Enabled: true, - ContractOwner: erc20types.OWNER_MODULE, - }, - } - - // ExampleAllowances creates a slice of allowances, that contains an allowance for the native denom of the example chain - // implementation. - ExampleAllowances = []erc20types.Allowance{ - { - Erc20Address: WEVMOSContractMainnet, - Owner: ExampleEvmAddressAlice, - Spender: ExampleEvmAddressBob, - Value: math.NewInt(100), - }, - } -) diff --git a/testutil/constants/constants_test.go b/testutil/constants/constants_test.go deleted file mode 100644 index 30c951cd4..000000000 --- a/testutil/constants/constants_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package constants_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/evm/testutil/config" - "github.com/cosmos/evm/testutil/constants" -) - -func TestRequireSameTestDenom(t *testing.T) { - require.Equal(t, - constants.ExampleAttoDenom, - config.ExampleChainDenom, - "test denoms should be the same across the repo", - ) -} - -func TestRequireSameTestBech32Prefix(t *testing.T) { - require.Equal(t, - constants.ExampleBech32Prefix, - config.Bech32Prefix, - "bech32 prefixes should be the same across the repo", - ) -} - -func TestRequireSameWEVMOSMainnet(t *testing.T) { - require.Equal(t, - constants.WEVMOSContractMainnet, - config.WEVMOSContractMainnet, - "wevmos contract addresses should be the same across the repo", - ) -} diff --git a/testutil/ibc/chain.go b/testutil/ibc/chain.go index e78c82c4b..f362d0ef3 100644 --- a/testutil/ibc/chain.go +++ b/testutil/ibc/chain.go @@ -19,9 +19,9 @@ import ( "github.com/cosmos/evm" "github.com/cosmos/evm/crypto/ethsecp256k1" - "github.com/cosmos/evm/testutil/config" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/tx" - "github.com/cosmos/evm/x/vm/types" + evmtypes "github.com/cosmos/evm/x/vm/types" clienttypes "github.com/cosmos/ibc-go/v10/modules/core/02-client/types" channeltypes "github.com/cosmos/ibc-go/v10/modules/core/04-channel/types" commitmenttypes "github.com/cosmos/ibc-go/v10/modules/core/23-commitment/types" @@ -131,11 +131,12 @@ func NewTestChainWithValSet(tb testing.TB, isEVM bool, coord *Coordinator, chain require.True(tb, ok) // add sender account + denom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) balance := banktypes.Balance{ Address: acc.GetAddress().String(), Coins: sdk.NewCoins( sdk.NewCoin(sdk.DefaultBondDenom, amount), - sdk.NewCoin(config.ExampleChainDenom, amount), + sdk.NewCoin(denom, amount), ), } @@ -369,7 +370,7 @@ func (chain *TestChain) SendEvmTx( amount *big.Int, data []byte, gasLimit uint64, -) (*abci.ExecTxResult, *types.MsgEthereumTx, *types.MsgEthereumTxResponse, error) { +) (*abci.ExecTxResult, *evmtypes.MsgEthereumTx, *evmtypes.MsgEthereumTxResponse, error) { app, ok := chain.App.(evm.EvmApp) require.True(chain.TB, ok) ctx := chain.GetContext() @@ -425,12 +426,12 @@ func (chain *TestChain) SendEvmTx( if txResult.Code != 0 { return txResult, nil, nil, fmt.Errorf("%s/%d: %q", txResult.Codespace, txResult.Code, txResult.Log) } - ethRes, err := types.DecodeTxResponse(txResult.Data) + ethRes, err := evmtypes.DecodeTxResponse(txResult.Data) if err != nil { return txResult, nil, nil, err } if ethRes.VmError != "" { - return txResult, msgEthereumTx, ethRes, errorsmod.Wrapf(types.ErrVMExecution, "vm error: %s", ethRes.VmError) + return txResult, msgEthereumTx, ethRes, errorsmod.Wrapf(evmtypes.ErrVMExecution, "vm error: %s", ethRes.VmError) } chain.Coordinator.IncrementTime() diff --git a/testutil/ibc/coordinator.go b/testutil/ibc/coordinator.go index c4823df48..d0b4b0bb1 100644 --- a/testutil/ibc/coordinator.go +++ b/testutil/ibc/coordinator.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/cosmos/evm/testutil/config" ibctesting "github.com/cosmos/ibc-go/v10/testing" ) @@ -42,7 +41,7 @@ func NewCoordinator(t *testing.T, nEVMChains, mCosmosChains int, evmAppCreator i chainID := GetChainID(i) evmChainID, err := strconv.ParseUint(GetEvmChainID(i), 10, 64) require.NoError(t, err) - require.NoError(t, config.EvmAppOptions(evmChainID)) + // Note: Chain configuration is handled by the test chain creation process // setup EVM chains chains[strconv.FormatUint(evmChainID, 10)] = NewTestChain(t, true, coord, chainID) } diff --git a/testutil/ibc/helpers.go b/testutil/ibc/helpers.go index 85f749944..e5acc7a4b 100644 --- a/testutil/ibc/helpers.go +++ b/testutil/ibc/helpers.go @@ -10,7 +10,8 @@ import ( abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/evm/testutil/config" + testconfig "github.com/cosmos/evm/testutil/config" + evmtypes "github.com/cosmos/evm/x/vm/types" bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -24,8 +25,9 @@ const FeeAmt = 10000000000 func FeeCoins() sdk.Coins { // Note: evmChain requires for gas price higher than base fee (see fee_checker.go). // Other Cosmos chains using simapp don’t rely on gas prices, so this works even if simapp isn’t aware of evmChain’s BaseDenom. + denom := evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) sdkExp := new(big.Int).Exp(big.NewInt(10), big.NewInt(6), nil) - return sdk.Coins{sdk.NewInt64Coin(config.BaseDenom, new(big.Int).Mul(big.NewInt(FeeAmt), sdkExp).Int64())} + return sdk.Coins{sdk.NewInt64Coin(denom, new(big.Int).Mul(big.NewInt(FeeAmt), sdkExp).Int64())} } // SignAndDeliver signs and delivers a transaction. No simulation occurs as the diff --git a/testutil/integration/evm/network/amounts.go b/testutil/integration/evm/network/amounts.go index a70b6d239..95988ec8d 100644 --- a/testutil/integration/evm/network/amounts.go +++ b/testutil/integration/evm/network/amounts.go @@ -3,7 +3,7 @@ package network import ( "math/big" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/types" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -18,18 +18,16 @@ type InitialAmounts struct { } func DefaultInitialAmounts() InitialAmounts { - baseCoinInfo := testconstants.ExampleChainCoinInfo[defaultChain] - + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo return InitialAmounts{ - Base: GetInitialAmount(baseCoinInfo.Decimals), - Evm: GetInitialAmount(baseCoinInfo.Decimals), + Base: GetInitialAmount(coinInfo.Decimals), + Evm: GetInitialAmount(coinInfo.Decimals), } } func DefaultInitialBondedAmount() math.Int { - baseCoinInfo := testconstants.ExampleChainCoinInfo[defaultChain] - - return GetInitialBondedAmount(baseCoinInfo.Decimals) + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + return GetInitialBondedAmount(coinInfo.Decimals) } func GetInitialAmount(decimals evmtypes.Decimals) math.Int { diff --git a/testutil/integration/evm/network/chain_id_modifiers.go b/testutil/integration/evm/network/chain_id_modifiers.go index 736c14e5c..538efb9ef 100644 --- a/testutil/integration/evm/network/chain_id_modifiers.go +++ b/testutil/integration/evm/network/chain_id_modifiers.go @@ -5,9 +5,8 @@ package network import ( - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" erc20types "github.com/cosmos/evm/x/erc20/types" - "github.com/cosmos/evm/x/precisebank/types" evmtypes "github.com/cosmos/evm/x/vm/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -25,10 +24,7 @@ func updateBankGenesisStateForChainID(bankGenesisState banktypes.GenesisState) b // for both extended and native EVM denominations depending on the chain. func generateBankGenesisMetadata() []banktypes.Metadata { // Basic denom settings - displayDenom := evmtypes.GetEVMCoinDisplayDenom() // e.g., "atom" - evmDenom := evmtypes.GetEVMCoinDenom() // e.g., "uatom" - extDenom := types.ExtendedCoinDenom() // always 18-decimals base denom - evmDecimals := evmtypes.GetEVMCoinDecimals() // native decimal precision, e.g., 6, 12, ..., or 18 + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo // Standard metadata fields name := "Cosmos EVM" @@ -36,62 +32,57 @@ func generateBankGenesisMetadata() []banktypes.Metadata { var metas []banktypes.Metadata - if evmDenom != extDenom { + if coinInfo.Decimals != coinInfo.ExtendedDecimals { // This means we are initializing a chain with non-18 decimals // // Note: extDenom is always 18-decimals and handled by the precisebank module's states, // So we don't need to add it to the bank module's metadata. metas = append(metas, banktypes.Metadata{ Description: "Native EVM denom metadata", - Base: evmDenom, + Base: coinInfo.GetDenom(), DenomUnits: []*banktypes.DenomUnit{ - {Denom: evmDenom, Exponent: 0}, - {Denom: displayDenom, Exponent: uint32(evmDecimals)}, + {Denom: coinInfo.GetDenom(), Exponent: 0}, + {Denom: coinInfo.DisplayDenom, Exponent: uint32(coinInfo.Decimals)}, }, Name: name, Symbol: symbol, - Display: displayDenom, + Display: coinInfo.DisplayDenom, }) } else { // EVM native chain: single metadata with 18-decimals metas = append(metas, banktypes.Metadata{ Description: "Native 18-decimal denom metadata for Cosmos EVM chain", - Base: evmDenom, + Base: coinInfo.GetDenom(), DenomUnits: []*banktypes.DenomUnit{ - {Denom: evmDenom, Exponent: 0}, - {Denom: displayDenom, Exponent: uint32(evmtypes.EighteenDecimals)}, + {Denom: coinInfo.GetDenom(), Exponent: 0}, + {Denom: coinInfo.DisplayDenom, Exponent: uint32(evmtypes.EighteenDecimals)}, }, Name: name, Symbol: symbol, - Display: displayDenom, + Display: coinInfo.DisplayDenom, }) } return metas } -// updateErc20GenesisStateForChainID modify the default genesis state for the -// erc20 module on the testing suite depending on the chainID. -func updateErc20GenesisStateForChainID(chainID testconstants.ChainID, erc20GenesisState erc20types.GenesisState) erc20types.GenesisState { - erc20GenesisState.TokenPairs = updateErc20TokenPairs(chainID, erc20GenesisState.TokenPairs) +// updateErc20GenesisStateForCoinInfo modify the default genesis state for the +// erc20 module on the testing suite depending on the coin info +func updateErc20GenesisStateForCoinInfo(coinInfo evmtypes.EvmCoinInfo, erc20GenesisState erc20types.GenesisState) erc20types.GenesisState { + erc20GenesisState.TokenPairs = updateErc20TokenPairs(coinInfo, erc20GenesisState.TokenPairs) return erc20GenesisState } // updateErc20TokenPairs modifies the erc20 token pairs to use the correct -// WEVMOS depending on ChainID -func updateErc20TokenPairs(chainID testconstants.ChainID, tokenPairs []erc20types.TokenPair) []erc20types.TokenPair { - testnetAddress := GetWEVMOSContractHex(chainID) - coinInfo := testconstants.ExampleChainCoinInfo[chainID] - - mainnetAddress := GetWEVMOSContractHex(testconstants.ExampleChainID) - +// WEVMOS depending on the coin info +func updateErc20TokenPairs(coinInfo evmtypes.EvmCoinInfo, tokenPairs []erc20types.TokenPair) []erc20types.TokenPair { updatedTokenPairs := make([]erc20types.TokenPair, len(tokenPairs)) for i, tokenPair := range tokenPairs { - if tokenPair.Erc20Address == mainnetAddress { + if tokenPair.Erc20Address == testconfig.DefaultWevmosContractMainnet { updatedTokenPairs[i] = erc20types.TokenPair{ - Erc20Address: testnetAddress, - Denom: coinInfo.Denom, + Erc20Address: testconfig.DefaultWevmosContractTestnet, + Denom: coinInfo.GetDenom(), Enabled: tokenPair.Enabled, ContractOwner: tokenPair.ContractOwner, } diff --git a/testutil/integration/evm/network/coins.go b/testutil/integration/evm/network/coins.go index 022a5d55f..1b2807393 100644 --- a/testutil/integration/evm/network/coins.go +++ b/testutil/integration/evm/network/coins.go @@ -1,7 +1,7 @@ package network import ( - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" ) @@ -25,7 +25,7 @@ type ChainCoins struct { // DefaultChainCoins returns the default values used for the ChainCoins in which // base and evm denom are the same. func DefaultChainCoins() ChainCoins { - baseCoinInfo := testconstants.ExampleChainCoinInfo[defaultChain] + baseCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo // baseCoin is used for both base and evm coin as default.. baseCoin := getCoinInfo(baseCoinInfo) @@ -39,7 +39,7 @@ func DefaultChainCoins() ChainCoins { func getCoinInfo(coinInfo evmtypes.EvmCoinInfo) CoinInfo { return CoinInfo{ - Denom: coinInfo.Denom, + Denom: coinInfo.GetDenom(), Decimals: coinInfo.Decimals, } } diff --git a/testutil/integration/evm/network/config.go b/testutil/integration/evm/network/config.go index ed612f75f..0064f0c39 100644 --- a/testutil/integration/evm/network/config.go +++ b/testutil/integration/evm/network/config.go @@ -6,7 +6,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" testtx "github.com/cosmos/evm/testutil/tx" evmtypes "github.com/cosmos/evm/x/vm/types" @@ -19,9 +19,6 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// defaultChain represents the default chain ID used in the suite setup. -var defaultChain = testconstants.ExampleChainID - // Config defines the configuration for a chain. // It allows for customization of the network to adjust to // testing needs. @@ -54,8 +51,8 @@ func DefaultConfig() Config { account, _ := testtx.NewAccAddressAndKey() return Config{ - chainID: testconstants.ExampleChainID.ChainID, - eip155ChainID: big.NewInt(testconstants.ExampleEIP155ChainID), + chainID: testconfig.DefaultChainConfig.ChainID, + eip155ChainID: new(big.Int).SetUint64(testconfig.DefaultChainConfig.EvmConfig.ChainConfig.ChainId), chainCoins: DefaultChainCoins(), initialAmounts: DefaultInitialAmounts(), initialBondedAmount: DefaultInitialBondedAmount(), @@ -115,28 +112,19 @@ func getGenAccountsAndBalances(cfg Config, validators []stakingtypes.Validator) // requires to be changed. type ConfigOption func(*Config) -// WithChainID sets a custom chainID for the network. Changing the chainID +// WithChainConfig sets a custom chainID for the network. Changing the chainID // change automatically also the EVM coin used. It panics if the chainID is invalid. -func WithChainID(chainID testconstants.ChainID) ConfigOption { - evmCoinInfo, found := testconstants.ExampleChainCoinInfo[chainID] - if !found { - panic(fmt.Sprintf( - "chain id %q not found in chain coin info; available: %v", - chainID, - testconstants.ExampleChainCoinInfo, - )) - } - +func WithChainConfig(chainConfig testconfig.ChainConfig) ConfigOption { return func(cfg *Config) { - cfg.chainID = chainID.ChainID - cfg.eip155ChainID = big.NewInt(int64(chainID.EVMChainID)) //nolint:gosec // G115 // won't exceed uint64 + cfg.chainID = chainConfig.ChainID + cfg.eip155ChainID = big.NewInt(int64(chainConfig.EvmConfig.ChainConfig.ChainId)) //nolint:gosec // G115 // won't exceed uint64 if cfg.chainCoins.IsBaseEqualToEVM() { - cfg.chainCoins.baseCoin.Denom = evmCoinInfo.Denom - cfg.chainCoins.baseCoin.Decimals = evmCoinInfo.Decimals + cfg.chainCoins.baseCoin.Denom = chainConfig.EvmConfig.CoinInfo.GetDenom() + cfg.chainCoins.baseCoin.Decimals = chainConfig.EvmConfig.CoinInfo.Decimals } - cfg.chainCoins.evmCoin.Denom = evmCoinInfo.Denom - cfg.chainCoins.evmCoin.Decimals = evmCoinInfo.Decimals + cfg.chainCoins.evmCoin.Denom = chainConfig.EvmConfig.CoinInfo.GetDenom() + cfg.chainCoins.evmCoin.Decimals = chainConfig.EvmConfig.CoinInfo.Decimals } } diff --git a/testutil/integration/evm/network/example_contracts.go b/testutil/integration/evm/network/example_contracts.go index ab3a3daba..962f7fba4 100644 --- a/testutil/integration/evm/network/example_contracts.go +++ b/testutil/integration/evm/network/example_contracts.go @@ -1,26 +1,26 @@ package network import ( - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" ) // chainsWEVMOSHex is an utility map used to retrieve the WEVMOS contract // address in hex format from the chain ID. // // TODO: refactor to define this in the example chain initialization and pass as function argument -var chainsWEVMOSHex = map[testconstants.ChainID]string{ - testconstants.ExampleChainID: testconstants.WEVMOSContractMainnet, +var chainsWEVMOSHex = map[testconfig.ChainInfo]string{ + testconfig.DefaultChainConfig.ChainInfo: testconfig.DefaultWevmosContractMainnet, } // GetWEVMOSContractHex returns the hex format of address for the WEVMOS contract // given the chainID. If the chainID is not found, it defaults to the mainnet // address. -func GetWEVMOSContractHex(chainID testconstants.ChainID) string { - address, found := chainsWEVMOSHex[chainID] +func GetWEVMOSContractHex(chainInfo testconfig.ChainInfo) string { + address, found := chainsWEVMOSHex[chainInfo] // default to mainnet address if !found { - address = chainsWEVMOSHex[testconstants.ExampleChainID] + address = chainsWEVMOSHex[testconfig.DefaultChainConfig.ChainInfo] } return address diff --git a/testutil/integration/evm/network/network.go b/testutil/integration/evm/network/network.go index b1db05400..e46f97d9f 100644 --- a/testutil/integration/evm/network/network.go +++ b/testutil/integration/evm/network/network.go @@ -259,7 +259,7 @@ func (n *IntegrationNetwork) configureAndInitChain(evmApp evm.EvmApp) error { return nil } -// GetConfig returns the network's configuration +// GetBaseDecimal returns the network's base decimal func (n *IntegrationNetwork) GetBaseDecimal() evmtypes.Decimals { return n.baseDecimal } @@ -308,11 +308,21 @@ func (n *IntegrationNetwork) GetBaseDenom() string { return n.cfg.chainCoins.baseCoin.Denom } +// GetBaseDecimals returns the network's base decimals +func (n *IntegrationNetwork) GetBaseDecimals() evmtypes.Decimals { + return n.cfg.chainCoins.BaseDecimals() +} + // GetEVMDenom returns the network's evm denom func (n *IntegrationNetwork) GetEVMDenom() string { return n.cfg.chainCoins.evmCoin.Denom } +// GetEVMDecimals returns the network's evm decimals +func (n *IntegrationNetwork) GetEVMDecimals() evmtypes.Decimals { + return n.cfg.chainCoins.EVMDecimals() +} + // GetOtherDenoms returns network's other supported denoms func (n *IntegrationNetwork) GetOtherDenoms() []string { return n.cfg.otherCoinDenoms diff --git a/testutil/integration/evm/network/setup.go b/testutil/integration/evm/network/setup.go index f352bd4af..f9f483cf1 100644 --- a/testutil/integration/evm/network/setup.go +++ b/testutil/integration/evm/network/setup.go @@ -9,7 +9,7 @@ import ( cmttypes "github.com/cometbft/cometbft/types" "github.com/cosmos/evm" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" cosmosevmtypes "github.com/cosmos/evm/types" erc20types "github.com/cosmos/evm/x/erc20/types" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" @@ -417,7 +417,8 @@ type GovCustomGenesisState struct { func setDefaultGovGenesisState(cosmosEVMApp evm.EvmApp, genesisState cosmosevmtypes.GenesisState, overwriteParams GovCustomGenesisState) cosmosevmtypes.GenesisState { govGen := govtypesv1.DefaultGenesisState() updatedParams := govGen.Params - minDepositAmt := sdkmath.NewInt(1e18).Quo(evmtypes.GetEVMCoinDecimals().ConversionFactor()) + defaultDecimals := testconfig.DefaultDecimals + minDepositAmt := sdkmath.NewInt(1e18).Quo(defaultDecimals.ConversionFactor()) updatedParams.MinDeposit = sdktypes.NewCoins(sdktypes.NewCoin(overwriteParams.denom, minDepositAmt)) updatedParams.ExpeditedMinDeposit = sdktypes.NewCoins(sdktypes.NewCoin(overwriteParams.denom, minDepositAmt)) govGen.Params = updatedParams @@ -461,12 +462,14 @@ func setDefaultMintGenesisState(cosmosEVMApp evm.EvmApp, genesisState cosmosevmt } func setDefaultErc20GenesisState(cosmosEVMApp evm.EvmApp, evmChainID uint64, genesisState cosmosevmtypes.GenesisState) cosmosevmtypes.GenesisState { - // NOTE: here we are using the setup from the example chain + coinInfo := evmtypes.EvmCoinInfo{ + DisplayDenom: testconfig.DefaultDisplayDenom, + Decimals: testconfig.DefaultDecimals, + ExtendedDecimals: testconfig.DefaultDecimals, + } + erc20Gen := newErc20GenesisState() - updatedErc20Gen := updateErc20GenesisStateForChainID(testconstants.ChainID{ - ChainID: cosmosEVMApp.ChainID(), - EVMChainID: evmChainID, - }, *erc20Gen) + updatedErc20Gen := updateErc20GenesisStateForCoinInfo(coinInfo, *erc20Gen) genesisState[erc20types.ModuleName] = cosmosEVMApp.AppCodec().MustMarshalJSON(&updatedErc20Gen) return genesisState @@ -479,8 +482,8 @@ func setDefaultErc20GenesisState(cosmosEVMApp evm.EvmApp, evmChainID uint64, gen // which is the base denomination of the chain (i.e. the WEVMOS contract). func newErc20GenesisState() *erc20types.GenesisState { erc20GenState := erc20types.DefaultGenesisState() - erc20GenState.TokenPairs = testconstants.ExampleTokenPairs - erc20GenState.NativePrecompiles = []string{testconstants.WEVMOSContractMainnet} + erc20GenState.TokenPairs = testconfig.DefaultTokenPairs + erc20GenState.NativePrecompiles = []string{testconfig.DefaultWevmosContractMainnet} return erc20GenState } diff --git a/testutil/integration/evm/utils/genesis.go b/testutil/integration/evm/utils/genesis.go index 76c340fe5..cb9ee2c2b 100644 --- a/testutil/integration/evm/utils/genesis.go +++ b/testutil/integration/evm/utils/genesis.go @@ -1,7 +1,7 @@ package utils import ( - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/testutil/integration/evm/network" testkeyring "github.com/cosmos/evm/testutil/keyring" utiltx "github.com/cosmos/evm/testutil/tx" @@ -50,7 +50,7 @@ func CreateGenesisWithTokenPairs(keyring testkeyring.Keyring, denoms ...string) tokenPairs := make([]erc20types.TokenPair, 0, len(denoms)+1) tokenPairs = append(tokenPairs, // NOTE: the example token pairs are being added in the integration test utils - testconstants.ExampleTokenPairs..., + testconfig.DefaultTokenPairs..., ) dynPrecAddr := make([]string, 0, len(denoms)) @@ -70,7 +70,7 @@ func CreateGenesisWithTokenPairs(keyring testkeyring.Keyring, denoms ...string) // with the WEVMOS (default is mainnet) and 'xmpl' tokens in the erc20 params erc20GenesisState := erc20types.DefaultGenesisState() erc20GenesisState.TokenPairs = tokenPairs - erc20GenesisState.NativePrecompiles = []string{testconstants.WEVMOSContractMainnet} + erc20GenesisState.NativePrecompiles = []string{testconfig.DefaultWevmosContractMainnet} erc20GenesisState.DynamicPrecompiles = dynPrecAddr // Combine module genesis states @@ -86,8 +86,8 @@ func CreateGenesisWithTokenPairs(keyring testkeyring.Keyring, denoms ...string) // which is the base denomination of the chain (i.e. the WEVMOS contract). func NewErc20GenesisState() *erc20types.GenesisState { erc20GenState := erc20types.DefaultGenesisState() - erc20GenState.TokenPairs = testconstants.ExampleTokenPairs - erc20GenState.NativePrecompiles = []string{testconstants.WEVMOSContractMainnet} + erc20GenState.TokenPairs = testconfig.DefaultTokenPairs + erc20GenState.NativePrecompiles = []string{testconfig.DefaultWevmosContractMainnet} return erc20GenState } diff --git a/testutil/tx/cosmos.go b/testutil/tx/cosmos.go index f130c360c..23f743d85 100644 --- a/testutil/tx/cosmos.go +++ b/testutil/tx/cosmos.go @@ -4,7 +4,8 @@ import ( protov2 "google.golang.org/protobuf/proto" "github.com/cosmos/evm" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" + evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -16,7 +17,10 @@ import ( authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" ) -var DefaultFee = sdk.NewCoin(constants.ExampleAttoDenom, sdkmath.NewInt(1e16)) // 0.01 AATOM +var ( + attoDenom = evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom) + DefaultFee = sdk.NewCoin(attoDenom, sdkmath.NewInt(1e16)) // 0.01 AATOM +) // CosmosTxArgs contains the params to create a cosmos tx type CosmosTxArgs struct { @@ -51,7 +55,7 @@ func PrepareCosmosTx( var fees sdk.Coins if args.GasPrice != nil { - fees = sdk.Coins{{Denom: constants.ExampleAttoDenom, Amount: args.GasPrice.MulRaw(int64(args.Gas))}} //#nosec G115 + fees = sdk.Coins{{Denom: attoDenom, Amount: args.GasPrice.MulRaw(int64(args.Gas))}} //#nosec G115 } else { fees = sdk.Coins{DefaultFee} } diff --git a/testutil/tx/eth.go b/testutil/tx/eth.go index 9a6b65540..4116042a5 100644 --- a/testutil/tx/eth.go +++ b/testutil/tx/eth.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/evm" "github.com/cosmos/evm/server/config" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" errorsmod "cosmossdk.io/errors" @@ -33,11 +34,14 @@ func PrepareEthTx( ) (authsigning.Tx, error) { txBuilder := txCfg.NewTxBuilder() - signer := ethtypes.LatestSignerForChainID(evmtypes.GetEthChainConfig().ChainID) + // Always use testconfig chainID for test consistency + evmConfig := testconfig.DefaultChainConfig.EvmConfig + chainID := new(big.Int).SetUint64(evmConfig.ChainConfig.ChainId) + signer := ethtypes.LatestSignerForChainID(chainID) txFee := sdk.Coins{} txGasLimit := uint64(0) - baseDenom := evmtypes.GetEVMCoinDenom() + baseDenom := evmConfig.CoinInfo.GetDenom() // Sign messages and compute gas/fees. for _, m := range msgs { @@ -109,7 +113,8 @@ func CreateEthTx( copy(toAddr[:], dest) } fromAddr := common.BytesToAddress(privKey.PubKey().Address().Bytes()) - chainID := evmtypes.GetEthChainConfig().ChainID + chainConfig := testconfig.DefaultChainConfig.EvmConfig.ChainConfig + ethConfig := chainConfig.EthereumConfig() baseFeeRes, err := evmApp.GetEVMKeeper().BaseFee(ctx, &evmtypes.QueryBaseFeeRequest{}) if err != nil { @@ -123,7 +128,7 @@ func CreateEthTx( gasLimit = 5_000_000 } evmTxParams := &evmtypes.EvmTxArgs{ - ChainID: chainID, + ChainID: ethConfig.ChainID, Nonce: nonce, To: toAddr, Amount: amount, @@ -139,7 +144,9 @@ func CreateEthTx( // If we are creating multiple eth Tx's with different senders, we need to sign here rather than later. if privKey != nil { - signer := ethtypes.LatestSignerForChainID(evmtypes.GetEthChainConfig().ChainID) + // Always use testconfig chainID for test consistency + chainID := ethConfig.ChainID + signer := ethtypes.LatestSignerForChainID(chainID) err := msgEthereumTx.Sign(signer, NewSigner(privKey)) if err != nil { return nil, err diff --git a/utils/utils_test.go b/utils/utils_test.go index c6d7d331f..cdc852049 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -14,11 +14,10 @@ import ( cryptocodec "github.com/cosmos/evm/crypto/codec" "github.com/cosmos/evm/crypto/ethsecp256k1" "github.com/cosmos/evm/crypto/hd" - "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/types" "github.com/cosmos/evm/utils" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" - evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -487,14 +486,12 @@ func TestAccountEquivalence(t *testing.T) { } func TestCalcBaseFee(t *testing.T) { - for _, chainID := range []constants.ChainID{constants.ExampleChainID, constants.TwelveDecimalsChainID, constants.SixDecimalsChainID} { - t.Run(chainID.ChainID, func(t *testing.T) { - evmConfigurator := evmtypes.NewEVMConfigurator(). - WithEVMCoinInfo(constants.ExampleChainCoinInfo[chainID]) - evmConfigurator.ResetTestConfig() - err := evmConfigurator.Configure() - require.NoError(t, err) - + for _, chainConfig := range []testconfig.ChainConfig{ + testconfig.DefaultChainConfig, + testconfig.TwelveDecimalsChainConfig, + testconfig.SixDecimalsChainConfig, + } { + t.Run(chainConfig.ChainID, func(t *testing.T) { config := ¶ms.ChainConfig{ LondonBlock: big.NewInt(0), } @@ -603,7 +600,8 @@ func TestCalcBaseFee(t *testing.T) { // baseFeeDelta = 1000000000 * 2500000 / 5000000 / 8 = 62500000 // result = max(1000000000 - 62500000, minGasPrice) // result = max(937500000, 1000000000) = 1000000000 (minGasPrice wins) - factor := sdkmath.LegacyNewDecFromInt(evmtypes.GetEVMCoinDecimals().ConversionFactor()) + decimals := chainConfig.EvmConfig.CoinInfo.Decimals + factor := sdkmath.LegacyNewDecFromInt(decimals.ConversionFactor()) return factor.Mul(sdkmath.LegacyNewDec(1_000_000_000)).TruncateInt().BigInt() }(), expectedError: "", @@ -712,7 +710,8 @@ func TestCalcBaseFee(t *testing.T) { checkFunc: func(t *testing.T, result *big.Int, parent *ethtypes.Header) { t.Helper() // Should be at least the minimum gas price - factor := sdkmath.LegacyNewDecFromInt(evmtypes.GetEVMCoinDecimals().ConversionFactor()) + decimals := chainConfig.EvmConfig.CoinInfo.Decimals + factor := sdkmath.LegacyNewDecFromInt(decimals.ConversionFactor()) expectedMinGasPrice := sdkmath.LegacyNewDec(50_000_000_000).Mul(factor).TruncateInt().BigInt() require.True(t, result.Cmp(expectedMinGasPrice) >= 0, "Result should be at least min gas price") }, diff --git a/x/erc20/types/genesis_test.go b/x/erc20/types/genesis_test.go index 10abb1373..6d3301bef 100644 --- a/x/erc20/types/genesis_test.go +++ b/x/erc20/types/genesis_test.go @@ -5,8 +5,9 @@ import ( "github.com/stretchr/testify/suite" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/erc20/types" + evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" ) @@ -23,7 +24,7 @@ func TestGenesisTestSuite(t *testing.T) { } func (suite *GenesisTestSuite) TestValidateGenesis() { - newGen := types.NewGenesisState(types.DefaultParams(), testconstants.ExampleTokenPairs, testconstants.ExampleAllowances) + newGen := types.NewGenesisState(types.DefaultParams(), testconfig.DefaultTokenPairs, testconfig.DefaultAllowances) testCases := []struct { name string @@ -44,8 +45,8 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { name: "valid genesis", genState: &types.GenesisState{ Params: types.DefaultParams(), - TokenPairs: testconstants.ExampleTokenPairs, - Allowances: testconstants.ExampleAllowances, + TokenPairs: testconfig.DefaultTokenPairs, + Allowances: testconfig.DefaultAllowances, }, expPass: true, }, @@ -60,12 +61,12 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: true, }, @@ -85,12 +86,12 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: false, }, @@ -110,12 +111,12 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: false, }, @@ -135,12 +136,12 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: false, }, @@ -155,12 +156,12 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: false, }, @@ -175,7 +176,7 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Enabled: true, }, }, - Allowances: testconstants.ExampleAllowances, + Allowances: testconfig.DefaultAllowances, }, expPass: false, }, @@ -183,18 +184,18 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { name: "invalid genesis - duplicated allowances", genState: &types.GenesisState{ Params: types.DefaultParams(), - TokenPairs: testconstants.ExampleTokenPairs, + TokenPairs: testconfig.DefaultTokenPairs, Allowances: []types.Allowance{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Owner: testconstants.ExampleEvmAddressAlice, - Spender: testconstants.ExampleEvmAddressBob, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Owner: testconfig.EvmAddressAlice, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(100), }, { - Erc20Address: testconstants.WEVMOSContractMainnet, - Owner: testconstants.ExampleEvmAddressAlice, - Spender: testconstants.ExampleEvmAddressBob, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Owner: testconfig.EvmAddressAlice, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(100), }, }, @@ -207,16 +208,16 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Params: types.DefaultParams(), TokenPairs: []types.TokenPair{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(evmtypes.EighteenDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, Allowances: []types.Allowance{ { Erc20Address: "bad", - Owner: testconstants.ExampleEvmAddressAlice, - Spender: testconstants.ExampleEvmAddressBob, + Owner: testconfig.EvmAddressAlice, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(-1), }, }, @@ -229,16 +230,16 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Params: types.DefaultParams(), TokenPairs: []types.TokenPair{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, Allowances: []types.Allowance{ { - Erc20Address: testconstants.WEVMOSContractMainnet, + Erc20Address: testconfig.DefaultWevmosContractMainnet, Owner: "bad", - Spender: testconstants.ExampleEvmAddressBob, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(-1), }, }, @@ -251,15 +252,15 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Params: types.DefaultParams(), TokenPairs: []types.TokenPair{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, Allowances: []types.Allowance{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Owner: testconstants.ExampleEvmAddressAlice, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Owner: testconfig.EvmAddressAlice, Spender: "bad", Value: math.NewInt(-1), }, @@ -273,16 +274,16 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Params: types.DefaultParams(), TokenPairs: []types.TokenPair{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, Allowances: []types.Allowance{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Owner: testconstants.ExampleEvmAddressAlice, - Spender: testconstants.ExampleEvmAddressBob, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Owner: testconfig.EvmAddressAlice, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(0), }, }, @@ -295,16 +296,16 @@ func (suite *GenesisTestSuite) TestValidateGenesis() { Params: types.DefaultParams(), TokenPairs: []types.TokenPair{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Denom: testconstants.ExampleAttoDenom, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Denom: evmtypes.CreateDenomStr(testconfig.DefaultDecimals, testconfig.DefaultDisplayDenom), Enabled: true, }, }, Allowances: []types.Allowance{ { - Erc20Address: testconstants.WEVMOSContractMainnet, - Owner: testconstants.ExampleEvmAddressAlice, - Spender: testconstants.ExampleEvmAddressBob, + Erc20Address: testconfig.DefaultWevmosContractMainnet, + Owner: testconfig.EvmAddressAlice, + Spender: testconfig.EvmAddressBob, Value: math.NewInt(-1), }, }, diff --git a/x/precisebank/genesis.go b/x/precisebank/genesis.go index 171dd89e1..791fbd946 100644 --- a/x/precisebank/genesis.go +++ b/x/precisebank/genesis.go @@ -35,8 +35,10 @@ func InitGenesis( totalAmt := gs.TotalAmountWithRemainder() moduleAddr := ak.GetModuleAddress(types.ModuleName) - moduleBal := bk.GetBalance(ctx, moduleAddr, types.IntegerCoinDenom()) - moduleBalExtended := moduleBal.Amount.Mul(types.ConversionFactor()) + coinInfo := keeper.GetCoinInfo() + + moduleBal := bk.GetBalance(ctx, moduleAddr, coinInfo.GetDenom()) + moduleBalExtended := moduleBal.Amount.Mul(types.ConversionFactor(coinInfo.ExtendedDecimals)) // Compare balances in full precise extended amounts if !totalAmt.Equal(moduleBalExtended) { @@ -46,15 +48,15 @@ func InitGenesis( fmt.Printf( "WARNING: module account balance does not match sum of fractional balances and remainder, balance is %s but expected %v%s (%v%s). This is expected during testing with default genesis state.\n", moduleBal, - totalAmt, types.ExtendedCoinDenom(), - totalAmt.Quo(types.ConversionFactor()), types.IntegerCoinDenom(), + totalAmt, coinInfo.GetExtendedDenom(), + totalAmt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)), coinInfo.GetDenom(), ) } else { // For non-default genesis states, enforce strict validation panic(fmt.Sprintf("module account balance does not match sum of fractional balances and remainder, balance is %s but expected %v%s (%v%s)", moduleBal, - totalAmt, types.ExtendedCoinDenom(), - totalAmt.Quo(types.ConversionFactor()), types.IntegerCoinDenom(), + totalAmt, coinInfo.GetExtendedDenom(), + totalAmt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)), coinInfo.GetDenom(), )) } } diff --git a/x/precisebank/keeper/burn.go b/x/precisebank/keeper/burn.go index f971f4d26..47f5f791e 100644 --- a/x/precisebank/keeper/burn.go +++ b/x/precisebank/keeper/burn.go @@ -18,6 +18,7 @@ import ( // It will panic if the module account does not exist or is unauthorized. func (k Keeper) BurnCoins(goCtx context.Context, moduleName string, amt sdk.Coins) error { ctx := sdk.UnwrapSDKContext(goCtx) + extendedDenom := k.GetCoinInfo().GetExtendedDenom() // Custom protection for x/precisebank, no external module should be able to // affect reserves. @@ -43,10 +44,10 @@ func (k Keeper) BurnCoins(goCtx context.Context, moduleName string, amt sdk.Coin // Get non-ExtendedCoinDenom coins passthroughCoins := amt - extendedAmount := amt.AmountOf(types.ExtendedCoinDenom()) + extendedAmount := amt.AmountOf(extendedDenom) if extendedAmount.IsPositive() { // Remove ExtendedCoinDenom from the coins as it is managed by x/precisebank - removeCoin := sdk.NewCoin(types.ExtendedCoinDenom(), extendedAmount) + removeCoin := sdk.NewCoin(extendedDenom, extendedAmount) passthroughCoins = amt.Sub(removeCoin) } @@ -75,14 +76,16 @@ func (k Keeper) burnExtendedCoin( ) error { // Get the module address moduleAddr := k.ak.GetModuleAddress(moduleName) + integerDenom := k.GetCoinInfo().GetDenom() + extendedDecimals := k.GetCoinInfo().ExtendedDecimals // Don't create fractional balances for the precisebank module account itself // The precisebank module account is the reserve and should not have fractional balances if moduleName == types.ModuleName { // For the precisebank module account, just burn the integer coins directly - integerBurnAmount := amt.Quo(types.ConversionFactor()) + integerBurnAmount := amt.Quo(types.ConversionFactor(extendedDecimals)) if integerBurnAmount.IsPositive() { - integerBurnCoin := sdk.NewCoin(types.IntegerCoinDenom(), integerBurnAmount) + integerBurnCoin := sdk.NewCoin(integerDenom, integerBurnAmount) if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(integerBurnCoin)); err != nil { return err } @@ -100,8 +103,8 @@ func (k Keeper) burnExtendedCoin( // ------------------------------------------------------------------------- // Pure stateless calculations - integerBurnAmount := amt.Quo(types.ConversionFactor()) - fractionalBurnAmount := amt.Mod(types.ConversionFactor()) + integerBurnAmount := amt.Quo(types.ConversionFactor(extendedDecimals)) + fractionalBurnAmount := amt.Mod(types.ConversionFactor(extendedDecimals)) // newFractionalBalance can be negative if fractional balance is insufficient. newFractionalBalance := prevFractionalBalance.Sub(fractionalBurnAmount) @@ -115,7 +118,7 @@ func (k Keeper) burnExtendedCoin( // If true, remainder has accumulated enough fractional amounts to burn 1 // integer coin. - overflowingRemainder := newRemainder.GTE(types.ConversionFactor()) + overflowingRemainder := newRemainder.GTE(types.ConversionFactor(extendedDecimals)) // ------------------------------------------------------------------------- // Stateful operations for burn @@ -131,8 +134,8 @@ func (k Keeper) burnExtendedCoin( // Case #1: (optimization) direct burn instead of borrow (reserve transfer) // & reserve burn. No additional reserve burn would be necessary after this. if requiresBorrow && overflowingRemainder { - newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor()) - newRemainder = newRemainder.Sub(types.ConversionFactor()) + newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor(extendedDecimals)) + newRemainder = newRemainder.Sub(types.ConversionFactor(extendedDecimals)) integerBurnAmount = integerBurnAmount.AddRaw(1) } @@ -140,13 +143,13 @@ func (k Keeper) burnExtendedCoin( // Case #2: Transfer 1 integer coin to reserve for integer borrow to ensure // reserve fully backs the fractional amount. if requiresBorrow && !overflowingRemainder { - newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor()) + newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor(extendedDecimals)) // Transfer 1 integer coin to reserve to cover the borrowed fractional // amount. SendCoinsFromModuleToModule will return an error if the // module account has insufficient funds and an error with the full // extended balance will be returned. - borrowCoin := sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.OneInt()) + borrowCoin := sdk.NewCoin(integerDenom, sdkmath.OneInt()) if err := k.bk.SendCoinsFromModuleToModule( ctx, moduleName, @@ -160,12 +163,12 @@ func (k Keeper) burnExtendedCoin( // Case #3: Does not require borrow, but remainder has accumulated enough // fractional amounts to burn 1 integer coin. if !requiresBorrow && overflowingRemainder { - reserveBurnCoins := sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.OneInt())) + reserveBurnCoins := sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.OneInt())) if err := k.bk.BurnCoins(ctx, types.ModuleName, reserveBurnCoins); err != nil { return fmt.Errorf("failed to burn %s for reserve: %w", reserveBurnCoins, err) } - newRemainder = newRemainder.Sub(types.ConversionFactor()) + newRemainder = newRemainder.Sub(types.ConversionFactor(extendedDecimals)) } // Case #4: No additional work required, no borrow needed and no additional @@ -174,7 +177,7 @@ func (k Keeper) burnExtendedCoin( // Burn the integer amount - this may include the extra optimization burn // from case #1 if !integerBurnAmount.IsZero() { - coin := sdk.NewCoin(types.IntegerCoinDenom(), integerBurnAmount) + coin := sdk.NewCoin(integerDenom, integerBurnAmount) if err := k.bk.BurnCoins(ctx, moduleName, sdk.NewCoins(coin)); err != nil { return k.updateInsufficientFundsError(ctx, moduleAddr, amt, err) } diff --git a/x/precisebank/keeper/burn_test.go b/x/precisebank/keeper/burn_test.go index 4905b916b..19e1cb683 100644 --- a/x/precisebank/keeper/burn_test.go +++ b/x/precisebank/keeper/burn_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -18,94 +19,108 @@ import ( const burnerModuleName = "burner-module" func TestBurnCoins_PanicValidations(t *testing.T) { - td := newMockedTestData(t) - // panic tests for invalid inputs + + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + integerCoinDenom := coinInfo.GetDenom() + extendedCoinDenom := coinInfo.GetExtendedDenom() + tests := []struct { name string recipientModule string - setupFn func(td testData) - burnAmount sdk.Coins + setupFn func(td testData) sdk.Coins // Return coins after EVM setup wantPanic string }{ { "invalid module", "notamodule", - func(td testData) { - // Make module not found + func(td testData) sdk.Coins { + // Make module not found - this will panic before GetModuleAddress is called td.ak.EXPECT(). GetModuleAccount(td.ctx, "notamodule"). Return(nil). Once() + return cs(c(extendedCoinDenom, 1000)) }, - cs(c(types.IntegerCoinDenom(), 1000)), "module account notamodule does not exist: unknown address", }, { "no permission", burnerModuleName, - func(td testData) { + func(td testData) sdk.Coins { + moduleAddr := sdk.AccAddress{1} + // This will panic before GetModuleAddress is called td.ak.EXPECT(). GetModuleAccount(td.ctx, burnerModuleName). Return(authtypes.NewModuleAccount( - authtypes.NewBaseAccountWithAddress(sdk.AccAddress{1}), + authtypes.NewBaseAccountWithAddress(moduleAddr), burnerModuleName, // no burn permission )). Once() + return cs(c(extendedCoinDenom, 1000)) }, - cs(c(types.IntegerCoinDenom(), 1000)), fmt.Sprintf("module account %s does not have permissions to burn tokens: unauthorized", burnerModuleName), }, { "has burn permission", burnerModuleName, - func(td testData) { + func(td testData) sdk.Coins { + moduleAddr := sdk.AccAddress{1} + // This case succeeds and calls burnExtendedCoin, which calls GetModuleAddress once + td.ak.EXPECT(). + GetModuleAddress(burnerModuleName). + Return(moduleAddr). + Once() + td.ak.EXPECT(). GetModuleAccount(td.ctx, burnerModuleName). Return(authtypes.NewModuleAccount( - authtypes.NewBaseAccountWithAddress(sdk.AccAddress{1}), + authtypes.NewBaseAccountWithAddress(moduleAddr), burnerModuleName, // includes burner permission authtypes.Burner, )). Once() - // Will call x/bank BurnCoins coins + coins := cs(c(extendedCoinDenom, 1000)) + // Will call burnExtendedCoin which calls GetModuleAddress + // Also need to borrow 1 integer coin to cover the fractional burn + borrowCoin := cs(c(integerCoinDenom, 1)) td.bk.EXPECT(). - BurnCoins(td.ctx, burnerModuleName, cs(c(types.IntegerCoinDenom(), 1000))). + SendCoinsFromModuleToModule(td.ctx, burnerModuleName, types.ModuleName, borrowCoin). Return(nil). Once() + return coins }, - cs(c(types.IntegerCoinDenom(), 1000)), "", }, { "disallow burning from x/precisebank", types.ModuleName, - func(td testData) { - // No mock setup needed since this is checked before module - // account checks + func(td testData) sdk.Coins { + // No expectations needed - this should panic before any module address calls + return cs(c(extendedCoinDenom, 1000)) }, - cs(c(types.IntegerCoinDenom(), 1000)), "module account precisebank cannot be burned from: unauthorized", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - tt.setupFn(td) + td := newMockedTestData(t) + burnAmount := tt.setupFn(td) if tt.wantPanic != "" { require.PanicsWithError(t, tt.wantPanic, func() { - _ = td.keeper.BurnCoins(td.ctx, tt.recipientModule, tt.burnAmount) + _ = td.keeper.BurnCoins(td.ctx, tt.recipientModule, burnAmount) }) return } require.NotPanics(t, func() { // Not testing errors, only panics for this test - _ = td.keeper.BurnCoins(td.ctx, tt.recipientModule, tt.burnAmount) + _ = td.keeper.BurnCoins(td.ctx, tt.recipientModule, burnAmount) }) }) } @@ -114,6 +129,9 @@ func TestBurnCoins_PanicValidations(t *testing.T) { func TestBurnCoins_Errors(t *testing.T) { // returned errors, not panics + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + integerCoinDenom := coinInfo.GetDenom() + tests := []struct { name string recipientModule string @@ -137,10 +155,10 @@ func TestBurnCoins_Errors(t *testing.T) { Once() }, sdk.Coins{sdk.Coin{ - Denom: types.IntegerCoinDenom(), + Denom: integerCoinDenom, Amount: sdkmath.NewInt(-1000), }}, - fmt.Sprintf("-1000%s: invalid coins", types.IntegerCoinDenom()), + fmt.Sprintf("-1000%s: invalid coins", integerCoinDenom), }, } diff --git a/x/precisebank/keeper/fractional_balance_test.go b/x/precisebank/keeper/fractional_balance_test.go index 89b7afd04..ffcfa4939 100644 --- a/x/precisebank/keeper/fractional_balance_test.go +++ b/x/precisebank/keeper/fractional_balance_test.go @@ -1,10 +1,12 @@ package keeper_test import ( + "fmt" "testing" "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -15,12 +17,13 @@ import ( func TestSetGetFractionalBalance(t *testing.T) { addr := sdk.AccAddress([]byte("test-address")) + extendedDecimals := testconfig.DefaultChainConfig.EvmConfig.CoinInfo.ExtendedDecimals tests := []struct { - name string - address sdk.AccAddress - amount sdkmath.Int - setPanicMsg string + name string + address sdk.AccAddress + amount sdkmath.Int // Function to compute amount after EVM is configured + panicMsg string }{ { "valid - min amount", @@ -37,7 +40,7 @@ func TestSetGetFractionalBalance(t *testing.T) { { "valid - max amount", addr, - types.ConversionFactor().SubRaw(1), + types.ConversionFactor(extendedDecimals).SubRaw(1), "", }, { @@ -55,8 +58,8 @@ func TestSetGetFractionalBalance(t *testing.T) { { "invalid - over max amount", addr, - types.ConversionFactor(), - "amount is invalid: amount 1000000000000 exceeds max of 999999999999", + types.ConversionFactor(extendedDecimals), + fmt.Sprintf("amount is invalid: amount %s exceeds max of %s", types.ConversionFactor(extendedDecimals).String(), types.ConversionFactor(extendedDecimals).SubRaw(1).String()), }, } @@ -65,8 +68,8 @@ func TestSetGetFractionalBalance(t *testing.T) { td := newMockedTestData(t) ctx, k := td.ctx, td.keeper - if tt.setPanicMsg != "" { - require.PanicsWithError(t, tt.setPanicMsg, func() { + if tt.panicMsg != "" { + require.PanicsWithError(t, tt.panicMsg, func() { k.SetFractionalBalance(ctx, tt.address, tt.amount) }) diff --git a/x/precisebank/keeper/grpc_query.go b/x/precisebank/keeper/grpc_query.go index c95b6b4ec..5b0e568cd 100644 --- a/x/precisebank/keeper/grpc_query.go +++ b/x/precisebank/keeper/grpc_query.go @@ -27,7 +27,8 @@ func (s queryServer) Remainder( ctx := sdk.UnwrapSDKContext(goCtx) remainder := s.keeper.GetRemainderAmount(ctx) - remainderCoin := sdk.NewCoin(types.ExtendedCoinDenom(), remainder) + coinInfo := s.keeper.GetCoinInfo() + remainderCoin := sdk.NewCoin(coinInfo.GetExtendedDenom(), remainder) return &types.QueryRemainderResponse{ Remainder: remainderCoin, @@ -47,7 +48,8 @@ func (s queryServer) FractionalBalance( } amt := s.keeper.GetFractionalBalance(ctx, address) - fractionalBalance := sdk.NewCoin(types.ExtendedCoinDenom(), amt) + coinInfo := s.keeper.GetCoinInfo() + fractionalBalance := sdk.NewCoin(coinInfo.GetExtendedDenom(), amt) return &types.QueryFractionalBalanceResponse{ FractionalBalance: fractionalBalance, diff --git a/x/precisebank/keeper/keeper.go b/x/precisebank/keeper/keeper.go index 1185ea518..ef13b19dc 100644 --- a/x/precisebank/keeper/keeper.go +++ b/x/precisebank/keeper/keeper.go @@ -22,6 +22,8 @@ type Keeper struct { bk types.BankKeeper ak types.AccountKeeper + + ci evmtypes.EvmCoinInfo } // NewKeeper creates a new keeper @@ -30,12 +32,14 @@ func NewKeeper( storeKey storetypes.StoreKey, bk types.BankKeeper, ak types.AccountKeeper, + ci evmtypes.EvmCoinInfo, ) Keeper { return Keeper{ cdc: cdc, storeKey: storeKey, bk: bk, ak: ak, + ci: ci, } } @@ -48,3 +52,7 @@ func (k Keeper) IterateTotalSupply(ctx context.Context, cb func(coin sdk.Coin) b func (k Keeper) GetSupply(ctx context.Context, denom string) sdk.Coin { return k.bk.GetSupply(ctx, denom) } + +func (k Keeper) GetCoinInfo() evmtypes.EvmCoinInfo { + return k.ci +} diff --git a/x/precisebank/keeper/keeper_test.go b/x/precisebank/keeper/keeper_test.go index 75a4656ef..95766dee6 100644 --- a/x/precisebank/keeper/keeper_test.go +++ b/x/precisebank/keeper/keeper_test.go @@ -4,8 +4,7 @@ import ( "testing" evmosencoding "github.com/cosmos/evm/encoding" - "github.com/cosmos/evm/testutil/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/keeper" "github.com/cosmos/evm/x/precisebank/types" "github.com/cosmos/evm/x/precisebank/types/mocks" @@ -40,14 +39,13 @@ func newMockedTestData(t *testing.T) testData { bk := mocks.NewBankKeeper(t) ak := mocks.NewAccountKeeper(t) - chainID := testconstants.SixDecimalsChainID.EVMChainID + // Use consistent chain configuration - SixDecimalsChainConfig for precisebank tests + chainConfig := testconfig.SixDecimalsChainConfig + chainID := chainConfig.EvmConfig.ChainConfig.ChainId + ci := chainConfig.EvmConfig.CoinInfo cfg := evmosencoding.MakeConfig(chainID) cdc := cfg.Codec - k := keeper.NewKeeper(cdc, storeKey, bk, ak) - err := config.EvmAppOptions(chainID) - if err != nil { - return testData{} - } + k := keeper.NewKeeper(cdc, storeKey, bk, ak, *ci) return testData{ ctx: ctx, diff --git a/x/precisebank/keeper/mint.go b/x/precisebank/keeper/mint.go index 2b3ca4496..c4c933474 100644 --- a/x/precisebank/keeper/mint.go +++ b/x/precisebank/keeper/mint.go @@ -45,10 +45,11 @@ func (k Keeper) MintCoins(goCtx context.Context, moduleName string, amt sdk.Coin // Get non-ExtendedCoinDenom coins passthroughCoins := amt - extendedAmount := amt.AmountOf(types.ExtendedCoinDenom()) + coinInfo := k.GetCoinInfo() + extendedAmount := amt.AmountOf(coinInfo.GetExtendedDenom()) if extendedAmount.IsPositive() { // Remove ExtendedCoinDenom from the coins as it is managed by x/precisebank - removeCoin := sdk.NewCoin(types.ExtendedCoinDenom(), extendedAmount) + removeCoin := sdk.NewCoin(coinInfo.GetExtendedDenom(), extendedAmount) passthroughCoins = amt.Sub(removeCoin) } @@ -91,14 +92,15 @@ func (k Keeper) mintExtendedCoin( amt sdkmath.Int, ) error { moduleAddr := k.ak.GetModuleAddress(recipientModuleName) + coinInfo := k.GetCoinInfo() // Don't create fractional balances for the precisebank module account itself // The precisebank module account is the reserve and should not have fractional balances if recipientModuleName == types.ModuleName { // For the precisebank module account, just mint the integer coins directly - integerMintAmount := amt.Quo(types.ConversionFactor()) + integerMintAmount := amt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)) if integerMintAmount.IsPositive() { - integerMintCoin := sdk.NewCoin(types.IntegerCoinDenom(), integerMintAmount) + integerMintCoin := sdk.NewCoin(coinInfo.GetDenom(), integerMintAmount) if err := k.bk.MintCoins(ctx, recipientModuleName, sdk.NewCoins(integerMintCoin)); err != nil { return err } @@ -110,8 +112,8 @@ func (k Keeper) mintExtendedCoin( fractionalAmount := k.GetFractionalBalance(ctx, moduleAddr) // Get separated mint amounts - integerMintAmount := amt.Quo(types.ConversionFactor()) - fractionalMintAmount := amt.Mod(types.ConversionFactor()) + integerMintAmount := amt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)) + fractionalMintAmount := amt.Mod(types.ConversionFactor(coinInfo.ExtendedDecimals)) // Get previous remainder amount, as we need to it before carry calculation // for the optimization path. @@ -133,11 +135,11 @@ func (k Keeper) mintExtendedCoin( newFractionalBalance := fractionalAmount.Add(fractionalMintAmount) // Case #3 - Integer carry, remainder is sufficient (0 or positive) - if newFractionalBalance.GTE(types.ConversionFactor()) && newRemainder.GTE(sdkmath.ZeroInt()) { + if newFractionalBalance.GTE(types.ConversionFactor(coinInfo.ExtendedDecimals)) && newRemainder.GTE(sdkmath.ZeroInt()) { // Carry should send from reserve -> account, instead of minting an // extra integer coin. Otherwise doing an extra mint will require a burn // from reserves to maintain exact backing. - carryCoin := sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.OneInt()) + carryCoin := sdk.NewCoin(coinInfo.GetDenom(), sdkmath.OneInt()) // SendCoinsFromModuleToModule allows for sending coins even if the // recipient module account is blocked. @@ -154,7 +156,7 @@ func (k Keeper) mintExtendedCoin( // Case #4 - Integer carry, remainder is insufficient // This is the optimization path where the integer mint amount is increased // by 1, instead of doing both a reserve -> account transfer and reserve mint. - if newFractionalBalance.GTE(types.ConversionFactor()) && newRemainder.IsNegative() { + if newFractionalBalance.GTE(types.ConversionFactor(coinInfo.ExtendedDecimals)) && newRemainder.IsNegative() { integerMintAmount = integerMintAmount.AddRaw(1) } @@ -163,16 +165,16 @@ func (k Keeper) mintExtendedCoin( // fractional amounts x and y where both x and y < ConversionFactor // x + y < (2 * ConversionFactor) - 2 // x + y < 1 integer amount + fractional amount - if newFractionalBalance.GTE(types.ConversionFactor()) { + if newFractionalBalance.GTE(types.ConversionFactor(coinInfo.ExtendedDecimals)) { // Subtract 1 integer equivalent amount of fractional balance. Same // behavior as using .Mod() in this case. - newFractionalBalance = newFractionalBalance.Sub(types.ConversionFactor()) + newFractionalBalance = newFractionalBalance.Sub(types.ConversionFactor(coinInfo.ExtendedDecimals)) } // Mint new integer amounts in x/bank - including carry over from fractional // amount if any. if integerMintAmount.IsPositive() { - integerMintCoin := sdk.NewCoin(types.IntegerCoinDenom(), integerMintAmount) + integerMintCoin := sdk.NewCoin(coinInfo.GetDenom(), integerMintAmount) if err := k.bk.MintCoins( ctx, @@ -197,10 +199,10 @@ func (k Keeper) mintExtendedCoin( // Optimization: This is only done when the integer amount does NOT carry, // as a direct account mint is done instead of integer carry transfer + // insufficient remainder reserve mint. - wasCarried := fractionalAmount.Add(fractionalMintAmount).GTE(types.ConversionFactor()) + wasCarried := fractionalAmount.Add(fractionalMintAmount).GTE(types.ConversionFactor(coinInfo.ExtendedDecimals)) if prevRemainder.LT(fractionalMintAmount) && !wasCarried { // Always only 1 integer coin, as fractionalMintAmount < ConversionFactor - reserveMintCoins := sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.OneInt())) + reserveMintCoins := sdk.NewCoins(sdk.NewCoin(coinInfo.GetDenom(), sdkmath.OneInt())) if err := k.bk.MintCoins(ctx, types.ModuleName, reserveMintCoins); err != nil { return fmt.Errorf("failed to mint %s for reserve: %w", reserveMintCoins, err) } @@ -210,7 +212,7 @@ func (k Keeper) mintExtendedCoin( // This needs to be adjusted back to the corresponding positive value. The // remainder will be always < conversionFactor after add if it is negative. if newRemainder.IsNegative() { - newRemainder = newRemainder.Add(types.ConversionFactor()) + newRemainder = newRemainder.Add(types.ConversionFactor(coinInfo.ExtendedDecimals)) } k.SetRemainderAmount(ctx, newRemainder) diff --git a/x/precisebank/keeper/mint_test.go b/x/precisebank/keeper/mint_test.go index 3c0f9f93f..8ba35bc34 100644 --- a/x/precisebank/keeper/mint_test.go +++ b/x/precisebank/keeper/mint_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -17,6 +18,7 @@ import ( func TestMintCoins_PanicValidations(t *testing.T) { // panic tests for invalid inputs + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() tests := []struct { name string @@ -35,7 +37,7 @@ func TestMintCoins_PanicValidations(t *testing.T) { Return(nil). Once() }, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "module account notamodule does not exist: unknown address", }, { @@ -51,7 +53,7 @@ func TestMintCoins_PanicValidations(t *testing.T) { )). Once() }, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "module account mint does not have permissions to mint tokens: unauthorized", }, { @@ -70,11 +72,11 @@ func TestMintCoins_PanicValidations(t *testing.T) { // Will call x/bank MintCoins coins td.bk.EXPECT(). - MintCoins(td.ctx, minttypes.ModuleName, cs(c(types.IntegerCoinDenom(), 1000))). + MintCoins(td.ctx, minttypes.ModuleName, cs(c(integerDenom, 1000))). Return(nil). Once() }, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "", }, { @@ -84,7 +86,7 @@ func TestMintCoins_PanicValidations(t *testing.T) { // No mock setup needed since this is checked before module // account checks }, - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), "module account precisebank cannot be minted to: unauthorized", }, } @@ -112,6 +114,8 @@ func TestMintCoins_PanicValidations(t *testing.T) { func TestMintCoins_Errors(t *testing.T) { // returned errors, not panics + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() + tests := []struct { name string recipientModule string @@ -135,10 +139,10 @@ func TestMintCoins_Errors(t *testing.T) { Once() }, sdk.Coins{sdk.Coin{ - Denom: types.IntegerCoinDenom(), + Denom: integerDenom, Amount: sdkmath.NewInt(-1000), }}, - fmt.Sprintf("-1000%s: invalid coins", types.IntegerCoinDenom()), + fmt.Sprintf("-1000%s: invalid coins", integerDenom), }, } @@ -165,6 +169,10 @@ func TestMintCoins_Errors(t *testing.T) { func TestMintCoins_ExpectedCalls(t *testing.T) { // Tests the expected calls to the bank keeper when minting coins + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string // Only care about starting fractional balance. @@ -177,7 +185,7 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { { "passthrough mint - integer denom", sdkmath.ZeroInt(), - cs(c(types.IntegerCoinDenom(), 1000)), + cs(c(integerDenom, 1000)), sdkmath.ZeroInt(), }, @@ -190,41 +198,41 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { { "no carry - 0 starting fractional", sdkmath.ZeroInt(), - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), sdkmath.NewInt(1000), }, { "no carry - non-zero fractional", sdkmath.NewInt(1_000_000), - cs(c(types.ExtendedCoinDenom(), 1000)), + cs(c(extendedDenom, 1000)), sdkmath.NewInt(1_001_000), }, { "fractional carry", // max fractional amount - types.ConversionFactor().SubRaw(1), - cs(c(types.ExtendedCoinDenom(), 1)), // +1 to carry + types.ConversionFactor(extendedDecimals).SubRaw(1), + cs(c(extendedDenom, 1)), // +1 to carry sdkmath.ZeroInt(), }, { "fractional carry max", // max fractional amount + max fractional amount - types.ConversionFactor().SubRaw(1), - cs(ci(types.ExtendedCoinDenom(), types.ConversionFactor().SubRaw(1))), - types.ConversionFactor().SubRaw(2), + types.ConversionFactor(extendedDecimals).SubRaw(1), + cs(ci(extendedDenom, types.ConversionFactor(extendedDecimals).SubRaw(1))), + types.ConversionFactor(extendedDecimals).SubRaw(2), }, { "integer with fractional no carry", sdkmath.NewInt(1234), // mint 100 fractional - cs(c(types.ExtendedCoinDenom(), 100)), + cs(c(extendedDenom, 100)), sdkmath.NewInt(1234 + 100), }, { "integer with fractional carry", - types.ConversionFactor().SubRaw(100), + types.ConversionFactor(extendedDecimals).SubRaw(100), // mint 105 fractional to carry - cs(c(types.ExtendedCoinDenom(), 105)), + cs(c(extendedDenom, 105)), sdkmath.NewInt(5), }, } @@ -264,20 +272,20 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { // Determine how much is passed through to x/bank passthroughCoins := tt.mintAmount - found, extCoins := tt.mintAmount.Find(types.ExtendedCoinDenom()) + found, extCoins := tt.mintAmount.Find(extendedDenom) if found { // Remove extended coin from passthrough coins passthroughCoins = passthroughCoins.Sub(extCoins) } else { - extCoins = sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.ZeroInt()) + extCoins = sdk.NewCoin(extendedDenom, sdkmath.ZeroInt()) } require.Equalf( t, sdkmath.ZeroInt(), - passthroughCoins.AmountOf(types.ExtendedCoinDenom()), + passthroughCoins.AmountOf(extendedDenom), "expected pass through coins should not include %v", - types.ExtendedCoinDenom(), + extendedDenom, ) // ---------------------------------------- @@ -295,15 +303,15 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { // ---------------------------------------- // Set expectations for reserve minting when fractional amounts // are minted & remainder is insufficient - mintFractionalAmount := extCoins.Amount.Mod(types.ConversionFactor()) + mintFractionalAmount := extCoins.Amount.Mod(types.ConversionFactor(extendedDecimals)) currentRemainder := td.keeper.GetRemainderAmount(td.ctx) - causesIntegerCarry := fBal.Add(mintFractionalAmount).GTE(types.ConversionFactor()) + causesIntegerCarry := fBal.Add(mintFractionalAmount).GTE(types.ConversionFactor(extendedDecimals)) remainderEnough := currentRemainder.GTE(mintFractionalAmount) // Optimization: Carry & insufficient remainder is directly minted if causesIntegerCarry && !remainderEnough { - extCoins = extCoins.AddAmount(types.ConversionFactor()) + extCoins = extCoins.AddAmount(types.ConversionFactor(extendedDecimals)) } // ---------------------------------------- @@ -315,10 +323,10 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { Once() // Initial integer balance is always 0 for this test - mintIntegerAmount := extCoins.Amount.Quo(types.ConversionFactor()) + mintIntegerAmount := extCoins.Amount.Quo(types.ConversionFactor(extendedDecimals)) // Minted coins does NOT include roll-over, simply excludes - mintCoins := cs(ci(types.IntegerCoinDenom(), mintIntegerAmount)) + mintCoins := cs(ci(integerDenom, mintIntegerAmount)) // Only expect MintCoins to be called with mint coins with // non-zero amount. @@ -339,14 +347,14 @@ func TestMintCoins_ExpectedCalls(t *testing.T) { td.ctx, types.ModuleName, minttypes.ModuleName, - cs(c(types.IntegerCoinDenom(), 1)), + cs(c(integerDenom, 1)), ). Return(nil). Once() } if !remainderEnough && !causesIntegerCarry { - reserveMintCoins := cs(c(types.IntegerCoinDenom(), 1)) + reserveMintCoins := cs(c(integerDenom, 1)) td.bk.EXPECT(). // Mints to x/precisebank MintCoins(td.ctx, types.ModuleName, reserveMintCoins). diff --git a/x/precisebank/keeper/remainder_amount.go b/x/precisebank/keeper/remainder_amount.go index 0c4eacdfd..e49cf4e35 100644 --- a/x/precisebank/keeper/remainder_amount.go +++ b/x/precisebank/keeper/remainder_amount.go @@ -44,7 +44,8 @@ func (k *Keeper) SetRemainderAmount( // Ensure the remainder is valid before setting it. Follows the same // validation as FractionalBalance with the same value range. - if err := types.ValidateFractionalAmount(amount); err != nil { + extendedDecimals := k.GetCoinInfo().ExtendedDecimals + if err := types.ValidateFractionalAmount(amount, extendedDecimals); err != nil { panic(fmt.Errorf("remainder amount is invalid: %w", err)) } diff --git a/x/precisebank/keeper/remainder_amount_test.go b/x/precisebank/keeper/remainder_amount_test.go index 98e1c3c37..52baf02ee 100644 --- a/x/precisebank/keeper/remainder_amount_test.go +++ b/x/precisebank/keeper/remainder_amount_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -36,6 +37,9 @@ func TestInvalidRemainderAmount(t *testing.T) { tk := newMockedTestData(t) ctx, k := tk.ctx, tk.keeper + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals + // Set negative amount require.PanicsWithError(t, "remainder amount is invalid: non-positive amount -1", func() { k.SetRemainderAmount(ctx, sdkmath.NewInt(-1)) @@ -43,7 +47,7 @@ func TestInvalidRemainderAmount(t *testing.T) { // Set amount over max require.PanicsWithError(t, "remainder amount is invalid: amount 1000000000000 exceeds max of 999999999999", func() { - k.SetRemainderAmount(ctx, types.ConversionFactor()) + k.SetRemainderAmount(ctx, types.ConversionFactor(extendedDecimals)) }) } diff --git a/x/precisebank/keeper/send.go b/x/precisebank/keeper/send.go index 938622925..0b1e2dc9d 100644 --- a/x/precisebank/keeper/send.go +++ b/x/precisebank/keeper/send.go @@ -8,10 +8,10 @@ import ( "github.com/hashicorp/go-metrics" "github.com/cosmos/evm/x/precisebank/types" - evmtypes "github.com/cosmos/evm/x/vm/types" errorsmod "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" + evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" @@ -43,8 +43,8 @@ func (k Keeper) IsSendEnabledCoins(ctx context.Context, coins ...sdk.Coin) error // it also checks for the SendEnabled status on the EVM denom. The rest pass through the // regular bank keeper implementation. func (k Keeper) IsSendEnabledCoin(ctx context.Context, coin sdk.Coin) bool { - if coin.Denom == evmtypes.GetEVMCoinExtendedDenom() { - return k.bk.IsSendEnabledCoin(ctx, sdk.NewCoin(evmtypes.GetEVMCoinDenom(), coin.Amount.Quo(types.ConversionFactor()))) + if coin.Denom == k.GetCoinInfo().GetExtendedDenom() { + return k.bk.IsSendEnabledCoin(ctx, sdk.NewCoin(k.GetCoinInfo().GetDenom(), coin.Amount.Quo(types.ConversionFactor(k.GetCoinInfo().ExtendedDecimals)))) } return k.bk.IsSendEnabledCoin(ctx, coin) } @@ -68,11 +68,12 @@ func (k Keeper) SendCoins( } passthroughCoins := amt - extendedCoinAmount := amt.AmountOf(types.ExtendedCoinDenom()) + coinInfo := k.GetCoinInfo() + extendedCoinAmount := amt.AmountOf(coinInfo.GetExtendedDenom()) // Remove the extended coin amount from the passthrough coins if extendedCoinAmount.IsPositive() { - subCoin := sdk.NewCoin(types.ExtendedCoinDenom(), extendedCoinAmount) + subCoin := sdk.NewCoin(coinInfo.GetExtendedDenom(), extendedCoinAmount) passthroughCoins = amt.Sub(subCoin) } @@ -130,11 +131,13 @@ func (k Keeper) sendExtendedCoins( // Don't create fractional balances for the precisebank module account // The precisebank module account is the reserve and should not have fractional balances moduleAddr := k.ak.GetModuleAddress(types.ModuleName) + coinInfo := k.GetCoinInfo() + if from.Equals(moduleAddr) || to.Equals(moduleAddr) { // For transfers involving the precisebank module account, just do the integer transfer - integerAmt := amt.Quo(types.ConversionFactor()) + integerAmt := amt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)) if integerAmt.IsPositive() { - transferCoin := sdk.NewCoin(types.IntegerCoinDenom(), integerAmt) + transferCoin := sdk.NewCoin(coinInfo.GetDenom(), integerAmt) if err := k.bk.SendCoins(ctx, from, to, sdk.NewCoins(transferCoin)); err != nil { return k.updateInsufficientFundsError(ctx, from, amt, err) } @@ -166,12 +169,12 @@ func (k Keeper) sendExtendedCoins( // ------------------------------------------------------------------------- // Pure stateless calculations - integerAmt := amt.Quo(types.ConversionFactor()) - fractionalAmt := amt.Mod(types.ConversionFactor()) + integerAmt := amt.Quo(types.ConversionFactor(coinInfo.ExtendedDecimals)) + fractionalAmt := amt.Mod(types.ConversionFactor(coinInfo.ExtendedDecimals)) // Account new fractional balances - senderNewFracBal, senderNeedsBorrow := subFromFractionalBalance(senderFracBal, fractionalAmt) - recipientNewFracBal, recipientNeedsCarry := addToFractionalBalance(recipientFracBal, fractionalAmt) + senderNewFracBal, senderNeedsBorrow := subFromFractionalBalance(senderFracBal, fractionalAmt, coinInfo.ExtendedDecimals) + recipientNewFracBal, recipientNeedsCarry := addToFractionalBalance(recipientFracBal, fractionalAmt, coinInfo.ExtendedDecimals) // Case #1: Sender borrow, recipient carry if senderNeedsBorrow && recipientNeedsCarry { @@ -186,7 +189,7 @@ func (k Keeper) sendExtendedCoins( // Full integer amount transfer, including direct transfer of borrow/carry // if any. if integerAmt.IsPositive() { - transferCoin := sdk.NewCoin(types.IntegerCoinDenom(), integerAmt) + transferCoin := sdk.NewCoin(coinInfo.GetDenom(), integerAmt) if err := k.bk.SendCoins(ctx, from, to, sdk.NewCoins(transferCoin)); err != nil { return k.updateInsufficientFundsError(ctx, from, amt, err) } @@ -196,7 +199,7 @@ func (k Keeper) sendExtendedCoins( // Sender borrows by transferring 1 integer amount to reserve to account for // lack of fractional balance. if senderNeedsBorrow && !recipientNeedsCarry { - borrowCoin := sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1)) + borrowCoin := sdk.NewCoin(coinInfo.GetDenom(), sdkmath.NewInt(1)) if err := k.bk.SendCoinsFromAccountToModule( ctx, from, // sender borrowing @@ -219,7 +222,7 @@ func (k Keeper) sendExtendedCoins( // a SendCoins operation. Only SendCoinsFromModuleToAccount should check // blocked addrs which is done by the parent SendCoinsFromModuleToAccount // method. - carryCoin := sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1)) + carryCoin := sdk.NewCoin(coinInfo.GetDenom(), sdkmath.NewInt(1)) if err := k.bk.SendCoins( ctx, reserveAddr, @@ -255,13 +258,14 @@ func (k Keeper) sendExtendedCoins( func subFromFractionalBalance( currentFractionalBalance sdkmath.Int, amountToSub sdkmath.Int, + extendedDecimals evmtypes.Decimals, ) (sdkmath.Int, bool) { // Enforce that currentFractionalBalance is not a full balance. - if currentFractionalBalance.GTE(types.ConversionFactor()) { + if currentFractionalBalance.GTE(types.ConversionFactor(extendedDecimals)) { panic("currentFractionalBalance must be less than ConversionFactor") } - if amountToSub.GTE(types.ConversionFactor()) { + if amountToSub.GTE(types.ConversionFactor(extendedDecimals)) { panic("amountToSub must be less than ConversionFactor") } @@ -274,7 +278,7 @@ func subFromFractionalBalance( // Borrowing 1 integer equivalent amount of fractional coins. We need to // add 1 integer equivalent amount to the fractional balance otherwise // the new fractional balance will be negative. - newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor()) + newFractionalBalance = newFractionalBalance.Add(types.ConversionFactor(extendedDecimals)) } return newFractionalBalance, borrowRequired @@ -283,13 +287,17 @@ func subFromFractionalBalance( // addToFractionalBalance adds a fractional amount to the provided current // fractional balance, returning the new fractional balance and true if a carry // is required. -func addToFractionalBalance(currentFractionalBalance sdkmath.Int, amountToAdd sdkmath.Int) (sdkmath.Int, bool) { +func addToFractionalBalance( + currentFractionalBalance sdkmath.Int, + amountToAdd sdkmath.Int, + extendedDecimals evmtypes.Decimals, +) (sdkmath.Int, bool) { // Enforce that currentFractionalBalance is not a full balance. - if currentFractionalBalance.GTE(types.ConversionFactor()) { + if currentFractionalBalance.GTE(types.ConversionFactor(extendedDecimals)) { panic("currentFractionalBalance must be less than ConversionFactor") } - if amountToAdd.GTE(types.ConversionFactor()) { + if amountToAdd.GTE(types.ConversionFactor(extendedDecimals)) { panic("amountToAdd must be less than ConversionFactor") } @@ -297,11 +305,11 @@ func addToFractionalBalance(currentFractionalBalance sdkmath.Int, amountToAdd sd // New balance exceeds max fractional balance, so we need to carry it over // to the integer balance. - carryRequired := newFractionalBalance.GTE(types.ConversionFactor()) + carryRequired := newFractionalBalance.GTE(types.ConversionFactor(extendedDecimals)) if carryRequired { // Carry over to integer amount - newFractionalBalance = newFractionalBalance.Sub(types.ConversionFactor()) + newFractionalBalance = newFractionalBalance.Sub(types.ConversionFactor(extendedDecimals)) } return newFractionalBalance, carryRequired @@ -410,9 +418,10 @@ func (k Keeper) updateInsufficientFundsError( return err } + coinInfo := k.GetCoinInfo() // Check balance is sufficient - bal := k.SpendableCoin(ctx, addr, types.ExtendedCoinDenom()) - coin := sdk.NewCoin(types.ExtendedCoinDenom(), amt) + bal := k.SpendableCoin(ctx, addr, coinInfo.GetExtendedDenom()) + coin := sdk.NewCoin(coinInfo.GetExtendedDenom(), amt) // TODO: This checks spendable coins and returns error with spendable // coins, not full balance. If GetBalance() is modified to return the diff --git a/x/precisebank/keeper/view.go b/x/precisebank/keeper/view.go index b83f6ca4e..2ad2bc5b6 100644 --- a/x/precisebank/keeper/view.go +++ b/x/precisebank/keeper/view.go @@ -19,22 +19,25 @@ func (k Keeper) GetBalance( denom string, ) sdk.Coin { ctx := sdk.UnwrapSDKContext(goCtx) + integerDenom := k.GetCoinInfo().GetDenom() + extendedDenom := k.GetCoinInfo().GetExtendedDenom() + extendedDecimals := k.GetCoinInfo().ExtendedDecimals // Module balance should display as empty for extended denom. Module // balances are **only** for the reserve which backs the fractional // balances. Returning the backing balances if querying extended denom would // result in a double counting of the fractional balances. - if denom == types.ExtendedCoinDenom() && addr.Equals(k.ak.GetModuleAddress(types.ModuleName)) { + if denom == extendedDenom && addr.Equals(k.ak.GetModuleAddress(types.ModuleName)) { return sdk.NewCoin(denom, sdkmath.ZeroInt()) } // Pass through to x/bank for denoms except ExtendedCoinDenom - if denom != types.ExtendedCoinDenom() { + if denom != extendedDenom { return k.bk.GetBalance(ctx, addr, denom) } // x/bank for integer balance - full balance, including locked - integerCoins := k.bk.GetBalance(ctx, addr, types.IntegerCoinDenom()) + integerCoins := k.bk.GetBalance(ctx, addr, integerDenom) // x/precisebank for fractional balance fractionalAmount := k.GetFractionalBalance(ctx, addr) @@ -42,10 +45,10 @@ func (k Keeper) GetBalance( // (Integer * ConversionFactor) + Fractional fullAmount := integerCoins. Amount. - Mul(types.ConversionFactor()). + Mul(types.ConversionFactor(extendedDecimals)). Add(fractionalAmount) - return sdk.NewCoin(types.ExtendedCoinDenom(), fullAmount) + return sdk.NewCoin(extendedDenom, fullAmount) } func (k Keeper) IterateAccountBalances(ctx context.Context, account sdk.AccAddress, cb func(coin sdk.Coin) bool) { @@ -61,27 +64,30 @@ func (k Keeper) SpendableCoin( denom string, ) sdk.Coin { ctx := sdk.UnwrapSDKContext(goCtx) + integerDenom := k.GetCoinInfo().GetDenom() + extendedDenom := k.GetCoinInfo().GetExtendedDenom() + extendedDecimals := k.GetCoinInfo().ExtendedDecimals // Same as GetBalance, extended denom balances are transparent to consumers. - if denom == types.ExtendedCoinDenom() && addr.Equals(k.ak.GetModuleAddress(types.ModuleName)) { + if denom == extendedDenom && addr.Equals(k.ak.GetModuleAddress(types.ModuleName)) { return sdk.NewCoin(denom, sdkmath.ZeroInt()) } // Pass through to x/bank for denoms except ExtendedCoinDenom - if denom != types.ExtendedCoinDenom() { + if denom != extendedDenom { return k.bk.SpendableCoin(ctx, addr, denom) } // x/bank for integer balance - excluding locked - integerCoin := k.bk.SpendableCoin(ctx, addr, types.IntegerCoinDenom()) + integerCoin := k.bk.SpendableCoin(ctx, addr, integerDenom) // x/precisebank for fractional balance fractionalAmount := k.GetFractionalBalance(ctx, addr) // Spendable = (Integer * ConversionFactor) + Fractional fullAmount := integerCoin.Amount. - Mul(types.ConversionFactor()). + Mul(types.ConversionFactor(extendedDecimals)). Add(fractionalAmount) - return sdk.NewCoin(types.ExtendedCoinDenom(), fullAmount) + return sdk.NewCoin(extendedDenom, fullAmount) } diff --git a/x/precisebank/keeper/view_test.go b/x/precisebank/keeper/view_test.go index 6172a80dc..be17f7034 100644 --- a/x/precisebank/keeper/view_test.go +++ b/x/precisebank/keeper/view_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" @@ -17,6 +18,10 @@ import ( func TestKeeper_GetBalance(t *testing.T) { tk := newMockedTestData(t) + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string giveDenom string // queried denom for balance @@ -28,50 +33,50 @@ func TestKeeper_GetBalance(t *testing.T) { }{ { "extended denom - no fractional balance", - types.ExtendedCoinDenom(), + extendedDenom, // queried bank balance in uatom when querying for aatom - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_000_000_000_000)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_000_000_000_000)), }, { "extended denom - with fractional balance", - types.ExtendedCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + extendedDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.NewInt(100), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_000_000_000_100)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_000_000_000_100)), }, { "extended denom - only fractional balance", - types.ExtendedCoinDenom(), + extendedDenom, // no coins in bank, only fractional balance sdk.NewCoins(), sdkmath.NewInt(100), - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(100)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(100)), }, { "extended denom - max fractional balance", - types.ExtendedCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), - types.ConversionFactor().SubRaw(1), + extendedDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), + types.ConversionFactor(extendedDecimals).SubRaw(1), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_999_999_999_999)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_999_999_999_999)), }, { "non-extended denom - uatom returns uatom", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000)), + sdk.NewCoin(integerDenom, sdkmath.NewInt(1000)), }, { "non-extended denom - unaffected by fractional balance", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.NewInt(100), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000)), + sdk.NewCoin(integerDenom, sdkmath.NewInt(1000)), }, { "unrelated denom - no fractional", @@ -97,19 +102,19 @@ func TestKeeper_GetBalance(t *testing.T) { tk.keeper.SetFractionalBalance(tk.ctx, addr, tt.giveFractionalBal) // Checks address if its a reserve denom - if tt.giveDenom == types.ExtendedCoinDenom() { + if tt.giveDenom == extendedDenom { tk.ak.EXPECT().GetModuleAddress(types.ModuleName). Return(authtypes.NewModuleAddress(types.ModuleName)). Once() } - if tt.giveDenom == types.ExtendedCoinDenom() { + if tt.giveDenom == extendedDenom { // No balance pass through tk.bk.EXPECT(). - GetBalance(tk.ctx, addr, types.IntegerCoinDenom()). + GetBalance(tk.ctx, addr, integerDenom). RunAndReturn(func(_ context.Context, _ sdk.AccAddress, _ string) sdk.Coin { - amt := tt.giveBankBal.AmountOf(types.IntegerCoinDenom()) - return sdk.NewCoin(types.IntegerCoinDenom(), amt) + amt := tt.giveBankBal.AmountOf(integerDenom) + return sdk.NewCoin(integerDenom, amt) }). Once() } else { @@ -131,6 +136,10 @@ func TestKeeper_GetBalance(t *testing.T) { } func TestKeeper_SpendableCoin(t *testing.T) { + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + extendedDecimals := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.ExtendedDecimals + tests := []struct { name string giveDenom string // queried denom for balance @@ -142,50 +151,50 @@ func TestKeeper_SpendableCoin(t *testing.T) { }{ { "extended denom - no fractional balance", - types.ExtendedCoinDenom(), + extendedDenom, // queried bank balance in uatom when querying for aatom - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_000_000_000_000)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_000_000_000_000)), }, { "extended denom - with fractional balance", - types.ExtendedCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + extendedDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.NewInt(100), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_000_000_000_100)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_000_000_000_100)), }, { "extended denom - only fractional balance", - types.ExtendedCoinDenom(), + extendedDenom, // no coins in bank, only fractional balance sdk.NewCoins(), sdkmath.NewInt(100), - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(100)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(100)), }, { "extended denom - max fractional balance", - types.ExtendedCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), - types.ConversionFactor().SubRaw(1), + extendedDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), + types.ConversionFactor(extendedDecimals).SubRaw(1), // integer + fractional - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(1000_999_999_999_999)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(1000_999_999_999_999)), }, { "non-extended denom - uatom returns uatom", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.ZeroInt(), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000)), + sdk.NewCoin(integerDenom, sdkmath.NewInt(1000)), }, { "non-extended denom - unaffected by fractional balance", - types.IntegerCoinDenom(), - sdk.NewCoins(sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000))), + integerDenom, + sdk.NewCoins(sdk.NewCoin(integerDenom, sdkmath.NewInt(1000))), sdkmath.NewInt(100), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1000)), + sdk.NewCoin(integerDenom, sdkmath.NewInt(1000)), }, { "unrelated denom - no fractional", @@ -212,19 +221,19 @@ func TestKeeper_SpendableCoin(t *testing.T) { tk.keeper.SetFractionalBalance(tk.ctx, addr, tt.giveFractionalBal) // If its a reserve denom, module address is checked - if tt.giveDenom == types.ExtendedCoinDenom() { + if tt.giveDenom == extendedDenom { tk.ak.EXPECT().GetModuleAddress(types.ModuleName). Return(authtypes.NewModuleAddress(types.ModuleName)). Once() } - if tt.giveDenom == types.ExtendedCoinDenom() { + if tt.giveDenom == extendedDenom { // No balance pass through tk.bk.EXPECT(). - SpendableCoin(tk.ctx, addr, types.IntegerCoinDenom()). + SpendableCoin(tk.ctx, addr, integerDenom). RunAndReturn(func(_ context.Context, _ sdk.AccAddress, _ string) sdk.Coin { - amt := tt.giveBankBal.AmountOf(types.IntegerCoinDenom()) - return sdk.NewCoin(types.IntegerCoinDenom(), amt) + amt := tt.giveBankBal.AmountOf(integerDenom) + return sdk.NewCoin(integerDenom, amt) }). Once() } else { @@ -253,6 +262,9 @@ func TestHiddenReserve(t *testing.T) { moduleAddr := authtypes.NewModuleAddress(types.ModuleName) + integerDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetDenom() + extendedDenom := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo.GetExtendedDenom() + // No mock bankkeeper expectations, which means the zero coin is returned // directly for reserve address. So the mock bankkeeper doesn't need to have // a handler for getting underlying balance. @@ -264,13 +276,13 @@ func TestHiddenReserve(t *testing.T) { }{ { "aatom", - types.ExtendedCoinDenom(), - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.ZeroInt()), + extendedDenom, + sdk.NewCoin(extendedDenom, sdkmath.ZeroInt()), }, { "uatom", - types.IntegerCoinDenom(), - sdk.NewCoin(types.IntegerCoinDenom(), sdkmath.NewInt(1)), + integerDenom, + sdk.NewCoin(integerDenom, sdkmath.NewInt(1)), }, { "unrelated denom", @@ -282,7 +294,7 @@ func TestHiddenReserve(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // 2 calls for GetBalance and SpendableCoin, only for reserve coins - if tt.denom == types.ExtendedCoinDenom() { + if tt.denom == extendedDenom { tk.ak.EXPECT().GetModuleAddress(types.ModuleName). Return(moduleAddr). Twice() diff --git a/x/precisebank/testutil/fractional_balances.go b/x/precisebank/testutil/fractional_balances.go index 927183af3..c074332ab 100644 --- a/x/precisebank/testutil/fractional_balances.go +++ b/x/precisebank/testutil/fractional_balances.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" + evmtypes "github.com/cosmos/evm/x/vm/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" @@ -44,6 +45,7 @@ func randAccAddress() sdk.AccAddress { func GenerateEqualFractionalBalances( t *testing.T, count int, + extendedDecimals evmtypes.Decimals, ) types.FractionalBalances { t.Helper() @@ -69,11 +71,11 @@ func GenerateEqualFractionalBalances( // If it's 0, Validate() will error. // Why start at 2 instead of 1? We want to make sure its divisible // for the last account, more details below. - amt := randRange(2, types.ConversionFactor().Int64()) + amt := randRange(2, types.ConversionFactor(extendedDecimals).Int64()) amtInt := sdkmath.NewInt(amt) fb := types.NewFractionalBalance(addr, amtInt) - require.NoError(t, fb.Validate()) + require.NoError(t, fb.Validate(extendedDecimals)) fbs[i] = fb @@ -96,9 +98,9 @@ func GenerateEqualFractionalBalances( // Note that we only have this issue in tests since we want to calculate a // new valid remainder, but we only validate in the actual code. - amt := types.ConversionFactor(). - Sub(sum.Mod(types.ConversionFactor())). - Mod(types.ConversionFactor()) + amt := types.ConversionFactor(extendedDecimals). + Sub(sum.Mod(types.ConversionFactor(extendedDecimals))). + Mod(types.ConversionFactor(extendedDecimals)) // We only want to generate VALID FractionalBalances - zero would not be // valid, so let's just borrow half of the previous amount. We generated @@ -110,7 +112,7 @@ func GenerateEqualFractionalBalances( } fb := types.NewFractionalBalance(addr, amt) - require.NoError(t, fb.Validate()) + require.NoError(t, fb.Validate(extendedDecimals)) fbs[count-1] = fb @@ -119,10 +121,10 @@ func GenerateEqualFractionalBalances( for _, fb := range fbs { verificationSum = verificationSum.Add(fb.Amount) } - require.True(t, verificationSum.Mod(types.ConversionFactor()).IsZero()) + require.True(t, verificationSum.Mod(types.ConversionFactor(extendedDecimals)).IsZero()) // Also make sure no duplicate addresses - require.NoError(t, fbs.Validate()) + require.NoError(t, fbs.Validate(extendedDecimals)) return fbs } @@ -135,6 +137,7 @@ func GenerateEqualFractionalBalances( func GenerateEqualFractionalBalancesWithRemainder( t *testing.T, count int, + extendedDecimals evmtypes.Decimals, ) (types.FractionalBalances, sdkmath.Int) { t.Helper() @@ -143,7 +146,7 @@ func GenerateEqualFractionalBalancesWithRemainder( countWithRemainder := count + 1 // Generate 1 additional FractionalBalance so we can use one as remainder - fbs := GenerateEqualFractionalBalances(t, countWithRemainder) + fbs := GenerateEqualFractionalBalances(t, countWithRemainder, extendedDecimals) // Use the last one as remainder remainder := fbs[countWithRemainder-1].Amount diff --git a/x/precisebank/types/extended_balance_test.go b/x/precisebank/types/extended_balance_test.go index d0a013f1b..38a54e83a 100644 --- a/x/precisebank/types/extended_balance_test.go +++ b/x/precisebank/types/extended_balance_test.go @@ -5,9 +5,8 @@ import ( "github.com/stretchr/testify/require" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" - evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -15,12 +14,11 @@ import ( ) func TestSumExtendedCoin(t *testing.T) { - coinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] - configurator := evmtypes.NewEVMConfigurator() - err := configurator. - WithEVMCoinInfo(coinInfo). - Configure() - require.NoError(t, err) + chainConfig := testconfig.SixDecimalsChainConfig + coinInfo := chainConfig.EvmConfig.CoinInfo + integerDenom := coinInfo.GetDenom() + extendedDecimals := coinInfo.ExtendedDecimals + extendedDenom := coinInfo.GetExtendedDenom() tests := []struct { name string @@ -30,25 +28,25 @@ func TestSumExtendedCoin(t *testing.T) { { "empty", sdk.NewCoins(), - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.ZeroInt()), + sdk.NewCoin(extendedDenom, sdkmath.ZeroInt()), }, { "only integer", - sdk.NewCoins(sdk.NewInt64Coin(types.IntegerCoinDenom(), 100)), - sdk.NewCoin(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(100)), + sdk.NewCoins(sdk.NewInt64Coin(integerDenom, 100)), + sdk.NewCoin(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(100)), }, { "only extended", - sdk.NewCoins(sdk.NewInt64Coin(types.ExtendedCoinDenom(), 100)), - sdk.NewCoin(types.ExtendedCoinDenom(), sdkmath.NewInt(100)), + sdk.NewCoins(sdk.NewInt64Coin(extendedDenom, 100)), + sdk.NewCoin(extendedDenom, sdkmath.NewInt(100)), }, { "integer and extended", sdk.NewCoins( - sdk.NewInt64Coin(types.IntegerCoinDenom(), 100), - sdk.NewInt64Coin(types.ExtendedCoinDenom(), 100), + sdk.NewInt64Coin(integerDenom, 100), + sdk.NewInt64Coin(extendedDenom, 100), ), - sdk.NewCoin(types.ExtendedCoinDenom(), types.ConversionFactor().MulRaw(100).AddRaw(100)), + sdk.NewCoin(extendedDenom, types.ConversionFactor(extendedDecimals).MulRaw(100).AddRaw(100)), }, } diff --git a/x/precisebank/types/fractional_balance.go b/x/precisebank/types/fractional_balance.go index 6b2f883ff..fa23859de 100644 --- a/x/precisebank/types/fractional_balance.go +++ b/x/precisebank/types/fractional_balance.go @@ -14,28 +14,14 @@ import ( // fractional balance to integer balances. This is also 1 greater than the max // valid fractional amount (999_999_999_999): // 0 < FractionalBalance < conversionFactor -func ConversionFactor() sdkmath.Int { - return sdkmath.NewIntFromBigInt(evmtypes.GetEVMCoinDecimals().ConversionFactor().BigInt()) +func ConversionFactor(decimals evmtypes.Decimals) sdkmath.Int { + return sdkmath.NewIntFromBigInt(decimals.ConversionFactor().BigInt()) } -// IntegerCoinDenom is the denomination for integer coins that are managed by -// x/bank. This is the "true" denomination of the coin, and is also used for -// the reserve to back all fractional coins. -func IntegerCoinDenom() string { - return evmtypes.GetEVMCoinDenom() -} - -// ExtendedCoinDenom is the denomination for the extended IntegerCoinDenom. This -// not only represents the fractional balance, but the total balance of -// integer + fractional balances. -func ExtendedCoinDenom() string { - return evmtypes.GetEVMCoinExtendedDenom() -} - -// IsExtendedDenomSameAsIntegerDenom returns true if the extended denom is the same as the integer denom +// IsDenomSameAsExtendedDenom returns true if the denom is the same as the extended denom // This happens in 18-decimal chains where both denoms are identical -func IsExtendedDenomSameAsIntegerDenom() bool { - return IntegerCoinDenom() == ExtendedCoinDenom() +func IsDenomSameAsExtendedDenom(coinInfo evmtypes.EvmCoinInfo) bool { + return coinInfo.GetDenom() == coinInfo.GetExtendedDenom() } // FractionalBalance returns a new FractionalBalance with the given address and @@ -49,19 +35,19 @@ func NewFractionalBalance(address string, amount sdkmath.Int) FractionalBalance // Validate returns an error if the FractionalBalance has an invalid address or // negative amount. -func (fb FractionalBalance) Validate() error { +func (fb FractionalBalance) Validate(decimals evmtypes.Decimals) error { if _, err := sdk.AccAddressFromBech32(fb.Address); err != nil { return err } // Validate the amount with the FractionalAmount wrapper - return ValidateFractionalAmount(fb.Amount) + return ValidateFractionalAmount(fb.Amount, decimals) } // ValidateFractionalAmount checks if an sdkmath.Int is a valid fractional // amount, ensuring it is positive and less than or equal to the maximum // fractional amount. -func ValidateFractionalAmount(amt sdkmath.Int) error { +func ValidateFractionalAmount(amt sdkmath.Int, decimals evmtypes.Decimals) error { if amt.IsNil() { return fmt.Errorf("nil amount") } @@ -70,8 +56,9 @@ func ValidateFractionalAmount(amt sdkmath.Int) error { return fmt.Errorf("non-positive amount %v", amt) } - if amt.GTE(ConversionFactor()) { - return fmt.Errorf("amount %v exceeds max of %v", amt, ConversionFactor().SubRaw(1)) + convFactor := ConversionFactor(decimals) + if amt.GTE(convFactor) { + return fmt.Errorf("amount %v exceeds max of %v", amt, convFactor.SubRaw(1)) } return nil diff --git a/x/precisebank/types/fractional_balance_test.go b/x/precisebank/types/fractional_balance_test.go index 8bfc8c730..f39b84f36 100644 --- a/x/precisebank/types/fractional_balance_test.go +++ b/x/precisebank/types/fractional_balance_test.go @@ -6,13 +6,15 @@ import ( "github.com/stretchr/testify/require" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/types" sdkmath "cosmossdk.io/math" ) func TestConversionFactor_Immutable(t *testing.T) { - cf1 := types.ConversionFactor() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + cf1 := types.ConversionFactor(coinInfo.ExtendedDecimals) origInt64 := cf1.Int64() // Get the internal pointer to the big.Int without copying @@ -24,24 +26,26 @@ func TestConversionFactor_Immutable(t *testing.T) { require.Equal(t, origInt64+5, internalBigInt.Int64()) // Fetch the max amount again - cf2 := types.ConversionFactor() + cf2 := types.ConversionFactor(coinInfo.ExtendedDecimals) require.Equal(t, origInt64, cf2.Int64(), "conversion factor should be immutable") } func TestConversionFactor_Copied(t *testing.T) { - max1 := types.ConversionFactor().BigIntMut() - max2 := types.ConversionFactor().BigIntMut() + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo + max1 := types.ConversionFactor(coinInfo.ExtendedDecimals).BigIntMut() + max2 := types.ConversionFactor(coinInfo.ExtendedDecimals).BigIntMut() // Checks that the returned two pointers do not reference the same object require.NotSame(t, max1, max2, "max fractional amount should be copied") } func TestConversionFactor(t *testing.T) { + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo require.Equal( t, sdkmath.NewInt(1_000_000_000_000), - types.ConversionFactor(), + types.ConversionFactor(coinInfo.ExtendedDecimals), "conversion factor should have 12 decimal points", ) } @@ -70,6 +74,7 @@ func TestNewFractionalBalance(t *testing.T) { } func TestFractionalBalance_Validate(t *testing.T) { + coinInfo := testconfig.DefaultChainConfig.EvmConfig.CoinInfo tests := []struct { name string giveAddress string @@ -97,7 +102,7 @@ func TestFractionalBalance_Validate(t *testing.T) { { "valid - max balance", "cosmos1gpxd677pp8zr97xvy3pmgk70a9vcpagsprcjap", - types.ConversionFactor().SubRaw(1), + types.ConversionFactor(coinInfo.ExtendedDecimals).SubRaw(1), "", }, { @@ -133,7 +138,7 @@ func TestFractionalBalance_Validate(t *testing.T) { { "invalid - max amount + 1", "cosmos1gpxd677pp8zr97xvy3pmgk70a9vcpagsprcjap", - types.ConversionFactor(), + types.ConversionFactor(coinInfo.ExtendedDecimals), "amount 1000000000000 exceeds max of 999999999999", }, { @@ -147,7 +152,7 @@ func TestFractionalBalance_Validate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fb := types.NewFractionalBalance(tt.giveAddress, tt.giveAmount) - err := fb.Validate() + err := fb.Validate(coinInfo.ExtendedDecimals) if tt.wantErr == "" { require.NoError(t, err) diff --git a/x/precisebank/types/fractional_balances.go b/x/precisebank/types/fractional_balances.go index 656e47b32..75c614324 100644 --- a/x/precisebank/types/fractional_balances.go +++ b/x/precisebank/types/fractional_balances.go @@ -5,18 +5,19 @@ import ( "strings" sdkmath "cosmossdk.io/math" + evmtypes "github.com/cosmos/evm/x/vm/types" ) // FractionalBalances is a slice of FractionalBalance type FractionalBalances []FractionalBalance // Validate returns an error if any FractionalBalance in the slice is invalid. -func (fbs FractionalBalances) Validate() error { +func (fbs FractionalBalances) Validate(extendedDecimals evmtypes.Decimals) error { seenAddresses := make(map[string]struct{}) for _, fb := range fbs { // Individual FractionalBalance validation - if err := fb.Validate(); err != nil { + if err := fb.Validate(extendedDecimals); err != nil { return fmt.Errorf("invalid fractional balance for %s: %w", fb.Address, err) } diff --git a/x/precisebank/types/genesis.go b/x/precisebank/types/genesis.go index 167d94b58..9f05fe502 100644 --- a/x/precisebank/types/genesis.go +++ b/x/precisebank/types/genesis.go @@ -4,6 +4,7 @@ import ( "fmt" sdkmath "cosmossdk.io/math" + evmtypes "github.com/cosmos/evm/x/vm/types" ) // NewGenesisState creates a new genesis state. @@ -24,9 +25,9 @@ func DefaultGenesisState() *GenesisState { // Validate performs basic validation of genesis data returning an error for // any failed validation criteria. -func (gs *GenesisState) Validate() error { +func (gs *GenesisState) Validate(extendedDecimals evmtypes.Decimals) error { // Validate all FractionalBalances - if err := gs.Balances.Validate(); err != nil { + if err := gs.Balances.Validate(extendedDecimals); err != nil { return fmt.Errorf("invalid balances: %w", err) } @@ -39,8 +40,8 @@ func (gs *GenesisState) Validate() error { return fmt.Errorf("negative remainder amount %s", gs.Remainder) } - if gs.Remainder.GTE(ConversionFactor()) { - return fmt.Errorf("remainder %v exceeds max of %v", gs.Remainder, ConversionFactor().SubRaw(1)) + if gs.Remainder.GTE(ConversionFactor(extendedDecimals)) { + return fmt.Errorf("remainder %v exceeds max of %v", gs.Remainder, ConversionFactor(extendedDecimals).SubRaw(1)) } // Determine if sum(fractionalBalances) + remainder = whole integer value @@ -48,14 +49,14 @@ func (gs *GenesisState) Validate() error { sum := gs.Balances.SumAmount() sumWithRemainder := sum.Add(gs.Remainder) - offBy := sumWithRemainder.Mod(ConversionFactor()) + offBy := sumWithRemainder.Mod(ConversionFactor(extendedDecimals)) if !offBy.IsZero() { return fmt.Errorf( "sum of fractional balances %v + remainder %v is not a multiple of %v", sum, gs.Remainder, - ConversionFactor(), + ConversionFactor(extendedDecimals), ) } diff --git a/x/precisebank/types/genesis.pb.go b/x/precisebank/types/genesis.pb.go index ef2ce6953..cbdd40faf 100644 --- a/x/precisebank/types/genesis.pb.go +++ b/x/precisebank/types/genesis.pb.go @@ -4,14 +4,15 @@ package types import ( - cosmossdk_io_math "cosmossdk.io/math" fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" io "io" math "math" math_bits "math/bits" + + cosmossdk_io_math "cosmossdk.io/math" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/precisebank/types/genesis_test.go b/x/precisebank/types/genesis_test.go index bd92f3e07..13dec4c08 100644 --- a/x/precisebank/types/genesis_test.go +++ b/x/precisebank/types/genesis_test.go @@ -5,10 +5,9 @@ import ( "github.com/stretchr/testify/require" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" "github.com/cosmos/evm/x/precisebank/testutil" "github.com/cosmos/evm/x/precisebank/types" - evmtypes "github.com/cosmos/evm/x/vm/types" sdkmath "cosmossdk.io/math" @@ -16,6 +15,9 @@ import ( ) func TestGenesisStateValidate_Basic(t *testing.T) { + coinInfo := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals + testCases := []struct { name string genesisState *types.GenesisState @@ -44,7 +46,7 @@ func TestGenesisStateValidate_Basic(t *testing.T) { types.FractionalBalances{ types.NewFractionalBalance(sdk.AccAddress{1}.String(), sdkmath.NewInt(1)), }, - types.ConversionFactor().SubRaw(1), + types.ConversionFactor(extendedDecimals).SubRaw(1), ), "", }, @@ -104,7 +106,7 @@ func TestGenesisStateValidate_Basic(t *testing.T) { types.NewFractionalBalance(sdk.AccAddress{1}.String(), sdkmath.NewInt(1)), types.NewFractionalBalance(sdk.AccAddress{2}.String(), sdkmath.NewInt(1)), }, - types.ConversionFactor(), + types.ConversionFactor(extendedDecimals), ), "remainder 1000000000000 exceeds max of 999999999999", }, @@ -112,7 +114,7 @@ func TestGenesisStateValidate_Basic(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(tt *testing.T) { - err := tc.genesisState.Validate() + err := tc.genesisState.Validate(extendedDecimals) if tc.wantErr == "" { require.NoError(tt, err) @@ -125,6 +127,9 @@ func TestGenesisStateValidate_Basic(t *testing.T) { } func TestGenesisStateValidate_Total(t *testing.T) { + coinInfo := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals + testCases := []struct { name string buildGenesisState func() *types.GenesisState @@ -140,7 +145,7 @@ func TestGenesisStateValidate_Total(t *testing.T) { { "valid - non-zero balances, zero remainder", func() *types.GenesisState { - fbs := testutil.GenerateEqualFractionalBalances(t, 100) + fbs := testutil.GenerateEqualFractionalBalances(t, 100, extendedDecimals) require.Len(t, fbs, 100) return types.NewGenesisState(fbs, sdkmath.ZeroInt()) @@ -150,7 +155,7 @@ func TestGenesisStateValidate_Total(t *testing.T) { { "valid - non-zero balances, non-zero remainder", func() *types.GenesisState { - fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, 100) + fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, 100, extendedDecimals) require.Len(t, fbs, 100) require.NotZero(t, remainder.Int64()) @@ -164,7 +169,7 @@ func TestGenesisStateValidate_Total(t *testing.T) { { "invalid - non-zero balances, invalid remainder", func() *types.GenesisState { - fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, 100) + fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, 100, extendedDecimals) require.Len(t, fbs, 100) require.NotZero(t, remainder.Int64()) @@ -187,7 +192,7 @@ func TestGenesisStateValidate_Total(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(tt *testing.T) { - err := tc.buildGenesisState().Validate() + err := tc.buildGenesisState().Validate(extendedDecimals) if tc.containsErr == "" { require.NoError(tt, err) @@ -200,6 +205,9 @@ func TestGenesisStateValidate_Total(t *testing.T) { } func TestGenesisState_TotalAmountWithRemainder(t *testing.T) { + coinInfo := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals + tests := []struct { name string giveBalances types.FractionalBalances @@ -215,28 +223,28 @@ func TestGenesisState_TotalAmountWithRemainder(t *testing.T) { { "non-empty balances, zero remainder", types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().QuoRaw(2)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), }, sdkmath.ZeroInt(), - types.ConversionFactor(), + types.ConversionFactor(extendedDecimals), }, { "non-empty balances, 1 remainder", types.FractionalBalances{ - types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor().QuoRaw(2)), - types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor().QuoRaw(2).SubRaw(1)), + types.NewFractionalBalance(sdk.AccAddress{1}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2)), + types.NewFractionalBalance(sdk.AccAddress{2}.String(), types.ConversionFactor(extendedDecimals).QuoRaw(2).SubRaw(1)), }, sdkmath.OneInt(), - types.ConversionFactor(), + types.ConversionFactor(extendedDecimals), }, { "non-empty balances, max remainder", types.FractionalBalances{ types.NewFractionalBalance(sdk.AccAddress{1}.String(), sdkmath.OneInt()), }, - types.ConversionFactor().SubRaw(1), - types.ConversionFactor(), + types.ConversionFactor(extendedDecimals).SubRaw(1), + types.ConversionFactor(extendedDecimals), }, } @@ -247,7 +255,7 @@ func TestGenesisState_TotalAmountWithRemainder(t *testing.T) { tt.giveRemainder, ) - require.NoError(t, gs.Validate(), "genesis state should be valid before testing total amount") + require.NoError(t, gs.Validate(extendedDecimals), "genesis state should be valid before testing total amount") totalAmt := gs.TotalAmountWithRemainder() require.Equal(t, tt.wantTotalAmountWithRemainder, totalAmt, "total amount should be balances + remainder") @@ -256,11 +264,8 @@ func TestGenesisState_TotalAmountWithRemainder(t *testing.T) { } func FuzzGenesisStateValidate_NonZeroRemainder(f *testing.F) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID]) - err := configurator.Configure() - require.NoError(f, err) + coinInfo := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals f.Add(5) f.Add(100) @@ -272,22 +277,19 @@ func FuzzGenesisStateValidate_NonZeroRemainder(f *testing.F) { t.Skip("count < 2") } - fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, count) + fbs, remainder := testutil.GenerateEqualFractionalBalancesWithRemainder(t, count, extendedDecimals) t.Logf("count: %v", count) t.Logf("remainder: %v", remainder) gs := types.NewGenesisState(fbs, remainder) - require.NoError(t, gs.Validate()) + require.NoError(t, gs.Validate(extendedDecimals)) }) } func FuzzGenesisStateValidate_ZeroRemainder(f *testing.F) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - configurator.WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID]) - err := configurator.Configure() - require.NoError(f, err) + coinInfo := testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo + extendedDecimals := coinInfo.ExtendedDecimals f.Add(5) f.Add(100) @@ -299,9 +301,9 @@ func FuzzGenesisStateValidate_ZeroRemainder(f *testing.F) { t.Skip("count < 2") } - fbs := testutil.GenerateEqualFractionalBalances(t, count) + fbs := testutil.GenerateEqualFractionalBalances(t, count, extendedDecimals) gs := types.NewGenesisState(fbs, sdkmath.ZeroInt()) - require.NoError(t, gs.Validate()) + require.NoError(t, gs.Validate(extendedDecimals)) }) } diff --git a/x/vm/client/cli/tx.go b/x/vm/client/cli/tx.go index 8c9e0528f..c3cf901d2 100644 --- a/x/vm/client/cli/tx.go +++ b/x/vm/client/cli/tx.go @@ -5,13 +5,16 @@ import ( "fmt" "math/big" "os" + "path/filepath" "strings" "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/pkg/errors" "github.com/spf13/cobra" + "github.com/spf13/viper" + serverconfig "github.com/cosmos/evm/server/config" "github.com/cosmos/evm/utils" "github.com/cosmos/evm/x/vm/types" @@ -74,7 +77,11 @@ func NewRawTxCmd() *cobra.Command { return err } - baseDenom := types.GetEVMCoinDenom() + // Read the base denomination from app.toml config + baseDenom, err := getBaseDenomFromConfig(clientCtx) + if err != nil { + return errors.Wrap(err, "failed to get base denomination from client.tomlconfig") + } tx, err := msg.BuildTx(clientCtx.TxConfig.NewTxBuilder(), baseDenom) if err != nil { @@ -177,3 +184,31 @@ When using '--dry-run' a key name cannot be used, only an 0x or bech32 address. return cmd } + +// getBaseDenomFromConfig reads the denomination configuration from client.toml +func getBaseDenomFromConfig(clientCtx client.Context) (string, error) { + homeDir := clientCtx.HomeDir + if homeDir == "" { + userHome, err := os.UserHomeDir() + if err != nil { + return "", errors.Wrap(err, "failed to get user home directory") + } + homeDir = filepath.Join(userHome, ".evmd") + } + + configPath := filepath.Join(homeDir, "config", "client.toml") + v := viper.New() + v.SetConfigFile(configPath) + v.SetConfigType("toml") + + if err := v.ReadInConfig(); err != nil { + return "", errors.Wrapf(err, "failed to read config file: %s", configPath) + } + + config, err := serverconfig.GetConfig(v) + if err != nil { + return "", errors.Wrap(err, "failed to parse config") + } + + return config.Coin.GetDenom(), nil +} diff --git a/x/vm/keeper/config.go b/x/vm/keeper/config.go index c957bee34..017ae91a2 100644 --- a/x/vm/keeper/config.go +++ b/x/vm/keeper/config.go @@ -45,7 +45,7 @@ func (k *Keeper) TxConfig(ctx sdk.Context, txHash common.Hash) statedb.TxConfig // module parameters. The config generated uses the default JumpTable from the EVM. func (k Keeper) VMConfig(ctx sdk.Context, _ core.Message, cfg *statedb.EVMConfig, tracer *tracing.Hooks) vm.Config { noBaseFee := true - if types.IsLondon(types.GetEthChainConfig(), ctx.BlockHeight()) { + if types.IsLondon(k.evmCfg.ChainConfig.EthereumConfig(), ctx.BlockHeight()) { noBaseFee = k.feeMarketWrapper.GetParams(ctx).NoBaseFee } diff --git a/x/vm/keeper/grpc_query.go b/x/vm/keeper/grpc_query.go index a748d29d6..59c9e86d9 100644 --- a/x/vm/keeper/grpc_query.go +++ b/x/vm/keeper/grpc_query.go @@ -246,7 +246,8 @@ func (k Keeper) EthCall(c context.Context, req *types.EthCallRequest) (*types.Ms nonce := k.GetNonce(ctx, args.GetFrom()) args.Nonce = (*hexutil.Uint64)(&nonce) - if err := args.CallDefaults(req.GasCap, cfg.BaseFee, types.GetEthChainConfig().ChainID); err != nil { + ethCfg := k.evmCfg.ChainConfig.EthereumConfig() + if err := args.CallDefaults(req.GasCap, cfg.BaseFee, ethCfg.ChainID); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } @@ -329,7 +330,9 @@ func (k Keeper) EstimateGasInternal(c context.Context, req *types.EthCallRequest if args.Gas == nil { args.Gas = new(hexutil.Uint64) } - if err := args.CallDefaults(req.GasCap, cfg.BaseFee, types.GetEthChainConfig().ChainID); err != nil { + chainConfig := k.evmCfg.ChainConfig + ethCfg := chainConfig.EthereumConfig() + if err := args.CallDefaults(req.GasCap, cfg.BaseFee, ethCfg.ChainID); err != nil { return nil, status.Error(codes.InvalidArgument, err.Error()) } @@ -338,7 +341,7 @@ func (k Keeper) EstimateGasInternal(c context.Context, req *types.EthCallRequest // Recap the highest gas limit with account's available balance. if msg.GasFeeCap.BitLen() != 0 { - baseDenom := types.GetEVMCoinDenom() + baseDenom := k.evmCfg.CoinInfo.GetDenom() balance := k.bankWrapper.SpendableCoin(ctx, sdk.AccAddress(args.From.Bytes()), baseDenom) available := balance.Amount @@ -523,7 +526,9 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ cfg.BaseFee = baseFee } - signer := ethtypes.MakeSigner(types.GetEthChainConfig(), big.NewInt(ctx.BlockHeight()), uint64(ctx.BlockTime().Unix())) //#nosec G115 -- int overflow is not a concern here + chainConfig := k.evmCfg.ChainConfig + ethCfg := chainConfig.EthereumConfig() + signer := ethtypes.MakeSigner(ethCfg, big.NewInt(ctx.BlockHeight()), uint64(ctx.BlockTime().Unix())) //#nosec G115 -- int overflow is not a concern here txConfig := statedb.NewEmptyTxConfig() // gas used at this point corresponds to GetProposerAddress & CalculateBaseFee @@ -614,7 +619,9 @@ func (k Keeper) TraceBlock(c context.Context, req *types.QueryTraceBlockRequest) cfg.BaseFee = baseFee } - signer := ethtypes.MakeSigner(types.GetEthChainConfig(), big.NewInt(ctx.BlockHeight()), uint64(ctx.BlockTime().Unix())) //#nosec G115 -- int overflow is not a concern here + chainConfig := k.evmCfg.ChainConfig + ethCfg := chainConfig.EthereumConfig() + signer := ethtypes.MakeSigner(ethCfg, big.NewInt(ctx.BlockHeight()), uint64(ctx.BlockTime().Unix())) //#nosec G115 -- int overflow is not a concern here txsLength := len(req.Txs) results := make([]*types.TxTraceResult, 0, txsLength) @@ -678,7 +685,7 @@ func (k *Keeper) traceTx( } if traceConfig.Overrides != nil { - overrides = traceConfig.Overrides.EthereumConfig(types.GetEthChainConfig().ChainID) + overrides = traceConfig.Overrides.EthereumConfig() } logConfig := logger.Config{ @@ -703,13 +710,15 @@ func (k *Keeper) traceTx( TxHash: txConfig.TxHash, } + chainConfig := k.evmCfg.ChainConfig + ethCfg := chainConfig.EthereumConfig() if traceConfig.Tracer != "" { var cfg json.RawMessage if traceConfig.TracerJsonConfig != "" { cfg = json.RawMessage(traceConfig.TracerJsonConfig) } if tracer, err = tracers.DefaultDirectory.New(traceConfig.Tracer, tCtx, cfg, - types.GetEthChainConfig()); err != nil { + ethCfg); err != nil { return nil, 0, status.Error(codes.Internal, err.Error()) } } @@ -772,10 +781,7 @@ func (k Keeper) GlobalMinGasPrice(c context.Context, _ *types.QueryGlobalMinGasP // Config implements the Query/Config gRPC method func (k Keeper) Config(_ context.Context, _ *types.QueryConfigRequest) (*types.QueryConfigResponse, error) { - config := types.GetChainConfig() - config.Denom = types.GetEVMCoinDenom() - config.Decimals = uint64(types.GetEVMCoinDecimals()) - + config := k.evmCfg.ChainConfig return &types.QueryConfigResponse{Config: config}, nil } diff --git a/x/vm/keeper/keeper.go b/x/vm/keeper/keeper.go index 774598fb2..42354211d 100644 --- a/x/vm/keeper/keeper.go +++ b/x/vm/keeper/keeper.go @@ -81,6 +81,10 @@ type Keeper struct { // evmMempool is the custom EVM appside mempool // if it is nil, the default comet mempool will be used evmMempool *evmmempool.ExperimentalEVMMempool + + // evmCfg contains the specific EVM configuration details, which must be passed down + // to any keepers that require evm config, chain id, and coin info + evmCfg *types.EvmConfig } // NewKeeper generates new evm module keeper @@ -96,6 +100,7 @@ func NewKeeper( consensusKeeper types.ConsensusParamsKeeper, erc20Keeper types.Erc20Keeper, tracer string, + evmCfg *types.EvmConfig, ) *Keeper { // ensure evm module account is set if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { @@ -107,8 +112,8 @@ func NewKeeper( panic(err) } - bankWrapper := wrappers.NewBankWrapper(bankKeeper) - feeMarketWrapper := wrappers.NewFeeMarketWrapper(fmk) + bankWrapper := wrappers.NewBankWrapper(bankKeeper, evmCfg) + feeMarketWrapper := wrappers.NewFeeMarketWrapper(fmk, evmCfg) // NOTE: we pass in the parameter space to the CommitStateDB in order to use custom denominations for the EVM operations return &Keeper{ @@ -124,6 +129,7 @@ func NewKeeper( consensusKeeper: consensusKeeper, erc20Keeper: erc20Keeper, storeKeys: keys, + evmCfg: evmCfg, } } @@ -311,7 +317,7 @@ func (k *Keeper) SpendableCoin(ctx sdk.Context, addr common.Address) *uint256.In cosmosAddr := sdk.AccAddress(addr.Bytes()) // Get the balance via bank wrapper to convert it to 18 decimals if needed. - coin := k.bankWrapper.SpendableCoin(ctx, cosmosAddr, types.GetEVMCoinDenom()) + coin := k.bankWrapper.SpendableCoin(ctx, cosmosAddr, k.evmCfg.CoinInfo.GetDenom()) result, err := utils.Uint256FromBigInt(coin.Amount.BigInt()) if err != nil { @@ -326,7 +332,7 @@ func (k *Keeper) GetBalance(ctx sdk.Context, addr common.Address) *uint256.Int { cosmosAddr := sdk.AccAddress(addr.Bytes()) // Get the balance via bank wrapper to convert it to 18 decimals if needed. - coin := k.bankWrapper.GetBalance(ctx, cosmosAddr, types.GetEVMCoinDenom()) + coin := k.bankWrapper.GetBalance(ctx, cosmosAddr, k.evmCfg.CoinInfo.GetDenom()) result, err := utils.Uint256FromBigInt(coin.Amount.BigInt()) if err != nil { @@ -341,7 +347,7 @@ func (k *Keeper) GetBalance(ctx sdk.Context, addr common.Address) *uint256.Int { // - `0`: london hardfork enabled but feemarket is not enabled. // - `n`: both london hardfork and feemarket are enabled. func (k Keeper) GetBaseFee(ctx sdk.Context) *big.Int { - ethCfg := types.GetEthChainConfig() + ethCfg := k.evmCfg.ChainConfig.EthereumConfig() if !types.IsLondon(ethCfg, ctx.BlockHeight()) { return nil } @@ -410,7 +416,7 @@ func (k Keeper) GetEvmMempool() *evmmempool.ExperimentalEVMMempool { // SetHeaderHash sets current block hash into EIP-2935 compatible storage contract. func (k Keeper) SetHeaderHash(ctx sdk.Context) { - window := uint64(types.DefaultHistoryServeWindow) + window := uint64(types.DefaultHistoryServeWindow()) params := k.GetParams(ctx) if params.HistoryServeWindow > 0 { window = params.HistoryServeWindow @@ -428,7 +434,7 @@ func (k Keeper) SetHeaderHash(ctx sdk.Context) { // GetHeaderHash sets block hash into EIP-2935 compatible storage contract. func (k Keeper) GetHeaderHash(ctx sdk.Context, height uint64) common.Hash { - window := uint64(types.DefaultHistoryServeWindow) + window := uint64(types.DefaultHistoryServeWindow()) params := k.GetParams(ctx) if params.HistoryServeWindow > 0 { window = params.HistoryServeWindow @@ -439,3 +445,15 @@ func (k Keeper) GetHeaderHash(ctx sdk.Context, height uint64) common.Hash { binary.BigEndian.PutUint64(key[24:], ringIndex) return k.GetState(ctx, ethparams.HistoryStorageAddress, key) } + +// GetEvmChainCfg returns the evm chain config +// This is primarily to be used for testing +func (k *Keeper) GetEvmConfig() *types.EvmConfig { + return k.evmCfg +} + +// SetEvmChainCfg sets the evm chain config so that methods can access chain and coin info +// This is primarily to be used for testing +func (k *Keeper) SetEvmConfig(evmCfg *types.EvmConfig) { + k.evmCfg = evmCfg +} diff --git a/x/vm/keeper/statedb.go b/x/vm/keeper/statedb.go index 828e0da60..2cca7c176 100644 --- a/x/vm/keeper/statedb.go +++ b/x/vm/keeper/statedb.go @@ -114,7 +114,7 @@ func (k *Keeper) SetBalance(ctx sdk.Context, addr common.Address, amount *uint25 return nil } cosmosAddr := sdk.AccAddress(addr.Bytes()) - coin := k.bankWrapper.SpendableCoin(ctx, cosmosAddr, types.GetEVMCoinDenom()) + coin := k.bankWrapper.SpendableCoin(ctx, cosmosAddr, k.evmCfg.CoinInfo.GetDenom()) balance := coin.Amount.BigInt() delta := new(big.Int).Sub(amount.ToBig(), balance) diff --git a/x/vm/types/chain_config.go b/x/vm/types/chain_config.go index 6a9877340..e3c014e93 100644 --- a/x/vm/types/chain_config.go +++ b/x/vm/types/chain_config.go @@ -1,7 +1,6 @@ package types import ( - "errors" "math/big" gethparams "github.com/ethereum/go-ethereum/params" @@ -10,22 +9,12 @@ import ( sdkmath "cosmossdk.io/math" ) -// testChainID represents the ChainID used for the purpose of testing. -const testChainID uint64 = 262144 - -// chainConfig is the chain configuration used in the EVM to defined which -// opcodes are active based on Ethereum upgrades. -var chainConfig *ChainConfig - // EthereumConfig returns an Ethereum ChainConfig for EVM state transitions. // All the negative or nil values are converted to nil -func (cc ChainConfig) EthereumConfig(chainID *big.Int) *gethparams.ChainConfig { - cID := new(big.Int).SetUint64(cc.ChainId) - if chainID != nil { - cID = chainID - } +func (cc ChainConfig) EthereumConfig() *gethparams.ChainConfig { + chainID := new(big.Int).SetUint64(cc.ChainId) return &gethparams.ChainConfig{ - ChainID: cID, + ChainID: chainID, HomesteadBlock: getBlockValue(cc.HomesteadBlock), DAOForkBlock: getBlockValue(cc.DAOForkBlock), DAOForkSupport: cc.DAOForkSupport, @@ -58,11 +47,7 @@ func (cc ChainConfig) EthereumConfig(chainID *big.Int) *gethparams.ChainConfig { } } -func DefaultChainConfig(evmChainID uint64) *ChainConfig { - if evmChainID == 0 { - evmChainID = testChainID - } - +func DefaultChainConfig(evmChainID uint64, coinInfo EvmCoinInfo) *ChainConfig { homesteadBlock := sdkmath.ZeroInt() daoForkBlock := sdkmath.ZeroInt() eip150Block := sdkmath.ZeroInt() @@ -84,8 +69,8 @@ func DefaultChainConfig(evmChainID uint64) *ChainConfig { cfg := &ChainConfig{ ChainId: evmChainID, - Denom: DefaultEVMDenom, - Decimals: DefaultEVMDecimals, + Denom: coinInfo.GetDenom(), + Decimals: uint64(coinInfo.Decimals), HomesteadBlock: &homesteadBlock, DAOForkBlock: &daoForkBlock, DAOForkSupport: true, @@ -111,25 +96,6 @@ func DefaultChainConfig(evmChainID uint64) *ChainConfig { return cfg } -// setChainConfig allows to set the `chainConfig` variable modifying the -// default values. The method is private because it should only be called once -// in the EVMConfigurator. -func setChainConfig(cc *ChainConfig) error { - if chainConfig != nil { - return errors.New("chainConfig already set. Cannot set again the chainConfig") - } - config := DefaultChainConfig(0) - if cc != nil { - config = cc - } - if err := config.Validate(); err != nil { - return err - } - chainConfig = config - - return nil -} - func getBlockValue(block *sdkmath.Int) *big.Int { if block == nil || block.IsNegative() { return nil @@ -210,7 +176,7 @@ func (cc ChainConfig) Validate() error { return errorsmod.Wrap(err, "VerkleTime") } // NOTE: chain ID is not needed to check config order - if err := cc.EthereumConfig(nil).CheckConfigForkOrder(); err != nil { + if err := cc.EthereumConfig().CheckConfigForkOrder(); err != nil { return errorsmod.Wrap(err, "invalid config fork order") } return nil diff --git a/x/vm/types/chain_config_test.go b/x/vm/types/chain_config_test.go index 827fcd31d..c5135715d 100644 --- a/x/vm/types/chain_config_test.go +++ b/x/vm/types/chain_config_test.go @@ -1,6 +1,7 @@ package types_test import ( + "math/rand" "testing" "github.com/stretchr/testify/require" @@ -16,12 +17,19 @@ func newIntPtr(i int64) *sdkmath.Int { } func TestChainConfigValidate(t *testing.T) { + testEvmChainID := uint64(rand.Intn(1000000) + 1) + testCoinInfo := types.EvmCoinInfo{ + DisplayDenom: "test", + Decimals: types.EighteenDecimals, + ExtendedDecimals: types.EighteenDecimals, + } + testCases := []struct { name string config types.ChainConfig expError bool }{ - {"default", *types.DefaultChainConfig(0), false}, + {"default", *types.DefaultChainConfig(testEvmChainID, testCoinInfo), false}, { "valid", types.ChainConfig{ diff --git a/x/vm/types/coin_info.go b/x/vm/types/coin_info.go new file mode 100644 index 000000000..8ddc64bb3 --- /dev/null +++ b/x/vm/types/coin_info.go @@ -0,0 +1,82 @@ +// +// The config package provides a convenient way to modify x/evm params and values. +// Its primary purpose is to be used during application initialization. + +package types + +import ( + "errors" + "fmt" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// EvmCoinInfo struct holds the display name and decimal precisions of the EVM denom +type EvmCoinInfo struct { + // DisplayDenom defines the display denomination shown to users + DisplayDenom string `mapstructure:"display-denom"` + // Decimals defines the precision/decimals for the base denomination (1-18) + Decimals Decimals `mapstructure:"decimals"` + // ExtendedDecimals defines the precision/decimals for the extended denomination (typically 18 decimals for atto-denom) + ExtendedDecimals Decimals `mapstructure:"extended-decimals"` +} + +// Validate returns an error if the coin configuration fields are invalid. +func (c EvmCoinInfo) Validate() error { + if err := c.Decimals.Validate(); err != nil { + return fmt.Errorf("decimals validation failed: %w", err) + } + if err := c.ExtendedDecimals.Validate(); err != nil { + return fmt.Errorf("extended decimals validation failed: %w", err) + } + + denom := c.GetDenom() + if strings.HasPrefix(denom, "invalid") { + return errors.New("invalid denom, not a valid SI decimal, so denom cannot be derived") + } + if err := sdk.ValidateDenom(denom); err != nil { + return fmt.Errorf("invalid denom: %w", err) + } + + extendedDenom := c.GetExtendedDenom() + if strings.HasPrefix(extendedDenom, "invalid") { + return errors.New("invalid extended denom, not a valid SI decimal, so extended denom cannot be derived") + } + if err := sdk.ValidateDenom(extendedDenom); err != nil { + return fmt.Errorf("invalid extended denom: %w", err) + } + + if c.DisplayDenom == "" { + return errors.New("display-denom cannot be empty") + } + if err := sdk.ValidateDenom(c.DisplayDenom); err != nil { + return fmt.Errorf("invalid display denom: %w", err) + } + + // For 18 decimals, denom and extended denom should be the same, as higher decimals are not supported + if c.Decimals == EighteenDecimals { + if c.Decimals != c.ExtendedDecimals { + return errors.New("decimals and extended decimals must be the same for 18 decimals") + } + if c.GetDenom() != c.GetExtendedDenom() { + return errors.New("denom and extended denom must be the same for 18 decimals") + } + } + + return nil +} + +// GetDenom returns the base denomination used in the chain, derived by SI prefix +func (c EvmCoinInfo) GetDenom() string { + return CreateDenomStr(c.Decimals, c.DisplayDenom) +} + +// GetExtendedDenom returns the extended denomination used in the chain, derived by SI prefix +func (c EvmCoinInfo) GetExtendedDenom() string { + return CreateDenomStr(c.ExtendedDecimals, c.DisplayDenom) +} + +func CreateDenomStr(decimals Decimals, displayDenom string) string { + return decimals.GetSIPrefix() + displayDenom +} diff --git a/x/vm/types/config.go b/x/vm/types/config.go deleted file mode 100644 index 34f87ffef..000000000 --- a/x/vm/types/config.go +++ /dev/null @@ -1,60 +0,0 @@ -// -// The config package provides a convenient way to modify x/evm params and values. -// Its primary purpose is to be used during application initialization. - -//go:build !test -// +build !test - -package types - -import ( - "fmt" - - "github.com/ethereum/go-ethereum/core/vm" - geth "github.com/ethereum/go-ethereum/params" -) - -// Configure applies the changes to the virtual machine configuration. -func (ec *EVMConfigurator) Configure() error { - // If Configure method has been already used in the object, return - // an error to avoid overriding configuration. - if ec.sealed { - return fmt.Errorf("error configuring EVMConfigurator: already sealed and cannot be modified") - } - - if err := setChainConfig(ec.chainConfig); err != nil { - return err - } - - if err := setEVMCoinInfo(ec.evmCoinInfo); err != nil { - return err - } - - if err := extendDefaultExtraEIPs(ec.extendedDefaultExtraEIPs); err != nil { - return err - } - - if err := vm.ExtendActivators(ec.extendedEIPs); err != nil { - return err - } - - // After applying modifiers the configurator is sealed. This way, it is not possible - // to call the configure method twice. - ec.sealed = true - - return nil -} - -func (ec *EVMConfigurator) ResetTestConfig() { - panic("this is only implemented with the 'test' build flag. Make sure you're running your tests using the '-tags=test' flag.") -} - -// GetEthChainConfig returns the `chainConfig` used in the EVM (geth type). -func GetEthChainConfig() *geth.ChainConfig { - return chainConfig.EthereumConfig(nil) -} - -// GetChainConfig returns the `chainConfig`. -func GetChainConfig() *ChainConfig { - return chainConfig -} diff --git a/x/vm/types/config_testing.go b/x/vm/types/config_testing.go deleted file mode 100644 index 1440ccb86..000000000 --- a/x/vm/types/config_testing.go +++ /dev/null @@ -1,82 +0,0 @@ -// -// The config package provides a convenient way to modify x/evm params and values. -// Its primary purpose is to be used during application initialization. - -//go:build test -// +build test - -package types - -import ( - "errors" - "fmt" - - "github.com/ethereum/go-ethereum/core/vm" - geth "github.com/ethereum/go-ethereum/params" -) - -// testChainConfig is the chain configuration used in the EVM to defined which -// opcodes are active based on Ethereum upgrades. -var testChainConfig *ChainConfig - -// Configure applies the changes to the virtual machine configuration. -func (ec *EVMConfigurator) Configure() error { - // If Configure method has been already used in the object, return - // an error to avoid overriding configuration. - if ec.sealed { - return fmt.Errorf("error configuring EVMConfigurator: already sealed and cannot be modified") - } - - if err := setTestChainConfig(ec.chainConfig); err != nil { - return err - } - - if err := setTestingEVMCoinInfo(ec.evmCoinInfo); err != nil { - return err - } - - if err := extendDefaultExtraEIPs(ec.extendedDefaultExtraEIPs); err != nil { - return err - } - - if err := vm.ExtendActivators(ec.extendedEIPs); err != nil { - return err - } - - // After applying modifications, the configurator is sealed. This way, it is not possible - // to call the configure method twice. - ec.sealed = true - - return nil -} - -func (ec *EVMConfigurator) ResetTestConfig() { - vm.ResetActivators() - resetEVMCoinInfo() - testChainConfig = nil -} - -func setTestChainConfig(cc *ChainConfig) error { - if testChainConfig != nil { - return errors.New("chainConfig already set. Cannot set again the chainConfig. Call the configurators ResetTestConfig method before configuring a new chain.") - } - config := DefaultChainConfig(0) - if cc != nil { - config = cc - } - if err := config.Validate(); err != nil { - return err - } - testChainConfig = config - return nil -} - -// GetEthChainConfig returns the `chainConfig` used in the EVM (geth type). -func GetEthChainConfig() *geth.ChainConfig { - return testChainConfig.EthereumConfig(nil) -} - -// GetChainConfig returns the `chainConfig`. -func GetChainConfig() *ChainConfig { - return testChainConfig -} diff --git a/x/vm/types/configurator.go b/x/vm/types/configurator.go deleted file mode 100644 index 44c1fd8ed..000000000 --- a/x/vm/types/configurator.go +++ /dev/null @@ -1,67 +0,0 @@ -// -// The config package provides a convenient way to modify x/evm params and values. -// Its primary purpose is to be used during application initialization. - -package types - -import ( - "fmt" - "slices" - - "github.com/ethereum/go-ethereum/core/vm" -) - -// EVMConfigurator allows to extend x/evm module configurations. The configurator modifies -// the EVM before starting the node. This means that all init genesis validations will be -// applied to each change. -type EVMConfigurator struct { - sealed bool - extendedEIPs map[int]func(*vm.JumpTable) - extendedDefaultExtraEIPs []int64 - chainConfig *ChainConfig - evmCoinInfo EvmCoinInfo -} - -// NewEVMConfigurator returns a pointer to a new EVMConfigurator object. -func NewEVMConfigurator() *EVMConfigurator { - return &EVMConfigurator{} -} - -// WithExtendedEips allows to add to the go-ethereum activators map the provided -// EIP activators. -func (ec *EVMConfigurator) WithExtendedEips(extendedEIPs map[int]func(*vm.JumpTable)) *EVMConfigurator { - ec.extendedEIPs = extendedEIPs - return ec -} - -// WithExtendedDefaultExtraEIPs update the x/evm DefaultExtraEIPs params -// by adding provided EIP numbers. -func (ec *EVMConfigurator) WithExtendedDefaultExtraEIPs(eips ...int64) *EVMConfigurator { - ec.extendedDefaultExtraEIPs = eips - return ec -} - -// WithChainConfig allows to define a custom `chainConfig` to be used in the -// EVM. -func (ec *EVMConfigurator) WithChainConfig(cc *ChainConfig) *EVMConfigurator { - ec.chainConfig = cc - return ec -} - -// WithEVMCoinInfo allows to define the denom and decimals of the token used as the -// EVM token. -func (ec *EVMConfigurator) WithEVMCoinInfo(coinInfo EvmCoinInfo) *EVMConfigurator { - ec.evmCoinInfo = coinInfo - return ec -} - -func extendDefaultExtraEIPs(extraEIPs []int64) error { - for _, eip := range extraEIPs { - if slices.Contains(DefaultExtraEIPs, eip) { - return fmt.Errorf("error configuring EVMConfigurator: EIP %d is already present in the default list: %v", eip, DefaultExtraEIPs) - } - - DefaultExtraEIPs = append(DefaultExtraEIPs, eip) - } - return nil -} diff --git a/x/vm/types/configurator_test.go b/x/vm/types/configurator_test.go deleted file mode 100644 index 8ba74f536..000000000 --- a/x/vm/types/configurator_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/ethereum/go-ethereum/core/vm" - "github.com/stretchr/testify/require" - - testconstants "github.com/cosmos/evm/testutil/constants" - "github.com/cosmos/evm/x/vm/types" -) - -func TestEVMConfigurator(t *testing.T) { - evmConfigurator := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]) - err := evmConfigurator.Configure() - require.NoError(t, err) - - err = evmConfigurator.Configure() - require.Error(t, err) - require.Contains(t, err.Error(), "sealed", "expected different error") -} - -func TestExtendedEips(t *testing.T) { - testCases := []struct { - name string - malleate func() *types.EVMConfigurator - expPass bool - errContains string - }{ - { - "fail - eip already present in activators return an error", - func() *types.EVMConfigurator { - extendedEIPs := map[int]func(*vm.JumpTable){ - 3855: func(_ *vm.JumpTable) {}, - } - ec := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - WithExtendedEips(extendedEIPs) - return ec - }, - false, - "duplicate activation", - }, - { - "success - new default extra eips without duplication added", - func() *types.EVMConfigurator { - extendedEIPs := map[int]func(*vm.JumpTable){ - 0o000: func(_ *vm.JumpTable) {}, - } - ec := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - WithExtendedEips(extendedEIPs) - return ec - }, - true, - "", - }, - } - - for _, tc := range testCases { - ec := tc.malleate() - ec.ResetTestConfig() - err := ec.Configure() - - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errContains, "expected different error") - } - } -} - -func TestExtendedDefaultExtraEips(t *testing.T) { - defaultExtraEIPsSnapshot := types.DefaultExtraEIPs - testCases := []struct { - name string - malleate func() *types.EVMConfigurator - postCheck func() - expPass bool - errContains string - }{ - { - "fail - duplicate default EIP entiries", - func() *types.EVMConfigurator { - extendedDefaultExtraEIPs := []int64{1000} - types.DefaultExtraEIPs = append(types.DefaultExtraEIPs, 1000) - ec := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - WithExtendedDefaultExtraEIPs(extendedDefaultExtraEIPs...) - return ec - }, - func() { - require.ElementsMatch(t, append(defaultExtraEIPsSnapshot, 1000), types.DefaultExtraEIPs) - types.DefaultExtraEIPs = defaultExtraEIPsSnapshot - }, - false, - "EIP 1000 is already present", - }, - { - "success - empty default extra eip", - func() *types.EVMConfigurator { - var extendedDefaultExtraEIPs []int64 - ec := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - WithExtendedDefaultExtraEIPs(extendedDefaultExtraEIPs...) - return ec - }, - func() { - require.ElementsMatch(t, defaultExtraEIPsSnapshot, types.DefaultExtraEIPs) - }, - true, - "", - }, - { - "success - extra default eip added", - func() *types.EVMConfigurator { - extendedDefaultExtraEIPs := []int64{1001} - ec := types.NewEVMConfigurator(). - WithEVMCoinInfo(testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID]). - WithExtendedDefaultExtraEIPs(extendedDefaultExtraEIPs...) - return ec - }, - func() { - require.ElementsMatch(t, append(defaultExtraEIPsSnapshot, 1001), types.DefaultExtraEIPs) - types.DefaultExtraEIPs = defaultExtraEIPsSnapshot - }, - true, - "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - ec := tc.malleate() - ec.ResetTestConfig() - err := ec.Configure() - - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errContains, "expected different error") - } - - tc.postCheck() - }) - } -} diff --git a/x/vm/types/denom.go b/x/vm/types/denom.go index b4d5d68dc..07413a599 100644 --- a/x/vm/types/denom.go +++ b/x/vm/types/denom.go @@ -77,13 +77,26 @@ func (d Decimals) ConversionFactor() math.Int { return ConversionFactor[d] } -// EvmCoinInfo struct holds the name and decimals of the EVM denom. The EVM denom -// is the token used to pay fees in the EVM. -// -// TODO: move to own file? at least rename file because it's unclear to use "denom" -type EvmCoinInfo struct { - Denom string - ExtendedDenom string - DisplayDenom string - Decimals Decimals +func (d Decimals) GetSIPrefix() string { + switch d { + case OneDecimals: + return "d" + case TwoDecimals: + return "c" + case ThreeDecimals: + return "m" + case SixDecimals: + return "u" + case NineDecimals: + return "n" + case TwelveDecimals: + return "p" + case FifteenDecimals: + return "f" + case EighteenDecimals: + return "a" + default: + // decimals must be one of 1, 2, 3, 6, 9, 12, 15, 18 to have a valid prefix + return "invalid" + } } diff --git a/x/vm/types/denom_config.go b/x/vm/types/denom_config.go deleted file mode 100644 index 04ff3fe8b..000000000 --- a/x/vm/types/denom_config.go +++ /dev/null @@ -1,103 +0,0 @@ -// -// The config package provides a convenient way to modify x/evm params and values. -// Its primary purpose is to be used during application initialization. - -//go:build !test -// +build !test - -package types - -import ( - "errors" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// evmCoinInfo hold the information of the coin used in the EVM as gas token. It -// can only be set via `EVMConfigurator` before starting the app. -var evmCoinInfo *EvmCoinInfo - -// setEVMCoinDecimals allows to define the decimals used in the representation -// of the EVM coin. -func setEVMCoinDecimals(d Decimals) error { - if err := d.Validate(); err != nil { - return fmt.Errorf("setting EVM coin decimals: %w", err) - } - - evmCoinInfo.Decimals = d - return nil -} - -// setEVMCoinDenom allows to define the denom of the coin used in the EVM. -func setEVMCoinDenom(denom string) error { - if err := sdk.ValidateDenom(denom); err != nil { - return fmt.Errorf("setting EVM coin denom: %w", err) - } - evmCoinInfo.Denom = denom - return nil -} - -// setEVMCoinExtendedDenom allows to define the extended denom of the coin used in the EVM. -func setEVMCoinExtendedDenom(extendedDenom string) error { - if err := sdk.ValidateDenom(extendedDenom); err != nil { - return err - } - evmCoinInfo.ExtendedDenom = extendedDenom - return nil -} - -func setDisplayDenom(displayDenom string) error { - if err := sdk.ValidateDenom(displayDenom); err != nil { - return fmt.Errorf("setting EVM coin display denom: %w", err) - } - evmCoinInfo.DisplayDenom = displayDenom - return nil -} - -// GetEVMCoinDecimals returns the decimals used in the representation of the EVM -// coin. -func GetEVMCoinDecimals() Decimals { - return evmCoinInfo.Decimals -} - -// GetEVMCoinDenom returns the denom used for the EVM coin. -func GetEVMCoinDenom() string { - return evmCoinInfo.Denom -} - -// GetEVMCoinExtendedDenom returns the extended denom used for the EVM coin. -func GetEVMCoinExtendedDenom() string { - return evmCoinInfo.ExtendedDenom -} - -// GetEVMCoinDisplayDenom returns the display denom used for the EVM coin. -func GetEVMCoinDisplayDenom() string { - return evmCoinInfo.DisplayDenom -} - -// setEVMCoinInfo allows to define denom and decimals of the coin used in the EVM. -func setEVMCoinInfo(eci EvmCoinInfo) error { - if evmCoinInfo != nil { - return errors.New("EVM coin info already set") - } - - if eci.Decimals == EighteenDecimals { - if eci.Denom != eci.ExtendedDenom { - return errors.New("EVM coin denom and extended denom must be the same for 18 decimals") - } - } - - evmCoinInfo = new(EvmCoinInfo) - - if err := setEVMCoinDenom(eci.Denom); err != nil { - return err - } - if err := setEVMCoinExtendedDenom(eci.ExtendedDenom); err != nil { - return err - } - if err := setDisplayDenom(eci.DisplayDenom); err != nil { - return err - } - return setEVMCoinDecimals(eci.Decimals) -} diff --git a/x/vm/types/denom_config_testing.go b/x/vm/types/denom_config_testing.go deleted file mode 100644 index 66b849c0c..000000000 --- a/x/vm/types/denom_config_testing.go +++ /dev/null @@ -1,108 +0,0 @@ -// -// The config package provides a convenient way to modify x/evm params and values. -// Its primary purpose is to be used during application initialization. - -//go:build test -// +build test - -package types - -import ( - "errors" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// testingEvmCoinInfo hold the information of the coin used in the EVM as gas token. It -// can only be set via `EVMConfigurator` before starting the app. -var testingEvmCoinInfo *EvmCoinInfo - -// setEVMCoinDecimals allows to define the decimals used in the representation -// of the EVM coin. -func setEVMCoinDecimals(d Decimals) error { - if err := d.Validate(); err != nil { - return fmt.Errorf("setting EVM coin decimals: %w", err) - } - - testingEvmCoinInfo.Decimals = d - return nil -} - -// setEVMCoinDenom allows to define the denom of the coin used in the EVM. -func setEVMCoinDenom(denom string) error { - if err := sdk.ValidateDenom(denom); err != nil { - return err - } - testingEvmCoinInfo.Denom = denom - return nil -} - -// setEVMCoinExtendedDenom allows to define the extended denom of the coin used in the EVM. -func setEVMCoinExtendedDenom(extendedDenom string) error { - if err := sdk.ValidateDenom(extendedDenom); err != nil { - return err - } - testingEvmCoinInfo.ExtendedDenom = extendedDenom - return nil -} - -func setDisplayDenom(displayDenom string) error { - if err := sdk.ValidateDenom(displayDenom); err != nil { - return fmt.Errorf("setting EVM coin display denom: %w", err) - } - testingEvmCoinInfo.DisplayDenom = displayDenom - return nil -} - -// GetEVMCoinDecimals returns the decimals used in the representation of the EVM -// coin. -func GetEVMCoinDecimals() Decimals { - return testingEvmCoinInfo.Decimals -} - -// GetEVMCoinDenom returns the denom used for the EVM coin. -func GetEVMCoinDenom() string { - return testingEvmCoinInfo.Denom -} - -// GetEVMCoinExtendedDenom returns the extended denom used for the EVM coin. -func GetEVMCoinExtendedDenom() string { - return testingEvmCoinInfo.ExtendedDenom -} - -// GetEVMCoinDisplayDenom returns the display denom used for the EVM coin. -func GetEVMCoinDisplayDenom() string { - return testingEvmCoinInfo.DisplayDenom -} - -// setTestingEVMCoinInfo allows to define denom and decimals of the coin used in the EVM. -func setTestingEVMCoinInfo(eci EvmCoinInfo) error { - if testingEvmCoinInfo != nil { - return errors.New("testing EVM coin info already set. Make sure you run the configurator's ResetTestConfig before trying to set a new evm coin info") - } - - if eci.Decimals == EighteenDecimals { - if eci.Denom != eci.ExtendedDenom { - return errors.New("EVM coin denom and extended denom must be the same for 18 decimals") - } - } - - testingEvmCoinInfo = new(EvmCoinInfo) - - if err := setEVMCoinDenom(eci.Denom); err != nil { - return err - } - if err := setEVMCoinExtendedDenom(eci.ExtendedDenom); err != nil { - return err - } - if err := setDisplayDenom(eci.DisplayDenom); err != nil { - return err - } - return setEVMCoinDecimals(eci.Decimals) -} - -// resetEVMCoinInfo resets to nil the testingEVMCoinInfo -func resetEVMCoinInfo() { - testingEvmCoinInfo = nil -} diff --git a/x/vm/types/denom_test.go b/x/vm/types/denom_test.go new file mode 100644 index 000000000..b57a7ad8b --- /dev/null +++ b/x/vm/types/denom_test.go @@ -0,0 +1,179 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEvmCoinInfoValidate(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + coinInfo EvmCoinInfo + expPass bool + errContains string + }{ + { + name: "valid 18 decimals config", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: EighteenDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + { + name: "valid 6 decimals config", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: SixDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + { + name: "valid 12 decimals config", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: TwelveDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + { + name: "valid 1 decimal config", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: OneDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + { + name: "empty display denom", + coinInfo: EvmCoinInfo{ + DisplayDenom: "", + Decimals: EighteenDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: false, + errContains: "display denom cannot be empty", + }, + { + name: "invalid denom format - starts with number", + coinInfo: EvmCoinInfo{ + DisplayDenom: "1test", + Decimals: EighteenDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: false, + errContains: "invalid denom", + }, + { + name: "invalid extended denom format - too short", + coinInfo: EvmCoinInfo{ + DisplayDenom: "t", + Decimals: SixDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: false, + errContains: "invalid display denom", + }, + { + name: "invalid display denom character", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test@", + Decimals: EighteenDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: false, + errContains: "invalid display denom", + }, + { + name: "zero decimals is invalid", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: 0, + ExtendedDecimals: EighteenDecimals, + }, + expPass: false, + errContains: "decimals validation failed", + }, + { + name: "invalid si decimals", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: TenDecimals, + ExtendedDecimals: TenDecimals, + }, + expPass: false, + errContains: "invalid extended denom", + }, + { + name: "decimals out of valid range", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: Decimals(19), + ExtendedDecimals: Decimals(19), + }, + expPass: false, + errContains: "received unsupported decimals", + }, + { + name: "18 decimals with different extended decimals", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: EighteenDecimals, + ExtendedDecimals: TwelveDecimals, + }, + expPass: false, + errContains: "decimals and extended decimals must be the same for 18 decimals", + }, + { + name: "valid 6 decimals with different extended decimals", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test", + Decimals: SixDecimals, + ExtendedDecimals: NineDecimals, + }, + expPass: true, + }, + { + name: "display denom with valid special characters", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test-coin", + Decimals: SixDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + { + name: "display denom with valid numbers", + coinInfo: EvmCoinInfo{ + DisplayDenom: "test123", + Decimals: SixDecimals, + ExtendedDecimals: EighteenDecimals, + }, + expPass: true, + }, + } + + for _, tc := range testCases { + tc := tc //nolint:copyloopvar // Needed to work correctly with concurrent tests + + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + err := tc.coinInfo.Validate() + + if tc.expPass { + require.NoError(t, err, "expected validation to pass for %s", tc.name) + } else { + require.Error(t, err, "expected validation to fail for %s", tc.name) + require.Contains(t, err.Error(), tc.errContains, "error message should contain expected text") + } + }) + } +} diff --git a/x/vm/types/evm_config.go b/x/vm/types/evm_config.go new file mode 100644 index 000000000..a0eaf8fc8 --- /dev/null +++ b/x/vm/types/evm_config.go @@ -0,0 +1,43 @@ +// The config package provides a convenient way to modify x/evm params and values. +// Its primary purpose is to be used during application initialization. + +package types + +import ( + "github.com/ethereum/go-ethereum/core/vm" +) + +// EvmConfig contains the specific EVM configuration details +type EvmConfig struct { + ChainConfig *ChainConfig + CoinInfo *EvmCoinInfo + ExtendedEIPs map[int]func(*vm.JumpTable) +} + +// NewEvmConfig returns a pointer to a new EvmConfig struct +func NewEvmConfig() *EvmConfig { + return &EvmConfig{} +} + +// WithChainConfig defines the custom EVM chain configuration +func (ec *EvmConfig) WithChainConfig(cc *ChainConfig) *EvmConfig { + ec.ChainConfig = cc + return ec +} + +// WithEVMCoinInfo defines EVM coin info, including denom and decimals details +func (ec *EvmConfig) WithEVMCoinInfo(coinInfo *EvmCoinInfo) *EvmConfig { + ec.CoinInfo = coinInfo + return ec +} + +// WithExtendedEips extends the global geth activators map with the provided EIP activators +func (ec *EvmConfig) WithExtendedEips(extendedEIPs map[int]func(*vm.JumpTable)) *EvmConfig { + ec.ExtendedEIPs = extendedEIPs + return ec +} + +// ApplyExtendedEips adds the extended EIPs to the GLOBAL geth activators map +func (ec *EvmConfig) ApplyExtendedEips() error { + return vm.ExtendActivators(ec.ExtendedEIPs) +} diff --git a/x/vm/types/msg.go b/x/vm/types/msg.go index 169a7c16a..cce7f5ef4 100644 --- a/x/vm/types/msg.go +++ b/x/vm/types/msg.go @@ -318,7 +318,7 @@ func (msg *MsgEthereumTx) BuildTx(b client.TxBuilder, evmDenom string) (signing. feeAmt := sdkmath.NewIntFromBigInt(msg.GetFee()) if feeAmt.Sign() > 0 { fees = append(fees, sdk.NewCoin(evmDenom, feeAmt)) - fees = ConvertCoinsDenomToExtendedDenom(fees) + fees = ConvertCoinsDenomTo18DecimalsDenom(fees) } builder.SetExtensionOptions(option) diff --git a/x/vm/types/msg_test.go b/x/vm/types/msg_test.go index 2692b3edb..735cb5c41 100644 --- a/x/vm/types/msg_test.go +++ b/x/vm/types/msg_test.go @@ -14,8 +14,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/cosmos/evm/encoding" - "github.com/cosmos/evm/testutil/config" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" utiltx "github.com/cosmos/evm/testutil/tx" "github.com/cosmos/evm/x/vm/types" @@ -53,9 +52,6 @@ func (suite *MsgsTestSuite) SetupTest() { encodingConfig := encoding.MakeConfig(suite.chainID.Uint64()) suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig) - - err := config.EvmAppOptions(9001) - suite.Require().NoError(err) } func (suite *MsgsTestSuite) TestMsgEthereumTx_Constructor() { @@ -111,17 +107,13 @@ func (suite *MsgsTestSuite) TestMsgEthereumTx_BuildTx() { false, }, } - for _, coinInfo := range []types.EvmCoinInfo{ - testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], - testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + for _, coinInfo := range []*types.EvmCoinInfo{ + testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo, + testconfig.DefaultChainConfig.EvmConfig.CoinInfo, } { for _, tc := range testCases { - configurator := types.NewEVMConfigurator() - configurator.ResetTestConfig() - suite.Require().NoError(configurator.WithEVMCoinInfo(coinInfo).Configure()) - - baseDenom := types.GetEVMCoinDenom() - extendedDenom := types.GetEVMCoinExtendedDenom() + baseDenom := coinInfo.Denom + extendedDenom := coinInfo.ExtendedDenom tx, err := tc.msg.BuildTx(suite.clientCtx.TxConfig.NewTxBuilder(), baseDenom) if tc.expError { diff --git a/x/vm/types/params.go b/x/vm/types/params.go index 5b3e8d400..d64256ff2 100644 --- a/x/vm/types/params.go +++ b/x/vm/types/params.go @@ -17,34 +17,19 @@ import ( ) var ( - // DefaultEVMDenom is the default value for the evm denom - DefaultEVMDenom = "atest" - // DefaultEVMChainID is the default value for the evm chain ID - DefaultEVMChainID = "cosmos_262144-1" - // DefaultEVMDecimals is the default value for the evm denom decimal precision - DefaultEVMDecimals uint64 = 18 - // DefaultStaticPrecompiles defines the default active precompiles. - DefaultStaticPrecompiles []string - // DefaultExtraEIPs defines the default extra EIPs to be included. - DefaultExtraEIPs []int64 - // DefaultEVMChannels defines a list of IBC channels that connect to EVM chains like injective or cronos. - DefaultEVMChannels []string - DefaultCreateAllowlistAddresses []string - DefaultCallAllowlistAddresses []string - DefaultAccessControl = AccessControl{ + defaultHistoryServeWindow = uint64(8192) // same as EIP-2935 + defaultAccessControl = AccessControl{ Create: AccessControlType{ AccessType: AccessTypePermissionless, - AccessControlList: DefaultCreateAllowlistAddresses, + AccessControlList: nil, }, Call: AccessControlType{ AccessType: AccessTypePermissionless, - AccessControlList: DefaultCallAllowlistAddresses, + AccessControlList: nil, }, } ) -const DefaultHistoryServeWindow = 8192 // same as EIP-2935 - // NewParams creates a new Params instance func NewParams( extraEIPs []int64, @@ -60,18 +45,24 @@ func NewParams( } } -// DefaultParams returns default evm parameters +// DefaultParams returns default evm parameters with denom atest func DefaultParams() Params { return Params{ - EvmDenom: DefaultEVMDenom, - ExtraEIPs: DefaultExtraEIPs, - ActiveStaticPrecompiles: DefaultStaticPrecompiles, - EVMChannels: DefaultEVMChannels, - AccessControl: DefaultAccessControl, - HistoryServeWindow: DefaultHistoryServeWindow, + HistoryServeWindow: defaultHistoryServeWindow, + AccessControl: defaultAccessControl, } } +// DefaultHistoryServeWindow returns the default EIP-2935 history serve window +func DefaultHistoryServeWindow() uint64 { + return defaultHistoryServeWindow +} + +// DefaultAccessControl returns the default access control, which is permissionless with no access control list +func DefaultAccessControl() AccessControl { + return defaultAccessControl +} + // validateChannels checks if channels ids are valid func validateChannels(i interface{}) error { channels, ok := i.([]string) diff --git a/x/vm/types/params_test.go b/x/vm/types/params_test.go index 23e8dc007..70ab35cba 100644 --- a/x/vm/types/params_test.go +++ b/x/vm/types/params_test.go @@ -9,8 +9,8 @@ import ( func TestParamsValidate(t *testing.T) { t.Parallel() - extraEips := []int64{2929, 1884, 1344} + testCases := []struct { name string params Params @@ -23,8 +23,12 @@ func TestParamsValidate(t *testing.T) { expPass: true, }, { - name: "valid", - params: NewParams(extraEips, nil, nil, DefaultAccessControl), + name: "valid", + params: func() Params { + defaultParams := DefaultParams() + defaultParams.ExtraEIPs = extraEips + return defaultParams + }(), expPass: true, }, { @@ -77,7 +81,8 @@ func TestParamsValidate(t *testing.T) { func TestParamsEIPs(t *testing.T) { extraEips := []int64{2929, 1884, 1344} - params := NewParams(extraEips, nil, nil, DefaultAccessControl) + params := DefaultParams() + params.ExtraEIPs = extraEips actual := params.EIPs() require.Equal(t, []int{2929, 1884, 1344}, actual) diff --git a/x/vm/types/scaling.go b/x/vm/types/scaling.go index ee7dde6c6..aaf8231ee 100644 --- a/x/vm/types/scaling.go +++ b/x/vm/types/scaling.go @@ -1,9 +1,9 @@ package types import ( - "fmt" "math/big" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" sdkmath "cosmossdk.io/math" @@ -13,54 +13,55 @@ import ( // ConvertAmountToLegacy18Decimals convert the given amount into a 18 decimals // representation. -func ConvertAmountTo18DecimalsLegacy(amt sdkmath.LegacyDec) sdkmath.LegacyDec { - evmCoinDecimal := GetEVMCoinDecimals() - - return amt.MulInt(evmCoinDecimal.ConversionFactor()) +func ConvertAmountTo18DecimalsLegacy(amt sdkmath.LegacyDec, decimals Decimals) sdkmath.LegacyDec { + return amt.MulInt(decimals.ConversionFactor()) } // ConvertAmountTo18DecimalsBigInt convert the given amount into a 18 decimals // representation. -func ConvertAmountTo18DecimalsBigInt(amt *big.Int) *big.Int { - evmCoinDecimal := GetEVMCoinDecimals() - - return new(big.Int).Mul(amt, evmCoinDecimal.ConversionFactor().BigInt()) +func ConvertAmountTo18DecimalsBigInt(amt *big.Int, decimals Decimals) *big.Int { + return new(big.Int).Mul(amt, decimals.ConversionFactor().BigInt()) } // ConvertAmountTo18Decimals256Int convert the given amount into a 18 decimals // representation. -func ConvertAmountTo18Decimals256Int(amt *uint256.Int) *uint256.Int { - evmCoinDecimal := GetEVMCoinDecimals() - - return new(uint256.Int).Mul(amt, uint256.NewInt(evmCoinDecimal.ConversionFactor().Uint64())) +func ConvertAmountTo18Decimals256Int(amt *uint256.Int, decimals Decimals) *uint256.Int { + return new(uint256.Int).Mul(amt, uint256.NewInt(decimals.ConversionFactor().Uint64())) } // ConvertBigIntFrom18DecimalsToLegacyDec converts the given amount into a LegacyDec // with the corresponding decimals of the EVM denom. -func ConvertBigIntFrom18DecimalsToLegacyDec(amt *big.Int) sdkmath.LegacyDec { - evmCoinDecimal := GetEVMCoinDecimals() +func ConvertBigIntFrom18DecimalsToLegacyDec(amt *big.Int, decimals Decimals) sdkmath.LegacyDec { decAmt := sdkmath.LegacyNewDecFromBigInt(amt) - return decAmt.QuoInt(evmCoinDecimal.ConversionFactor()) + return decAmt.QuoInt(decimals.ConversionFactor()) } -// ConvertEvmCoinDenomToExtendedDenom converts the coin's Denom to the extended denom. -// Return an error if the coin denom is not the EVM. -func ConvertEvmCoinDenomToExtendedDenom(coin sdk.Coin) (sdk.Coin, error) { - if coin.Denom != GetEVMCoinDenom() { - return sdk.Coin{}, fmt.Errorf("expected coin denom %s, received %s", GetEVMCoinDenom(), coin.Denom) +// ConvertCoinDenomTo18DecimalsDenom converts the coin's Denom to the extended denom. +func ConvertCoinDenomTo18DecimalsDenom(coin sdk.Coin) (sdk.Coin, error) { + if err := sdk.ValidateDenom(coin.Denom); err != nil { + return sdk.Coin{}, err } + displayDenom := coin.Denom[1:] + extendedDenom := CreateDenomStr(EighteenDecimals, displayDenom) - return sdk.Coin{Denom: GetEVMCoinExtendedDenom(), Amount: coin.Amount}, nil + // we are just changing the denom without scaling the amount with conversion factor + return sdk.Coin{ + Denom: extendedDenom, + Amount: coin.Amount, + }, nil } -// ConvertCoinsDenomToExtendedDenom returns the given coins with the Denom of the evm +// ConvertCoinsDenomTo18DecimalsDenom returns the given coins with the Denom of the evm // coin converted to the extended denom. -func ConvertCoinsDenomToExtendedDenom(coins sdk.Coins) sdk.Coins { - evmDenom := GetEVMCoinDenom() +func ConvertCoinsDenomTo18DecimalsDenom(coins sdk.Coins, matchDenom string) sdk.Coins { convertedCoins := make(sdk.Coins, len(coins)) for i, coin := range coins { - if coin.Denom == evmDenom { - coin, _ = ConvertEvmCoinDenomToExtendedDenom(coin) + var err error + if coin.Denom == matchDenom { + coin, err = ConvertCoinDenomTo18DecimalsDenom(coin) + if err != nil { + log.Debug("failed to set denom to 18 decimals, adding zero coin", "error", err) + } } convertedCoins[i] = coin } diff --git a/x/vm/types/scaling_test.go b/x/vm/types/scaling_test.go index 421914fe1..776ec2cb9 100644 --- a/x/vm/types/scaling_test.go +++ b/x/vm/types/scaling_test.go @@ -8,7 +8,7 @@ import ( "github.com/holiman/uint256" "github.com/stretchr/testify/require" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" "cosmossdk.io/math" @@ -17,11 +17,17 @@ import ( ) func TestConvertEvmCoinFrom18Decimals(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo - eighteenDecimalsBaseCoinZero := sdk.Coin{Denom: eighteenDecimalsCoinInfo.Denom, Amount: math.NewInt(0)} - sixDecimalsBaseCoinZero := sdk.Coin{Denom: sixDecimalsCoinInfo.Denom, Amount: math.NewInt(0)} + eighteenDecimalsBaseCoinZero := sdk.Coin{ + Denom: eighteenDecimalsCoinInfo.GetDenom(), + Amount: math.NewInt(0), + } + sixDecimalsBaseCoinZero := sdk.Coin{ + Denom: sixDecimalsCoinInfo.GetDenom(), + Amount: math.NewInt(0), + } testCases := []struct { name string @@ -42,62 +48,72 @@ func TestConvertEvmCoinFrom18Decimals(t *testing.T) { evmCoinInfo: sixDecimalsCoinInfo, coin: sixDecimalsBaseCoinZero, expErr: false, - expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.ExtendedDenom, Amount: math.NewInt(0)}, + expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.GetExtendedDenom(), Amount: math.NewInt(0)}, }, { name: "pass - no conversion with 18 decimals", evmCoinInfo: eighteenDecimalsCoinInfo, - coin: sdk.Coin{Denom: eighteenDecimalsCoinInfo.Denom, Amount: math.NewInt(10)}, + coin: sdk.Coin{Denom: eighteenDecimalsCoinInfo.GetDenom(), Amount: math.NewInt(10)}, expErr: false, - expCoin: sdk.Coin{Denom: eighteenDecimalsCoinInfo.Denom, Amount: math.NewInt(10)}, + expCoin: sdk.Coin{Denom: eighteenDecimalsCoinInfo.GetDenom(), Amount: math.NewInt(10)}, }, { name: "pass - conversion with 6 decimals", evmCoinInfo: sixDecimalsCoinInfo, - coin: sdk.Coin{Denom: sixDecimalsCoinInfo.Denom, Amount: math.NewInt(1e12)}, + coin: sdk.Coin{Denom: sixDecimalsCoinInfo.GetDenom(), Amount: math.NewInt(1e12)}, expErr: false, - expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.ExtendedDenom, Amount: math.NewInt(1e12)}, + expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.GetExtendedDenom(), Amount: math.NewInt(1e12)}, }, { name: "pass - conversion with amount less than conversion factor", evmCoinInfo: sixDecimalsCoinInfo, - coin: sdk.Coin{Denom: sixDecimalsCoinInfo.Denom, Amount: math.NewInt(1e11)}, + coin: sdk.Coin{Denom: sixDecimalsCoinInfo.GetDenom(), Amount: math.NewInt(1e11)}, expErr: false, - expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.ExtendedDenom, Amount: math.NewInt(1e11)}, + expCoin: sdk.Coin{Denom: sixDecimalsCoinInfo.GetExtendedDenom(), Amount: math.NewInt(1e11)}, }, { - name: "fail - not evm denom", + name: "fail - not valid denom should panic", evmCoinInfo: sixDecimalsCoinInfo, - coin: sdk.Coin{Denom: "atom", Amount: math.NewInt(1)}, + coin: sdk.Coin{Denom: "", Amount: math.NewInt(1)}, expErr: true, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - require.NoError(t, configurator.WithEVMCoinInfo(tc.evmCoinInfo).Configure()) - - coinConverted, err := evmtypes.ConvertEvmCoinDenomToExtendedDenom(tc.coin) - - if !tc.expErr { - require.NoError(t, err) - require.Equal(t, tc.expCoin, coinConverted, "expected a different coin") - } else { - require.Error(t, err) + if tc.expErr { + defer func() { + r := recover() + if r == nil { + t.Errorf("expected panic, but did not") + } else { + require.Contains(t, r, "invalid denom") + } + }() } + coinConverted, err := evmtypes.ConvertCoinDenomTo18DecimalsDenom(tc.coin) + require.NoError(t, err) + require.Equal(t, tc.expCoin, coinConverted, "expected a different coin") }) } } func TestConvertCoinsFrom18Decimals(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo - nonBaseCoin := sdk.Coin{Denom: "btc", Amount: math.NewInt(10)} - eighteenDecimalsBaseCoin := sdk.Coin{Denom: eighteenDecimalsCoinInfo.Denom, Amount: math.NewInt(10)} - sixDecimalsBaseCoin := sdk.Coin{Denom: sixDecimalsCoinInfo.Denom, Amount: math.NewInt(10)} + nonBaseCoin := sdk.Coin{ + Denom: "btc", + Amount: math.NewInt(10), + } + eighteenDecimalsBaseCoin := sdk.Coin{ + Denom: eighteenDecimalsCoinInfo.GetDenom(), + Amount: math.NewInt(10), + } + sixDecimalsBaseCoin := sdk.Coin{ + Denom: sixDecimalsCoinInfo.GetDenom(), + Amount: math.NewInt(10), + } testCases := []struct { name string @@ -121,7 +137,7 @@ func TestConvertCoinsFrom18Decimals(t *testing.T) { name: "pass - only base denom 6 decimals", evmCoinInfo: sixDecimalsCoinInfo, coins: sdk.Coins{sixDecimalsBaseCoin}, - expCoins: sdk.Coins{sdk.Coin{Denom: sixDecimalsCoinInfo.ExtendedDenom, Amount: math.NewInt(10)}}, + expCoins: sdk.Coins{sdk.Coin{Denom: sixDecimalsCoinInfo.GetExtendedDenom(), Amount: math.NewInt(10)}}, }, { name: "pass - multiple coins and base denom 18 decimals", @@ -133,17 +149,13 @@ func TestConvertCoinsFrom18Decimals(t *testing.T) { name: "pass - multiple coins and base denom 6 decimals", evmCoinInfo: sixDecimalsCoinInfo, coins: sdk.Coins{nonBaseCoin, sixDecimalsBaseCoin}.Sort(), - expCoins: sdk.Coins{nonBaseCoin, sdk.Coin{Denom: sixDecimalsCoinInfo.ExtendedDenom, Amount: math.NewInt(10)}}.Sort(), + expCoins: sdk.Coins{nonBaseCoin, sdk.Coin{Denom: sixDecimalsCoinInfo.GetExtendedDenom(), Amount: math.NewInt(10)}}.Sort(), }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - require.NoError(t, configurator.WithEVMCoinInfo(tc.evmCoinInfo).Configure()) - - coinConverted := evmtypes.ConvertCoinsDenomToExtendedDenom(tc.coins) + coinConverted := evmtypes.ConvertCoinsDenomTo18DecimalsDenom(tc.coins, tc.evmCoinInfo.GetDenom()) require.Equal(t, tc.expCoins, coinConverted, "expected a different coin") }) } @@ -182,16 +194,13 @@ func TestConvertAmountTo18DecimalsLegacy(t *testing.T) { }, } - for _, coinInfo := range []evmtypes.EvmCoinInfo{ - testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], - testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + for _, coinInfo := range []*evmtypes.EvmCoinInfo{ + testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo, + testconfig.DefaultChainConfig.EvmConfig.CoinInfo, } { for _, tc := range testCases { t.Run(fmt.Sprintf("%d dec - %s", coinInfo.Decimals, tc.name), func(t *testing.T) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - require.NoError(t, configurator.WithEVMCoinInfo(coinInfo).Configure()) - res := evmtypes.ConvertBigIntFrom18DecimalsToLegacyDec(tc.amt.ToBig()) + res := evmtypes.ConvertBigIntFrom18DecimalsToLegacyDec(tc.amt.ToBig(), coinInfo.Decimals) exp := math.LegacyNewDecFromBigInt(tc.amt.ToBig()) if coinInfo.Decimals == evmtypes.SixDecimals { exp = tc.exp6dec @@ -220,16 +229,13 @@ func TestConvertAmountTo18DecimalsBigInt(t *testing.T) { }, } - for _, coinInfo := range []evmtypes.EvmCoinInfo{ - testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], - testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + for _, coinInfo := range []*evmtypes.EvmCoinInfo{ + testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo, + testconfig.DefaultChainConfig.EvmConfig.CoinInfo, } { for _, tc := range testCases { t.Run(fmt.Sprintf("%d dec - %s", coinInfo.Decimals, tc.name), func(t *testing.T) { - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - require.NoError(t, configurator.WithEVMCoinInfo(coinInfo).Configure()) - res := evmtypes.ConvertAmountTo18DecimalsBigInt(tc.amt) + res := evmtypes.ConvertAmountTo18DecimalsBigInt(tc.amt, coinInfo.Decimals) exp := tc.amt if coinInfo.Decimals == evmtypes.SixDecimals { exp = tc.exp6dec diff --git a/x/vm/wrappers/bank.go b/x/vm/wrappers/bank.go index ac50e3089..bed537657 100644 --- a/x/vm/wrappers/bank.go +++ b/x/vm/wrappers/bank.go @@ -19,14 +19,17 @@ var _ types.BankWrapper = BankWrapper{} // that is used to manage an evm denom with a custom decimal representation. type BankWrapper struct { types.BankKeeper + evmCfg *types.EvmConfig } // NewBankWrapper creates a new BankWrapper instance. func NewBankWrapper( bk types.BankKeeper, + evmCfg *types.EvmConfig, ) *BankWrapper { return &BankWrapper{ bk, + evmCfg, } } @@ -37,9 +40,12 @@ func NewBankWrapper( // MintAmountToAccount converts the given amount into the evm coin scaling // the amount to the original decimals, then mints that amount to the provided account. func (w BankWrapper) MintAmountToAccount(ctx context.Context, recipientAddr sdk.AccAddress, amt *big.Int) error { - coin := sdk.Coin{Denom: types.GetEVMCoinDenom(), Amount: sdkmath.NewIntFromBigInt(amt)} + coin := sdk.Coin{ + Denom: w.evmCfg.CoinInfo.GetDenom(), + Amount: sdkmath.NewIntFromBigInt(amt), + } - convertedCoin, err := types.ConvertEvmCoinDenomToExtendedDenom(coin) + convertedCoin, err := types.ConvertCoinDenomTo18DecimalsDenom(coin) if err != nil { return errors.Wrap(err, "failed to mint coin to account in bank wrapper") } @@ -55,9 +61,12 @@ func (w BankWrapper) MintAmountToAccount(ctx context.Context, recipientAddr sdk. // BurnAmountFromAccount converts the given amount into the evm coin scaling // the amount to the original decimals, then burns that quantity from the provided account. func (w BankWrapper) BurnAmountFromAccount(ctx context.Context, account sdk.AccAddress, amt *big.Int) error { - coin := sdk.Coin{Denom: types.GetEVMCoinDenom(), Amount: sdkmath.NewIntFromBigInt(amt)} + coin := sdk.Coin{ + Denom: w.evmCfg.CoinInfo.GetDenom(), + Amount: sdkmath.NewIntFromBigInt(amt), + } - convertedCoin, err := types.ConvertEvmCoinDenomToExtendedDenom(coin) + convertedCoin, err := types.ConvertCoinDenomTo18DecimalsDenom(coin) if err != nil { return errors.Wrap(err, "failed to burn coins from account in bank wrapper") } @@ -76,27 +85,27 @@ func (w BankWrapper) BurnAmountFromAccount(ctx context.Context, account sdk.AccA // GetBalance returns the balance of the given account. func (w BankWrapper) GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if denom != types.GetEVMCoinDenom() { - panic(fmt.Sprintf("expected evm denom %s, received %s", types.GetEVMCoinDenom(), denom)) + if denom != w.evmCfg.CoinInfo.GetDenom() { + panic(fmt.Sprintf("expected evm denom %s, received %s", w.evmCfg.CoinInfo.GetDenom(), denom)) } - return w.BankKeeper.GetBalance(ctx, addr, types.GetEVMCoinExtendedDenom()) + return w.BankKeeper.GetBalance(ctx, addr, w.evmCfg.CoinInfo.GetExtendedDenom()) } // SpendableCoin returns the balance of the given account. func (w BankWrapper) SpendableCoin(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if denom != types.GetEVMCoinDenom() { - panic(fmt.Sprintf("expected evm denom %s, received %s", types.GetEVMCoinDenom(), denom)) + if denom != w.evmCfg.CoinInfo.GetDenom() { + panic(fmt.Sprintf("expected evm denom %s, received %s", w.evmCfg.CoinInfo.GetDenom(), denom)) } - return w.BankKeeper.SpendableCoin(ctx, addr, types.GetEVMCoinExtendedDenom()) + return w.BankKeeper.SpendableCoin(ctx, addr, w.evmCfg.CoinInfo.GetExtendedDenom()) } // SendCoinsFromAccountToModule wraps around the Cosmos SDK x/bank module's // SendCoinsFromAccountToModule method to convert the evm coin, if present in // the input, to its original representation. func (w BankWrapper) SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, coins sdk.Coins) error { - convertedCoins := types.ConvertCoinsDenomToExtendedDenom(coins) + convertedCoins := types.ConvertCoinsDenomTo18DecimalsDenom(coins, w.evmCfg.CoinInfo.GetDenom()) if convertedCoins.IsZero() { // if after scaling the coins the amt is zero // then is a no-op. @@ -112,7 +121,7 @@ func (w BankWrapper) SendCoinsFromAccountToModule(ctx context.Context, senderAdd // SendCoinsFromModuleToAccount method to convert the evm coin, if present in // the input, to its original representation. func (w BankWrapper) SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, coins sdk.Coins) error { - convertedCoins := types.ConvertCoinsDenomToExtendedDenom(coins) + convertedCoins := types.ConvertCoinsDenomTo18DecimalsDenom(coins, w.evmCfg.CoinInfo.GetDenom()) if convertedCoins.IsZero() { return nil } diff --git a/x/vm/wrappers/bank_test.go b/x/vm/wrappers/bank_test.go index 590da9908..843cdca8b 100644 --- a/x/vm/wrappers/bank_test.go +++ b/x/vm/wrappers/bank_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/cosmos/evm/x/vm/wrappers" "github.com/cosmos/evm/x/vm/wrappers/testutil" @@ -23,8 +23,8 @@ import ( // --------------------------------------TRANSACTIONS----------------------------------------------- func TestMintAmountToAccount(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo testCases := []struct { name string @@ -38,12 +38,12 @@ func TestMintAmountToAccount(t *testing.T) { { name: "success - convert evm coin denom to extended denom", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, + evmDenom: sixDecimalsCoinInfo.GetDenom(), amount: big.NewInt(1e18), // 1 token in 18 decimals recipient: sdk.AccAddress([]byte("test_address")), expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) // 1 token in 18 decimals + expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) // 1 token in 18 decimals expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -62,12 +62,12 @@ func TestMintAmountToAccount(t *testing.T) { { name: "success - 18 decimals amount not modified", coinInfo: eighteenDecimalsCoinInfo, - evmDenom: eighteenDecimalsCoinInfo.Denom, + evmDenom: eighteenDecimalsCoinInfo.GetDenom(), amount: big.NewInt(1e18), // 1 token in 18 decimals recipient: sdk.AccAddress([]byte("test_address")), expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -86,12 +86,12 @@ func TestMintAmountToAccount(t *testing.T) { { name: "fail - mint coins error", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, + evmDenom: sixDecimalsCoinInfo.GetDenom(), amount: big.NewInt(1e18), recipient: sdk.AccAddress([]byte("test_address")), expectErr: "failed to mint coins to account in bank wrapper", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -103,20 +103,15 @@ func TestMintAmountToAccount(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - // Setup mock controller ctrl := gomock.NewController(t) mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) - err = bankWrapper.MintAmountToAccount(context.Background(), tc.recipient, tc.amount) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) + err := bankWrapper.MintAmountToAccount(context.Background(), tc.recipient, tc.amount) if tc.expectErr != "" { require.ErrorContains(t, err, tc.expectErr) @@ -128,8 +123,8 @@ func TestMintAmountToAccount(t *testing.T) { } func TestBurnAmountFromAccount(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo account := sdk.AccAddress([]byte("test_address")) @@ -146,7 +141,7 @@ func TestBurnAmountFromAccount(t *testing.T) { amount: big.NewInt(1e18), expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -168,7 +163,7 @@ func TestBurnAmountFromAccount(t *testing.T) { amount: big.NewInt(1e18), expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -190,7 +185,7 @@ func TestBurnAmountFromAccount(t *testing.T) { amount: big.NewInt(1e18), expectErr: "failed to burn coins from account in bank wrapper", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -208,7 +203,7 @@ func TestBurnAmountFromAccount(t *testing.T) { amount: big.NewInt(1e18), expectErr: "burn error", mockSetup: func(mbk *testutil.MockBankWrapper) { - expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + expectedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) expectedCoins := sdk.NewCoins(expectedCoin) mbk.EXPECT(). @@ -224,11 +219,6 @@ func TestBurnAmountFromAccount(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") // Setup mock controller ctrl := gomock.NewController(t) @@ -236,8 +226,9 @@ func TestBurnAmountFromAccount(t *testing.T) { mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) - err = bankWrapper.BurnAmountFromAccount(context.Background(), account, tc.amount) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) + err := bankWrapper.BurnAmountFromAccount(context.Background(), account, tc.amount) if tc.expectErr != "" { require.ErrorContains(t, err, tc.expectErr) @@ -249,8 +240,8 @@ func TestBurnAmountFromAccount(t *testing.T) { } func TestSendCoinsFromModuleToAccount(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo account := sdk.AccAddress([]byte("test_address")) @@ -266,14 +257,14 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { coinInfo: eighteenDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) return coins }, expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) mbk.EXPECT(). @@ -290,14 +281,14 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) return coins }, expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), }...) mbk.EXPECT(). @@ -314,7 +305,7 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { coinInfo: eighteenDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) return coins @@ -322,7 +313,7 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) @@ -340,7 +331,7 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) return coins @@ -348,7 +339,7 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) @@ -366,7 +357,7 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.ZeroInt()), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.ZeroInt()), }...) return coins }, @@ -385,20 +376,15 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - // Setup mock controller ctrl := gomock.NewController(t) mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) - err = bankWrapper.SendCoinsFromModuleToAccount(context.Background(), evmtypes.ModuleName, account, tc.coins()) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) + err := bankWrapper.SendCoinsFromModuleToAccount(context.Background(), evmtypes.ModuleName, account, tc.coins()) if tc.expectErr != "" { require.ErrorContains(t, err, tc.expectErr) @@ -410,8 +396,8 @@ func TestSendCoinsFromModuleToAccount(t *testing.T) { } func TestSendCoinsFromAccountToModule(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo account := sdk.AccAddress([]byte("test_address")) @@ -427,14 +413,14 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { coinInfo: eighteenDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) return coins }, expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) mbk.EXPECT(). @@ -451,14 +437,14 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), }...) return coins }, expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), }...) mbk.EXPECT(). @@ -475,7 +461,7 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { coinInfo: eighteenDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) return coins @@ -483,7 +469,7 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) @@ -501,7 +487,7 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) return coins @@ -509,7 +495,7 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { expectErr: "", mockSetup: func(mbk *testutil.MockBankWrapper) { expectedCoins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), + sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), sdk.NewCoin("something", sdkmath.NewInt(3e18)), }...) @@ -527,7 +513,7 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { coinInfo: sixDecimalsCoinInfo, coins: func() sdk.Coins { coins := sdk.NewCoins([]sdk.Coin{ - sdk.NewCoin(sixDecimalsCoinInfo.Denom, sdkmath.ZeroInt()), + sdk.NewCoin(sixDecimalsCoinInfo.GetDenom(), sdkmath.ZeroInt()), }...) return coins }, @@ -546,20 +532,15 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - // Setup mock controller ctrl := gomock.NewController(t) mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) - err = bankWrapper.SendCoinsFromAccountToModule(context.Background(), account, evmtypes.ModuleName, tc.coins()) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) + err := bankWrapper.SendCoinsFromAccountToModule(context.Background(), account, evmtypes.ModuleName, tc.coins()) if tc.expectErr != "" { require.ErrorContains(t, err, tc.expectErr) @@ -573,8 +554,8 @@ func TestSendCoinsFromAccountToModule(t *testing.T) { // ----------------------------------------QUERIES------------------------------------------------- func TestGetBalance(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo maxInt64 := int64(9223372036854775807) account := sdk.AccAddress([]byte("test_address")) @@ -584,92 +565,86 @@ func TestGetBalance(t *testing.T) { coinInfo evmtypes.EvmCoinInfo evmDenom string expCoin sdk.Coin - expErr string expPanic string mockSetup func(*testutil.MockBankWrapper) }{ { name: "success - convert 6 decimals amount to 18 decimals", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) mbk.EXPECT(). GetBalance( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - convert max int 6 decimals amount to 18 decimals", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e12).MulRaw(maxInt64)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e12).MulRaw(maxInt64)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e12).MulRaw(maxInt64)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e12).MulRaw(maxInt64)) mbk.EXPECT(). GetBalance( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - does not convert 18 decimals amount", coinInfo: eighteenDecimalsCoinInfo, - evmDenom: eighteenDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), - expErr: "", + evmDenom: eighteenDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)) + returnedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)) mbk.EXPECT(). GetBalance( gomock.Any(), account, - eighteenDecimalsCoinInfo.Denom, + eighteenDecimalsCoinInfo.GetDenom(), ).Return(returnedCoin) }, }, { name: "success - zero balance", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(0)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(0)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(0)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(0)) mbk.EXPECT(). GetBalance( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - small amount (less than 1 full token)", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e14)), // 0.0001 token in 18 decimals - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e14)), // 0.0001 token in 18 decimals mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e14)) // 0.0001 token in 6 decimals + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e14)) // 0.0001 token in 6 decimals mbk.EXPECT(). GetBalance( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, @@ -684,19 +659,14 @@ func TestGetBalance(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - // Setup mock controller ctrl := gomock.NewController(t) mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) // When calling the function with a denom different than the evm one, it should panic defer func() { @@ -706,22 +676,16 @@ func TestGetBalance(t *testing.T) { }() balance := bankWrapper.GetBalance(context.Background(), account, tc.evmDenom) - - if tc.expErr != "" { - require.ErrorContains(t, err, tc.expErr) - } else { - require.NoError(t, err) - require.Equal(t, tc.expCoin, balance, "expected a different balance") - } + require.Equal(t, tc.expCoin, balance, "expected a different balance") }) } } // ----------------------------------------QUERIES------------------------------------------------- -func TestSppendableCoin(t *testing.T) { - eighteenDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID] - sixDecimalsCoinInfo := testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID] +func TestSpendableCoin(t *testing.T) { + eighteenDecimalsCoinInfo := *testconfig.DefaultChainConfig.EvmConfig.CoinInfo + sixDecimalsCoinInfo := *testconfig.SixDecimalsChainConfig.EvmConfig.CoinInfo maxInt64 := int64(9223372036854775807) account := sdk.AccAddress([]byte("test_address")) @@ -731,92 +695,86 @@ func TestSppendableCoin(t *testing.T) { coinInfo evmtypes.EvmCoinInfo evmDenom string expCoin sdk.Coin - expErr string expPanic string mockSetup func(*testutil.MockBankWrapper) }{ { name: "success - convert 6 decimals amount to 18 decimals", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e18)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e18)) mbk.EXPECT(). SpendableCoin( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - convert max int 6 decimals amount to 18 decimals", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e12).MulRaw(maxInt64)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e12).MulRaw(maxInt64)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e12).MulRaw(maxInt64)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e12).MulRaw(maxInt64)) mbk.EXPECT(). SpendableCoin( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - does not convert 18 decimals amount", coinInfo: eighteenDecimalsCoinInfo, - evmDenom: eighteenDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)), - expErr: "", + evmDenom: eighteenDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.Denom, sdkmath.NewInt(1e18)) + returnedCoin := sdk.NewCoin(eighteenDecimalsCoinInfo.GetDenom(), sdkmath.NewInt(1e18)) mbk.EXPECT(). SpendableCoin( gomock.Any(), account, - eighteenDecimalsCoinInfo.Denom, + eighteenDecimalsCoinInfo.GetDenom(), ).Return(returnedCoin) }, }, { name: "success - zero balance", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(0)), - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(0)), mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(0)) + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(0)) mbk.EXPECT(). SpendableCoin( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, { name: "success - small amount (less than 1 full token)", coinInfo: sixDecimalsCoinInfo, - evmDenom: sixDecimalsCoinInfo.Denom, - expCoin: sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e14)), // 0.0001 token in 18 decimals - expErr: "", + evmDenom: sixDecimalsCoinInfo.GetDenom(), + expCoin: sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e14)), // 0.0001 token in 18 decimals mockSetup: func(mbk *testutil.MockBankWrapper) { - returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.ExtendedDenom, sdkmath.NewInt(1e14)) // 0.0001 token in 6 decimals + returnedCoin := sdk.NewCoin(sixDecimalsCoinInfo.GetExtendedDenom(), sdkmath.NewInt(1e14)) // 0.0001 token in 6 decimals mbk.EXPECT(). SpendableCoin( gomock.Any(), account, - sixDecimalsCoinInfo.ExtendedDenom, + sixDecimalsCoinInfo.GetExtendedDenom(), ).Return(returnedCoin) }, }, @@ -831,19 +789,14 @@ func TestSppendableCoin(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - // Setup mock controller ctrl := gomock.NewController(t) mockBankKeeper := testutil.NewMockBankWrapper(ctrl) tc.mockSetup(mockBankKeeper) - bankWrapper := wrappers.NewBankWrapper(mockBankKeeper) + defaultEvmConfig := testconfig.DefaultChainConfig.EvmConfig + bankWrapper := wrappers.NewBankWrapper(mockBankKeeper, defaultEvmConfig) // When calling the function with a denom different than the evm one, it should panic defer func() { @@ -853,13 +806,7 @@ func TestSppendableCoin(t *testing.T) { }() balance := bankWrapper.SpendableCoin(context.Background(), account, tc.evmDenom) - - if tc.expErr != "" { - require.ErrorContains(t, err, tc.expErr) - } else { - require.NoError(t, err) - require.Equal(t, tc.expCoin, balance, "expected a different balance") - } + require.Equal(t, tc.expCoin, balance, "expected a different balance") }) } } diff --git a/x/vm/wrappers/feemarket.go b/x/vm/wrappers/feemarket.go index ad0cb2f6c..5d89c958e 100644 --- a/x/vm/wrappers/feemarket.go +++ b/x/vm/wrappers/feemarket.go @@ -17,15 +17,18 @@ import ( // with the bank module decimals (either 6 or 18). type FeeMarketWrapper struct { types.FeeMarketKeeper + evmCfg *types.EvmConfig } // NewFeeMarketWrapper creates a new feemarket Keeper wrapper instance. // The BankWrapper is used to manage an evm denom with 6 or 18 decimals. func NewFeeMarketWrapper( fk types.FeeMarketKeeper, + evmCfg *types.EvmConfig, ) *FeeMarketWrapper { return &FeeMarketWrapper{ fk, + evmCfg, } } @@ -35,7 +38,7 @@ func (w FeeMarketWrapper) GetBaseFee(ctx sdk.Context) *big.Int { if baseFee.IsNil() { return nil } - return types.ConvertAmountTo18DecimalsLegacy(baseFee).TruncateInt().BigInt() + return types.ConvertAmountTo18DecimalsLegacy(baseFee, w.evmCfg.CoinInfo.Decimals).TruncateInt().BigInt() } // CalculateBaseFee returns the calculated base fee converted to 18 decimals. @@ -44,15 +47,18 @@ func (w FeeMarketWrapper) CalculateBaseFee(ctx sdk.Context) *big.Int { if baseFee.IsNil() { return nil } - return types.ConvertAmountTo18DecimalsLegacy(baseFee).TruncateInt().BigInt() + baseDecimals := w.evmCfg.CoinInfo.Decimals + return types.ConvertAmountTo18DecimalsLegacy(baseFee, baseDecimals).TruncateInt().BigInt() } // GetParams returns the params with associated fees values converted to 18 decimals. func (w FeeMarketWrapper) GetParams(ctx sdk.Context) feemarkettypes.Params { + baseDecimals := w.evmCfg.CoinInfo.Decimals + params := w.FeeMarketKeeper.GetParams(ctx) if !params.BaseFee.IsNil() { - params.BaseFee = types.ConvertAmountTo18DecimalsLegacy(params.BaseFee) + params.BaseFee = types.ConvertAmountTo18DecimalsLegacy(params.BaseFee, baseDecimals) } - params.MinGasPrice = types.ConvertAmountTo18DecimalsLegacy(params.MinGasPrice) + params.MinGasPrice = types.ConvertAmountTo18DecimalsLegacy(params.MinGasPrice, baseDecimals) return params } diff --git a/x/vm/wrappers/feemarket_test.go b/x/vm/wrappers/feemarket_test.go index 710f905ff..4e73d548e 100644 --- a/x/vm/wrappers/feemarket_test.go +++ b/x/vm/wrappers/feemarket_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" - testconstants "github.com/cosmos/evm/testutil/constants" + testconfig "github.com/cosmos/evm/testutil/config" feemarkettypes "github.com/cosmos/evm/x/feemarket/types" evmtypes "github.com/cosmos/evm/x/vm/types" "github.com/cosmos/evm/x/vm/wrappers" @@ -21,13 +21,13 @@ import ( func TestGetBaseFee(t *testing.T) { testCases := []struct { name string - coinInfo evmtypes.EvmCoinInfo + evmConfig *evmtypes.EvmConfig expResult *big.Int mockSetup func(*testutil.MockFeeMarketKeeper) }{ { name: "success - does not convert 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + evmConfig: testconfig.DefaultChainConfig.EvmConfig, expResult: big.NewInt(1e18), // 1 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -37,7 +37,7 @@ func TestGetBaseFee(t *testing.T) { }, { name: "success - convert 6 decimals to 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(1e18), // 1 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -47,7 +47,7 @@ func TestGetBaseFee(t *testing.T) { }, { name: "success - nil base fee", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: nil, mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -57,7 +57,7 @@ func TestGetBaseFee(t *testing.T) { }, { name: "success - small amount 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(1e12), // 0.000001 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -67,7 +67,7 @@ func TestGetBaseFee(t *testing.T) { }, { name: "success - base fee is zero", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(0), mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -77,7 +77,7 @@ func TestGetBaseFee(t *testing.T) { }, { name: "success - truncate decimals with number less than 1", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(0), // 0.000001 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -89,17 +89,11 @@ func TestGetBaseFee(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - ctrl := gomock.NewController(t) mockFeeMarketKeeper := testutil.NewMockFeeMarketKeeper(ctrl) tc.mockSetup(mockFeeMarketKeeper) - feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper) + feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper, tc.evmConfig) result := feeMarketWrapper.GetBaseFee(sdk.Context{}) require.Equal(t, tc.expResult, result) @@ -110,14 +104,14 @@ func TestGetBaseFee(t *testing.T) { func TestCalculateBaseFee(t *testing.T) { testCases := []struct { name string - coinInfo evmtypes.EvmCoinInfo + evmConfig *evmtypes.EvmConfig baseFee sdkmath.LegacyDec expResult *big.Int mockSetup func(*testutil.MockFeeMarketKeeper) }{ { name: "success - does not convert 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + evmConfig: testconfig.DefaultChainConfig.EvmConfig, expResult: big.NewInt(1e18), // 1 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -127,7 +121,7 @@ func TestCalculateBaseFee(t *testing.T) { }, { name: "success - convert 6 decimals to 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(1e18), // 1 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -137,7 +131,7 @@ func TestCalculateBaseFee(t *testing.T) { }, { name: "success - nil base fee", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: nil, mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -147,7 +141,7 @@ func TestCalculateBaseFee(t *testing.T) { }, { name: "success - small amount 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(1e12), // 0.000001 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -157,7 +151,7 @@ func TestCalculateBaseFee(t *testing.T) { }, { name: "success - base fee is zero", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(0), mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -167,7 +161,7 @@ func TestCalculateBaseFee(t *testing.T) { }, { name: "success - truncate decimals with number less than 1", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expResult: big.NewInt(0), // 0.000001 token in 18 decimals mockSetup: func(mfk *testutil.MockFeeMarketKeeper) { mfk.EXPECT(). @@ -179,17 +173,11 @@ func TestCalculateBaseFee(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - ctrl := gomock.NewController(t) mockFeeMarketKeeper := testutil.NewMockFeeMarketKeeper(ctrl) tc.mockSetup(mockFeeMarketKeeper) - feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper) + feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper, tc.evmConfig) result := feeMarketWrapper.CalculateBaseFee(sdk.Context{}) require.Equal(t, tc.expResult, result) @@ -200,13 +188,13 @@ func TestCalculateBaseFee(t *testing.T) { func TestGetParams(t *testing.T) { testCases := []struct { name string - coinInfo evmtypes.EvmCoinInfo + evmConfig *evmtypes.EvmConfig expParams feemarkettypes.Params mockSetup func(*testutil.MockFeeMarketKeeper) }{ { - name: "success - convert 6 decimals to 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.SixDecimalsChainID], + name: "success - convert 6 decimals to 18 decimals", + evmConfig: testconfig.SixDecimalsChainConfig.EvmConfig, expParams: feemarkettypes.Params{ BaseFee: sdkmath.LegacyNewDec(1e18), MinGasPrice: sdkmath.LegacyNewDec(1e18), @@ -221,8 +209,8 @@ func TestGetParams(t *testing.T) { }, }, { - name: "success - does not convert 18 decimals", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + name: "success - does not convert 18 decimals", + evmConfig: testconfig.DefaultChainConfig.EvmConfig, expParams: feemarkettypes.Params{ BaseFee: sdkmath.LegacyNewDec(1e18), MinGasPrice: sdkmath.LegacyNewDec(1e18), @@ -237,8 +225,8 @@ func TestGetParams(t *testing.T) { }, }, { - name: "success - nil base fee", - coinInfo: testconstants.ExampleChainCoinInfo[testconstants.ExampleChainID], + name: "success - nil base fee", + evmConfig: testconfig.DefaultChainConfig.EvmConfig, expParams: feemarkettypes.Params{ MinGasPrice: sdkmath.LegacyNewDec(1e18), }, @@ -254,17 +242,11 @@ func TestGetParams(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - // Setup EVM configurator to have access to the EVM coin info. - configurator := evmtypes.NewEVMConfigurator() - configurator.ResetTestConfig() - err := configurator.WithEVMCoinInfo(tc.coinInfo).Configure() - require.NoError(t, err, "failed to configure EVMConfigurator") - ctrl := gomock.NewController(t) mockFeeMarketKeeper := testutil.NewMockFeeMarketKeeper(ctrl) tc.mockSetup(mockFeeMarketKeeper) - feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper) + feeMarketWrapper := wrappers.NewFeeMarketWrapper(mockFeeMarketKeeper, tc.evmConfig) result := feeMarketWrapper.GetParams(sdk.Context{}) require.Equal(t, tc.expParams, result)