Sync from fork #74

Merged
0xmuralik merged 232 commits from murali/update-fork into main 2023-01-10 04:50:57 +00:00
90 changed files with 1379 additions and 974 deletions
Showing only changes of commit 29d3abcf09 - Show all commits

View File

@ -45,6 +45,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (evm) [\#1174](https://github.com/evmos/ethermint/pull/1174) Don't allow eth txs with 0 in mempool.
* (ante) [#1176](https://github.com/evmos/ethermint/pull/1176) Fix invalid tx hashes; Remove `Size_` field and validate `Hash`/`From` fields in ante handler,
recompute eth tx hashes in JSON-RPC APIs to fix old blocks.
* (deps) [#1168](https://github.com/evmos/ethermint/pull/1168) Upgrade cosmos-sdk to v0.46.
### Improvements

View File

@ -5,6 +5,8 @@ import (
"math/big"
"strings"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -278,7 +280,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
expFee := txData.Fee()
invalidFee := new(big.Int).Add(expFee, big.NewInt(1))
invalidFeeAmount := sdk.Coins{sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewIntFromBigInt(invalidFee))}
invalidFeeAmount := sdk.Coins{sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewIntFromBigInt(invalidFee))}
txBuilder.SetFeeAmount(invalidFeeAmount)
return txBuilder.GetTx()
}, false, false, false,
@ -303,7 +305,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"success - DeliverTx EIP712 signed Cosmos Tx with MsgSend",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9000-1", gas, amount)
return txBuilder.GetTx()
@ -313,7 +315,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"success - DeliverTx EIP712 signed Cosmos Tx with DelegateMsg",
func() sdk.Tx {
from := acc.GetAddress()
coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20))
coinAmount := sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20))
amount := sdk.NewCoins(coinAmount)
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgDelegate(from, privKey, "ethermint_9000-1", gas, amount)
@ -324,7 +326,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"fails - DeliverTx EIP712 signed Cosmos Tx with wrong Chain ID",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9002-1", gas, amount)
return txBuilder.GetTx()
@ -334,11 +336,11 @@ func (suite AnteTestSuite) TestAnteHandler() {
"fails - DeliverTx EIP712 signed Cosmos Tx with different gas fees",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9001-1", gas, amount)
txBuilder.SetGasLimit(uint64(300000))
txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(30))))
txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(30))))
return txBuilder.GetTx()
}, false, false, false,
},
@ -346,7 +348,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"fails - DeliverTx EIP712 signed Cosmos Tx with empty signature",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9001-1", gas, amount)
sigsV2 := signing.SignatureV2{}
@ -358,7 +360,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"fails - DeliverTx EIP712 signed Cosmos Tx with invalid sequence",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9001-1", gas, amount)
nonce, err := suite.app.AccountKeeper.GetSequence(suite.ctx, acc.GetAddress())
@ -378,7 +380,7 @@ func (suite AnteTestSuite) TestAnteHandler() {
"fails - DeliverTx EIP712 signed Cosmos Tx with invalid signMode",
func() sdk.Tx {
from := acc.GetAddress()
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
txBuilder := suite.CreateTestEIP712TxBuilderMsgSend(from, privKey, "ethermint_9001-1", gas, amount)
nonce, err := suite.app.AccountKeeper.GetSequence(suite.ctx, acc.GetAddress())

View File

@ -10,7 +10,7 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
@ -171,7 +171,7 @@ func VerifySignature(
Amount: tx.GetFee(),
Gas: tx.GetGas(),
},
msgs, tx.GetMemo(),
msgs, tx.GetMemo(), tx.GetTip(),
)
signerChainID, err := ethermint.ParseChainID(signerData.ChainID)
@ -188,13 +188,7 @@ func VerifySignature(
return sdkerrors.Wrap(sdkerrors.ErrUnknownExtensionOptions, "tx doesnt contain expected amount of extension options")
}
var optIface ethermint.ExtensionOptionsWeb3TxI
if err := ethermintCodec.UnpackAny(opts[0], &optIface); err != nil {
return sdkerrors.Wrap(err, "failed to proto-unpack ExtensionOptionsWeb3Tx")
}
extOpt, ok := optIface.(*ethermint.ExtensionOptionsWeb3Tx)
extOpt, ok := opts[0].GetCachedValue().(*ethermint.ExtensionOptionsWeb3Tx)
if !ok {
return sdkerrors.Wrap(sdkerrors.ErrInvalidChainID, "unknown extension option")
}

View File

@ -5,6 +5,8 @@ import (
"math/big"
"strconv"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
@ -128,7 +130,7 @@ func (avd EthAccountVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx
"the sender is not EOA: address %s, codeHash <%s>", fromAddr, acct.CodeHash)
}
if err := evmkeeper.CheckSenderBalance(sdk.NewIntFromBigInt(acct.Balance), txData); err != nil {
if err := evmkeeper.CheckSenderBalance(sdkmath.NewIntFromBigInt(acct.Balance), txData); err != nil {
return ctx, sdkerrors.Wrap(err, "failed to check sender balance")
}
@ -455,7 +457,7 @@ func (vbd EthValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simu
return ctx, sdkerrors.Wrap(ethtypes.ErrTxTypeNotSupported, "dynamic fee tx not supported")
}
txFee = txFee.Add(sdk.NewCoin(params.EvmDenom, sdk.NewIntFromBigInt(txData.Fee())))
txFee = txFee.Add(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(txData.Fee())))
}
authInfo := protoTx.AuthInfo

View File

