From 8970a6c7dde3e03e93cf033f151155d0f80e60e9 Mon Sep 17 00:00:00 2001 From: Oleg Nikonychev Date: Fri, 12 Jul 2024 18:19:48 +0400 Subject: [PATCH] chore(evm): code cleanup, unused code, typos, styles, warnings (#1962) * chore: code cleanup, typos, styles, warnings * chore: changelog update * fix: rolled back pointer receivers for read-only methods --- CHANGELOG.md | 1 + app/ante.go | 9 ++-- app/evmante_sigverify_test.go | 1 - app/server/json_rpc.go | 3 +- eth/codec.go | 10 ----- eth/rpc/backend/client_test.go | 27 ------------ eth/rpc/rpcapi/apis.go | 12 ------ x/common/testutil/testnetwork/network.go | 2 +- x/devgas/v1/ante/expected_keepers.go | 2 +- x/devgas/v1/keeper/keeper.go | 2 +- x/devgas/v1/types/msg.go | 4 +- x/evm/access_list.go | 4 +- x/evm/chain_config.go | 2 +- x/evm/codec.go | 8 +--- x/evm/errors.go | 14 ++---- x/evm/evmtest/tx.go | 43 ------------------- x/evm/keeper/erc20.go | 22 +++++----- x/evm/keeper/erc20_from_coin.go | 6 +-- x/evm/keeper/erc20_test.go | 4 +- x/evm/keeper/evm_state.go | 10 +---- x/evm/keeper/grpc_query.go | 4 +- x/evm/keeper/keeper.go | 2 +- x/evm/keeper/msg_server.go | 14 +++--- x/evm/keeper/statedb.go | 2 +- x/evm/legacy_tx.go | 2 +- x/evm/logs.go | 4 +- x/evm/logs_test.go | 2 +- x/evm/msg.go | 6 +-- x/evm/params.go | 21 --------- x/evm/precompile/funtoken.go | 2 +- x/evm/precompile/funtoken_test.go | 2 +- x/evm/statedb/config.go | 2 +- x/evm/tx.go | 4 +- x/evm/tx_data.go | 2 +- x/evm/vmtracer.go | 6 --- x/inflation/keeper/hooks.go | 4 +- x/inflation/keeper/inflation.go | 2 +- x/inflation/keeper/keeper.go | 4 +- .../types/inflation_calculation_test.go | 4 +- 39 files changed, 69 insertions(+), 206 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8baac699..aa67b50b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#1959](https://github.com/NibiruChain/nibiru/pull/1959) - feat(evm): Add precompile to the EVM that enables trasnfers of ERC20 tokens to "nibi" accounts as regular Ethereum transactions - [#1960](https://github.com/NibiruChain/nibiru/pull/1960) - test(network): graceful cleanup for more consistent CI runs - [#1961](https://github.com/NibiruChain/nibiru/pull/1961) - chore(test): reverted funtoken precompile test back to the isolated state +- [#1962](https://github.com/NibiruChain/nibiru/pull/1962) - chore(evm): code cleanup, unused code, typos, styles, warnings #### Dapp modules: perp, spot, oracle, etc diff --git a/app/ante.go b/app/ante.go index 003bec946..0a18887b4 100644 --- a/app/ante.go +++ b/app/ante.go @@ -32,13 +32,13 @@ func NewAnteHandler( var anteHandler sdk.AnteHandler hasExt, typeUrl := TxHasExtensions(tx) if hasExt && typeUrl != "" { - anteHandler = AnteHandlerExtendedTx(typeUrl, keepers, opts, ctx) + anteHandler = AnteHandlerExtendedTx(typeUrl, keepers, opts) return anteHandler(ctx, tx, sim) } switch tx.(type) { case sdk.Tx: - anteHandler = NewAnteHandlerNonEVM(keepers, opts) + anteHandler = NewAnteHandlerNonEVM(opts) default: return ctx, fmt.Errorf("invalid tx type (%T) in AnteHandler", tx) } @@ -50,13 +50,12 @@ func AnteHandlerExtendedTx( typeUrl string, keepers AppKeepers, opts ante.AnteHandlerOptions, - ctx sdk.Context, ) (anteHandler sdk.AnteHandler) { switch typeUrl { case evm.TYPE_URL_ETHEREUM_TX: anteHandler = NewAnteHandlerEVM(keepers, opts) case eth.TYPE_URL_DYNAMIC_FEE_TX: - anteHandler = NewAnteHandlerNonEVM(keepers, opts) + anteHandler = NewAnteHandlerNonEVM(opts) default: errUnsupported := fmt.Errorf( `encountered tx with unsupported extension option, "%s"`, typeUrl) @@ -71,7 +70,7 @@ func AnteHandlerExtendedTx( // NewAnteHandlerNonEVM: Default ante handler for non-EVM transactions. func NewAnteHandlerNonEVM( - k AppKeepers, opts ante.AnteHandlerOptions, + opts ante.AnteHandlerOptions, ) sdk.AnteHandler { return sdk.ChainAnteDecorators( AnteDecoratorPreventEtheruemTxMsgs{}, // reject MsgEthereumTxs diff --git a/app/evmante_sigverify_test.go b/app/evmante_sigverify_test.go index be48262a9..145174e09 100644 --- a/app/evmante_sigverify_test.go +++ b/app/evmante_sigverify_test.go @@ -13,7 +13,6 @@ import ( var ( InvalidChainID = big.NewInt(987654321) - RandomAddress = evmtest.NewEthAccInfo().EthAddr.Hex() ) func (s *TestSuite) TestEthSigVerificationDecorator() { diff --git a/app/server/json_rpc.go b/app/server/json_rpc.go index ae02cfe60..6baf8f06f 100644 --- a/app/server/json_rpc.go +++ b/app/server/json_rpc.go @@ -1,6 +1,7 @@ package server import ( + "errors" "net/http" "time" @@ -87,7 +88,7 @@ func StartJSONRPC(ctx *server.Context, go func() { ctx.Logger.Info("Starting JSON-RPC server", "address", config.JSONRPC.Address) if err := httpSrv.Serve(ln); err != nil { - if err == http.ErrServerClosed { + if errors.Is(err, http.ErrServerClosed) { close(httpSrvDone) return } diff --git a/eth/codec.go b/eth/codec.go index fe0116973..6fd7fc346 100644 --- a/eth/codec.go +++ b/eth/codec.go @@ -2,8 +2,6 @@ package eth import ( - "math/big" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdktx "github.com/cosmos/cosmos-sdk/types/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -64,11 +62,3 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { &ExtensionOptionDynamicFeeTx{}, ) } - -func ParseEIP155ChainIDNumber(chainId string) *big.Int { - idNum, err := ParseEthChainID(chainId) - if err != nil { - panic(err) - } - return idNum -} diff --git a/eth/rpc/backend/client_test.go b/eth/rpc/backend/client_test.go index 21f22ce4d..642a473df 100644 --- a/eth/rpc/backend/client_test.go +++ b/eth/rpc/backend/client_test.go @@ -4,8 +4,6 @@ import ( "context" "testing" - "github.com/cosmos/cosmos-sdk/client" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" errortypes "github.com/cosmos/cosmos-sdk/types/errors" abci "github.com/cometbft/cometbft/abci/types" @@ -13,7 +11,6 @@ import ( tmrpcclient "github.com/cometbft/cometbft/rpc/client" tmrpctypes "github.com/cometbft/cometbft/rpc/core/types" "github.com/cometbft/cometbft/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/ethereum/go-ethereum/common" mock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -42,11 +39,6 @@ func RegisterTxSearchEmpty(client *mocks.Client, query string) { Return(&tmrpctypes.ResultTxSearch{}, nil) } -func RegisterTxSearchError(client *mocks.Client, query string) { - client.On("TxSearch", rpc.NewContextWithHeight(1), query, false, (*int)(nil), (*int)(nil), ""). - Return(nil, errortypes.ErrInvalidRequest) -} - // Broadcast Tx func RegisterBroadcastTx(client *mocks.Client, tx types.Tx) { client.On("BroadcastTxSync", context.Background(), tx). @@ -265,22 +257,3 @@ func RegisterABCIQueryWithOptions(client *mocks.Client, height int64, path strin }, }, nil) } - -func RegisterABCIQueryWithOptionsError(clients *mocks.Client, path string, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions) { - clients.On("ABCIQueryWithOptions", context.Background(), path, data, opts). - Return(nil, errortypes.ErrInvalidRequest) -} - -func RegisterABCIQueryAccount(clients *mocks.Client, data bytes.HexBytes, opts tmrpcclient.ABCIQueryOptions, acc client.Account) { - baseAccount := authtypes.NewBaseAccount(acc.GetAddress(), acc.GetPubKey(), acc.GetAccountNumber(), acc.GetSequence()) - accAny, _ := codectypes.NewAnyWithValue(baseAccount) - accResponse := authtypes.QueryAccountResponse{Account: accAny} - respBz, _ := accResponse.Marshal() - clients.On("ABCIQueryWithOptions", context.Background(), "/cosmos.auth.v1beta1.Query/Account", data, opts). - Return(&tmrpctypes.ResultABCIQuery{ - Response: abci.ResponseQuery{ - Value: respBz, - Height: 1, - }, - }, nil) -} diff --git a/eth/rpc/rpcapi/apis.go b/eth/rpc/rpcapi/apis.go index b499c88c2..2a8f376ad 100644 --- a/eth/rpc/rpcapi/apis.go +++ b/eth/rpc/rpcapi/apis.go @@ -2,8 +2,6 @@ package rpcapi import ( - "fmt" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" @@ -137,13 +135,3 @@ func GetRPCAPIs(ctx *server.Context, return apis } - -// RegisterAPINamespace registers a new API namespace with the API creator. -// This function fails if the namespace is already registered. -func RegisterAPINamespace(ns string, creator APICreator) error { - if _, ok := apiCreators[ns]; ok { - return fmt.Errorf("duplicated api namespace %s", ns) - } - apiCreators[ns] = creator - return nil -} diff --git a/x/common/testutil/testnetwork/network.go b/x/common/testutil/testnetwork/network.go index 71835d191..8ecfec073 100644 --- a/x/common/testutil/testnetwork/network.go +++ b/x/common/testutil/testnetwork/network.go @@ -52,7 +52,7 @@ var lock = new(sync.Mutex) // creates an ABCI Application to provide to Tendermint. type AppConstructor = func(val Validator) servertypes.Application -// Network defines a in-process testing network. It is primarily intended +// Network defines an in-process testing network. It is primarily intended // for client and integration testing. The Network struct can spawn any // number of validators, each with its own RPC and API clients. // diff --git a/x/devgas/v1/ante/expected_keepers.go b/x/devgas/v1/ante/expected_keepers.go index eefe11c35..6f49b0dc4 100644 --- a/x/devgas/v1/ante/expected_keepers.go +++ b/x/devgas/v1/ante/expected_keepers.go @@ -1,6 +1,6 @@ package ante -// Interfaces needed for the for the Nibiru Chain ante handler +// Interfaces needed for the Nibiru Chain ante handler import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/devgas/v1/keeper/keeper.go b/x/devgas/v1/keeper/keeper.go index 97081ccd2..908854cf4 100644 --- a/x/devgas/v1/keeper/keeper.go +++ b/x/devgas/v1/keeper/keeper.go @@ -26,7 +26,7 @@ type Keeper struct { wasmKeeper wasmkeeper.Keeper accountKeeper devgastypes.AccountKeeper - // feeCollectorName is the name of of x/auth module's fee collector module + // feeCollectorName is the name of x/auth module's fee collector module // account, "fee_collector", which collects transaction fees for distribution // to all stakers. // diff --git a/x/devgas/v1/types/msg.go b/x/devgas/v1/types/msg.go index ab2da1005..608bc8f36 100644 --- a/x/devgas/v1/types/msg.go +++ b/x/devgas/v1/types/msg.go @@ -39,7 +39,7 @@ func NewMsgRegisterFeeShare( // Route returns the name of the module func (msg MsgRegisterFeeShare) Route() string { return RouterKey } -// Type returns the the action +// Type returns the action func (msg MsgRegisterFeeShare) Type() string { return TypeMsgRegisterFeeShare } // ValidateBasic runs stateless checks on the message @@ -129,7 +129,7 @@ func NewMsgUpdateFeeShare( // Route returns the name of the module func (msg MsgUpdateFeeShare) Route() string { return RouterKey } -// Type returns the the action +// Type returns the action func (msg MsgUpdateFeeShare) Type() string { return TypeMsgUpdateFeeShare } // ValidateBasic runs stateless checks on the message diff --git a/x/evm/access_list.go b/x/evm/access_list.go index 19be79d0d..118679122 100644 --- a/x/evm/access_list.go +++ b/x/evm/access_list.go @@ -41,7 +41,7 @@ func NewAccessList(ethAccessList *gethcore.AccessList) AccessList { return al } -// ToEthAccessList is an utility function to convert the protobuf compatible +// ToEthAccessList is a utility function to convert the protobuf compatible // AccessList to eth core AccessList from go-ethereum func (al AccessList) ToEthAccessList() *gethcore.AccessList { var ethAccessList gethcore.AccessList @@ -140,7 +140,7 @@ func (tx *AccessListTx) GetAccessList() gethcore.AccessList { return *tx.Accesses.ToEthAccessList() } -// GetData returns the a copy of the input data bytes. +// GetData returns a copy of the input data bytes. func (tx *AccessListTx) GetData() []byte { return common.CopyBytes(tx.Data) } diff --git a/x/evm/chain_config.go b/x/evm/chain_config.go index fc47b4ddf..eb3662d8a 100644 --- a/x/evm/chain_config.go +++ b/x/evm/chain_config.go @@ -40,7 +40,7 @@ func EthereumConfig(chainID *big.Int) *params.ChainConfig { } // Validate performs a basic validation of the ChainConfig params. The function will return an error -// if any of the block values is uninitialized (i.e nil) or if the EIP150Hash is an invalid hash. +// if any of the block values is uninitialized (i.e. nil) or if the EIP150Hash is an invalid hash. func Validate() error { // NOTE: chain ID is not needed to check config order if err := EthereumConfig(nil).CheckConfigForkOrder(); err != nil { diff --git a/x/evm/codec.go b/x/evm/codec.go index a382495ac..42fec4565 100644 --- a/x/evm/codec.go +++ b/x/evm/codec.go @@ -9,15 +9,11 @@ import ( errortypes "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/types/tx" - proto "github.com/cosmos/gogoproto/proto" + "github.com/cosmos/gogoproto/proto" ) var ( amino = codec.NewLegacyAmino() - // ModuleCdc references the global evm module codec. Note, the codec should - // ONLY be used in certain instances of tests and for JSON encoding. - ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - // AminoCdc is a amino codec created to support amino JSON compatible msgs. AminoCdc = codec.NewAminoCodec(amino) ) @@ -57,7 +53,7 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { } // PackTxData constructs a new Any packed with the given tx data value. It returns -// an error if the client state can't be casted to a protobuf message or if the concrete +// an error if the client state can't be cast to a protobuf message or if the concrete // implementation is not registered to the protobuf codec. func PackTxData(txData TxData) (*codectypes.Any, error) { msg, ok := txData.(proto.Message) diff --git a/x/evm/errors.go b/x/evm/errors.go index 78ee2bda9..9e47690e8 100644 --- a/x/evm/errors.go +++ b/x/evm/errors.go @@ -14,14 +14,12 @@ import ( const ( codeErrInvalidState = uint32(iota) + 2 // NOTE: code 1 is reserved for internal errors - codeErrInvalidChainConfig codeErrZeroAddress codeErrCreateDisabled codeErrCallDisabled codeErrInvalidAmount codeErrInvalidGasPrice codeErrInvalidGasFee - codeErrVMExecution codeErrInvalidRefund codeErrInvalidGasCap codeErrInvalidBaseFee @@ -37,9 +35,6 @@ var ( // ErrInvalidState returns an error resulting from an invalid Storage State. ErrInvalidState = errorsmod.Register(ModuleName, codeErrInvalidState, "invalid storage state") - // ErrInvalidChainConfig returns an error resulting from an invalid ChainConfig. - ErrInvalidChainConfig = errorsmod.Register(ModuleName, codeErrInvalidChainConfig, "invalid chain configuration") - // ErrZeroAddress returns an error resulting from an zero (empty) ethereum Address. ErrZeroAddress = errorsmod.Register(ModuleName, codeErrZeroAddress, "invalid zero address") @@ -58,16 +53,13 @@ var ( // ErrInvalidGasFee returns an error if the tx gas fee is out of bound. ErrInvalidGasFee = errorsmod.Register(ModuleName, codeErrInvalidGasFee, "invalid gas fee") - // ErrVMExecution returns an error resulting from an error in EVM execution. - ErrVMExecution = errorsmod.Register(ModuleName, codeErrVMExecution, "evm transaction execution failed") - - // ErrInvalidRefund returns an error if a the gas refund value is invalid. + // ErrInvalidRefund returns an error if the gas refund value is invalid. ErrInvalidRefund = errorsmod.Register(ModuleName, codeErrInvalidRefund, "invalid gas refund amount") - // ErrInvalidGasCap returns an error if a the gas cap value is negative or invalid + // ErrInvalidGasCap returns an error if the gas cap value is negative or invalid ErrInvalidGasCap = errorsmod.Register(ModuleName, codeErrInvalidGasCap, "invalid gas cap") - // ErrInvalidBaseFee returns an error if a the base fee cap value is invalid + // ErrInvalidBaseFee returns an error if the base fee cap value is invalid ErrInvalidBaseFee = errorsmod.Register(ModuleName, codeErrInvalidBaseFee, "invalid base fee") // ErrGasOverflow returns an error if gas computation overlow/underflow diff --git a/x/evm/evmtest/tx.go b/x/evm/evmtest/tx.go index bbe5a5456..ee968b551 100644 --- a/x/evm/evmtest/tx.go +++ b/x/evm/evmtest/tx.go @@ -23,43 +23,6 @@ import ( type GethTxType = uint8 -func NewEthTx( - deps *TestDeps, txData gethcore.TxData, nonce uint64, -) (ethCoreTx *gethcore.Transaction, err error) { - ethCoreTx, err = NewEthTxUnsigned(deps, txData, nonce) - if err != nil { - return ethCoreTx, err - } - - sig, _, err := deps.Sender.KeyringSigner.SignByAddress( - deps.Sender.NibiruAddr, ethCoreTx.Hash().Bytes(), - ) - if err != nil { - return ethCoreTx, err - } - - return ethCoreTx.WithSignature(deps.GethSigner(), sig) -} - -func NewEthTxUnsigned( - deps *TestDeps, txData gethcore.TxData, nonce uint64, -) (ethCoreTx *gethcore.Transaction, err error) { - switch typedTxData := txData.(type) { - case *gethcore.LegacyTx: - typedTxData.Nonce = nonce - ethCoreTx = gethcore.NewTx(typedTxData) - case *gethcore.AccessListTx: - typedTxData.Nonce = nonce - ethCoreTx = gethcore.NewTx(typedTxData) - case *gethcore.DynamicFeeTx: - typedTxData.Nonce = nonce - ethCoreTx = gethcore.NewTx(typedTxData) - default: - return ethCoreTx, fmt.Errorf("received unknown tx type in NewEthTxUnsigned") - } - return ethCoreTx, err -} - func TxTemplateAccessListTx() *gethcore.AccessListTx { return &gethcore.AccessListTx{ GasPrice: big.NewInt(1), @@ -154,12 +117,6 @@ func ExecuteNibiTransfer(deps *TestDeps, t *testing.T) *evm.MsgEthereumTx { return ethTxMsg } -func GasLimitCreateContract() *big.Int { - return new(big.Int).SetUint64( - gethparams.TxGasContractCreation + 700, - ) -} - type DeployContractResult struct { TxResp *evm.MsgEthereumTxResponse EthTxMsg *evm.MsgEthereumTx diff --git a/x/evm/keeper/erc20.go b/x/evm/keeper/erc20.go index d65a32433..20bd0ef9a 100644 --- a/x/evm/keeper/erc20.go +++ b/x/evm/keeper/erc20.go @@ -107,7 +107,7 @@ func (k *Keeper) CreateFunTokenFromERC20( if funtokens := k.FunTokens.Collect( ctx, k.FunTokens.Indexes.ERC20Addr.ExactMatch(ctx, erc20Addr), ); len(funtokens) > 0 { - return funtoken, fmt.Errorf("Funtoken mapping already created for ERC20 \"%s\"", erc20Addr.Hex()) + return funtoken, fmt.Errorf("funtoken mapping already created for ERC20 \"%s\"", erc20Addr.Hex()) } // 2 | Get existing ERC20 metadata @@ -120,12 +120,12 @@ func (k *Keeper) CreateFunTokenFromERC20( // 3 | Coin already registered with FunToken? _, isAlreadyCoin := k.bankKeeper.GetDenomMetaData(ctx, bankDenom) if isAlreadyCoin { - return funtoken, fmt.Errorf("Bank coin denom already registered with denom \"%s\"", bankDenom) + return funtoken, fmt.Errorf("bank coin denom already registered with denom \"%s\"", bankDenom) } if funtokens := k.FunTokens.Collect( ctx, k.FunTokens.Indexes.BankDenom.ExactMatch(ctx, bankDenom), ); len(funtokens) > 0 { - return funtoken, fmt.Errorf("Funtoken mapping already created for bank denom \"%s\"", bankDenom) + return funtoken, fmt.Errorf("funtoken mapping already created for bank denom \"%s\"", bankDenom) } // 4 | Set bank coin denom metadata in state @@ -249,7 +249,7 @@ func (k Keeper) CallContractWithInput( // Apply EVM message cfg, err := k.GetEVMConfig( ctx, - sdk.ConsAddress(ctx.BlockHeader().ProposerAddress), + ctx.BlockHeader().ProposerAddress, k.EthChainID(ctx), ) if err != nil { @@ -415,19 +415,19 @@ func (k Keeper) LoadERC20BigInt( return erc20Val.Value, err } -func (k Keeper) ERC20() erc20Calls { - return erc20Calls{ +func (k Keeper) ERC20() Erc20Calls { + return Erc20Calls{ Keeper: &k, ABI: embeds.Contract_ERC20Minter.ABI, } } -type erc20Calls struct { +type Erc20Calls struct { *Keeper ABI gethabi.ABI } -func (e erc20Calls) Mint( +func (e Erc20Calls) Mint( contract, from, to gethcommon.Address, amount *big.Int, ctx sdk.Context, ) (evmResp *evm.MsgEthereumTxResponse, err error) { @@ -449,7 +449,7 @@ Transfer implements "ERC20.transfer" function transfer(address to, uint256 amount) external returns (bool); ``` */ -func (e erc20Calls) Transfer( +func (e Erc20Calls) Transfer( contract, from, to gethcommon.Address, amount *big.Int, ctx sdk.Context, ) (evmResp *evm.MsgEthereumTxResponse, err error) { @@ -463,7 +463,7 @@ func (e erc20Calls) Transfer( // BalanceOf retrieves the balance of an ERC20 token for a specific account. // Implements "ERC20.balanceOf". -func (e erc20Calls) BalanceOf( +func (e Erc20Calls) BalanceOf( contract, account gethcommon.Address, ctx sdk.Context, ) (out *big.Int, err error) { @@ -478,7 +478,7 @@ Burn implements "ERC20Burnable.burn" function burn(uint256 amount) public virtual { ``` */ -func (e erc20Calls) Burn( +func (e Erc20Calls) Burn( contract, from gethcommon.Address, amount *big.Int, ctx sdk.Context, ) (evmResp *evm.MsgEthereumTxResponse, err error) { diff --git a/x/evm/keeper/erc20_from_coin.go b/x/evm/keeper/erc20_from_coin.go index bfde3487e..151d48552 100644 --- a/x/evm/keeper/erc20_from_coin.go +++ b/x/evm/keeper/erc20_from_coin.go @@ -21,13 +21,13 @@ func (k *Keeper) CreateFunTokenFromCoin( if funtokens := k.FunTokens.Collect( ctx, k.FunTokens.Indexes.BankDenom.ExactMatch(ctx, bankDenom), ); len(funtokens) > 0 { - return funtoken, fmt.Errorf("Funtoken mapping already created for bank denom \"%s\"", bankDenom) + return funtoken, fmt.Errorf("funtoken mapping already created for bank denom \"%s\"", bankDenom) } // 2 | Check for denom metadata in bank state bankCoin, isAlreadyCoin := k.bankKeeper.GetDenomMetaData(ctx, bankDenom) if !isAlreadyCoin { - return funtoken, fmt.Errorf("Bank coin denom should have bank metadata for denom \"%s\"", bankDenom) + return funtoken, fmt.Errorf("bank coin denom should have bank metadata for denom \"%s\"", bankDenom) } // 3 | deploy ERC20 for metadata @@ -40,7 +40,7 @@ func (k *Keeper) CreateFunTokenFromCoin( if funtokens := k.FunTokens.Collect( ctx, k.FunTokens.Indexes.ERC20Addr.ExactMatch(ctx, erc20Addr), ); len(funtokens) > 0 { - return funtoken, fmt.Errorf("Funtoken mapping already created for ERC20 \"%s\"", erc20Addr.Hex()) + return funtoken, fmt.Errorf("funtoken mapping already created for ERC20 \"%s\"", erc20Addr.Hex()) } // 5 | Officially create the funtoken mapping diff --git a/x/evm/keeper/erc20_test.go b/x/evm/keeper/erc20_test.go index 411a5a688..7aa8cda28 100644 --- a/x/evm/keeper/erc20_test.go +++ b/x/evm/keeper/erc20_test.go @@ -98,7 +98,7 @@ func (s *Suite) TestCreateFunTokenFromERC20() { Sender: deps.Sender.NibiruAddr.String(), }, ) - s.ErrorContains(err, "Funtoken mapping already created") + s.ErrorContains(err, "funtoken mapping already created") s.T().Log("sad: CreateFunToken for the ERC20: invalid sender") _, err = deps.K.CreateFunToken( @@ -209,7 +209,7 @@ func (s *Suite) TestCreateFunTokenFromCoin() { Sender: deps.Sender.NibiruAddr.String(), }, ) - s.ErrorContains(err, "Funtoken mapping already created") + s.ErrorContains(err, "funtoken mapping already created") } // TestSendFunTokenToEvm executes sending fun tokens from bank coin to erc20 and checks the results: diff --git a/x/evm/keeper/evm_state.go b/x/evm/keeper/evm_state.go index 318beb4d8..9045b1c1d 100644 --- a/x/evm/keeper/evm_state.go +++ b/x/evm/keeper/evm_state.go @@ -2,7 +2,6 @@ package keeper import ( - "fmt" "math/big" "slices" @@ -95,11 +94,6 @@ func NewEvmState( } } -// BytesToHex converts a byte array to a hexadecimal string -func BytesToHex(bz []byte) string { - return fmt.Sprintf("%x", bz) -} - func (state EvmState) SetAccCode(ctx sdk.Context, codeHash, code []byte) { if len(code) > 0 { state.ContractBytecode.Insert(ctx, codeHash, code) @@ -170,12 +164,12 @@ func (state EvmState) CalcBloomFromLogs( // ResetTransientGasUsed resets gas to prepare for the next block of execution. // Called in an ante handler. -func (k Keeper) ResetTransientGasUsed(ctx sdk.Context) { +func (k *Keeper) ResetTransientGasUsed(ctx sdk.Context) { k.EvmState.BlockGasUsed.Set(ctx, 0) } // GetAccNonce returns the sequence number of an account, returns 0 if not exists. -func (k *Keeper) GetAccNonce(ctx sdk.Context, addr gethcommon.Address) uint64 { +func (k Keeper) GetAccNonce(ctx sdk.Context, addr gethcommon.Address) uint64 { nibiruAddr := sdk.AccAddress(addr.Bytes()) acct := k.accountKeeper.GetAccount(ctx, nibiruAddr) if acct == nil { diff --git a/x/evm/keeper/grpc_query.go b/x/evm/keeper/grpc_query.go index 2cc0cd4cd..2560ea5ae 100644 --- a/x/evm/keeper/grpc_query.go +++ b/x/evm/keeper/grpc_query.go @@ -34,7 +34,7 @@ import ( ) // Compile-time interface assertion -var _ evm.QueryServer = Keeper{} +var _ evm.QueryServer = &Keeper{} // EthAccount: Implements the gRPC query for "/eth.evm.v1.Query/EthAccount". // EthAccount retrieves the account details for a given Ethereum hex address. @@ -269,7 +269,7 @@ func (k Keeper) Params( // Returns: // - A pointer to the MsgEthereumTxResponse object containing the result of the eth_call. // - An error if the eth_call process encounters any issues. -func (k Keeper) EthCall( +func (k *Keeper) EthCall( goCtx context.Context, req *evm.EthCallRequest, ) (*evm.MsgEthereumTxResponse, error) { if err := req.Validate(); err != nil { diff --git a/x/evm/keeper/keeper.go b/x/evm/keeper/keeper.go index 45a357338..3379c6159 100644 --- a/x/evm/keeper/keeper.go +++ b/x/evm/keeper/keeper.go @@ -103,7 +103,7 @@ func (k Keeper) EthChainID(ctx sdk.Context) *big.Int { // AddToBlockGasUsed accumulate gas used by each eth msgs included in current // block tx. -func (k Keeper) AddToBlockGasUsed( +func (k *Keeper) AddToBlockGasUsed( ctx sdk.Context, gasUsed uint64, ) (uint64, error) { result := k.EvmState.BlockGasUsed.GetOr(ctx, 0) + gasUsed diff --git a/x/evm/keeper/msg_server.go b/x/evm/keeper/msg_server.go index ea42381f5..b24df1e3e 100644 --- a/x/evm/keeper/msg_server.go +++ b/x/evm/keeper/msg_server.go @@ -105,7 +105,7 @@ func (k *Keeper) ApplyEvmTx( ctx sdk.Context, tx *gethcore.Transaction, ) (*evm.MsgEthereumTxResponse, error) { ethChainId := k.EthChainID(ctx) - cfg, err := k.GetEVMConfig(ctx, sdk.ConsAddress(ctx.BlockHeader().ProposerAddress), ethChainId) + cfg, err := k.GetEVMConfig(ctx, ctx.BlockHeader().ProposerAddress, ethChainId) if err != nil { return nil, errors.Wrap(err, "failed to load evm config") } @@ -118,7 +118,7 @@ func (k *Keeper) ApplyEvmTx( return nil, errors.Wrap(err, "failed to return ethereum transaction as core message") } - // snapshot to contain the tx processing and post processing in same scope + // snapshot to contain the tx processing and post-processing in same scope var commit func() tmpCtx := ctx if k.hooks != nil { @@ -176,7 +176,7 @@ func (k *Keeper) ApplyEvmTx( res.VmError = evm.ErrPostTxProcessing.Error() k.Logger(ctx).Error("tx post processing failed", "error", err) - // If the tx failed in post processing hooks, we should clear the logs + // If the tx failed in post-processing hooks, we should clear the logs res.Logs = nil } else if commit != nil { // PostTxProcessing is successful, commit the tmpCtx @@ -219,7 +219,7 @@ func (k *Keeper) ApplyEvmTx( func (k *Keeper) ApplyEvmMsgWithEmptyTxConfig( ctx sdk.Context, msg core.Message, tracer vm.EVMLogger, commit bool, ) (*evm.MsgEthereumTxResponse, error) { - cfg, err := k.GetEVMConfig(ctx, sdk.ConsAddress(ctx.BlockHeader().ProposerAddress), k.EthChainID(ctx)) + cfg, err := k.GetEVMConfig(ctx, ctx.BlockHeader().ProposerAddress, k.EthChainID(ctx)) if err != nil { return nil, errors.Wrap(err, "failed to load evm config") } @@ -268,7 +268,7 @@ func (k *Keeper) NewEVM( // GetHashFn implements vm.GetHashFunc for Ethermint. It handles 3 cases: // 1. The requested height matches the current height from context (and thus same epoch number) -// 2. The requested height is from an previous height from the same chain epoch +// 2. The requested height is from a previous height from the same chain epoch // 3. The requested height is from a height greater than the latest one func (k Keeper) GetHashFn(ctx sdk.Context) vm.GetHashFunc { return func(height uint64) gethcommon.Hash { @@ -280,7 +280,7 @@ func (k Keeper) GetHashFn(ctx sdk.Context) vm.GetHashFunc { switch { case ctx.BlockHeight() == h: - // Case 1: The requested height matches the one from the context so we can retrieve the header + // Case 1: The requested height matches the one from the context, so we can retrieve the header // hash directly from the context. // Note: The headerHash is only set at begin block, it will be nil in case of a query context headerHash := ctx.HeaderHash() @@ -527,7 +527,7 @@ func (k *Keeper) CreateFunToken( default: // Impossible to reach this case due to ValidateBasic err = fmt.Errorf( - "Either the \"from_erc20\" or \"from_bank_denom\" must be set (but not both).") + "either the \"from_erc20\" or \"from_bank_denom\" must be set (but not both)") } if err != nil { return diff --git a/x/evm/keeper/statedb.go b/x/evm/keeper/statedb.go index 3eb751999..e1c2ceeaa 100644 --- a/x/evm/keeper/statedb.go +++ b/x/evm/keeper/statedb.go @@ -22,7 +22,7 @@ var _ statedb.Keeper = &Keeper{} // GetAccount: Ethereum account getter for a [statedb.Account]. // Implements the `statedb.Keeper` interface. -// Returns nil if the account does not not exist or has the wrong type. +// Returns nil if the account does not exist or has the wrong type. func (k *Keeper) GetAccount(ctx sdk.Context, addr gethcommon.Address) *statedb.Account { acct := k.GetAccountWithoutBalance(ctx, addr) if acct == nil { diff --git a/x/evm/legacy_tx.go b/x/evm/legacy_tx.go index e12b019ce..3ffd6c1b1 100644 --- a/x/evm/legacy_tx.go +++ b/x/evm/legacy_tx.go @@ -76,7 +76,7 @@ func (tx *LegacyTx) GetAccessList() gethcore.AccessList { return nil } -// GetData returns the a copy of the input data bytes. +// GetData returns a copy of the input data bytes. func (tx *LegacyTx) GetData() []byte { return common.CopyBytes(tx.Data) } diff --git a/x/evm/logs.go b/x/evm/logs.go index b96de5d8a..12007f591 100644 --- a/x/evm/logs.go +++ b/x/evm/logs.go @@ -98,7 +98,7 @@ func NewLogsFromEth(ethlogs []*gethcore.Log) []*Log { return logs } -// LogsToEthereum casts the Ethermint Logs to a slice of Ethereum Logs. +// LogsToEthereum casts the Proto Logs to a slice of Ethereum Logs. func LogsToEthereum(logs []*Log) []*gethcore.Log { var ethLogs []*gethcore.Log //nolint: prealloc for i := range logs { @@ -107,7 +107,7 @@ func LogsToEthereum(logs []*Log) []*gethcore.Log { return ethLogs } -// NewLogFromEth creates a new Log instance from a Ethereum type Log. +// NewLogFromEth creates a new Log instance from an Ethereum type Log. func NewLogFromEth(log *gethcore.Log) *Log { topics := make([]string, len(log.Topics)) for i, topic := range log.Topics { diff --git a/x/evm/logs_test.go b/x/evm/logs_test.go index 9d83d311c..39bbee0a3 100644 --- a/x/evm/logs_test.go +++ b/x/evm/logs_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/NibiruChain/nibiru/x/evm" - evmtest "github.com/NibiruChain/nibiru/x/evm/evmtest" + "github.com/NibiruChain/nibiru/x/evm/evmtest" "github.com/ethereum/go-ethereum/common" ) diff --git a/x/evm/msg.go b/x/evm/msg.go index 252b46d86..1a60a2cec 100644 --- a/x/evm/msg.go +++ b/x/evm/msg.go @@ -194,7 +194,7 @@ func (msg MsgEthereumTx) ValidateBasic() error { return nil } -// GetMsgs returns a single MsgEthereumTx as an sdk.Msg. +// GetMsgs returns a single MsgEthereumTx as sdk.Msg. func (msg *MsgEthereumTx) GetMsgs() []sdk.Msg { return []sdk.Msg{msg} } @@ -419,7 +419,7 @@ func EncodeTransactionLogs(res *TransactionLogs) ([]byte, error) { return proto.Marshal(res) } -// DecodeTransactionLogs decodes an protobuf-encoded byte slice into +// DecodeTransactionLogs decodes a protobuf-encoded byte slice into // TransactionLogs func DecodeTransactionLogs(data []byte) (TransactionLogs, error) { var logs TransactionLogs @@ -461,7 +461,7 @@ func BinSearch( // If this errors, there was a consensus error, and the provided message // call or tx will never be accepted, regardless of how high we set the // gas limit. - // Return the error directly, don't struggle any more. + // Return the error directly, don't struggle anymore. if err != nil { return 0, err } diff --git a/x/evm/params.go b/x/evm/params.go index a72cdce44..80989d6ff 100644 --- a/x/evm/params.go +++ b/x/evm/params.go @@ -36,27 +36,6 @@ var ( DefaultEVMChannels = []string{} ) -// NewParams creates a new Params instance -func NewParams( - evmDenom string, - allowUnprotectedTxs, - enableCreate, - enableCall bool, - extraEIPs []int64, - activePrecompiles, - evmChannels []string, -) Params { - return Params{ - EvmDenom: evmDenom, - AllowUnprotectedTxs: allowUnprotectedTxs, - EnableCreate: enableCreate, - EnableCall: enableCall, - ExtraEIPs: extraEIPs, - ActivePrecompiles: activePrecompiles, - EVMChannels: evmChannels, - } -} - // DefaultParams returns default evm parameters // ExtraEIPs is empty to prevent overriding the latest hard fork instruction set // ActivePrecompiles is empty to prevent overriding the default precompiles diff --git a/x/evm/precompile/funtoken.go b/x/evm/precompile/funtoken.go index e73eaabe0..361b38881 100644 --- a/x/evm/precompile/funtoken.go +++ b/x/evm/precompile/funtoken.go @@ -54,7 +54,7 @@ func (p precompileFunToken) Run( defer func() { if err != nil { precompileType := reflect.TypeOf(p).Name() - err = fmt.Errorf("Precompile error: failed to run %s: %w", precompileType, err) + err = fmt.Errorf("precompile error: failed to run %s: %w", precompileType, err) } }() diff --git a/x/evm/precompile/funtoken_test.go b/x/evm/precompile/funtoken_test.go index 08b9f9fe7..c7765189e 100644 --- a/x/evm/precompile/funtoken_test.go +++ b/x/evm/precompile/funtoken_test.go @@ -66,7 +66,7 @@ func (s *Suite) FunToken_PrecompileExists() { deps.Ctx, fromEvmAddr, &contractAddr, commit, bytecodeForCall, ) - s.ErrorContains(err, "Precompile error") + s.ErrorContains(err, "precompile error") } func (s *Suite) FunToken_HappyPath() { diff --git a/x/evm/statedb/config.go b/x/evm/statedb/config.go index 22f056433..e618c2964 100644 --- a/x/evm/statedb/config.go +++ b/x/evm/statedb/config.go @@ -10,7 +10,7 @@ import ( "github.com/NibiruChain/nibiru/x/evm" ) -// TxConfig encapulates the readonly information of current tx for `StateDB`. +// TxConfig encapsulates the readonly information of current tx for `StateDB`. type TxConfig struct { BlockHash common.Hash // hash of current block TxHash common.Hash // hash of current tx diff --git a/x/evm/tx.go b/x/evm/tx.go index 2abff89e2..2907e06ad 100644 --- a/x/evm/tx.go +++ b/x/evm/tx.go @@ -39,7 +39,7 @@ type EvmTxArgs struct { //revive:disable-line:exported // The default value is the same as the `sdk.DefaultPowerReduction`. var DefaultPriorityReduction = sdk.DefaultPowerReduction -// GetTxPriority returns the priority of a given Ethereum tx. It relies of the +// GetTxPriority returns the priority of a given Ethereum tx. It relies on the // priority reduction global variable to calculate the tx priority given the tx // tip price: // @@ -167,7 +167,7 @@ func (tx *DynamicFeeTx) GetAccessList() gethcore.AccessList { return *tx.Accesses.ToEthAccessList() } -// GetData returns the a copy of the input data bytes. +// GetData returns a copy of the input data bytes. func (tx *DynamicFeeTx) GetData() []byte { return common.CopyBytes(tx.Data) } diff --git a/x/evm/tx_data.go b/x/evm/tx_data.go index ddf6a355e..24dde1e19 100644 --- a/x/evm/tx_data.go +++ b/x/evm/tx_data.go @@ -48,7 +48,7 @@ type TxData interface { EffectiveCost(baseFee *big.Int) *big.Int } -// NOTE: All non-protected transactions (i.e non EIP155 signed) will fail if the +// NOTE: All non-protected transactions (i.e. non EIP155 signed) will fail if the // AllowUnprotectedTxs parameter is disabled. func NewTxDataFromTx(tx *gethcore.Transaction) (TxData, error) { var txData TxData diff --git a/x/evm/vmtracer.go b/x/evm/vmtracer.go index 3eeddde9f..5438d778d 100644 --- a/x/evm/vmtracer.go +++ b/x/evm/vmtracer.go @@ -11,8 +11,6 @@ import ( "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/eth/tracers/logger" "github.com/ethereum/go-ethereum/params" - - "github.com/NibiruChain/nibiru/x/common/set" ) const ( @@ -22,10 +20,6 @@ const ( TracerMarkdown = "markdown" ) -func TracerTypes() set.Set[string] { - return set.New(TracerAccessList, TracerJSON, TracerStruct, TracerMarkdown) -} - // NewTracer creates a new Logger tracer to collect execution traces from an // EVM transaction. func NewTracer(tracer string, msg core.Message, cfg *params.ChainConfig, height int64) vm.EVMLogger { diff --git a/x/inflation/keeper/hooks.go b/x/inflation/keeper/hooks.go index 0c78c3e0d..a83d5149a 100644 --- a/x/inflation/keeper/hooks.go +++ b/x/inflation/keeper/hooks.go @@ -13,8 +13,8 @@ import ( ) // Hooks implements module-specific calls ([epochstypes.EpochHooks]) that will -// occur at the end of every epoch. Hooks is meant for use with with -// `EpochsKeeper.SetHooks`. These functions run outside of the normal body of +// occur at the end of every epoch. Hooks is meant for use with +// `EpochsKeeper.SetHooks`. These functions run outside the normal body of // transactions. type Hooks struct { K Keeper diff --git a/x/inflation/keeper/inflation.go b/x/inflation/keeper/inflation.go index 67f8ab81f..aa52897ac 100644 --- a/x/inflation/keeper/inflation.go +++ b/x/inflation/keeper/inflation.go @@ -55,7 +55,7 @@ func (k Keeper) MintCoins(ctx sdk.Context, coin sdk.Coin) error { } // AllocatePolynomialInflation allocates coins from the inflation to external -// modules according to proportions proportions: +// modules according to proportions: // // Returns: // - staking: Tokens minted for staking inflation that go to the decentralized diff --git a/x/inflation/keeper/keeper.go b/x/inflation/keeper/keeper.go index 43742b843..026fe67fc 100644 --- a/x/inflation/keeper/keeper.go +++ b/x/inflation/keeper/keeper.go @@ -13,7 +13,7 @@ import ( // Keeper of the inflation module. Keepers are module-specific "gate keepers" // responsible for encapsulating access to the key-value stores (state) of the -// network. The functions on the Keeper contain all of the business logic for +// network. The functions on the Keeper contain all the business logic for // reading and modifying state. type Keeper struct { cdc codec.BinaryCodec @@ -27,7 +27,7 @@ type Keeper struct { distrKeeper types.DistrKeeper stakingKeeper types.StakingKeeper sudoKeeper types.SudoKeeper - // feeCollectorName is the name of of x/auth module's fee collector module + // feeCollectorName is the name of x/auth module's fee collector module // account, "fee_collector", which collects transaction fees for distribution // to all stakers. // By sending staking inflation to the fee collector, the tokens are properly diff --git a/x/inflation/types/inflation_calculation_test.go b/x/inflation/types/inflation_calculation_test.go index f8a3d83f1..e0782798f 100644 --- a/x/inflation/types/inflation_calculation_test.go +++ b/x/inflation/types/inflation_calculation_test.go @@ -38,7 +38,7 @@ func TestCalculateEpochMintProvision(t *testing.T) { period := uint64(0) totalInflation := math.LegacyZeroDec() - // Only the first 8 years have inflation with default params but we run + // Only the first 8 years have inflation with default params, but we run // for 10 years expecting 0 inflation in the last 2 years. for year := uint64(0); year < 10; year++ { yearlyInflation := math.LegacyZeroDec() @@ -67,7 +67,7 @@ func TestCalculateEpochMintProvisionInflationNotEnabled(t *testing.T) { epochId := uint64(0) totalInflation := math.LegacyZeroDec() - // Only the first 8 years have inflation with default params but we run + // Only the first 8 years have inflation with default params, but we run // for 10 years expecting 0 inflation for year := uint64(0); year < 10; year++ { yearlyInflation := math.LegacyZeroDec()