@ -1,6 +1,7 @@
package ante_test
import (
"math"
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -234,25 +235,25 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() {
expPass bool
expPanic bool
}{
{"invalid transaction type", &invalidTx{}, 0, func() {}, false, false},
{"invalid transaction type", &invalidTx{}, math.MaxUint64, func() {}, false, false},
{
"sender not found",
evmtypes.NewTxContract(suite.app.EvmKeeper.ChainID(), 1, big.NewInt(10), 1000, big.NewInt(1), nil, nil, nil, nil),
0,
math.MaxUint64,
func() {},
false, false,
},
{
"gas limit too low",
tx,
0,
math.MaxUint64,
func() {},
false, false,
},
{
"not enough balance for fees",
tx2,
0,
math.MaxUint64,
func() {},
false, false,
},

View File

@ -3,6 +3,7 @@ package ante_test
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -31,9 +32,9 @@ func (suite AnteTestSuite) TestGasWantedDecorator() {
testMsg := banktypes.MsgSend{
FromAddress: "evmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp",
ToAddress: "evmos1dx67l23hz9l0k9hcher8xz04uj7wf3yu26l2yn",
Amount: sdk.Coins{sdk.Coin{Amount: sdk.NewInt(10), Denom: denom}},
Amount: sdk.Coins{sdk.Coin{Amount: sdkmath.NewInt(10), Denom: denom}},
}
txBuilder := suite.CreateTestCosmosTxBuilder(sdk.NewInt(10), "stake", &testMsg)
txBuilder := suite.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), "stake", &testMsg)
return txBuilder.GetTx()
},
},
@ -67,7 +68,7 @@ func (suite AnteTestSuite) TestGasWantedDecorator() {
"EIP712 message",
200000,
func() sdk.Tx {
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
amount := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
gas := uint64(200000)
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, from.Bytes())
suite.Require().NoError(acc.SetSequence(1))

View File

@ -3,6 +3,7 @@ package ante_test
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -25,7 +26,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
testMsg := banktypes.MsgSend{
FromAddress: "evmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp",
ToAddress: "evmos1dx67l23hz9l0k9hcher8xz04uj7wf3yu26l2yn",
Amount: sdk.Coins{sdk.Coin{Amount: sdk.NewInt(10), Denom: denom}},
Amount: sdk.Coins{sdk.Coin{Amount: sdkmath.NewInt(10), Denom: denom}},
}
testCases := []struct {
@ -49,7 +50,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
params.MinGasPrice = sdk.ZeroDec()
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(0), denom, &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(0), denom, &testMsg)
return txBuilder.GetTx()
},
true,
@ -62,7 +63,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
params.MinGasPrice = sdk.ZeroDec()
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(10), denom, &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), denom, &testMsg)
return txBuilder.GetTx()
},
true,
@ -75,7 +76,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
params.MinGasPrice = sdk.NewDec(10)
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(10), denom, &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), denom, &testMsg)
return txBuilder.GetTx()
},
true,
@ -88,7 +89,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
params.MinGasPrice = sdk.NewDec(10)
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(0), denom, &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(0), denom, &testMsg)
return txBuilder.GetTx()
},
false,
@ -101,7 +102,7 @@ func (s AnteTestSuite) TestMinGasPriceDecorator() {
params.MinGasPrice = sdk.NewDec(10)
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(10), "stake", &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(10), "stake", &testMsg)
return txBuilder.GetTx()
},
false,
@ -160,9 +161,9 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() {
testMsg := banktypes.MsgSend{
FromAddress: "evmos1x8fhpj9nmhqk8z9kpgjt95ck2xwyue0ptzkucp",
ToAddress: "evmos1dx67l23hz9l0k9hcher8xz04uj7wf3yu26l2yn",
Amount: sdk.Coins{sdk.Coin{Amount: sdk.NewInt(10), Denom: denom}},
Amount: sdk.Coins{sdk.Coin{Amount: sdkmath.NewInt(10), Denom: denom}},
}
txBuilder := s.CreateTestCosmosTxBuilder(sdk.NewInt(0), denom, &testMsg)
txBuilder := s.CreateTestCosmosTxBuilder(sdkmath.NewInt(0), denom, &testMsg)
return txBuilder.GetTx()
},
false,
@ -291,7 +292,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() {
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
feemarketParams := s.app.FeeMarketKeeper.GetParams(s.ctx)
feemarketParams.BaseFee = sdk.NewInt(10)
feemarketParams.BaseFee = sdkmath.NewInt(10)
s.app.FeeMarketKeeper.SetParams(s.ctx, feemarketParams)
msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(1000), big.NewInt(0), &emptyAccessList)
@ -308,7 +309,7 @@ func (s AnteTestSuite) TestEthMinGasPriceDecorator() {
s.app.FeeMarketKeeper.SetParams(s.ctx, params)
feemarketParams := s.app.FeeMarketKeeper.GetParams(s.ctx)
feemarketParams.BaseFee = sdk.NewInt(10)
feemarketParams.BaseFee = sdkmath.NewInt(10)
s.app.FeeMarketKeeper.SetParams(s.ctx, feemarketParams)
msg := s.BuildTestEthTx(from, to, nil, make([]byte, 0), nil, big.NewInt(1000), big.NewInt(101), &emptyAccessList)

View File

@ -8,8 +8,8 @@ import (
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
ibcante "github.com/cosmos/ibc-go/v4/modules/core/ante"
ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper"
ibcante "github.com/cosmos/ibc-go/v5/modules/core/ante"
ibckeeper "github.com/cosmos/ibc-go/v5/modules/core/keeper"
evmtypes "github.com/evmos/ethermint/x/evm/types"
)
@ -17,15 +17,17 @@ import (
// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC
// channel keeper, EVM Keeper and Fee Market Keeper.
type HandlerOptions struct {
AccountKeeper evmtypes.AccountKeeper
BankKeeper evmtypes.BankKeeper
IBCKeeper *ibckeeper.Keeper
FeeMarketKeeper evmtypes.FeeMarketKeeper
EvmKeeper EVMKeeper
FeegrantKeeper ante.FeegrantKeeper
SignModeHandler authsigning.SignModeHandler
SigGasConsumer func(meter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params) error
MaxTxGasWanted uint64
AccountKeeper evmtypes.AccountKeeper
BankKeeper evmtypes.BankKeeper
IBCKeeper *ibckeeper.Keeper
FeeMarketKeeper evmtypes.FeeMarketKeeper
EvmKeeper EVMKeeper
FeegrantKeeper ante.FeegrantKeeper
SignModeHandler authsigning.SignModeHandler
SigGasConsumer func(meter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params) error
MaxTxGasWanted uint64
ExtensionOptionChecker ante.ExtensionOptionChecker
TxFeeChecker ante.TxFeeChecker
}
func (options HandlerOptions) validate() error {
@ -67,21 +69,20 @@ func newCosmosAnteHandler(options HandlerOptions) sdk.AnteHandler {
return sdk.ChainAnteDecorators(
RejectMessagesDecorator{}, // reject MsgEthereumTxs
ante.NewSetUpContextDecorator(),
ante.NewRejectExtensionOptionsDecorator(),
ante.NewMempoolFeeDecorator(),
ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper),
ante.NewValidateBasicDecorator(),
ante.NewTxTimeoutHeightDecorator(),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
// SetPubKeyDecorator must be called before all signature verification decorators
ante.NewSetPubKeyDecorator(options.AccountKeeper),
ante.NewValidateSigCountDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler),
ante.NewIncrementSequenceDecorator(options.AccountKeeper),
ibcante.NewAnteDecorator(options.IBCKeeper),
ibcante.NewRedundancyDecorator(options.IBCKeeper),
NewGasWantedDecorator(options.EvmKeeper, options.FeeMarketKeeper),
)
}
@ -92,13 +93,12 @@ func newCosmosAnteHandlerEip712(options HandlerOptions) sdk.AnteHandler {
ante.NewSetUpContextDecorator(),
// NOTE: extensions option decorator removed
// ante.NewRejectExtensionOptionsDecorator(),
ante.NewMempoolFeeDecorator(),
NewMinGasPriceDecorator(options.FeeMarketKeeper, options.EvmKeeper),
ante.NewValidateBasicDecorator(),
ante.NewTxTimeoutHeightDecorator(),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
// SetPubKeyDecorator must be called before all signature verification decorators
ante.NewSetPubKeyDecorator(options.AccountKeeper),
ante.NewValidateSigCountDecorator(options.AccountKeeper),
@ -106,7 +106,7 @@ func newCosmosAnteHandlerEip712(options HandlerOptions) sdk.AnteHandler {
// Note: signature verification uses EIP instead of the cosmos signature validator
NewEip712SigVerificationDecorator(options.AccountKeeper, options.SignModeHandler),
ante.NewIncrementSequenceDecorator(options.AccountKeeper),
ibcante.NewAnteDecorator(options.IBCKeeper),
ibcante.NewRedundancyDecorator(options.IBCKeeper),
NewGasWantedDecorator(options.EvmKeeper, options.FeeMarketKeeper),
)
}

View File

@ -6,8 +6,11 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
types2 "github.com/cosmos/cosmos-sdk/x/bank/types"
types3 "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/ethereum/go-ethereum/crypto"
@ -17,8 +20,6 @@ import (
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -78,7 +79,7 @@ func (suite *AnteTestSuite) SetupTest() {
evmGenesis := evmtypes.DefaultGenesisState()
evmGenesis.Params.AllowUnprotectedTxs = false
if !suite.enableLondonHF {
maxInt := sdk.NewInt(math.MaxInt64)
maxInt := sdkmath.NewInt(math.MaxInt64)
evmGenesis.Params.ChainConfig.LondonBlock = &maxInt
evmGenesis.Params.ChainConfig.ArrowGlacierBlock = &maxInt
evmGenesis.Params.ChainConfig.GrayGlacierBlock = &maxInt
@ -197,7 +198,7 @@ func (suite *AnteTestSuite) CreateTestTxBuilder(
txData, err := evmtypes.UnpackTxData(msg.Data)
suite.Require().NoError(err)
fees := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewIntFromBigInt(txData.Fee())))
fees := sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewIntFromBigInt(txData.Fee())))
builder.SetFeeAmount(fees)
builder.SetGasLimit(msg.GetGas())
@ -240,7 +241,7 @@ func (suite *AnteTestSuite) CreateTestTxBuilder(
return txBuilder
}
func (suite *AnteTestSuite) CreateTestCosmosTxBuilder(gasPrice sdk.Int, denom string, msgs ...sdk.Msg) client.TxBuilder {
func (suite *AnteTestSuite) CreateTestCosmosTxBuilder(gasPrice sdkmath.Int, denom string, msgs ...sdk.Msg) client.TxBuilder {
txBuilder := suite.clientCtx.TxConfig.NewTxBuilder()
txBuilder.SetGasLimit(TestGasLimit)
@ -254,7 +255,7 @@ func (suite *AnteTestSuite) CreateTestCosmosTxBuilder(gasPrice sdk.Int, denom st
func (suite *AnteTestSuite) CreateTestEIP712TxBuilderMsgSend(from sdk.AccAddress, priv cryptotypes.PrivKey, chainId string, gas uint64, gasAmount sdk.Coins) client.TxBuilder {
// Build MsgSend
recipient := sdk.AccAddress(common.Address{}.Bytes())
msgSend := types2.NewMsgSend(from, recipient, sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(1))))
msgSend := types2.NewMsgSend(from, recipient, sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(1))))
return suite.CreateTestEIP712CosmosTxBuilder(from, priv, chainId, gas, gasAmount, msgSend)
}
@ -262,7 +263,7 @@ func (suite *AnteTestSuite) CreateTestEIP712TxBuilderMsgDelegate(from sdk.AccAdd
// Build MsgSend
valEthAddr := tests.GenerateAddress()
valAddr := sdk.ValAddress(valEthAddr.Bytes())
msgSend := types3.NewMsgDelegate(from, valAddr, sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewInt(20)))
msgSend := types3.NewMsgDelegate(from, valAddr, sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(20)))
return suite.CreateTestEIP712CosmosTxBuilder(from, priv, chainId, gas, gasAmount, msgSend)
}
@ -283,7 +284,7 @@ func (suite *AnteTestSuite) CreateTestEIP712CosmosTxBuilder(
fee := legacytx.NewStdFee(gas, gasAmount)
accNumber := suite.app.AccountKeeper.GetAccount(suite.ctx, from).GetAccountNumber()
data := legacytx.StdSignBytes(chainId, accNumber, nonce, 0, fee, []sdk.Msg{msg}, "")
data := legacytx.StdSignBytes(chainId, accNumber, nonce, 0, fee, []sdk.Msg{msg}, "", nil)
typedData, err := eip712.WrapTxToTypedData(ethermintCodec, ethChainId, msg, data, &eip712.FeeDelegationOptions{
FeePayer: from,
})

View File

@ -19,7 +19,6 @@ import (
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server/api"
@ -27,11 +26,13 @@ import (
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
"github.com/cosmos/cosmos-sdk/x/auth/posthandler"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -62,8 +63,11 @@ import (
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/gov"
govclient "github.com/cosmos/cosmos-sdk/x/gov/client"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
"github.com/cosmos/cosmos-sdk/x/mint"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
@ -83,15 +87,15 @@ import (
upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/cosmos/ibc-go/v4/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v4/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types"
ibc "github.com/cosmos/ibc-go/v4/modules/core"
ibcclient "github.com/cosmos/ibc-go/v4/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v4/modules/core/02-client/client"
porttypes "github.com/cosmos/ibc-go/v4/modules/core/05-port/types"
ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host"
ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper"
"github.com/cosmos/ibc-go/v5/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v5/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types"
ibc "github.com/cosmos/ibc-go/v5/modules/core"
ibcclient "github.com/cosmos/ibc-go/v5/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v5/modules/core/02-client/client"
porttypes "github.com/cosmos/ibc-go/v5/modules/core/05-port/types"
ibchost "github.com/cosmos/ibc-go/v5/modules/core/24-host"
ibckeeper "github.com/cosmos/ibc-go/v5/modules/core/keeper"
// unnamed import of statik for swagger UI support
_ "github.com/evmos/ethermint/client/docs/statik"
@ -100,7 +104,6 @@ import (
srvflags "github.com/evmos/ethermint/server/flags"
ethermint "github.com/evmos/ethermint/types"
"github.com/evmos/ethermint/x/evm"
evmrest "github.com/evmos/ethermint/x/evm/client/rest"
evmkeeper "github.com/evmos/ethermint/x/evm/keeper"
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/evmos/ethermint/x/feemarket"
@ -138,10 +141,10 @@ var (
staking.AppModuleBasic{},
mint.AppModuleBasic{},
distr.AppModuleBasic{},
gov.NewAppModuleBasic(
paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler,
gov.NewAppModuleBasic([]govclient.ProposalHandler{
paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.LegacyProposalHandler, upgradeclient.LegacyCancelProposalHandler,
ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler,
),
}),
params.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
@ -193,9 +196,9 @@ type EthermintApp struct {
invCheckPeriod uint
// keys to access the substores
keys map[string]*sdk.KVStoreKey
tkeys map[string]*sdk.TransientStoreKey
memKeys map[string]*sdk.MemoryStoreKey
keys map[string]*storetypes.KVStoreKey
tkeys map[string]*storetypes.TransientStoreKey
memKeys map[string]*storetypes.MemoryStoreKey
// keepers
AccountKeeper authkeeper.AccountKeeper
@ -246,7 +249,7 @@ func NewEthermintApp(
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) *EthermintApp {
appCodec := encodingConfig.Marshaler
appCodec := encodingConfig.Codec
cdc := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
@ -293,7 +296,7 @@ func NewEthermintApp(
// init params keeper and subspaces
app.ParamsKeeper = initParamsKeeper(appCodec, cdc, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
// set the BaseApp's parameter store
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable()))
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()))
// add capability keeper and ScopeToModule for ibc module
app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])
@ -307,7 +310,7 @@ func NewEthermintApp(
// use custom Ethermint account for contracts
app.AccountKeeper = authkeeper.NewAccountKeeper(
appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), ethermint.ProtoAccount, maccPerms,
appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), ethermint.ProtoAccount, maccPerms, sdk.GetConfig().GetBech32AccountAddrPrefix(),
)
app.BankKeeper = bankkeeper.NewBaseKeeper(
appCodec, keys[banktypes.StoreKey], app.AccountKeeper, app.GetSubspace(banktypes.ModuleName), app.BlockedAddrs(),
@ -321,7 +324,7 @@ func NewEthermintApp(
)
app.DistrKeeper = distrkeeper.NewKeeper(
appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(),
&stakingKeeper, authtypes.FeeCollectorName,
)
app.SlashingKeeper = slashingkeeper.NewKeeper(
appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.GetSubspace(slashingtypes.ModuleName),
@ -330,7 +333,9 @@ func NewEthermintApp(
app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName,
)
app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper)
app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath, app.BaseApp)
// set the governance module account as the authority for conducting upgrades
app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String())
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
@ -338,7 +343,7 @@ func NewEthermintApp(
stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()),
)
app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.BaseApp.MsgServiceRouter())
app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper)
tracer := cast.ToString(appOpts.Get(srvflags.EVMTracer))
@ -359,16 +364,20 @@ func NewEthermintApp(
)
// register the proposal types
govRouter := govtypes.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
govRouter := govv1beta1.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)).
AddRoute(ibchost.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper))
govConfig := govtypes.DefaultConfig()
/*
Example of setting gov params:
govConfig.MaxMetadataLen = 10000
*/
govKeeper := govkeeper.NewKeeper(
appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, govRouter,
&stakingKeeper, govRouter, app.MsgServiceRouter(), govConfig,
)
app.GovKeeper = *govKeeper.SetHooks(
@ -417,15 +426,15 @@ func NewEthermintApp(
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
upgrade.NewAppModule(app.UpgradeKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
params.NewAppModule(app.ParamsKeeper),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
// ibc modules
@ -440,7 +449,7 @@ func NewEthermintApp(
// there is nothing left over in the validator fee pool, so as to keep the
// CanWithdrawInvariant invariant.
// NOTE: upgrade module must go first to handle software upgrades.
// NOTE: staking module is required if HistoricalEntries param > 0.
// NOTE: staking module is required if HistoricalEntries param > 0
// NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC)
app.mm.SetOrderBeginBlockers(
upgradetypes.ModuleName,
@ -493,6 +502,7 @@ func NewEthermintApp(
// NOTE: The genutils module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: The genutils module must also occur after auth so that it can access the params from auth.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
// can do so safely.
@ -524,37 +534,29 @@ func NewEthermintApp(
crisistypes.ModuleName,
)
// Uncomment if you want to set a custom migration order here.
// app.mm.SetOrderMigrations(custom order)
app.mm.RegisterInvariants(&app.CrisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
// RegisterUpgradeHandlers is used for registering any on-chain upgrades.
// Make sure it's called after `app.mm` and `app.configurator` are set.
// app.RegisterUpgradeHandlers()
// add test gRPC service for testing gRPC queries in isolation
// testdata.RegisterTestServiceServer(app.GRPCQueryRouter(), testdata.TestServiceImpl{})
// create the simulation manager and define the order of the modules for deterministic simulations
//
// NOTE: this is not required apps that don't use the simulator for fuzz testing
// transactions
app.sm = module.NewSimulationManager(
// Use custom RandomGenesisAccounts so that auth module could create random EthAccounts in genesis state when genesis.json not specified
auth.NewAppModule(appCodec, app.AccountKeeper, RandomGenesisAccounts),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
params.NewAppModule(app.ParamsKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
ibc.NewAppModule(app.IBCKeeper),
transferModule,
evm.NewAppModule(app.EvmKeeper, app.AccountKeeper),
feemarket.NewAppModule(app.FeeMarketKeeper),
)
overrideModules := map[string]module.AppModuleSimulation{
authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts),
}
app.sm = module.NewSimulationManagerFromAppModules(app.mm.Modules, overrideModules)
app.sm.RegisterStoreDecoders()
@ -566,26 +568,22 @@ func NewEthermintApp(
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
// use Ethermint's custom AnteHandler
maxGasWanted := cast.ToUint64(appOpts.Get(srvflags.EVMMaxTxGasWanted))
anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{
AccountKeeper: app.AccountKeeper,
BankKeeper: app.BankKeeper,
EvmKeeper: app.EvmKeeper,
FeegrantKeeper: app.FeeGrantKeeper,
IBCKeeper: app.IBCKeeper,
FeeMarketKeeper: app.FeeMarketKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
MaxTxGasWanted: maxGasWanted,
})
if err != nil {
panic(err)
}
app.SetAnteHandler(anteHandler)
app.SetEndBlocker(app.EndBlocker)
app.setAnteHandler(encodingConfig.TxConfig, cast.ToUint64(appOpts.Get(srvflags.EVMMaxTxGasWanted)))
// In v0.46, the SDK introduces _postHandlers_. PostHandlers are like
// antehandlers, but are run _after_ the `runMsgs` execution. They are also
// defined as a chain, and have the same signature as antehandlers.
//
// In baseapp, postHandlers are run in the same store branch as `runMsgs`,
// meaning that both `runMsgs` and `postHandler` state will be committed if
// both are successful, and both will be reverted if any of the two fails.
//
// The SDK exposes a default empty postHandlers chain.
//
// Please note that changing any of the anteHandler or postHandler chain is
// likely to be a state-machine breaking change, which needs a coordinated
// upgrade.
app.setPostHandler()
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
@ -599,6 +597,37 @@ func NewEthermintApp(
return app
}
// use Ethermint's custom AnteHandler
func (app *EthermintApp) setAnteHandler(txConfig client.TxConfig, maxGasWanted uint64) {
anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{
AccountKeeper: app.AccountKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: txConfig.SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
IBCKeeper: app.IBCKeeper,
EvmKeeper: app.EvmKeeper,
FeeMarketKeeper: app.FeeMarketKeeper,
MaxTxGasWanted: maxGasWanted,
})
if err != nil {
panic(err)
}
app.SetAnteHandler(anteHandler)
}
func (app *EthermintApp) setPostHandler() {
postHandler, err := posthandler.NewPostHandler(
posthandler.HandlerOptions{},
)
if err != nil {
panic(err)
}
app.SetPostHandler(postHandler)
}
// Name returns the name of the App
func (app *EthermintApp) Name() string { return app.BaseApp.Name() }
@ -672,21 +701,21 @@ func (app *EthermintApp) InterfaceRegistry() types.InterfaceRegistry {
// GetKey returns the KVStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *EthermintApp) GetKey(storeKey string) *sdk.KVStoreKey {
func (app *EthermintApp) GetKey(storeKey string) *storetypes.KVStoreKey {
return app.keys[storeKey]
}
// GetTKey returns the TransientStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *EthermintApp) GetTKey(storeKey string) *sdk.TransientStoreKey {
func (app *EthermintApp) GetTKey(storeKey string) *storetypes.TransientStoreKey {
return app.tkeys[storeKey]
}
// GetMemKey returns the MemStoreKey for the provided mem key.
//
// NOTE: This is solely used for testing purposes.
func (app *EthermintApp) GetMemKey(storeKey string) *sdk.MemoryStoreKey {
func (app *EthermintApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey {
return app.memKeys[storeKey]
}
@ -707,17 +736,12 @@ func (app *EthermintApp) SimulationManager() *module.SimulationManager {
// API server.
func (app *EthermintApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
clientCtx := apiSvr.ClientCtx
rpc.RegisterRoutes(clientCtx, apiSvr.Router)
evmrest.RegisterTxRoutes(clientCtx, apiSvr.Router)
// Register new tx routes from grpc-gateway.
authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register new tendermint queries routes from grpc-gateway.
tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register legacy and grpc-gateway routes for all modules.
ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router)
// Register grpc-gateway routes for all modules.
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// register swagger API from root so that other applications can override easily
@ -726,12 +750,19 @@ func (app *EthermintApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.
}
}
// RegisterTxService implements the Application.RegisterTxService method.
func (app *EthermintApp) RegisterTxService(clientCtx client.Context) {
authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry)
}
// RegisterTendermintService implements the Application.RegisterTendermintService method.
func (app *EthermintApp) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry)
tmservice.RegisterTendermintService(
clientCtx,
app.BaseApp.GRPCQueryRouter(),
app.interfaceRegistry,
app.Query,
)
}
// RegisterSwaggerAPI registers swagger route with API Server
@ -751,14 +782,11 @@ func GetMaccPerms() map[string][]string {
for k, v := range maccPerms {
dupMaccPerms[k] = v
}
return dupMaccPerms
}
// initParamsKeeper init params keeper and its subspaces
func initParamsKeeper(
appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey,
) paramskeeper.Keeper {
func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper {
paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey)
// SDK subspaces
@ -768,7 +796,7 @@ func initParamsKeeper(
paramsKeeper.Subspace(minttypes.ModuleName)
paramsKeeper.Subspace(distrtypes.ModuleName)
paramsKeeper.Subspace(slashingtypes.ModuleName)
paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable())
paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable())
paramsKeeper.Subspace(crisistypes.ModuleName)
paramsKeeper.Subspace(ibctransfertypes.ModuleName)
paramsKeeper.Subspace(ibchost.ModuleName)

View File

@ -19,7 +19,7 @@ import (
// NewDefaultGenesisState generates the default state for the application.
func NewDefaultGenesisState() simapp.GenesisState {
encCfg := encoding.MakeConfig(ModuleBasics)
return ModuleBasics.DefaultGenesis(encCfg.Marshaler)
return ModuleBasics.DefaultGenesis(encCfg.Codec)
}
// ExportAppStateAndValidators exports the state of the application for a genesis
@ -125,7 +125,9 @@ func (app *EthermintApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAd
feePool.CommunityPool = feePool.CommunityPool.Add(scraps...)
app.DistrKeeper.SetFeePool(ctx, feePool)
app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator())
if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil {
return true
}
return false
})
@ -139,8 +141,12 @@ func (app *EthermintApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAd
if err != nil {
return err
}
app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr)
app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr)
if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil {
return err
}
if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil {
return err
}
}
// reset context height

View File

@ -6,6 +6,8 @@ import (
"fmt"
"math/rand"
"os"
"runtime/debug"
"strings"
"testing"
"github.com/stretchr/testify/require"
@ -14,8 +16,10 @@ import (
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
@ -26,8 +30,8 @@ import (
"github.com/cosmos/cosmos-sdk/x/simulation"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types"
ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host"
ibctransfertypes "github.com/cosmos/ibc-go/v5/modules/apps/transfer/types"
ibchost "github.com/cosmos/ibc-go/v5/modules/core/24-host"
evmenc "github.com/evmos/ethermint/encoding"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
@ -47,8 +51,8 @@ func init() {
const SimAppChainID = "simulation_777-1"
type storeKeysPrefixes struct {
A sdk.StoreKey
B sdk.StoreKey
A storetypes.StoreKey
B storetypes.StoreKey
Prefixes [][]byte
}
@ -74,7 +78,7 @@ func TestFullAppSimulation(t *testing.T) {
config.ChainID = SimAppChainID
defer func() {
db.Close()
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
@ -114,7 +118,7 @@ func TestAppImportExport(t *testing.T) {
config.ChainID = SimAppChainID
defer func() {
db.Close()
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
@ -155,7 +159,7 @@ func TestAppImportExport(t *testing.T) {
require.NoError(t, err, "simulation setup failed")
defer func() {
newDB.Close()
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()
@ -166,6 +170,17 @@ func TestAppImportExport(t *testing.T) {
err = json.Unmarshal(exported.AppState, &genesisState)
require.NoError(t, err)
defer func() {
if r := recover(); r != nil {
err := fmt.Sprintf("%v", r)
if !strings.Contains(err, "validator set is empty after InitGenesis") {
panic(r)
}
logger.Info("Skipping simulation as all validators have been unbonded")
logger.Info("err", err, "stacktrace", string(debug.Stack()))
}
}()
ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight(), ChainID: SimAppChainID})
ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight(), ChainID: SimAppChainID})
newApp.mm.InitGenesis(ctxB, app.AppCodec(), genesisState)
@ -190,6 +205,7 @@ func TestAppImportExport(t *testing.T) {
{app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}},
{app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}},
{app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}},
{app.keys[authzkeeper.StoreKey], newApp.keys[authzkeeper.StoreKey], [][]byte{authzkeeper.GrantKey, authzkeeper.GrantQueuePrefix}},
{app.keys[ibchost.StoreKey], newApp.keys[ibchost.StoreKey], [][]byte{}},
{app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}},
}
@ -216,7 +232,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
config.ChainID = SimAppChainID
defer func() {
db.Close()
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
}()
@ -261,7 +277,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
require.NoError(t, err, "simulation setup failed")
defer func() {
newDB.Close()
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()

View File

@ -10,6 +10,7 @@ import (
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/mock"
"github.com/cosmos/cosmos-sdk/types/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
@ -177,13 +178,13 @@ func StateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simtypes
// NewTestGenesisState generate genesis state with single validator
func NewTestGenesisState(codec codec.Codec) simapp.GenesisState {
privVal := ed25519.GenPrivKey()
// create validator set with single validator
tmPk, err := cryptocodec.ToTmPubKeyInterface(privVal.PubKey())
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
if err != nil {
panic(err)
}
validator := tmtypes.NewValidator(tmPk, 1)
// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator})
// generate genesis account

View File

@ -33,14 +33,14 @@ func TestRandomGenesisAccounts(t *testing.T) {
accs := RandomAccounts(r, rand.Intn(maxTestingAccounts))
encodingConfig := MakeEncodingConfig()
appCodec := encodingConfig.Marshaler
appCodec := encodingConfig.Codec
cdc := encodingConfig.Amino
paramsKeeper := initParamsKeeper(appCodec, cdc, sdk.NewKVStoreKey(paramstypes.StoreKey), sdk.NewTransientStoreKey(paramstypes.StoreKey))
subSpace, find := paramsKeeper.GetSubspace(authtypes.ModuleName)
require.True(t, find)
accountKeeper := authkeeper.NewAccountKeeper(
appCodec, sdk.NewKVStoreKey(authtypes.StoreKey), subSpace, ethermint.ProtoAccount, maccPerms,
appCodec, sdk.NewKVStoreKey(authtypes.StoreKey), subSpace, ethermint.ProtoAccount, maccPerms, sdk.GetConfig().GetBech32AccountAddrPrefix(),
)
authModule := auth.NewAppModule(appCodec, accountKeeper, RandomGenesisAccounts)

View File

@ -5,10 +5,9 @@ import (
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/spf13/cobra"
@ -26,18 +25,8 @@ func UnsafeExportEthKeyCommand() *cobra.Command {
Long: `**UNSAFE** Export an Ethereum private key unencrypted to use in dev tooling`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
rootDir, _ := cmd.Flags().GetString(flags.FlagHome)
kr, err := keyring.New(
sdk.KeyringServiceName(),
keyringBackend,
rootDir,
inBuf,
hd.EthSecp256k1Option(),
)
clientCtx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(hd.EthSecp256k1Option())
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
@ -45,7 +34,8 @@ func UnsafeExportEthKeyCommand() *cobra.Command {
decryptPassword := ""
conf := true
switch keyringBackend {
inBuf := bufio.NewReader(cmd.InOrStdin())
switch clientCtx.Keyring.Backend() {
case keyring.BackendFile:
decryptPassword, err = input.GetPassword(
"**WARNING this is an unsafe way to export your unencrypted private key**\nEnter key password:",
@ -60,7 +50,7 @@ func UnsafeExportEthKeyCommand() *cobra.Command {
}
// Exports private key from keybase using password
armor, err := kr.ExportPrivKeyArmor(args[0], decryptPassword)
armor, err := clientCtx.Keyring.ExportPrivKeyArmor(args[0], decryptPassword)
if err != nil {
return err
}

View File

@ -5,11 +5,9 @@ import (
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/evmos/ethermint/crypto/ethsecp256k1"
@ -28,21 +26,13 @@ func UnsafeImportKeyCommand() *cobra.Command {
}
func runImportCmd(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
rootDir, _ := cmd.Flags().GetString(flags.FlagHome)
kb, err := keyring.New(
sdk.KeyringServiceName(),
keyringBackend,
rootDir,
inBuf,
hd.EthSecp256k1Option(),
)
clientCtx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(hd.EthSecp256k1Option())
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
inBuf := bufio.NewReader(cmd.InOrStdin())
passphrase, err := input.GetPassword("Enter passphrase to encrypt your key:", inBuf)
if err != nil {
return err
@ -54,5 +44,5 @@ func runImportCmd(cmd *cobra.Command, args []string) error {
armor := crypto.EncryptArmorPrivKey(privKey, passphrase, "eth_secp256k1")
return kb.ImportPrivKey(args[0], armor, passphrase)
return clientCtx.Keyring.ImportPrivKey(args[0], armor, passphrase)
}

View File

@ -6,7 +6,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/cli"
@ -49,7 +48,7 @@ The pass backend requires GnuPG: https://gnupg.org/
addCmd := keys.AddKeyCommand()
// update the default signing algorithm value to "eth_secp256k1"
algoFlag := addCmd.Flag("algo")
algoFlag := addCmd.Flag(flags.FlagKeyAlgorithm)
algoFlag.DefValue = string(hd.EthSecp256k1Type)
err := algoFlag.Value.Set(string(hd.EthSecp256k1Type))
if err != nil {
@ -65,8 +64,8 @@ The pass backend requires GnuPG: https://gnupg.org/
keys.ImportKeyCommand(),
keys.ListKeysCmd(),
keys.ShowKeysCmd(),
flags.LineBreak,
keys.DeleteKeyCommand(),
keys.RenameKeyCommand(),
keys.ParseKeyStringCommand(),
keys.MigrateCommand(),
flags.LineBreak,
@ -82,23 +81,11 @@ The pass backend requires GnuPG: https://gnupg.org/
}
func runAddCmd(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
var (
kr keyring.Keyring
err error
)
dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun)
if dryRun {
kr, err = keyring.New(sdk.KeyringServiceName(), keyring.BackendMemory, clientCtx.KeyringDir, buf, hd.EthSecp256k1Option())
clientCtx = clientCtx.WithKeyring(kr)
}
clientCtx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(hd.EthSecp256k1Option())
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
buf := bufio.NewReader(clientCtx.Input)
return clientkeys.RunAddCmd(clientCtx, cmd, args, buf)
}

View File

@ -38,63 +38,7 @@ const (
mnemonicEntropySize = 256
)
// AddKeyCommand defines a keys command to add a generated or recovered private key to keybase.
func AddKeyCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "add <name>",
Short: "Add an encrypted private key (either newly generated or recovered), encrypt it, and save to <name> file",
Long: `Derive a new private key and encrypt to disk.
Optionally specify a BIP39 mnemonic, a BIP39 passphrase to further secure the mnemonic,
and a bip32 HD path to derive a specific account. The key will be stored under the given name
and encrypted with the given password. The only input that is required is the encryption password.
If run with -i, it will prompt the user for BIP44 path, BIP39 mnemonic, and passphrase.
The flag --recover allows one to recover a key from a seed passphrase.
If run with --dry-run, a key would be generated (or recovered) but not stored to the
local keystore.
Use the --pubkey flag to add arbitrary public keys to the keystore for constructing
multisig transactions.
You can create and store a multisig key by passing the list of key names stored in a keyring
and the minimum number of signatures required through --multisig-threshold. The keys are
sorted by address, unless the flag --nosort is set.
Example:
keys add mymultisig --multisig "keyname1,keyname2,keyname3" --multisig-threshold 2
`,
Args: cobra.ExactArgs(1),
RunE: runAddCmdPrepare,
}
f := cmd.Flags()
f.StringSlice(flagMultisig, nil, "List of key names stored in keyring to construct a public legacy multisig key")
f.Int(flagMultiSigThreshold, 1, "K out of N required signatures. For use in conjunction with --multisig")
f.Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied")
f.String(keys.FlagPublicKey, "", "Parse a public key in JSON format and saves key info to <name> file.")
f.BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic")
f.Bool(flags.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device")
f.Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
f.Bool(flagNoBackup, false, "Don't print out seed phrase (if others are watching the terminal)")
f.Bool(flags.FlagDryRun, false, "Perform action, but don't add key to local keystore")
f.String(flagHDPath, "", "Manual HD Path derivation (overrides BIP44 config)")
f.Uint32(flagCoinType, sdk.GetConfig().GetCoinType(), "coin type number for HD derivation")
f.Uint32(flagAccount, 0, "Account number for HD derivation")
f.Uint32(flagIndex, 0, "Address index number for HD derivation")
f.String(flags.FlagKeyAlgorithm, string(etherminthd.EthSecp256k1Type), "Key signing algorithm to generate keys for")
return cmd
}
func runAddCmdPrepare(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
return RunAddCmd(clientCtx, cmd, args, buf)
}
/*
/* RunAddCmd
input
- bip39 mnemonic
- bip39 passphrase
@ -122,7 +66,7 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
if dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun); dryRun {
// use in memory keybase
kb = keyring.NewInMemory(etherminthd.EthSecp256k1Option())
kb = keyring.NewInMemory(ctx.Codec, etherminthd.EthSecp256k1Option())
} else {
_, err = kb.Key(name)
if err == nil {
@ -156,7 +100,11 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
return err
}
pks[i] = k.GetPubKey()
key, err := k.GetPubKey()
if err != nil {
return err
}
pks[i] = key
}
if noSort, _ := cmd.Flags().GetBool(flagNoSort); !noSort {
@ -166,29 +114,28 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
}
pk := multisig.NewLegacyAminoPubKey(multisigThreshold, pks)
info, err := kb.SaveMultisig(name, pk)
k, err := kb.SaveMultisig(name, pk)
if err != nil {
return err
}
return printCreate(cmd, info, false, "", outputFormat)
return printCreate(cmd, k, false, "", outputFormat)
}
}
pubKey, _ := cmd.Flags().GetString(keys.FlagPublicKey)
if pubKey != "" {
var pk cryptotypes.PubKey
err = ctx.Codec.UnmarshalInterfaceJSON([]byte(pubKey), &pk)
if err = ctx.Codec.UnmarshalInterfaceJSON([]byte(pubKey), &pk); err != nil {
return err
}
k, err := kb.SaveOfflineKey(name, pk)
if err != nil {
return err
}
info, err := kb.SavePubKey(name, pk, algo.Name())
if err != nil {
return err
}
return printCreate(cmd, info, false, "", outputFormat)
return printCreate(cmd, k, false, "", outputFormat)
}
coinType, _ := cmd.Flags().GetUint32(flagCoinType)
@ -206,13 +153,12 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
// If we're using ledger, only thing we need is the path and the bech32 prefix.
if useLedger {
bech32PrefixAccAddr := sdk.GetConfig().GetBech32AccountAddrPrefix()
info, err := kb.SaveLedgerKey(name, algo, bech32PrefixAccAddr, coinType, account, index)
k, err := kb.SaveLedgerKey(name, hd.Secp256k1, bech32PrefixAccAddr, coinType, account, index)
if err != nil {
return err
}
return printCreate(cmd, info, false, "", outputFormat)
return printCreate(cmd, k, false, "", outputFormat)
}
// Get bip39 mnemonic
@ -274,7 +220,7 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
}
}
info, err := kb.NewAccount(name, mnemonic, bip39Passphrase, hdPath, algo)
k, err := kb.NewAccount(name, mnemonic, bip39Passphrase, hdPath, algo)
if err != nil {
return err
}
@ -286,24 +232,25 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
mnemonic = ""
}
return printCreate(cmd, info, showMnemonic, mnemonic, outputFormat)
return printCreate(cmd, k, showMnemonic, mnemonic, outputFormat)
}
func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic, outputFormat string) error {
func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemonic, outputFormat string) error {
switch outputFormat {
case OutputFormatText:
cmd.PrintErrln()
printKeyInfo(cmd.OutOrStdout(), info, keyring.MkAccKeyOutput, outputFormat)
if err := printKeyringRecord(cmd.OutOrStdout(), k, keyring.MkAccKeyOutput, outputFormat); err != nil {
return err
}
// print mnemonic unless requested not to.
if showMnemonic {
fmt.Fprintln(cmd.ErrOrStderr(), "\n**Important** write this mnemonic phrase in a safe place.")
fmt.Fprintln(cmd.ErrOrStderr(), "It is the only way to recover your account if you ever forget your password.")
fmt.Fprintln(cmd.ErrOrStderr(), "")
fmt.Fprintln(cmd.ErrOrStderr(), mnemonic)
if _, err := fmt.Fprintf(cmd.ErrOrStderr(), "\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n\n", mnemonic); err != nil {
return fmt.Errorf("failed to print mnemonic: %v", err)
}
}
case OutputFormatJSON:
out, err := keyring.MkAccKeyOutput(info)
out, err := keyring.MkAccKeyOutput(k)
if err != nil {
return err
}
@ -325,3 +272,14 @@ func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemo
return nil
}
func validateMultisigThreshold(k, nKeys int) error {
if k <= 0 {
return fmt.Errorf("threshold must be a positive integer")
}
if nKeys < k {
return fmt.Errorf(
"threshold k of n multisignature: %d < %d", nKeys, k)
}
return nil
}

View File

@ -1,61 +0,0 @@
package keys
import (
"github.com/spf13/cobra"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
)
// Commands registers a sub-tree of commands to interact with
// local private key storage.
func Commands(defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "keys",
Short: "Manage your application's keys",
Long: `Keyring management commands. These keys may be in any format supported by the
Tendermint crypto library and can be used by light-clients, full nodes, or any other application
that needs to sign with a private key.
The keyring supports the following backends:
os Uses the operating system's default credentials store.
file Uses encrypted file-based keystore within the app's configuration directory.
This keyring will request a password each time it is accessed, which may occur
multiple times in a single command resulting in repeated password prompts.
kwallet Uses KDE Wallet Manager as a credentials management application.
pass Uses the pass command line utility to store and retrieve keys.
test Stores keys insecurely to disk. It does not prompt for a password to be unlocked
and it should be use only for testing purposes.
kwallet and pass backends depend on external tools. Refer to their respective documentation for more
information:
KWallet https://github.com/KDE/kwallet
pass https://www.passwordstore.org/
The pass backend requires GnuPG: https://gnupg.org/
`,
}
cmd.AddCommand(
keys.MnemonicKeyCommand(),
AddKeyCommand(),
keys.ExportKeyCommand(),
keys.ImportKeyCommand(),
keys.ListKeysCmd(),
keys.ShowKeysCmd(),
flags.LineBreak,
keys.DeleteKeyCommand(),
keys.ParseKeyStringCommand(),
keys.MigrateCommand(),
)
cmd.PersistentFlags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.PersistentFlags().String(flags.FlagKeyringDir, "", "The client Keyring directory; if omitted, the default 'home' directory will be used")
cmd.PersistentFlags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)")
cmd.PersistentFlags().String(cli.OutputFlag, "text", "Output format (text|json)")
return cmd
}

View File

@ -3,9 +3,8 @@ package keys
import (
"fmt"
"io"
"path/filepath"
yaml "gopkg.in/yaml.v2"
"sigs.k8s.io/yaml"
"github.com/cosmos/cosmos-sdk/client/keys"
cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring"
@ -15,58 +14,45 @@ import (
const (
OutputFormatText = "text"
OutputFormatJSON = "json"
// defaultKeyDBName is the client's subdirectory where keys are stored.
defaultKeyDBName = "keys"
)
type bechKeyOutFn func(keyInfo cryptokeyring.Info) (cryptokeyring.KeyOutput, error)
type bechKeyOutFn func(k *cryptokeyring.Record) (cryptokeyring.KeyOutput, error)
// NewLegacyKeyBaseFromDir initializes a legacy keybase at the rootDir directory. Keybase
// options can be applied when generating this new Keybase.
func NewLegacyKeyBaseFromDir(rootDir string, opts ...cryptokeyring.KeybaseOption) (cryptokeyring.LegacyKeybase, error) {
return getLegacyKeyBaseFromDir(rootDir, opts...)
}
func getLegacyKeyBaseFromDir(rootDir string, opts ...cryptokeyring.KeybaseOption) (cryptokeyring.LegacyKeybase, error) {
return cryptokeyring.NewLegacy(defaultKeyDBName, filepath.Join(rootDir, "keys"), opts...)
}
func printKeyInfo(w io.Writer, keyInfo cryptokeyring.Info, bechKeyOut bechKeyOutFn, output string) {
ko, err := bechKeyOut(keyInfo)
func printKeyringRecord(w io.Writer, k *cryptokeyring.Record, bechKeyOut bechKeyOutFn, output string) error {
ko, err := bechKeyOut(k)
if err != nil {
panic(err)
return err
}
switch output {
case OutputFormatText:
printTextInfos(w, []cryptokeyring.KeyOutput{ko})
if err := printTextRecords(w, []cryptokeyring.KeyOutput{ko}); err != nil {
return err
}
case OutputFormatJSON:
out, err := keys.KeysCdc.MarshalJSON(ko)
if err != nil {
panic(err)
return err
}
fmt.Fprintln(w, string(out))
if _, err := fmt.Fprintln(w, string(out)); err != nil {
return err
}
}
return nil
}
func printTextRecords(w io.Writer, kos []cryptokeyring.KeyOutput) error {
out, err := yaml.Marshal(&kos)
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(out)); err != nil {
return err
}
}
func printTextInfos(w io.Writer, kos []cryptokeyring.KeyOutput) {
out, err := yaml.Marshal(&kos)
if err != nil {
panic(err)
}
fmt.Fprintln(w, string(out))
}
func validateMultisigThreshold(k, nKeys int) error {
if k <= 0 {
return fmt.Errorf("threshold must be a positive integer")
}
if nKeys < k {
return fmt.Errorf(
"threshold k of n multisignature: %d < %d", nKeys, k)
}
return nil
}

View File

@ -34,6 +34,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
mintypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
@ -261,7 +262,7 @@ func initTestnetFiles(
memo := fmt.Sprintf("%s@%s:26656", nodeIDs[i], ip)
genFiles = append(genFiles, nodeConfig.GenesisFile())
kb, err := keyring.New(sdk.KeyringServiceName(), args.keyringBackend, nodeDir, inBuf, hd.EthSecp256k1Option())
kb, err := keyring.New(sdk.KeyringServiceName(), args.keyringBackend, nodeDir, inBuf, clientCtx.Codec, hd.EthSecp256k1Option())
if err != nil {
return err
}
@ -343,7 +344,7 @@ func initTestnetFiles(
customAppTemplate, customAppConfig := config.AppConfig(ethermint.AttoPhoton)
srvconfig.SetConfigTemplate(customAppTemplate)
if err := sdkserver.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig); err != nil {
if err := sdkserver.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, tmconfig.DefaultConfig()); err != nil {
return err
}
@ -402,7 +403,7 @@ func initGenFiles(
stakingGenState.Params.BondDenom = coinDenom
appGenState[stakingtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&stakingGenState)
var govGenState govtypes.GenesisState
var govGenState govv1.GenesisState
clientCtx.Codec.MustUnmarshalJSON(appGenState[govtypes.ModuleName], &govGenState)
govGenState.DepositParams.MinDeposit[0].Denom = coinDenom

View File

@ -23,6 +23,6 @@ func TestInitCmd(t *testing.T) {
fmt.Sprintf("--%s=%s", flags.FlagChainID, "ethermint_9000-1"),
})
err := svrcmd.Execute(rootCmd, app.DefaultNodeHome)
err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome)
require.NoError(t, err)
}

View File

@ -1,7 +1,6 @@
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
@ -11,7 +10,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -43,41 +41,29 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(hd.EthSecp256k1Option())
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
config.SetRoot(clientCtx.HomeDir)
var kr keyring.Keyring
kr := clientCtx.Keyring
addr, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
if keyringBackend != "" && clientCtx.Keyring == nil {
var err error
kr, err = keyring.New(
sdk.KeyringServiceName(),
keyringBackend,
clientCtx.HomeDir,
inBuf,
hd.EthSecp256k1Option(),
)
if err != nil {
return err
}
} else {
kr = clientCtx.Keyring
}
info, err := kr.Key(args[0])
if err != nil {
return fmt.Errorf("failed to get address from Keyring: %w", err)
}
addr = info.GetAddress()
addr, err = info.GetAddress()
if err != nil {
return err
}
}
coins, err := sdk.ParseCoinsNormalized(args[1])

View File

@ -17,7 +17,7 @@ func main() {
rootCmd, _ := NewRootCmd()
if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil {
if err := svrcmd.Execute(rootCmd, EnvPrefix, app.DefaultNodeHome); err != nil {
switch e := err.(type) {
case server.ErrorCode:
os.Exit(e.Code)

View File

@ -9,6 +9,7 @@ import (
"github.com/spf13/cast"
"github.com/spf13/cobra"
tmcfg "github.com/tendermint/tendermint/config"
tmcli "github.com/tendermint/tendermint/libs/cli"
tmlog "github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"
@ -22,6 +23,7 @@ import (
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/snapshots"
snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
@ -48,7 +50,7 @@ const EnvPrefix = "ETHERMINT"
func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
encodingConfig := encoding.MakeConfig(app.ModuleBasics)
initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler).
WithCodec(encodingConfig.Codec).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
@ -84,12 +86,12 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
// FIXME: replace AttoPhoton with bond denom
customAppTemplate, customAppConfig := servercfg.AppConfig(ethermint.AttoPhoton)
return sdkserver.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig)
return sdkserver.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, tmcfg.DefaultConfig())
},
}
// TODO: double-check
// authclient.Codec = encodingConfig.Marshaler
// authclient.Codec = encodingConfig.Codec
cfg := sdk.GetConfig()
cfg.Seal()
@ -126,7 +128,7 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
}
// add rosetta
rootCmd.AddCommand(sdkserver.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler))
rootCmd.AddCommand(sdkserver.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Codec))
return rootCmd, encodingConfig
}
@ -208,7 +210,7 @@ func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer,
}
snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots")
snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir)
snapshotDB, err := dbm.NewDB("metadata", sdkserver.GetAppDBBackend(appOpts), snapshotDir)
if err != nil {
panic(err)
}
@ -217,6 +219,11 @@ func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer,
panic(err)
}
snapshotOptions := snapshottypes.NewSnapshotOptions(
cast.ToUint64(appOpts.Get(sdkserver.FlagStateSyncSnapshotInterval)),
cast.ToUint32(appOpts.Get(sdkserver.FlagStateSyncSnapshotKeepRecent)),
)
ethermintApp := app.NewEthermintApp(
logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
@ -231,9 +238,7 @@ func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer,
baseapp.SetInterBlockCache(cache),
baseapp.SetTrace(cast.ToBool(appOpts.Get(sdkserver.FlagTrace))),
baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(sdkserver.FlagIndexEvents))),
baseapp.SetSnapshotStore(snapshotStore),
baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(sdkserver.FlagStateSyncSnapshotInterval))),
baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(sdkserver.FlagStateSyncSnapshotKeepRecent))),
baseapp.SetSnapshot(snapshotStore, snapshotOptions),
)
return ethermintApp

View File

@ -10,4 +10,5 @@ import (
// RegisterInterfaces register the Ethermint key concrete types.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &ethsecp256k1.PubKey{})
registry.RegisterImplementations((*cryptotypes.PrivKey)(nil), &ethsecp256k1.PrivKey{})
}

View File

@ -11,15 +11,24 @@ import (
hdwallet "github.com/miguelmota/go-ethereum-hdwallet"
"github.com/cosmos/cosmos-sdk/codec"
amino "github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptocodec "github.com/evmos/ethermint/crypto/codec"
enccodec "github.com/evmos/ethermint/encoding/codec"
ethermint "github.com/evmos/ethermint/types"
)
var TestCodec codec.Codec
func init() {
amino := codec.NewLegacyAmino()
cryptocodec.RegisterCrypto(amino)
cdc := codec.NewLegacyAmino()
cryptocodec.RegisterCrypto(cdc)
interfaceRegistry := types.NewInterfaceRegistry()
TestCodec = amino.NewProtoCodec(interfaceRegistry)
enccodec.RegisterInterfaces(interfaceRegistry)
}
const mnemonic = "picnic rent average infant boat squirrel federal assault mercy purity very motor fossil wheel verify upset box fresh horse vivid copy predict square regret"
@ -28,7 +37,7 @@ func TestKeyring(t *testing.T) {
dir := t.TempDir()
mockIn := strings.NewReader("")
kr, err := keyring.New("ethermint", keyring.BackendTest, dir, mockIn, EthSecp256k1Option())
kr, err := keyring.New("ethermint", keyring.BackendTest, dir, mockIn, TestCodec, EthSecp256k1Option())
require.NoError(t, err)
// fail in retrieving key
@ -40,9 +49,11 @@ func TestKeyring(t *testing.T) {
info, mnemonic, err := kr.NewMnemonic("foo", keyring.English, ethermint.BIP44HDPath, keyring.DefaultBIP39Passphrase, EthSecp256k1)
require.NoError(t, err)
require.NotEmpty(t, mnemonic)
require.Equal(t, "foo", info.GetName())
require.Equal(t, "foo", info.Name)
require.Equal(t, "local", info.GetType().String())
require.Equal(t, EthSecp256k1Type, info.GetAlgo())
pubKey, err := info.GetPubKey()
require.NoError(t, err)
require.Equal(t, string(EthSecp256k1Type), pubKey.Type())
hdPath := ethermint.BIP44HDPath

View File

@ -14,12 +14,12 @@ import (
func MakeConfig(mb module.BasicManager) params.EncodingConfig {
cdc := amino.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := amino.NewProtoCodec(interfaceRegistry)
codec := amino.NewProtoCodec(interfaceRegistry)
encodingConfig := params.EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: tx.NewTxConfig(marshaler, tx.DefaultSignModes),
Codec: codec,
TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes),
Amino: cdc,
}

View File

@ -8,6 +8,7 @@ import (
"reflect"
"strings"
sdkmath "cosmossdk.io/math"
"golang.org/x/text/cases"
"golang.org/x/text/language"
@ -379,7 +380,7 @@ var (
hashType = reflect.TypeOf(common.Hash{})
addressType = reflect.TypeOf(common.Address{})
bigIntType = reflect.TypeOf(big.Int{})
cosmIntType = reflect.TypeOf(sdk.Int{})
cosmIntType = reflect.TypeOf(sdkmath.Int{})
cosmosAnyType = reflect.TypeOf(&codectypes.Any{})
)

98
go.mod
View File

@ -3,12 +3,13 @@ module github.com/evmos/ethermint
go 1.18
require (
cosmossdk.io/math v1.0.0-beta.2
github.com/armon/go-metrics v0.4.0
github.com/btcsuite/btcd v0.22.1
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce
github.com/cosmos/cosmos-sdk v0.45.6
github.com/cosmos/cosmos-sdk v0.46.0
github.com/cosmos/go-bip39 v1.0.0
github.com/cosmos/ibc-go/v4 v4.0.0-rc1
github.com/cosmos/ibc-go/v5 v5.0.0
github.com/davecgh/go-spew v1.1.1
github.com/ethereum/go-ethereum v1.10.19
github.com/gogo/protobuf v1.3.3
@ -29,49 +30,57 @@ require (
github.com/spf13/viper v1.12.0
github.com/status-im/keycard-go v0.0.0-20200402102358-957c09536969
github.com/stretchr/testify v1.8.0
github.com/tendermint/tendermint v0.34.20-0.20220517115723-e6f071164839
github.com/tendermint/tendermint v0.34.20
github.com/tendermint/tm-db v0.6.7
github.com/tyler-smith/go-bip39 v1.1.0
golang.org/x/text v0.3.7
google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03
google.golang.org/grpc v1.47.0
google.golang.org/grpc v1.48.0
google.golang.org/protobuf v1.28.0
gopkg.in/yaml.v2 v2.4.0
sigs.k8s.io/yaml v1.3.0
)
require (
filippo.io/edwards25519 v1.0.0-beta.2 // indirect
github.com/99designs/keyring v1.1.6 // indirect
cloud.google.com/go v0.100.2 // indirect
cloud.google.com/go/compute v1.6.1 // indirect
cloud.google.com/go/iam v0.3.0 // indirect
cloud.google.com/go/storage v1.14.0 // indirect
cosmossdk.io/errors v1.0.0-beta.7 // indirect
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
github.com/99designs/keyring v1.2.1 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect
github.com/DataDog/zstd v1.4.5 // indirect
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 // indirect
github.com/VictoriaMetrics/fastcache v1.6.0 // indirect
github.com/Workiva/go-datastructures v1.0.53 // indirect
github.com/aws/aws-sdk-go v1.40.45 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.1.1 // indirect
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect
github.com/cockroachdb/apd/v2 v2.0.2 // indirect
github.com/coinbase/rosetta-sdk-go v0.7.9 // indirect
github.com/confio/ics23/go v0.7.0 // indirect
github.com/cosmos/btcutil v1.0.4 // indirect
github.com/cosmos/cosmos-proto v1.0.0-alpha7 // indirect
github.com/cosmos/gorocksdb v1.2.0 // indirect
github.com/cosmos/iavl v0.17.3 // indirect
github.com/cosmos/iavl v0.19.0 // indirect
github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect
github.com/cosmos/ledger-go v0.9.2 // indirect
github.com/danieljoos/wincred v1.0.2 // indirect
github.com/danieljoos/wincred v1.1.2 // indirect
github.com/deckarep/golang-set v1.8.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
github.com/dgraph-io/badger/v2 v2.2007.2 // indirect
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
github.com/dgraph-io/ristretto v0.1.0 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dlclark/regexp2 v1.4.1-0.20201116162257-a2a8dda75c91 // indirect
github.com/dop251/goja v0.0.0-20220405120441-9037c2b61cbf // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
github.com/edsrzf/mmap-go v1.0.0 // indirect
github.com/felixge/httpsnoop v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
@ -79,84 +88,107 @@ require (
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-ole/go-ole v1.2.1 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/gateway v1.1.0 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.0.0 // indirect
github.com/google/btree v1.0.1 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/google/orderedcode v0.0.1 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/googleapis/gax-go/v2 v2.4.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/gtank/ristretto255 v0.1.2 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-getter v1.6.1 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-safetemp v1.0.0 // indirect
github.com/hashicorp/go-version v1.4.0 // indirect
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20220222234857-c00d1f31bab3 // indirect
github.com/holiman/bloomfilter/v2 v2.0.3 // indirect
github.com/holiman/uint256 v1.2.0 // indirect
github.com/huin/goupnp v1.0.3 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/klauspost/compress v1.15.1 // indirect
github.com/lib/pq v1.10.6 // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect
github.com/minio/highwayhash v1.0.2 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.0.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/common v0.34.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/prometheus/tsdb v0.7.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect
github.com/rjeczalik/notify v0.9.1 // indirect
github.com/rs/zerolog v1.23.0 // indirect
github.com/rs/zerolog v1.27.0 // indirect
github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.4.0 // indirect
github.com/subosito/gotenv v1.3.0 // indirect
github.com/subosito/gotenv v1.4.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
github.com/tendermint/btcd v0.1.1 // indirect
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tklauser/go-sysconf v0.3.5 // indirect
github.com/tklauser/numcpus v0.2.2 // indirect
github.com/zondax/hid v0.9.0 // indirect
github.com/tklauser/go-sysconf v0.3.10 // indirect
github.com/tklauser/numcpus v0.4.0 // indirect
github.com/ulikunitz/xz v0.5.8 // indirect
github.com/zondax/hid v0.9.1-0.20220302062450-5552068d2266 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
go.opencensus.io v0.23.0 // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect
golang.org/x/net v0.0.0-20220617184016-355a448f1bc9 // indirect
golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 // indirect
golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 // indirect
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c // indirect
golang.org/x/term v0.0.0-20220526004731-065cf7ba2467 // indirect
golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect
google.golang.org/api v0.81.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
gopkg.in/ini.v1 v1.66.6 // indirect
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.6 // indirect
)
replace (
github.com/99designs/keyring => github.com/cosmos/keyring v1.1.7-0.20210622111912-ef00f8ac3d76
github.com/cosmos/ibc-go/v5 => github.com/notional-labs/ibc-go/v5 v5.0.0-20220728121949-040aca93dda5
// Fix upstream GHSA-h395-qcrw-5vmq vulnerability.
// TODO Remove it: https://github.com/cosmos/cosmos-sdk/issues/10409
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.7.0
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
google.golang.org/grpc => google.golang.org/grpc v1.33.2
)

841
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -22,6 +22,7 @@ import (
"github.com/tendermint/tendermint/libs/log"
tmrpctypes "github.com/tendermint/tendermint/rpc/core/types"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
@ -74,6 +75,7 @@ func NewPublicAPI(
viper.GetString(flags.FlagKeyringBackend),
clientCtx.KeyringDir,
clientCtx.Input,
clientCtx.Codec,
hd.EthSecp256k1Option(),
)
if err != nil {
@ -252,7 +254,11 @@ func (e *PublicAPI) Accounts() ([]common.Address, error) {
}
for _, info := range infos {
addressBytes := info.GetPubKey().Address().Bytes()
pubKey, err := info.GetPubKey()
if err != nil {
return nil, err
}
addressBytes := pubKey.Address().Bytes()
addresses = append(addresses, common.BytesToAddress(addressBytes))
}
@ -283,7 +289,7 @@ func (e *PublicAPI) GetBalance(address common.Address, blockNrOrHash rpctypes.Bl
return nil, err
}
val, ok := sdk.NewIntFromString(res.Balance)
val, ok := sdkmath.NewIntFromString(res.Balance)
if !ok {
return nil, errors.New("invalid balance")
}
@ -1116,7 +1122,7 @@ func (e *PublicAPI) GetProof(address common.Address, storageKeys []string, block
accProofStr = proof.String()
}
balance, ok := sdk.NewIntFromString(res.Balance)
balance, ok := sdkmath.NewIntFromString(res.Balance)
if !ok {
return nil, errors.New("invalid balance")
}

View File

@ -389,6 +389,7 @@ func (api *PublicFilterAPI) Logs(ctx context.Context, crit filters.FilterCriteri
txResponse, err := evmtypes.DecodeTxResponse(dataTx.TxResult.Result.Data)
if err != nil {
api.logger.Error("fail to decode tx response", "error", err)
return
}
@ -465,6 +466,7 @@ func (api *PublicFilterAPI) NewFilter(criteria filters.FilterCriteria) (rpc.ID,
txResponse, err := evmtypes.DecodeTxResponse(dataTx.TxResult.Result.Data)
if err != nil {
api.logger.Error("fail to decode tx response", "error", err)
return
}

View File

@ -3,8 +3,9 @@ package miner
import (
"math/big"
"github.com/cosmos/cosmos-sdk/client"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/server"
@ -114,7 +115,7 @@ func (api *API) SetEtherbase(etherbase common.Address) bool {
txFactory = txFactory.WithGas(gas)
value := new(big.Int).SetUint64(gas * minGasPriceValue.Ceil().TruncateInt().Uint64())
fees := sdk.Coins{sdk.NewCoin(denom, sdk.NewIntFromBigInt(value))}
fees := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(value))}
builder.SetFeeAmount(fees)
builder.SetGasLimit(gas)
@ -124,7 +125,7 @@ func (api *API) SetEtherbase(etherbase common.Address) bool {
return false
}
if err := tx.Sign(txFactory, keyInfo.GetName(), builder, false); err != nil {
if err := tx.Sign(txFactory, keyInfo.Name, builder, false); err != nil {
api.logger.Debug("failed to sign tx", "error", err.Error())
return false
}
@ -177,7 +178,7 @@ func (api *API) SetGasPrice(gasPrice hexutil.Big) bool {
unit = minGasPrices[0].Denom
}
c := sdk.NewDecCoin(unit, sdk.NewIntFromBigInt(gasPrice.ToInt()))
c := sdk.NewDecCoin(unit, sdkmath.NewIntFromBigInt(gasPrice.ToInt()))
appConf.SetMinGasPrices(sdk.DecCoins{c})
sdkconfig.WriteConfigFile(api.ctx.Viper.ConfigFileUsed(), appConf)

View File

@ -106,7 +106,11 @@ func (api *PrivateAccountAPI) ListAccounts() ([]common.Address, error) {
}
for _, info := range list {
addrs = append(addrs, common.BytesToAddress(info.GetPubKey().Address()))
pubKey, err := info.GetPubKey()
if err != nil {
return nil, err
}
addrs = append(addrs, common.BytesToAddress(pubKey.Address()))
}
return addrs, nil
@ -135,7 +139,11 @@ func (api *PrivateAccountAPI) NewAccount(password string) (common.Address, error
return common.Address{}, err
}
addr := common.BytesToAddress(info.GetPubKey().Address().Bytes())
pubKey, err := info.GetPubKey()
if err != nil {
return common.Address{}, err
}
addr := common.BytesToAddress(pubKey.Address().Bytes())
api.logger.Info("Your new key was generated", "address", addr.String())
api.logger.Info("Please backup your key file!", "path", os.Getenv("HOME")+"/.ethermint/"+name) // TODO: pass the correct binary
api.logger.Info("Please remember your password!")

View File

@ -33,13 +33,12 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
pruningtypes "github.com/cosmos/cosmos-sdk/pruning/types"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/api"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
servergrpc "github.com/cosmos/cosmos-sdk/server/grpc"
"github.com/cosmos/cosmos-sdk/server/types"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
ethdebug "github.com/evmos/ethermint/rpc/namespaces/ethereum/debug"
"github.com/evmos/ethermint/server/config"
@ -137,9 +136,8 @@ which accepts a path for the resulting pprof file.
cmd.Flags().Bool(server.FlagInterBlockCache, true, "Enable inter-block caching")
cmd.Flags().String(srvflags.CPUProfile, "", "Enable CPU profiling and write to the provided file")
cmd.Flags().Bool(server.FlagTrace, false, "Provide full stack traces for errors in ABCI Log")
cmd.Flags().String(server.FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)")
cmd.Flags().String(server.FlagPruning, pruningtypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)")
cmd.Flags().Uint64(server.FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')")
cmd.Flags().Uint64(server.FlagPruningKeepEvery, 0, "Offset heights to keep on disk after 'keep-every' (ignored if pruning is not 'custom')")
cmd.Flags().Uint64(server.FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')")
cmd.Flags().Uint(server.FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks")
cmd.Flags().Uint64(server.FlagMinRetainBlocks, 0, "Minimum block height offset during ABCI commit to prune Tendermint blocks")
@ -185,7 +183,7 @@ func startStandAlone(ctx *server.Context, appCreator types.AppCreator) error {
transport := ctx.Viper.GetString(srvflags.Transport)
home := ctx.Viper.GetString(flags.FlagHome)
db, err := openDB(home)
db, err := openDB(home, server.GetAppDBBackend(ctx.Viper))
if err != nil {
return err
}
@ -260,7 +258,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, appCreator ty
}
traceWriterFile := ctx.Viper.GetString(srvflags.TraceStore)
db, err := openDB(home)
db, err := openDB(home, server.GetAppDBBackend(ctx.Viper))
if err != nil {
logger.Error("failed to open DB", "error", err.Error())
return err
@ -363,7 +361,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, appCreator ty
grpcWebSrv *http.Server
)
if config.GRPC.Enable {
grpcSrv, err = servergrpc.StartGRPCServer(clientCtx, app, config.GRPC.Address)
grpcSrv, err = servergrpc.StartGRPCServer(clientCtx, app, config.GRPC)
if err != nil {
return err
}
@ -477,9 +475,9 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, appCreator ty
return server.WaitForQuitSignals()
}
func openDB(rootDir string) (dbm.DB, error) {
func openDB(rootDir string, backendType dbm.BackendType) (dbm.DB, error) {
dataDir := filepath.Join(rootDir, "data")
return sdk.NewLevelDB("application", dataDir)
return dbm.NewDB("application", backendType, dataDir)
}
func openTraceWriter(traceWriterFile string) (w io.Writer, err error) {

View File

@ -18,6 +18,7 @@ import (
// . "github.com/onsi/ginkgo/v2"
// . "github.com/onsi/gomega"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/ethereum/go-ethereum"
@ -576,7 +577,7 @@ func (s *IntegrationTestSuite) deployContract(data []byte) (transaction common.H
// Deploys erc20 contract, commits block and returns contract address
func (s *IntegrationTestSuite) deployERC20Contract() (transaction common.Hash, contractAddr common.Address) {
owner := common.BytesToAddress(s.network.Validators[0].Address)
supply := sdk.NewIntWithDecimal(1000, 18).BigInt()
supply := sdkmath.NewIntWithDecimal(1000, 18).BigInt()
ctorArgs, err := evmtypes.ERC20Contract.ABI.Pack("", owner, supply)
s.Require().NoError(err)
@ -799,7 +800,7 @@ func (s *IntegrationTestSuite) TestBatchETHTransactions() {
msgs = append(msgs, msgTx.GetMsgs()...)
txData, err := evmtypes.UnpackTxData(msgTx.Data)
s.Require().NoError(err)
feeAmount = feeAmount.Add(sdk.NewIntFromBigInt(txData.Fee()))
feeAmount = feeAmount.Add(sdkmath.NewIntFromBigInt(txData.Fee()))
gasLimit = gasLimit + txData.GetGas()
}

View File

@ -15,6 +15,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/spf13/cobra"
@ -34,13 +35,13 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
pruningtypes "github.com/cosmos/cosmos-sdk/pruning/types"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/api"
srvconfig "github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/simapp/params"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -71,7 +72,7 @@ func NewAppConstructor(encodingCfg params.EncodingConfig) AppConstructor {
val.Ctx.Logger, dbm.NewMemDB(), nil, true, make(map[int64]bool), val.Ctx.Config.RootDir, 0,
encodingCfg,
simapp.EmptyAppOptions{},
baseapp.SetPruning(storetypes.NewPruningOptionsFromString(val.AppConfig.Pruning)),
baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)),
baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices),
)
}
@ -89,9 +90,9 @@ type Config struct {
AppConstructor AppConstructor // the ABCI application constructor
GenesisState simapp.GenesisState // custom gensis state to provide
TimeoutCommit time.Duration // the consensus commitment timeout
AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0)
StakingTokens sdk.Int // the amount of tokens each validator has available to stake
BondedTokens sdk.Int // the amount of tokens each validator stakes
AccountTokens sdkmath.Int // the amount of unique validator tokens (e.g. 1000node0)
StakingTokens sdkmath.Int // the amount of tokens each validator has available to stake
BondedTokens sdkmath.Int // the amount of tokens each validator stakes
NumValidators int // the total number of validators to create and bond
ChainID string // the network chain-id
BondDenom string // the staking bond denomination
@ -113,13 +114,13 @@ func DefaultConfig() Config {
encCfg := encoding.MakeConfig(app.ModuleBasics)
return Config{
Codec: encCfg.Marshaler,
Codec: encCfg.Codec,
TxConfig: encCfg.TxConfig,
LegacyAmino: encCfg.Amino,
InterfaceRegistry: encCfg.InterfaceRegistry,
AccountRetriever: authtypes.AccountRetriever{},
AppConstructor: NewAppConstructor(encCfg),
GenesisState: app.ModuleBasics.DefaultGenesis(encCfg.Marshaler),
GenesisState: app.ModuleBasics.DefaultGenesis(encCfg.Codec),
TimeoutCommit: 2 * time.Second,
ChainID: fmt.Sprintf("ethermint_%d-1", tmrand.Int63n(9999999999999)+1),
NumValidators: 4,
@ -128,7 +129,7 @@ func DefaultConfig() Config {
AccountTokens: sdk.TokensFromConsensusPower(1000, ethermint.PowerReduction),
StakingTokens: sdk.TokensFromConsensusPower(500, ethermint.PowerReduction),
BondedTokens: sdk.TokensFromConsensusPower(100, ethermint.PowerReduction),
PruningStrategy: storetypes.PruningOptionNothing,
PruningStrategy: pruningtypes.PruningOptionNothing,
CleanupDir: true,
SigningAlgo: string(hd.EthSecp256k1Type),
KeyringOptions: []keyring.Option{hd.EthSecp256k1Option()},
@ -370,7 +371,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) {
nodeIDs[i] = nodeID
valPubKeys[i] = pubKey
kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, cfg.KeyringOptions...)
kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, clientDir, buf, cfg.Codec, cfg.KeyringOptions...)
if err != nil {
return nil, err
}
@ -439,7 +440,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) {
}
memo := fmt.Sprintf("%s@%s:%s", nodeIDs[i], p2pURL.Hostname(), p2pURL.Port())
fee := sdk.NewCoins(sdk.NewCoin(cfg.BondDenom, sdk.NewInt(0)))
fee := sdk.NewCoins(sdk.NewCoin(cfg.BondDenom, sdkmath.NewInt(0)))
txBuilder := cfg.TxConfig.NewTxBuilder()
err = txBuilder.SetMsgs(createValMsg)
if err != nil {

View File

@ -25,6 +25,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
mintypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
@ -107,7 +108,7 @@ func startInProcess(cfg Config, val *Validator) error {
}
if val.AppConfig.GRPC.Enable {
grpcSrv, err := servergrpc.StartGRPCServer(val.ClientCtx, app, val.AppConfig.GRPC.Address)
grpcSrv, err := servergrpc.StartGRPCServer(val.ClientCtx, app, val.AppConfig.GRPC)
if err != nil {
return err
}
@ -205,7 +206,7 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance
stakingGenState.Params.BondDenom = cfg.BondDenom
cfg.GenesisState[stakingtypes.ModuleName] = cfg.Codec.MustMarshalJSON(&stakingGenState)
var govGenState govtypes.GenesisState
var govGenState govv1.GenesisState
cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[govtypes.ModuleName], &govGenState)
govGenState.DepositParams.MinDeposit[0].Denom = cfg.BondDenom

View File

@ -2,11 +2,10 @@ package types
import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/types/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
type ExtensionOptionsWeb3TxI interface{}
// RegisterInterfaces registers the tendermint concrete client-related
// implementations and interfaces.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
@ -18,9 +17,8 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
(*authtypes.GenesisAccount)(nil),
&EthAccount{},
)
registry.RegisterInterface(
"ethermint.v1.ExtensionOptionsWeb3Tx",
(*ExtensionOptionsWeb3TxI)(nil),
registry.RegisterImplementations(
(*tx.TxExtensionOptionI)(nil),
&ExtensionOptionsWeb3Tx{},
)
}

View File

@ -3,6 +3,8 @@ package types
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -25,17 +27,17 @@ const (
)
// PowerReduction defines the default power reduction value for staking
var PowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(BaseDenomUnit), nil))
var PowerReduction = sdkmath.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(BaseDenomUnit), nil))
// NewPhotonCoin is a utility function that returns an "aphoton" coin with the given sdk.Int amount.
// NewPhotonCoin is a utility function that returns an "aphoton" coin with the given sdkmath.Int amount.
// The function will panic if the provided amount is negative.
func NewPhotonCoin(amount sdk.Int) sdk.Coin {
func NewPhotonCoin(amount sdkmath.Int) sdk.Coin {
return sdk.NewCoin(AttoPhoton, amount)
}
// NewPhotonDecCoin is a utility function that returns an "aphoton" decimal coin with the given sdk.Int amount.
// NewPhotonDecCoin is a utility function that returns an "aphoton" decimal coin with the given sdkmath.Int amount.
// The function will panic if the provided amount is negative.
func NewPhotonDecCoin(amount sdk.Int) sdk.DecCoin {
func NewPhotonDecCoin(amount sdkmath.Int) sdk.DecCoin {
return sdk.NewDecCoin(AttoPhoton, amount)
}

View File

@ -89,3 +89,7 @@ func (g *infiniteGasMeterWithLimit) IsOutOfGas() bool {
func (g *infiniteGasMeterWithLimit) String() string {
return fmt.Sprintf("InfiniteGasMeter:\n consumed: %d", g.consumed)
}
func (g *infiniteGasMeterWithLimit) GasRemaining() sdk.Gas {
return math.MaxUint64
}

View File

@ -5,7 +5,8 @@ import (
math "math"
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -21,11 +22,11 @@ func SafeInt64(value uint64) (int64, error) {
}
// SafeNewIntFromBigInt constructs Int from big.Int, return error if more than 256bits
func SafeNewIntFromBigInt(i *big.Int) (sdk.Int, error) {
func SafeNewIntFromBigInt(i *big.Int) (sdkmath.Int, error) {
if !IsValidInt256(i) {
return sdk.NewInt(0), fmt.Errorf("big int out of bound: %s", i)
return sdkmath.NewInt(0), fmt.Errorf("big int out of bound: %s", i)
}
return sdk.NewIntFromBigInt(i), nil
return sdkmath.NewIntFromBigInt(i), nil
}
// IsValidInt256 check the bound of 256 bit number

View File

@ -25,7 +25,7 @@ func cosmosAddressFromArg(addr string) (sdk.AccAddress, error) {
// Strip 0x prefix if exists
addr = strings.TrimPrefix(addr, "0x")
return sdk.AccAddressFromHex(addr)
return sdk.AccAddressFromHexUnsafe(addr)
}
func TestAddressFormats(t *testing.T) {
@ -59,7 +59,7 @@ func TestAddressFormats(t *testing.T) {
func TestCosmosToEthereumTypes(t *testing.T) {
hexString := "0x3B98D72760f7bbA69d62Ed6F48278451251948E7"
cosmosAddr, err := sdk.AccAddressFromHex(hexString[2:])
cosmosAddr, err := sdk.AccAddressFromHexUnsafe(hexString[2:])
require.NoError(t, err)
cosmosFormatted := cosmosAddr.String()
@ -81,7 +81,7 @@ func TestCosmosToEthereumTypes(t *testing.T) {
}
func TestAddressToCosmosAddress(t *testing.T) {
baseAddr, err := sdk.AccAddressFromHex("6A98D72760f7bbA69d62Ed6F48278451251948E7")
baseAddr, err := sdk.AccAddressFromHexUnsafe("6A98D72760f7bbA69d62Ed6F48278451251948E7")
require.NoError(t, err)
// Test cosmos string back to address

View File

@ -1,116 +0,0 @@
package rest
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"math/big"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client"
clientrest "github.com/cosmos/cosmos-sdk/client/rest"
"github.com/cosmos/cosmos-sdk/types/rest"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
rpctypes "github.com/evmos/ethermint/rpc/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
"github.com/ethereum/go-ethereum/common"
)
// RegisterTxRoutes - Central function to define routes that get registered by the main application
func RegisterTxRoutes(clientCtx client.Context, rtr *mux.Router) {
r := clientrest.WithHTTPDeprecationHeaders(rtr)
r.HandleFunc("/txs/{hash}", QueryTxRequestHandlerFn(clientCtx)).Methods("GET")
r.HandleFunc("/txs", authrest.QueryTxsRequestHandlerFn(clientCtx)).Methods("GET")
r.HandleFunc("/txs/decode", authrest.DecodeTxRequestHandlerFn(clientCtx)).Methods("POST")
}
// QueryTxRequestHandlerFn implements a REST handler that queries a transaction
// by hash in a committed block.
func QueryTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hashHexStr := vars["hash"]
clientCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, clientCtx, r)
if !ok {
return
}
ethHashPrefix := "0x"
if !strings.HasPrefix(hashHexStr, ethHashPrefix) {
authrest.QueryTxRequestHandlerFn(clientCtx)
return
}
// eth Tx
ethHashPrefixLength := len(ethHashPrefix)
output, err := getEthTransactionByHash(clientCtx, hashHexStr[ethHashPrefixLength:])
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponseBare(w, clientCtx, output)
}
}
// GetTransactionByHash returns the transaction identified by hash.
func getEthTransactionByHash(clientCtx client.Context, hashHex string) ([]byte, error) {
hash, err := hex.DecodeString(hashHex)
if err != nil {
return nil, err
}
node, err := clientCtx.GetNode()
if err != nil {
return nil, err
}
tx, err := node.Tx(context.Background(), hash, false)
if err != nil {
return nil, err
}
// Can either cache or just leave this out if not necessary
block, err := node.Block(context.Background(), &tx.Height)
if err != nil {
return nil, err
}
client := feemarkettypes.NewQueryClient(clientCtx)
res, err := client.BaseFee(context.Background(), &feemarkettypes.QueryBaseFeeRequest{})
if err != nil {
return nil, err
}
var baseFee *big.Int
if res.BaseFee != nil {
baseFee = res.BaseFee.BigInt()
}
blockHash := common.BytesToHash(block.Block.Header.Hash())
ethTxs, err := rpctypes.RawTxToEthTx(clientCtx, tx.Tx)
if err != nil {
return nil, err
}
height := uint64(tx.Height)
for _, ethTx := range ethTxs {
if common.HexToHash(ethTx.Hash) == common.BytesToHash(hash) {
rpcTx, err := rpctypes.NewRPCTransaction(ethTx.AsTransaction(), blockHash, height, uint64(tx.Index), baseFee)
if err != nil {
return nil, err
}
return json.Marshal(rpcTx)
}
}
return nil, errors.New("eth tx not found")
}

View File

@ -6,6 +6,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/gogo/protobuf/proto"
abci "github.com/tendermint/tendermint/abci/types"
@ -86,7 +87,7 @@ func (suite *EvmTestSuite) DoSetupTest(t require.TestingT) {
return genesis
})
coins := sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdk.NewInt(100000000000000)))
coins := sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdkmath.NewInt(100000000000000)))
genesisState := app.NewTestGenesisState(suite.app.AppCodec())
b32address := sdk.MustBech32ifyAddressBytes(sdk.GetConfig().GetBech32AccountAddrPrefix(), priv.PubKey().Address().Bytes())
balances := []banktypes.Balance{

View File

@ -4,6 +4,7 @@ import (
"math/big"
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -25,7 +26,7 @@ func SetupContract(b *testing.B) (*KeeperTestSuite, common.Address) {
err = suite.app.BankKeeper.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, suite.address.Bytes(), amt)
require.NoError(b, err)
contractAddr := suite.DeployTestContract(b, suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(b, suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
return &suite, contractAddr
@ -66,7 +67,7 @@ func DoBenchmark(b *testing.B, txBuilder TxBuilder) {
txData, err := types.UnpackTxData(msg.Data)
require.NoError(b, err)
fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdk.NewIntFromBigInt(txData.Fee()))}
fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdkmath.NewIntFromBigInt(txData.Fee()))}
err = authante.DeductFees(suite.app.BankKeeper, suite.ctx, suite.app.AccountKeeper.GetAccount(ctx, msg.GetFrom()), fees)
require.NoError(b, err)
@ -133,7 +134,7 @@ func BenchmarkMessageCall(b *testing.B) {
txData, err := types.UnpackTxData(msg.Data)
require.NoError(b, err)
fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdk.NewIntFromBigInt(txData.Fee()))}
fees := sdk.Coins{sdk.NewCoin(suite.EvmDenom(), sdkmath.NewIntFromBigInt(txData.Fee()))}
err = authante.DeductFees(suite.app.BankKeeper, suite.ctx, suite.app.AccountKeeper.GetAccount(ctx, msg.GetFrom()), fees)
require.NoError(b, err)

View File

@ -15,6 +15,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
@ -572,7 +573,7 @@ func (k Keeper) BaseFee(c context.Context, _ *types.QueryBaseFeeRequest) (*types
res := &types.QueryBaseFeeResponse{}
if baseFee != nil {
aux := sdk.NewIntFromBigInt(baseFee)
aux := sdkmath.NewIntFromBigInt(baseFee)
res.BaseFee = &aux
}

View File

@ -5,6 +5,8 @@ import (
"fmt"
"math/big"
sdkmath "cosmossdk.io/math"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/vm"
@ -524,7 +526,7 @@ func (suite *KeeperTestSuite) TestEstimateGas() {
}, false, 0, false},
// estimate gas of an erc20 contract deployment, the exact gas number is checked with geth
{"contract deployment", func() {
ctorArgs, err := types.ERC20Contract.ABI.Pack("", &suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
ctorArgs, err := types.ERC20Contract.ABI.Pack("", &suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Require().NoError(err)
data := append(types.ERC20Contract.Bin, ctorArgs...)
args = types.TransactionArgs{
@ -534,7 +536,7 @@ func (suite *KeeperTestSuite) TestEstimateGas() {
}, true, 1186778, false},
// estimate gas of an erc20 transfer, the exact gas number is checked with geth
{"erc20 transfer", func() {
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
transferData, err := types.ERC20Contract.ABI.Pack("transfer", common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), big.NewInt(1000))
suite.Require().NoError(err)
@ -559,7 +561,7 @@ func (suite *KeeperTestSuite) TestEstimateGas() {
gasCap = 20000
}, false, 0, true},
{"contract deployment w/ enableFeemarket", func() {
ctorArgs, err := types.ERC20Contract.ABI.Pack("", &suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
ctorArgs, err := types.ERC20Contract.ABI.Pack("", &suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Require().NoError(err)
data := append(types.ERC20Contract.Bin, ctorArgs...)
args = types.TransactionArgs{
@ -568,7 +570,7 @@ func (suite *KeeperTestSuite) TestEstimateGas() {
}
}, true, 1186778, true},
{"erc20 transfer w/ enableFeemarket", func() {
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
transferData, err := types.ERC20Contract.ABI.Pack("transfer", common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), big.NewInt(1000))
suite.Require().NoError(err)
@ -687,11 +689,11 @@ func (suite *KeeperTestSuite) TestTraceTx() {
vmdb.SetNonce(suite.address, vmdb.GetNonce(suite.address)+1)
suite.Require().NoError(vmdb.Commit())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
// Generate token transfer transaction
firstTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
txMsg = suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
firstTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
txMsg = suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
suite.Commit()
predecessors = append(predecessors, firstTx)
@ -707,10 +709,10 @@ func (suite *KeeperTestSuite) TestTraceTx() {
suite.enableFeemarket = tc.enableFeemarket
suite.SetupTest()
// Deploy contract
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
// Generate token transfer transaction
txMsg = suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
txMsg = suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
suite.Commit()
tc.malleate()
@ -821,11 +823,11 @@ func (suite *KeeperTestSuite) TestTraceBlock() {
vmdb.SetNonce(suite.address, vmdb.GetNonce(suite.address)+1)
suite.Require().NoError(vmdb.Commit())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
// create multiple transactions in the same block
firstTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
secondTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
firstTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
secondTx := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
suite.Commit()
// overwrite txs to include only the ones on new block
txs = append([]*types.MsgEthereumTx{}, firstTx, secondTx)
@ -842,10 +844,10 @@ func (suite *KeeperTestSuite) TestTraceBlock() {
suite.enableFeemarket = tc.enableFeemarket
suite.SetupTest()
// Deploy contract
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit()
// Generate token transfer transaction
txMsg := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdk.NewIntWithDecimal(1, 18).BigInt())
txMsg := suite.TransferERC20Token(suite.T(), contractAddr, suite.address, common.HexToAddress("0x378c50D9264C63F3F92B806d4ee56E9D86FfB3Ec"), sdkmath.NewIntWithDecimal(1, 18).BigInt())
suite.Commit()
txs = append(txs, txMsg)
@ -880,7 +882,7 @@ func (suite *KeeperTestSuite) TestNonceInQuery() {
suite.Require().NoError(err)
address := common.BytesToAddress(priv.PubKey().Address().Bytes())
suite.Require().Equal(uint64(0), suite.app.EvmKeeper.GetNonce(suite.ctx, address))
supply := sdk.NewIntWithDecimal(1000, 18).BigInt()
supply := sdkmath.NewIntWithDecimal(1000, 18).BigInt()
// accupy nonce 0
_ = suite.DeployTestContract(suite.T(), address, supply)
@ -909,7 +911,7 @@ func (suite *KeeperTestSuite) TestNonceInQuery() {
func (suite *KeeperTestSuite) TestQueryBaseFee() {
var (
aux sdk.Int
aux sdkmath.Int
expRes *types.QueryBaseFeeResponse
)
@ -923,7 +925,7 @@ func (suite *KeeperTestSuite) TestQueryBaseFee() {
{
"pass - default Base Fee",
func() {
initialBaseFee := sdk.NewInt(ethparams.InitialBaseFee)
initialBaseFee := sdkmath.NewInt(ethparams.InitialBaseFee)
expRes = &types.QueryBaseFeeResponse{BaseFee: &initialBaseFee}
},
true, true, true,
@ -934,7 +936,7 @@ func (suite *KeeperTestSuite) TestQueryBaseFee() {
baseFee := sdk.OneInt().BigInt()
suite.app.FeeMarketKeeper.SetBaseFee(suite.ctx, baseFee)
aux = sdk.NewIntFromBigInt(baseFee)
aux = sdkmath.NewIntFromBigInt(baseFee)
expRes = &types.QueryBaseFeeResponse{BaseFee: &aux}
},
true, true, true,

View File

@ -183,7 +183,7 @@ func setupChain(localMinGasPricesStr string) {
baseapp.SetMinGasPrices(localMinGasPricesStr),
)
genesisState := app.NewDefaultGenesisState()
genesisState := app.NewTestGenesisState(newapp.AppCodec())
genesisState[types.ModuleName] = newapp.AppCodec().MustMarshalJSON(types.DefaultGenesisState())
stateBytes, err := json.MarshalIndent(genesisState, "", " ")

View File

@ -5,6 +5,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
@ -29,10 +30,10 @@ type Keeper struct {
// - storing account's Code
// - storing transaction Logs
// - storing Bloom filters by block height. Needed for the Web3 API.
storeKey sdk.StoreKey
storeKey storetypes.StoreKey
// key to access the transient store, which is reset on every block during Commit
transientKey sdk.StoreKey
transientKey storetypes.StoreKey
// module specific parameter space that can be configured through governance
paramSpace paramtypes.Subspace
@ -58,7 +59,7 @@ type Keeper struct {
// NewKeeper generates new evm module keeper
func NewKeeper(
cdc codec.BinaryCodec,
storeKey, transientKey sdk.StoreKey, paramSpace paramtypes.Subspace,
storeKey, transientKey storetypes.StoreKey, paramSpace paramtypes.Subspace,
ak types.AccountKeeper, bankKeeper types.BankKeeper, sk types.StakingKeeper,
fmk types.FeeMarketKeeper,
tracer string,

View File

@ -11,6 +11,7 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
@ -49,7 +50,7 @@ import (
"github.com/tendermint/tendermint/version"
)
var testTokens = sdk.NewIntWithDecimal(1000, 18)
var testTokens = sdkmath.NewIntWithDecimal(1000, 18)
type KeeperTestSuite struct {
suite.Suite
@ -120,7 +121,7 @@ func (suite *KeeperTestSuite) SetupApp(checkTx bool) {
genesis[feemarkettypes.ModuleName] = app.AppCodec().MustMarshalJSON(feemarketGenesis)
if !suite.enableLondonHF {
evmGenesis := types.DefaultGenesisState()
maxInt := sdk.NewInt(math.MaxInt64)
maxInt := sdkmath.NewInt(math.MaxInt64)
evmGenesis.Params.ChainConfig.LondonBlock = &maxInt
evmGenesis.Params.ChainConfig.ArrowGlacierBlock = &maxInt
evmGenesis.Params.ChainConfig.GrayGlacierBlock = &maxInt
@ -132,7 +133,7 @@ func (suite *KeeperTestSuite) SetupApp(checkTx bool) {
if suite.mintFeeCollector {
// mint some coin to fee collector
coins := sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdk.NewInt(int64(params.TxGas)-1)))
coins := sdk.NewCoins(sdk.NewCoin(types.DefaultEVMDenom, sdkmath.NewInt(int64(params.TxGas)-1)))
genesisState := app.NewTestGenesisState(suite.app.AppCodec())
balances := []banktypes.Balance{
{
@ -208,7 +209,7 @@ func (suite *KeeperTestSuite) SetupApp(checkTx bool) {
encodingConfig := encoding.MakeConfig(app.ModuleBasics)
suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig)
suite.ethSigner = ethtypes.LatestSignerForChainID(suite.app.EvmKeeper.ChainID())
suite.appCodec = encodingConfig.Marshaler
suite.appCodec = encodingConfig.Codec
suite.denom = evmtypes.DefaultEVMDenom
}

View File

@ -4,6 +4,8 @@ import (
"math"
"math/big"
sdkmath "cosmossdk.io/math"
tmtypes "github.com/tendermint/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -484,7 +486,7 @@ func (k *Keeper) RefundGas(ctx sdk.Context, msg core.Message, leftoverGas uint64
return sdkerrors.Wrapf(types.ErrInvalidRefund, "refunded amount value cannot be negative %d", remaining.Int64())
case 1:
// positive amount refund
refundedCoins := sdk.Coins{sdk.NewCoin(denom, sdk.NewIntFromBigInt(remaining))}
refundedCoins := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(remaining))}
// refund to sender from the fee collector module account, which is the escrow account in charge of collecting tx fees

View File

@ -5,6 +5,8 @@ import (
"fmt"
"math/big"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -79,7 +81,7 @@ func (k *Keeper) SetBalance(ctx sdk.Context, addr common.Address, amount *big.In
switch delta.Sign() {
case 1:
// mint
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdk.NewIntFromBigInt(delta)))
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(delta)))
if err := k.bankKeeper.MintCoins(ctx, types.ModuleName, coins); err != nil {
return err
}
@ -88,7 +90,7 @@ func (k *Keeper) SetBalance(ctx sdk.Context, addr common.Address, amount *big.In
}
case -1:
// burn
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdk.NewIntFromBigInt(new(big.Int).Neg(delta))))
coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(new(big.Int).Neg(delta))))
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, cosmosAddr, types.ModuleName, coins); err != nil {
return err
}

View File

@ -3,6 +3,7 @@ package keeper
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
@ -71,7 +72,7 @@ func (k Keeper) DeductTxCostsFromUserBalance(
return sdk.Coins{}, nil
}
fees := sdk.Coins{sdk.NewCoin(denom, sdk.NewIntFromBigInt(feeAmt))}
fees := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(feeAmt))}
// deduct the full gas cost from the user balance
if err := authante.DeductFees(k.bankKeeper, ctx, signerAcc, fees); err != nil {
@ -87,7 +88,7 @@ func (k Keeper) DeductTxCostsFromUserBalance(
// CheckSenderBalance validates that the tx cost value is positive and that the
// sender has enough funds to pay for the fees and value of the transaction.
func CheckSenderBalance(
balance sdk.Int,
balance sdkmath.Int,
txData evmtypes.TxData,
) error {
cost := txData.Cost()

View File

@ -3,6 +3,7 @@ package keeper_test
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -12,21 +13,21 @@ import (
)
func (suite *KeeperTestSuite) TestCheckSenderBalance() {
hundredInt := sdk.NewInt(100)
hundredInt := sdkmath.NewInt(100)
zeroInt := sdk.ZeroInt()
oneInt := sdk.OneInt()
fiveInt := sdk.NewInt(5)
fiftyInt := sdk.NewInt(50)
negInt := sdk.NewInt(-10)
fiveInt := sdkmath.NewInt(5)
fiftyInt := sdkmath.NewInt(50)
negInt := sdkmath.NewInt(-10)
testCases := []struct {
name string
to string
gasLimit uint64
gasPrice *sdk.Int
gasPrice *sdkmath.Int
gasFeeCap *big.Int
gasTipCap *big.Int
cost *sdk.Int
cost *sdkmath.Int
from string
accessList *ethtypes.AccessList
expectPass bool
@ -237,7 +238,7 @@ func (suite *KeeperTestSuite) TestCheckSenderBalance() {
acct := suite.app.EvmKeeper.GetAccountOrEmpty(suite.ctx, suite.address)
err := evmkeeper.CheckSenderBalance(
sdk.NewIntFromBigInt(acct.Balance),
sdkmath.NewIntFromBigInt(acct.Balance),
txData,
)
@ -251,22 +252,22 @@ func (suite *KeeperTestSuite) TestCheckSenderBalance() {
}
func (suite *KeeperTestSuite) TestDeductTxCostsFromUserBalance() {
hundredInt := sdk.NewInt(100)
hundredInt := sdkmath.NewInt(100)
zeroInt := sdk.ZeroInt()
oneInt := sdk.NewInt(1)
fiveInt := sdk.NewInt(5)
fiftyInt := sdk.NewInt(50)
oneInt := sdkmath.NewInt(1)
fiveInt := sdkmath.NewInt(5)
fiftyInt := sdkmath.NewInt(50)
// should be enough to cover all test cases
initBalance := sdk.NewInt((ethparams.InitialBaseFee + 10) * 105)
initBalance := sdkmath.NewInt((ethparams.InitialBaseFee + 10) * 105)
testCases := []struct {
name string
gasLimit uint64
gasPrice *sdk.Int
gasPrice *sdkmath.Int
gasFeeCap *big.Int
gasTipCap *big.Int
cost *sdk.Int
cost *sdkmath.Int
accessList *ethtypes.AccessList
expectPass bool
enableFeemarket bool
@ -419,7 +420,7 @@ func (suite *KeeperTestSuite) TestDeductTxCostsFromUserBalance() {
suite.Require().Equal(
fees,
sdk.NewCoins(
sdk.NewCoin(evmtypes.DefaultEVMDenom, sdk.NewIntFromBigInt(txData.EffectiveFee(baseFee))),
sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewIntFromBigInt(txData.EffectiveFee(baseFee))),
),
"valid test %d failed, fee value is wrong ", i,
)
@ -427,7 +428,7 @@ func (suite *KeeperTestSuite) TestDeductTxCostsFromUserBalance() {
suite.Require().Equal(
fees,
sdk.NewCoins(
sdk.NewCoin(evmtypes.DefaultEVMDenom, tc.gasPrice.Mul(sdk.NewIntFromUint64(tc.gasLimit))),
sdk.NewCoin(evmtypes.DefaultEVMDenom, tc.gasPrice.Mul(sdkmath.NewIntFromUint64(tc.gasLimit))),
),
"valid test %d failed, fee value is wrong ", i,
)

View File

@ -24,7 +24,7 @@ func TestMigrateStore(t *testing.T) {
tFeeMarketKey := sdk.NewTransientStoreKey(fmt.Sprintf("%s_test", types.StoreKey))
ctx := testutil.DefaultContext(feemarketKey, tFeeMarketKey)
paramstore := paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, feemarketKey, tFeeMarketKey, "evm",
encCfg.Codec, encCfg.Amino, feemarketKey, tFeeMarketKey, "evm",
).WithKeyTable(v2types.ParamKeyTable())
params := v2types.DefaultParams()
@ -36,7 +36,7 @@ func TestMigrateStore(t *testing.T) {
})
paramstore = paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, feemarketKey, tFeeMarketKey, "evm",
encCfg.Codec, encCfg.Amino, feemarketKey, tFeeMarketKey, "evm",
).WithKeyTable(types.ParamKeyTable())
err := v2.MigrateStore(ctx, &paramstore)
require.NoError(t, err)

View File

@ -4,6 +4,8 @@ import (
"math/big"
"strings"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -77,7 +79,7 @@ func DefaultChainConfig() ChainConfig {
}
}
func getBlockValue(block *sdk.Int) *big.Int {
func getBlockValue(block *sdkmath.Int) *big.Int {
if block == nil || block.IsNegative() {
return nil
}
@ -149,7 +151,7 @@ func validateHash(hex string) error {
return nil
}
func validateBlock(block *sdk.Int) error {
func validateBlock(block *sdkmath.Int) error {
// nil value means that the fork has not yet been applied
if block == nil {
return nil

View File

@ -107,7 +107,7 @@ func (m *Params) GetChainConfig() ChainConfig {
return ChainConfig{}
}
// ChainConfig defines the Ethereum ChainConfig parameters using *sdk.Int values
// ChainConfig defines the Ethereum ChainConfig parameters using *sdkmath.Int values
// instead of *big.Int.
type ChainConfig struct {
// Homestead switch block (nil no fork, 0 = already homestead)

View File

@ -2,9 +2,10 @@ package v3_test
import (
"fmt"
v3 "github.com/evmos/ethermint/x/evm/migrations/v3"
"testing"
v3 "github.com/evmos/ethermint/x/evm/migrations/v3"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/testutil"
@ -24,7 +25,7 @@ func TestMigrateStore(t *testing.T) {
tEvmKey := sdk.NewTransientStoreKey(fmt.Sprintf("%s_test", types.StoreKey))
ctx := testutil.DefaultContext(evmKey, tEvmKey)
paramstore := paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, evmKey, tEvmKey, "evm",
encCfg.Codec, encCfg.Amino, evmKey, tEvmKey, "evm",
).WithKeyTable(v3types.ParamKeyTable())
params := v3types.DefaultParams()
@ -39,7 +40,7 @@ func TestMigrateStore(t *testing.T) {
require.NotNil(t, preMigrationConfig.MergeForkBlock)
paramstore = paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, evmKey, tEvmKey, "evm",
encCfg.Codec, encCfg.Amino, evmKey, tEvmKey, "evm",
).WithKeyTable(types.ParamKeyTable())
err := v3.MigrateStore(ctx, &paramstore)
require.NoError(t, err)

View File

@ -4,6 +4,8 @@ import (
"math/big"
"strings"
sdkmath "cosmossdk.io/math"
"github.com/evmos/ethermint/x/evm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -76,7 +78,7 @@ func DefaultChainConfig() ChainConfig {
}
}
func getBlockValue(block *sdk.Int) *big.Int {
func getBlockValue(block *sdkmath.Int) *big.Int {
if block == nil || block.IsNegative() {
return nil
}
@ -148,7 +150,7 @@ func validateHash(hex string) error {
return nil
}
func validateBlock(block *sdk.Int) error {
func validateBlock(block *sdkmath.Int) error {
// nil value means that the fork has not yet been applied
if block == nil {
return nil

View File

@ -5,6 +5,7 @@ import (
"math/rand"
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
@ -31,7 +32,7 @@ func TestRandomizedGenState(t *testing.T) {
Rand: r,
NumBonded: 3,
Accounts: simtypes.RandomAccounts(r, 3),
InitialStake: 1000,
InitialStake: sdkmath.NewInt(1000),
GenState: make(map[string]json.RawMessage),
}

View File

@ -7,6 +7,8 @@ import (
"math/rand"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -123,7 +125,7 @@ func SimulateEthCreateContract(ak types.AccountKeeper, k *keeper.Keeper) simtype
from := common.BytesToAddress(simAccount.Address)
nonce := k.GetNonce(ctx, from)
ctorArgs, err := types.ERC20Contract.ABI.Pack("", from, sdk.NewIntWithDecimal(1000, 18).BigInt())
ctorArgs, err := types.ERC20Contract.ABI.Pack("", from, sdkmath.NewIntWithDecimal(1000, 18).BigInt())
if err != nil {
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgEthereumTx, "can not pack owner and supply"), nil, err
}
@ -192,7 +194,7 @@ func SimulateEthTx(
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgEthereumTx, "can not sign ethereum tx"), nil, err
}
_, _, err = ctx.bapp.Deliver(txConfig.TxEncoder(), signedTx)
_, _, err = ctx.bapp.SimDeliver(txConfig.TxEncoder(), signedTx)
if err != nil {
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgEthereumTx, "failed to deliver tx"), nil, err
}
@ -258,7 +260,7 @@ func RandomTransferableAmount(ctx *simulateContext, address common.Address, esti
amount = new(big.Int).Set(spendable)
return amount, nil
}
simAmount, err := simtypes.RandPositiveInt(ctx.rand, sdk.NewIntFromBigInt(spendable))
simAmount, err := simtypes.RandPositiveInt(ctx.rand, sdkmath.NewIntFromBigInt(spendable))
if err != nil {
return nil, err
}
@ -291,7 +293,7 @@ func GetSignedTx(ctx *simulateContext, txBuilder client.TxBuilder, msg *types.Ms
return nil, err
}
fees := sdk.NewCoins(sdk.NewCoin(ctx.keeper.GetParams(ctx.context).EvmDenom, sdk.NewIntFromBigInt(txData.Fee())))
fees := sdk.NewCoins(sdk.NewCoin(ctx.keeper.GetParams(ctx.context).EvmDenom, sdkmath.NewIntFromBigInt(txData.Fee())))
builder.SetFeeAmount(fees)
builder.SetGasLimit(msg.GetGas())

View File

@ -3,7 +3,7 @@ package types
import (
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/common"
@ -174,7 +174,7 @@ func (tx *AccessListTx) SetSignatureValues(chainID, v, r, s *big.Int) {
tx.S = s.Bytes()
}
if chainID != nil {
chainIDInt := sdk.NewIntFromBigInt(chainID)
chainIDInt := sdkmath.NewIntFromBigInt(chainID)
tx.ChainID = &chainIDInt
}
}

View File

@ -4,6 +4,8 @@ import (
"math/big"
"strings"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -78,7 +80,7 @@ func DefaultChainConfig() ChainConfig {
}
}
func getBlockValue(block *sdk.Int) *big.Int {
func getBlockValue(block *sdkmath.Int) *big.Int {
if block == nil || block.IsNegative() {
return nil
}
@ -153,7 +155,7 @@ func validateHash(hex string) error {
return nil
}
func validateBlock(block *sdk.Int) error {
func validateBlock(block *sdkmath.Int) error {
// nil value means that the fork has not yet been applied
if block == nil {
return nil

View File

@ -3,17 +3,16 @@ package types
import (
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
)
var defaultEIP150Hash = common.Hash{}.String()
func newIntPtr(i int64) *sdk.Int {
v := sdk.NewInt(i)
func newIntPtr(i int64) *sdkmath.Int {
v := sdkmath.NewInt(i)
return &v
}

View File

@ -6,24 +6,20 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/types/tx"
proto "github.com/gogo/protobuf/proto"
)
var ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
type (
ExtensionOptionsEthereumTxI interface{}
)
// RegisterInterfaces registers the client interfaces to protobuf Any.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgEthereumTx{},
)
registry.RegisterInterface(
"ethermint.evm.v1.ExtensionOptionsEthereumTx",
(*ExtensionOptionsEthereumTxI)(nil),
registry.RegisterImplementations(
(*tx.TxExtensionOptionI)(nil),
&ExtensionOptionsEthereumTx{},
)
registry.RegisterInterface(

View File

@ -3,7 +3,7 @@ package types
import (
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ethereum/go-ethereum/common"
@ -188,7 +188,7 @@ func (tx *DynamicFeeTx) SetSignatureValues(chainID, v, r, s *big.Int) {
tx.S = s.Bytes()
}
if chainID != nil {
chainIDInt := sdk.NewIntFromBigInt(chainID)
chainIDInt := sdkmath.NewIntFromBigInt(chainID)
tx.ChainID = &chainIDInt
}
}

View File

@ -4,6 +4,8 @@ import (
"math/big"
"testing"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -14,24 +16,24 @@ import (
type TxDataTestSuite struct {
suite.Suite
sdkInt sdk.Int
sdkInt sdkmath.Int
uint64 uint64
bigInt *big.Int
overflowBigInt *big.Int
sdkZeroInt sdk.Int
sdkMinusOneInt sdk.Int
sdkZeroInt sdkmath.Int
sdkMinusOneInt sdkmath.Int
invalidAddr string
addr common.Address
hexAddr string
}
func (suite *TxDataTestSuite) SetupTest() {
suite.sdkInt = sdk.NewInt(100)
suite.sdkInt = sdkmath.NewInt(100)
suite.uint64 = suite.sdkInt.Uint64()
suite.bigInt = big.NewInt(1)
suite.overflowBigInt = big.NewInt(0).Exp(big.NewInt(10), big.NewInt(256), nil)
suite.sdkZeroInt = sdk.ZeroInt()
suite.sdkMinusOneInt = sdk.NewInt(-1)
suite.sdkMinusOneInt = sdkmath.NewInt(-1)
suite.invalidAddr = "123456"
suite.addr = tests.GenerateAddress()
suite.hexAddr = suite.addr.Hex()

2
x/evm/types/evm.pb.go generated
View File

@ -117,7 +117,7 @@ func (m *Params) GetAllowUnprotectedTxs() bool {
return false
}
// ChainConfig defines the Ethereum ChainConfig parameters using *sdk.Int values
// ChainConfig defines the Ethereum ChainConfig parameters using *sdkmath.Int values
// instead of *big.Int.
type ChainConfig struct {
// Homestead switch block (nil no fork, 0 = already homestead)

View File

@ -27,10 +27,9 @@ type AccountKeeper interface {
// BankKeeper defines the expected interface needed to retrieve account balances.
type BankKeeper interface {
authtypes.BankKeeper
GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin
SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
// SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error
SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
}

View File

@ -5,6 +5,8 @@ import (
"fmt"
"math/big"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
@ -62,7 +64,7 @@ func newMsgEthereumTx(
gasLimit uint64, gasPrice, gasFeeCap, gasTipCap *big.Int, input []byte, accesses *ethtypes.AccessList,
) *MsgEthereumTx {
var (
cid, amt, gp *sdk.Int
cid, amt, gp *sdkmath.Int
toAddr string
txData TxData
)
@ -72,17 +74,17 @@ func newMsgEthereumTx(
}
if amount != nil {
amountInt := sdk.NewIntFromBigInt(amount)
amountInt := sdkmath.NewIntFromBigInt(amount)
amt = &amountInt
}
if chainID != nil {
chainIDInt := sdk.NewIntFromBigInt(chainID)
chainIDInt := sdkmath.NewIntFromBigInt(chainID)
cid = &chainIDInt
}
if gasPrice != nil {
gasPriceInt := sdk.NewIntFromBigInt(gasPrice)
gasPriceInt := sdkmath.NewIntFromBigInt(gasPrice)
gp = &gasPriceInt
}
@ -97,8 +99,8 @@ func newMsgEthereumTx(
Data: input,
}
case accesses != nil && gasFeeCap != nil && gasTipCap != nil:
gtc := sdk.NewIntFromBigInt(gasTipCap)
gfc := sdk.NewIntFromBigInt(gasFeeCap)
gtc := sdkmath.NewIntFromBigInt(gasTipCap)
gfc := sdkmath.NewIntFromBigInt(gasFeeCap)
txData = &DynamicFeeTx{
ChainID: cid,
@ -352,7 +354,7 @@ func (msg *MsgEthereumTx) BuildTx(b client.TxBuilder, evmDenom string) (signing.
return nil, err
}
fees := make(sdk.Coins, 0)
feeAmt := sdk.NewIntFromBigInt(txData.Fee())
feeAmt := sdkmath.NewIntFromBigInt(txData.Fee())
if feeAmt.Sign() > 0 {
fees = append(fees, sdk.NewCoin(evmDenom, feeAmt))
}

View File

@ -7,6 +7,7 @@ import (
"strings"
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/client"
@ -104,7 +105,7 @@ func (suite *MsgsTestSuite) TestMsgEthereumTx_BuildTx() {
suite.Require().Empty(tx.GetMemo())
suite.Require().Empty(tx.GetTimeoutHeight())
suite.Require().Equal(uint64(100000), tx.GetGas())
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("aphoton", sdk.NewInt(100000))), tx.GetFee())
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("aphoton", sdkmath.NewInt(100000))), tx.GetFee())
}
}
}

View File

@ -5,7 +5,8 @@ import (
"fmt"
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
@ -55,14 +56,14 @@ func (args *TransactionArgs) String() string {
// This assumes that setTxDefaults has been called.
func (args *TransactionArgs) ToTransaction() *MsgEthereumTx {
var (
chainID, value, gasPrice, maxFeePerGas, maxPriorityFeePerGas sdk.Int
chainID, value, gasPrice, maxFeePerGas, maxPriorityFeePerGas sdkmath.Int
gas, nonce uint64
from, to string
)
// Set sender address or use zero address if none specified.
if args.ChainID != nil {
chainID = sdk.NewIntFromBigInt(args.ChainID.ToInt())
chainID = sdkmath.NewIntFromBigInt(args.ChainID.ToInt())
}
if args.Nonce != nil {
@ -74,19 +75,19 @@ func (args *TransactionArgs) ToTransaction() *MsgEthereumTx {
}
if args.GasPrice != nil {
gasPrice = sdk.NewIntFromBigInt(args.GasPrice.ToInt())
gasPrice = sdkmath.NewIntFromBigInt(args.GasPrice.ToInt())
}
if args.MaxFeePerGas != nil {
maxFeePerGas = sdk.NewIntFromBigInt(args.MaxFeePerGas.ToInt())
maxFeePerGas = sdkmath.NewIntFromBigInt(args.MaxFeePerGas.ToInt())
}
if args.MaxPriorityFeePerGas != nil {
maxPriorityFeePerGas = sdk.NewIntFromBigInt(args.MaxPriorityFeePerGas.ToInt())
maxPriorityFeePerGas = sdkmath.NewIntFromBigInt(args.MaxPriorityFeePerGas.ToInt())
}
if args.Value != nil {
value = sdk.NewIntFromBigInt(args.Value.ToInt())
value = sdkmath.NewIntFromBigInt(args.Value.ToInt())
}
if args.To != nil {

View File

@ -4,13 +4,12 @@ import (
"math/big"
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestTxData_chainID(t *testing.T) {
chainID := sdk.NewInt(1)
chainID := sdkmath.NewInt(1)
testCases := []struct {
msg string

View File

@ -21,15 +21,12 @@ func DecodeTxResponse(in []byte) (*MsgEthereumTxResponse, error) {
return nil, err
}
data := txMsgData.GetData()
if len(data) == 0 {
if len(txMsgData.MsgResponses) == 0 {
return &MsgEthereumTxResponse{}, nil
}
var res MsgEthereumTxResponse
err := proto.Unmarshal(data[0].GetData(), &res)
if err != nil {
if err := proto.Unmarshal(txMsgData.MsgResponses[0].Value, &res); err != nil {
return nil, sdkerrors.Wrap(err, "failed to unmarshal tx response message data")
}
@ -41,7 +38,7 @@ func EncodeTransactionLogs(res *TransactionLogs) ([]byte, error) {
return proto.Marshal(res)
}
// DecodeTxResponse decodes an protobuf-encoded byte slice into TransactionLogs
// DecodeTransactionLogs decodes an protobuf-encoded byte slice into TransactionLogs
func DecodeTransactionLogs(data []byte) (TransactionLogs, error) {
var logs TransactionLogs
err := proto.Unmarshal(data, &logs)

View File

@ -6,6 +6,7 @@ import (
"testing"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/evmos/ethermint/app"
@ -30,11 +31,9 @@ func TestEvmDataEncoding(t *testing.T) {
Ret: ret,
}
enc, err := proto.Marshal(data)
require.NoError(t, err)
any := codectypes.UnsafePackAny(data)
txData := &sdk.TxMsgData{
Data: []*sdk.MsgData{{MsgType: evmtypes.TypeMsgEthereumTx, Data: enc}},
MsgResponses: []*codectypes.Any{any},
}
txDataBz, err := proto.Marshal(txData)

View File

@ -2,6 +2,7 @@ package keeper_test
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/abci/types"
)

View File

@ -3,6 +3,7 @@ package keeper
import (
"context"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/evmos/ethermint/x/feemarket/types"
@ -28,7 +29,7 @@ func (k Keeper) BaseFee(c context.Context, _ *types.QueryBaseFeeRequest) (*types
baseFee := k.GetBaseFee(ctx)
if baseFee != nil {
aux := sdk.NewIntFromBigInt(baseFee)
aux := sdkmath.NewIntFromBigInt(baseFee)
res.BaseFee = &aux
}

View File

@ -1,6 +1,7 @@
package keeper_test
import (
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
ethparams "github.com/ethereum/go-ethereum/params"
"github.com/evmos/ethermint/x/feemarket/types"
@ -32,7 +33,7 @@ func (suite *KeeperTestSuite) TestQueryParams() {
func (suite *KeeperTestSuite) TestQueryBaseFee() {
var (
aux sdk.Int
aux sdkmath.Int
expRes *types.QueryBaseFeeResponse
)
@ -44,7 +45,7 @@ func (suite *KeeperTestSuite) TestQueryBaseFee() {
{
"pass - default Base Fee",
func() {
initialBaseFee := sdk.NewInt(ethparams.InitialBaseFee)
initialBaseFee := sdkmath.NewInt(ethparams.InitialBaseFee)
expRes = &types.QueryBaseFeeResponse{BaseFee: &initialBaseFee}
},
true,
@ -55,7 +56,7 @@ func (suite *KeeperTestSuite) TestQueryBaseFee() {
baseFee := sdk.OneInt().BigInt()
suite.app.FeeMarketKeeper.SetBaseFee(suite.ctx, baseFee)
aux = sdk.NewIntFromBigInt(baseFee)
aux = sdkmath.NewIntFromBigInt(baseFee)
expRes = &types.QueryBaseFeeResponse{BaseFee: &aux}
},
true,

View File

@ -5,6 +5,7 @@ import (
"math/big"
"strings"
sdkmath "cosmossdk.io/math"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -46,7 +47,7 @@ var _ = Describe("Feemarket", func() {
Context("during CheckTx", func() {
It("should reject transactions with gasPrice < MinGasPrices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -56,7 +57,7 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with gasPrice >= MinGasPrices", func() {
gasPrice := sdk.NewInt(3)
gasPrice := sdkmath.NewInt(3)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -64,7 +65,7 @@ var _ = Describe("Feemarket", func() {
Context("during DeliverTx", func() {
It("should reject transactions with gasPrice < MinGasPrices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -74,7 +75,7 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with gasPrice >= MinGasPrices", func() {
gasPrice := sdk.NewInt(3)
gasPrice := sdkmath.NewInt(3)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -88,7 +89,7 @@ var _ = Describe("Feemarket", func() {
Context("during CheckTx", func() {
It("should reject transactions with gasPrice < min-gas-prices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -98,7 +99,7 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with gasPrice >= MinGasPrices", func() {
gasPrice := sdk.NewInt(3)
gasPrice := sdkmath.NewInt(3)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -106,7 +107,7 @@ var _ = Describe("Feemarket", func() {
Context("during DeliverTx", func() {
It("should reject transactions with gasPrice < MinGasPrices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -116,7 +117,7 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with gasPrice >= MinGasPrices", func() {
gasPrice := sdk.NewInt(3)
gasPrice := sdkmath.NewInt(3)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -129,7 +130,7 @@ var _ = Describe("Feemarket", func() {
})
Context("during CheckTx", func() {
It("should reject transactions with gasPrice < MinGasPrices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -139,7 +140,7 @@ var _ = Describe("Feemarket", func() {
})
It("should reject transactions with MinGasPrices < gasPrice < min-gas-prices", func() {
gasPrice := sdk.NewInt(4)
gasPrice := sdkmath.NewInt(4)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -149,7 +150,7 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with gasPrice > min-gas-prices", func() {
gasPrice := sdk.NewInt(5)
gasPrice := sdkmath.NewInt(5)
res := checkTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -157,7 +158,7 @@ var _ = Describe("Feemarket", func() {
Context("during DeliverTx", func() {
It("should reject transactions with gasPrice < MinGasPrices", func() {
gasPrice := sdk.NewInt(2)
gasPrice := sdkmath.NewInt(2)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(false), "transaction should have failed")
Expect(
@ -167,13 +168,13 @@ var _ = Describe("Feemarket", func() {
})
It("should accept transactions with MinGasPrices < gasPrice < than min-gas-prices", func() {
gasPrice := sdk.NewInt(4)
gasPrice := sdkmath.NewInt(4)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
It("should accept transactions with gasPrice >= min-gas-prices", func() {
gasPrice := sdk.NewInt(5)
gasPrice := sdkmath.NewInt(5)
res := deliverTx(privKey, &gasPrice, &msg)
Expect(res.IsOK()).To(Equal(true), "transaction should have succeeded", res.GetLog())
})
@ -204,7 +205,7 @@ var _ = Describe("Feemarket", func() {
// 100000`. With the fee calculation `Fee = (baseFee + tip) * gasLimit`,
// a `minGasPrices = 40_000_000_000` results in `minGlobalFee =
// 4000000000000000`
privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), sdk.NewInt(baseFee))
privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), sdkmath.NewInt(baseFee))
})
Context("during CheckTx", func() {
@ -312,7 +313,7 @@ var _ = Describe("Feemarket", func() {
// 100_000`. With the fee calculation `Fee = (baseFee + tip) * gasLimit`,
// a `minGasPrices = 5_000_000_000` results in `minGlobalFee =
// 500_000_000_000_000`
privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), sdk.NewInt(baseFee))
privKey, _ = setupTestWithContext("1", sdk.NewDec(minGasPrices), sdkmath.NewInt(baseFee))
})
Context("during CheckTx", func() {
@ -441,7 +442,7 @@ var _ = Describe("Feemarket", func() {
// setupTestWithContext sets up a test chain with an example Cosmos send msg,
// given a local (validator config) and a gloabl (feemarket param) minGasPrice
func setupTestWithContext(valMinGasPrice string, minGasPrice sdk.Dec, baseFee sdk.Int) (*ethsecp256k1.PrivKey, banktypes.MsgSend) {
func setupTestWithContext(valMinGasPrice string, minGasPrice sdk.Dec, baseFee sdkmath.Int) (*ethsecp256k1.PrivKey, banktypes.MsgSend) {
privKey, msg := setupTest(valMinGasPrice + s.denom)
params := types.DefaultParams()
params.MinGasPrice = minGasPrice
@ -456,7 +457,7 @@ func setupTest(localMinGasPrices string) (*ethsecp256k1.PrivKey, banktypes.MsgSe
setupChain(localMinGasPrices)
privKey, address := generateKey()
amount, ok := sdk.NewIntFromString("10000000000000000000")
amount, ok := sdkmath.NewIntFromString("10000000000000000000")
s.Require().True(ok)
initBalance := sdk.Coins{sdk.Coin{
Denom: s.denom,
@ -469,7 +470,7 @@ func setupTest(localMinGasPrices string) (*ethsecp256k1.PrivKey, banktypes.MsgSe
ToAddress: address.String(),
Amount: sdk.Coins{sdk.Coin{
Denom: s.denom,
Amount: sdk.NewInt(10000),
Amount: sdkmath.NewInt(10000),
}},
}
s.Commit()
@ -575,7 +576,7 @@ func prepareEthTx(priv *ethsecp256k1.PrivKey, msgEthereumTx *evmtypes.MsgEthereu
s.Require().NoError(err)
evmDenom := s.app.EvmKeeper.GetParams(s.ctx).EvmDenom
fees := sdk.Coins{{Denom: evmDenom, Amount: sdk.NewIntFromBigInt(txData.Fee())}}
fees := sdk.Coins{{Denom: evmDenom, Amount: sdkmath.NewIntFromBigInt(txData.Fee())}}
builder.SetFeeAmount(fees)
builder.SetGasLimit(msgEthereumTx.GetGas())
@ -600,7 +601,7 @@ func deliverEthTx(priv *ethsecp256k1.PrivKey, msgEthereumTx *evmtypes.MsgEthereu
return res
}
func prepareCosmosTx(priv *ethsecp256k1.PrivKey, gasPrice *sdk.Int, msgs ...sdk.Msg) []byte {
func prepareCosmosTx(priv *ethsecp256k1.PrivKey, gasPrice *sdkmath.Int, msgs ...sdk.Msg) []byte {
encodingConfig := encoding.MakeConfig(app.ModuleBasics)
accountAddress := sdk.AccAddress(priv.PubKey().Address().Bytes())
@ -608,7 +609,7 @@ func prepareCosmosTx(priv *ethsecp256k1.PrivKey, gasPrice *sdk.Int, msgs ...sdk.
txBuilder.SetGasLimit(1000000)
if gasPrice == nil {
_gasPrice := sdk.NewInt(1)
_gasPrice := sdkmath.NewInt(1)
gasPrice = &_gasPrice
}
fees := &sdk.Coins{{Denom: s.denom, Amount: gasPrice.MulRaw(1000000)}}
@ -659,14 +660,14 @@ func prepareCosmosTx(priv *ethsecp256k1.PrivKey, gasPrice *sdk.Int, msgs ...sdk.
return bz
}
func checkTx(priv *ethsecp256k1.PrivKey, gasPrice *sdk.Int, msgs ...sdk.Msg) abci.ResponseCheckTx {
func checkTx(priv *ethsecp256k1.PrivKey, gasPrice *sdkmath.Int, msgs ...sdk.Msg) abci.ResponseCheckTx {
bz := prepareCosmosTx(priv, gasPrice, msgs...)
req := abci.RequestCheckTx{Tx: bz}
res := s.app.BaseApp.CheckTx(req)
return res
}
func deliverTx(priv *ethsecp256k1.PrivKey, gasPrice *sdk.Int, msgs ...sdk.Msg) abci.ResponseDeliverTx {
func deliverTx(priv *ethsecp256k1.PrivKey, gasPrice *sdkmath.Int, msgs ...sdk.Msg) abci.ResponseDeliverTx {
bz := prepareCosmosTx(priv, gasPrice, msgs...)
req := abci.RequestDeliverTx{Tx: bz}
res := s.app.BaseApp.DeliverTx(req)

View File

@ -2,6 +2,7 @@ package keeper
import (
"github.com/cosmos/cosmos-sdk/codec"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/tendermint/tendermint/libs/log"
@ -14,15 +15,15 @@ type Keeper struct {
// Protobuf codec
cdc codec.BinaryCodec
// Store key required for the Fee Market Prefix KVStore.
storeKey sdk.StoreKey
transientKey sdk.StoreKey
storeKey storetypes.StoreKey
transientKey storetypes.StoreKey
// module specific parameter space that can be configured through governance
paramSpace paramtypes.Subspace
}
// NewKeeper generates new fee market module keeper
func NewKeeper(
cdc codec.BinaryCodec, paramSpace paramtypes.Subspace, storeKey, transientKey sdk.StoreKey,
cdc codec.BinaryCodec, paramSpace paramtypes.Subspace, storeKey, transientKey storetypes.StoreKey,
) Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {

View File

@ -128,7 +128,8 @@ func (suite *KeeperTestSuite) SetupApp(checkTx bool) {
validator, err := stakingtypes.NewValidator(valAddr, priv.PubKey(), stakingtypes.Description{})
require.NoError(t, err)
validator = stakingkeeper.TestingUpdateValidator(suite.app.StakingKeeper, suite.ctx, validator, true)
suite.app.StakingKeeper.AfterValidatorCreated(suite.ctx, validator.GetOperator())
err = suite.app.StakingKeeper.AfterValidatorCreated(suite.ctx, validator.GetOperator())
require.NoError(t, err)
err = suite.app.StakingKeeper.SetValidatorByConsAddr(suite.ctx, validator)
require.NoError(t, err)
@ -137,7 +138,7 @@ func (suite *KeeperTestSuite) SetupApp(checkTx bool) {
encodingConfig := encoding.MakeConfig(app.ModuleBasics)
suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig)
suite.ethSigner = ethtypes.LatestSignerForChainID(suite.app.EvmKeeper.ChainID())
suite.appCodec = encodingConfig.Marshaler
suite.appCodec = encodingConfig.Codec
suite.denom = evmtypes.DefaultEVMDenom
}

View File

@ -3,6 +3,7 @@ package keeper
import (
"math/big"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/evmos/ethermint/x/feemarket/types"
)
@ -40,5 +41,5 @@ func (k Keeper) GetBaseFee(ctx sdk.Context) *big.Int {
// SetBaseFee set's the base fee in the paramSpace
func (k Keeper) SetBaseFee(ctx sdk.Context, baseFee *big.Int) {
k.paramSpace.Set(ctx, types.ParamStoreKeyBaseFee, sdk.NewIntFromBigInt(baseFee))
k.paramSpace.Set(ctx, types.ParamStoreKeyBaseFee, sdkmath.NewIntFromBigInt(baseFee))
}

View File

@ -3,6 +3,8 @@ package v010
import (
"math/big"
sdkmath "cosmossdk.io/math"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
@ -15,7 +17,7 @@ var KeyPrefixBaseFeeV1 = []byte{2}
// MigrateStore migrates the BaseFee value from the store to the params for
// In-Place Store migration logic.
func MigrateStore(ctx sdk.Context, paramstore *paramtypes.Subspace, storeKey sdk.StoreKey) error {
func MigrateStore(ctx sdk.Context, paramstore *paramtypes.Subspace, storeKey storetypes.StoreKey) error {
baseFee := types.DefaultParams().BaseFee
store := ctx.KVStore(storeKey)
@ -28,7 +30,7 @@ func MigrateStore(ctx sdk.Context, paramstore *paramtypes.Subspace, storeKey sdk
switch {
case store.Has(KeyPrefixBaseFeeV1):
bz := store.Get(KeyPrefixBaseFeeV1)
baseFee = sdk.NewIntFromBigInt(new(big.Int).SetBytes(bz))
baseFee = sdkmath.NewIntFromBigInt(new(big.Int).SetBytes(bz))
case paramstore.Has(ctx, types.ParamStoreKeyNoBaseFee):
paramstore.GetIfExists(ctx, types.ParamStoreKeyBaseFee, &baseFee)
}

View File

@ -26,9 +26,9 @@ func TestMigrateStore(t *testing.T) {
tFeeMarketKey := sdk.NewTransientStoreKey(fmt.Sprintf("%s_test", feemarkettypes.StoreKey))
ctx := testutil.DefaultContext(feemarketKey, tFeeMarketKey)
paramstore := paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, feemarketKey, tFeeMarketKey, "feemarket",
encCfg.Codec, encCfg.Amino, feemarketKey, tFeeMarketKey, "feemarket",
)
fmKeeper := feemarketkeeper.NewKeeper(encCfg.Marshaler, paramstore, feemarketKey, tFeeMarketKey)
fmKeeper := feemarketkeeper.NewKeeper(encCfg.Codec, paramstore, feemarketKey, tFeeMarketKey)
fmKeeper.SetParams(ctx, types.DefaultParams())
require.True(t, paramstore.HasKeyTable())
@ -60,7 +60,7 @@ func TestMigrateJSON(t *testing.T) {
}`
encCfg := encoding.MakeConfig(app.ModuleBasics)
var genState v09types.GenesisState
err := encCfg.Marshaler.UnmarshalJSON([]byte(rawJson), &genState)
err := encCfg.Codec.UnmarshalJSON([]byte(rawJson), &genState)
require.NoError(t, err)
migratedGenState := v010.MigrateJSON(genState)

View File

@ -3,7 +3,8 @@ package types
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/ethereum/go-ethereum/params"
)
@ -30,7 +31,7 @@ func NewParams(noBaseFee bool, baseFeeChangeDenom, elasticityMultiplier uint32,
NoBaseFee: noBaseFee,
BaseFeeChangeDenominator: baseFeeChangeDenom,
ElasticityMultiplier: elasticityMultiplier,
BaseFee: sdk.NewIntFromUint64(baseFee),
BaseFee: sdkmath.NewIntFromUint64(baseFee),
EnableHeight: enableHeight,
}
}
@ -41,7 +42,7 @@ func DefaultParams() Params {
NoBaseFee: false,
BaseFeeChangeDenominator: params.BaseFeeChangeDenominator,
ElasticityMultiplier: params.ElasticityMultiplier,
BaseFee: sdk.NewIntFromUint64(params.InitialBaseFee),
BaseFee: sdkmath.NewIntFromUint64(params.InitialBaseFee),
EnableHeight: 0,
}
}
@ -108,7 +109,7 @@ func validateElasticityMultiplier(i interface{}) error {
}
func validateBaseFee(i interface{}) error {
value, ok := i.(sdk.Int)
value, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}

View File

@ -30,7 +30,7 @@ func TestMigrateStore(t *testing.T) {
tFeeMarketKey := sdk.NewTransientStoreKey(fmt.Sprintf("%s_test", feemarkettypes.StoreKey))
ctx := testutil.DefaultContext(feemarketKey, tFeeMarketKey)
paramstore := paramtypes.NewSubspace(
encCfg.Marshaler, encCfg.Amino, feemarketKey, tFeeMarketKey, "feemarket",
encCfg.Codec, encCfg.Amino, feemarketKey, tFeeMarketKey, "feemarket",
)
paramstore = paramstore.WithKeyTable(feemarkettypes.ParamKeyTable())
@ -78,7 +78,7 @@ func TestMigrateJSON(t *testing.T) {
}`
encCfg := encoding.MakeConfig(app.ModuleBasics)
var genState v010types.GenesisState
err := encCfg.Marshaler.UnmarshalJSON([]byte(rawJson), &genState)
err := encCfg.Codec.UnmarshalJSON([]byte(rawJson), &genState)
require.NoError(t, err)
migratedGenState := v011.MigrateJSON(genState)

View File

@ -3,6 +3,7 @@ package types
import (
"fmt"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/ethereum/go-ethereum/params"
@ -47,7 +48,7 @@ func NewParams(
NoBaseFee: noBaseFee,
BaseFeeChangeDenominator: baseFeeChangeDenom,
ElasticityMultiplier: elasticityMultiplier,
BaseFee: sdk.NewIntFromUint64(baseFee),
BaseFee: sdkmath.NewIntFromUint64(baseFee),
EnableHeight: enableHeight,
MinGasPrice: minGasPrice,
MinGasMultiplier: minGasPriceMultiplier,
@ -60,7 +61,7 @@ func DefaultParams() Params {
NoBaseFee: false,
BaseFeeChangeDenominator: params.BaseFeeChangeDenominator,
ElasticityMultiplier: params.ElasticityMultiplier,
BaseFee: sdk.NewIntFromUint64(params.InitialBaseFee),
BaseFee: sdkmath.NewIntFromUint64(params.InitialBaseFee),
EnableHeight: 0,
MinGasPrice: DefaultMinGasPrice,
MinGasMultiplier: DefaultMinGasMultiplier,
@ -135,7 +136,7 @@ func validateElasticityMultiplier(i interface{}) error {
}
func validateBaseFee(i interface{}) error {
value, ok := i.(sdk.Int)
value, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}

View File

@ -3,10 +3,11 @@ package types
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
type ParamsTestSuite struct {
@ -45,7 +46,7 @@ func (suite *ParamsTestSuite) TestParamsValidate() {
},
{
"invalid: min gas price negative",
NewParams(true, 7, 3, 2000000000, int64(544435345345435345), sdk.NewDecFromInt(sdk.NewInt(-1)), DefaultMinGasMultiplier),
NewParams(true, 7, 3, 2000000000, int64(544435345345435345), sdk.NewDecFromInt(sdkmath.NewInt(-1)), DefaultMinGasMultiplier),
true,
},
{
@ -86,8 +87,8 @@ func (suite *ParamsTestSuite) TestParamsValidatePriv() {
suite.Require().NoError(validateElasticityMultiplier(uint32(2)))
suite.Require().Error(validateBaseFee(""))
suite.Require().Error(validateBaseFee(int64(2000000000)))
suite.Require().Error(validateBaseFee(sdk.NewInt(-2000000000)))
suite.Require().NoError(validateBaseFee(sdk.NewInt(2000000000)))
suite.Require().Error(validateBaseFee(sdkmath.NewInt(-2000000000)))
suite.Require().NoError(validateBaseFee(sdkmath.NewInt(2000000000)))
suite.Require().Error(validateEnableHeight(""))
suite.Require().Error(validateEnableHeight(int64(-544435345345435345)))
suite.Require().NoError(validateEnableHeight(int64(544435345345435345)))
@ -104,13 +105,13 @@ func (suite *ParamsTestSuite) TestParamsValidateMinGasPrice() {
expError bool
}{
{"default", DefaultParams().MinGasPrice, false},
{"valid", sdk.NewDecFromInt(sdk.NewInt(1)), false},
{"valid", sdk.NewDecFromInt(sdkmath.NewInt(1)), false},
{"invalid - wrong type - bool", false, true},
{"invalid - wrong type - string", "", true},
{"invalid - wrong type - int64", int64(123), true},
{"invalid - wrong type - sdk.Int", sdk.NewInt(1), true},
{"invalid - wrong type - sdkmath.Int", sdkmath.NewInt(1), true},
{"invalid - is nil", nil, true},
{"invalid - is negative", sdk.NewDecFromInt(sdk.NewInt(-1)), true},
{"invalid - is negative", sdk.NewDecFromInt(sdkmath.NewInt(-1)), true},
}
for _, tc := range testCases {