all: linter (#532)

* add additional linters

* fixes

* rm action
This commit is contained in:
Federico Kunze Küllmer 2021-09-05 13:03:06 +02:00 committed by GitHub
parent c7554e96aa
commit 26c5eabb18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
61 changed files with 150 additions and 194 deletions

View File

@ -25,7 +25,7 @@ jobs:
run: go version run: go version
- name: Install tparse - name: Install tparse
run: | run: |
export GO111MODULE="on" && go get github.com/mfridman/tparse@v0.8.3 export GO111MODULE="on" && go get github.com/mfridman/tparse@latest
- uses: actions/cache@v2.1.6 - uses: actions/cache@v2.1.6
with: with:
path: ~/go/bin path: ~/go/bin

View File

@ -36,6 +36,14 @@ linters:
- varcheck - varcheck
- nolintlint - nolintlint
- asciicheck - asciicheck
# - exhaustive
- exportloopref
- gofumpt
- gomodguard
# - nestif
# - nlreturn
- noctx
- rowserrcheck
# - whitespace # - whitespace
# - wsl # - wsl
@ -63,3 +71,14 @@ linters-settings:
allow-leading-space: true allow-leading-space: true
require-explanation: false require-explanation: false
require-specific: false require-specific: false
gofumpt:
lang-version: "1.17"
gomodguard:
blocked:
versions: # List of blocked module version constraints
- https://github.com/etcd-io/etcd: # Blocked module with version constraint
version: ">= 3.4.10 || ~3.3.23" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons
reason: "CVE-2020-15114; CVE-2020-15136; CVE-2020-15115" # Reason why the version constraint exists. (Optional)
- https://github.com/dgrijalva/jwt-go: # Blocked module with version constraint
version: ">= 4.0.0-preview1" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons
reason: "CVE-2020-26160" # Reason why the version constraint exists. (Optional)

View File

@ -406,14 +406,16 @@ benchmark:
lint: lint:
golangci-lint run --out-format=tab golangci-lint run --out-format=tab
format:
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.pb.gw.go' | xargs gofumpt -d -e -extra
lint-fix: lint-fix:
golangci-lint run --fix --out-format=tab --issues-exit-code=0 golangci-lint run --fix --out-format=tab --issues-exit-code=0
.PHONY: lint lint-fix .PHONY: lint lint-fix
format: format-fix:
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' | xargs gofmt -w -s find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.pb.gw.go' | xargs gofumpt -w -s
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.pb.gw.go' | xargs misspell -w
find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' | xargs goimports -w -local github.com/tharsis/ethermint
.PHONY: format .PHONY: format
############################################################################### ###############################################################################

View File

@ -128,7 +128,6 @@ func (suite AnteTestSuite) TestAnteHandler() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
suite.ctx = suite.ctx.WithIsCheckTx(tc.reCheckTx).WithIsReCheckTx(tc.reCheckTx) suite.ctx = suite.ctx.WithIsCheckTx(tc.reCheckTx).WithIsReCheckTx(tc.reCheckTx)
// expConsumed := params.TxGasContractCreation + params.TxGas // expConsumed := params.TxGasContractCreation + params.TxGas
@ -142,8 +141,6 @@ func (suite AnteTestSuite) TestAnteHandler() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }

View File

@ -1,6 +1,7 @@
package ante package ante
import ( import (
"errors"
"math/big" "math/big"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
@ -293,7 +294,6 @@ func (egcd EthGasConsumeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simula
homestead, homestead,
istanbul, istanbul,
) )
if err != nil { if err != nil {
return ctx, stacktrace.Propagate(err, "failed to deduct transaction costs from user balance") return ctx, stacktrace.Propagate(err, "failed to deduct transaction costs from user balance")
} }
@ -403,7 +403,6 @@ func NewAccessListDecorator(evmKeeper EVMKeeper) AccessListDecorator {
// //
// The AnteHandler will only prepare the access list if Yolov3/Berlin/EIPs 2929 and 2930 are applicable at the current number. // The AnteHandler will only prepare the access list if Yolov3/Berlin/EIPs 2929 and 2930 are applicable at the current number.
func (ald AccessListDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { func (ald AccessListDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
params := ald.evmKeeper.GetParams(ctx) params := ald.evmKeeper.GetParams(ctx)
ethCfg := params.ChainConfig.EthereumConfig(ald.evmKeeper.ChainID()) ethCfg := params.ChainConfig.EthereumConfig(ald.evmKeeper.ChainID())
@ -457,7 +456,6 @@ func NewEthIncrementSenderSequenceDecorator(ak evmtypes.AccountKeeper) EthIncrem
// contract creation, the nonce will be incremented during the transaction execution and not within // contract creation, the nonce will be incremented during the transaction execution and not within
// this AnteHandler decorator. // this AnteHandler decorator.
func (issd EthIncrementSenderSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { func (issd EthIncrementSenderSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
for i, msg := range tx.GetMsgs() { for i, msg := range tx.GetMsgs() {
msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx) msgEthTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok { if !ok {
@ -523,7 +521,7 @@ func (vbd EthValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simu
err := tx.ValidateBasic() err := tx.ValidateBasic()
// ErrNoSignatures is fine with eth tx // ErrNoSignatures is fine with eth tx
if err != nil && err != sdkerrors.ErrNoSignatures { if err != nil && !errors.Is(err, sdkerrors.ErrNoSignatures) {
return ctx, stacktrace.Propagate(err, "tx basic validation failed") return ctx, stacktrace.Propagate(err, "tx basic validation failed")
} }

View File

@ -52,7 +52,6 @@ func (suite AnteTestSuite) TestEthSigVerificationDecorator() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }
@ -120,7 +119,6 @@ func (suite AnteTestSuite) TestNewEthAccountVerificationDecorator() {
suite.app.AccountKeeper.SetAccount(suite.ctx, acc) suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
suite.app.EvmKeeper.AddBalance(addr, big.NewInt(1000000)) suite.app.EvmKeeper.AddBalance(addr, big.NewInt(1000000))
}, },
true, true,
true, true,
@ -137,7 +135,6 @@ func (suite AnteTestSuite) TestNewEthAccountVerificationDecorator() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }
@ -185,7 +182,6 @@ func (suite AnteTestSuite) TestEthNonceVerificationDecorator() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
_, err := dec.AnteHandle(suite.ctx.WithIsReCheckTx(tc.reCheckTx), tc.tx, false, nextFn) _, err := dec.AnteHandle(suite.ctx.WithIsReCheckTx(tc.reCheckTx), tc.tx, false, nextFn)
@ -194,7 +190,6 @@ func (suite AnteTestSuite) TestEthNonceVerificationDecorator() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }
@ -285,7 +280,6 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
if tc.expPanic { if tc.expPanic {
@ -301,7 +295,6 @@ func (suite AnteTestSuite) TestEthGasConsumeDecorator() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }
@ -351,7 +344,6 @@ func (suite AnteTestSuite) TestCanTransferDecorator() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
_, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true), tc.tx, false, nextFn) _, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true), tc.tx, false, nextFn)
@ -412,7 +404,6 @@ func (suite AnteTestSuite) TestAccessListDecorator() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
_, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true), tc.tx, false, nextFn) _, err := dec.AnteHandle(suite.ctx.WithIsCheckTx(true), tc.tx, false, nextFn)
@ -486,7 +477,6 @@ func (suite AnteTestSuite) TestEthIncrementSenderSequenceDecorator() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
if tc.expPanic { if tc.expPanic {
@ -544,7 +534,6 @@ func (suite AnteTestSuite) TestEthSetupContextDecorator() {
} else { } else {
suite.Require().Error(err) suite.Require().Error(err)
} }
}) })
} }
} }

View File

@ -116,10 +116,6 @@ func init() {
DefaultNodeHome = filepath.Join(userHomeDir, ".ethermintd") DefaultNodeHome = filepath.Join(userHomeDir, ".ethermintd")
} }
func init() {
}
const appName = "ethermintd" const appName = "ethermintd"
var ( var (
@ -245,7 +241,6 @@ func NewEthermintApp(
appOpts servertypes.AppOptions, appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp), baseAppOptions ...func(*baseapp.BaseApp),
) *EthermintApp { ) *EthermintApp {
appCodec := encodingConfig.Marshaler appCodec := encodingConfig.Marshaler
cdc := encodingConfig.Amino cdc := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry interfaceRegistry := encodingConfig.InterfaceRegistry
@ -483,7 +478,7 @@ func NewEthermintApp(
// create the simulation manager and define the order of the modules for deterministic simulations // 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 // NOTE: this is not required apps that don't use the simulator for fuzz testing
// transactions // transactions
app.sm = module.NewSimulationManager( app.sm = module.NewSimulationManager(
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts),

View File

@ -27,7 +27,6 @@ func NewDefaultGenesisState() simapp.GenesisState {
func (app *EthermintApp) ExportAppStateAndValidators( func (app *EthermintApp) ExportAppStateAndValidators(
forZeroHeight bool, jailAllowedAddrs []string, forZeroHeight bool, jailAllowedAddrs []string,
) (servertypes.ExportedApp, error) { ) (servertypes.ExportedApp, error) {
// Creates context with current height and checks txs for ctx to be usable by start of next block // Creates context with current height and checks txs for ctx to be usable by start of next block
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})

View File

@ -75,7 +75,6 @@ func AddrCmd() *cobra.Command {
$ %s debug addr 0xA588C66983a81e800Db4dF74564F09f91c026351`, version.AppName, version.AppName), $ %s debug addr 0xA588C66983a81e800Db4dF74564F09f91c026351`, version.AppName, version.AppName),
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
addrString := args[0] addrString := args[0]
cfg := sdk.GetConfig() cfg := sdk.GetConfig()

File diff suppressed because one or more lines are too long

View File

@ -289,7 +289,7 @@ func RunAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf
return printCreate(cmd, info, showMnemonic, mnemonic, outputFormat) return printCreate(cmd, info, showMnemonic, mnemonic, outputFormat)
} }
func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic string, outputFormat string) error { func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic, outputFormat string) error {
switch outputFormat { switch outputFormat {
case OutputFormatText: case OutputFormatText:
cmd.PrintErrln() cmd.PrintErrln()

View File

@ -54,7 +54,7 @@ var (
flagIPAddrs = "ip-addresses" flagIPAddrs = "ip-addresses"
) )
const nodeDirPerm = 0755 const nodeDirPerm = 0o755
// TestnetCmd initializes all files for tendermint testnet and application // TestnetCmd initializes all files for tendermint testnet and application
func TestnetCmd( func TestnetCmd(
@ -128,7 +128,6 @@ func InitTestnet(
ipAddresses []string, ipAddresses []string,
numValidators int, numValidators int,
) error { ) error {
if chainID == "" { if chainID == "" {
chainID = fmt.Sprintf("ethermint_%d-1", tmrand.Int63n(9999999999999)+1) chainID = fmt.Sprintf("ethermint_%d-1", tmrand.Int63n(9999999999999)+1)
} }
@ -258,7 +257,6 @@ func InitTestnet(
stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()),
sdk.OneInt(), sdk.OneInt(),
) )
if err != nil { if err != nil {
return err return err
} }
@ -319,7 +317,6 @@ func initGenFiles(
genFiles []string, genFiles []string,
numValidators int, numValidators int,
) error { ) error {
appGenState := mbm.DefaultGenesis(clientCtx.Codec) appGenState := mbm.DefaultGenesis(clientCtx.Codec)
// set the accounts in the genesis state // set the accounts in the genesis state
@ -396,7 +393,6 @@ func collectGenFiles(
nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int, nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int,
outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator,
) error { ) error {
var appState json.RawMessage var appState json.RawMessage
genTime := tmtime.Now() genTime := tmtime.Now()
@ -461,16 +457,16 @@ func calculateIP(ip string, i int) (string, error) {
return ipv4.String(), nil return ipv4.String(), nil
} }
func writeFile(name string, dir string, contents []byte) error { func writeFile(name, dir string, contents []byte) error {
writePath := filepath.Join(dir) writePath := filepath.Join(dir)
file := filepath.Join(writePath, name) file := filepath.Join(writePath, name)
err := tmos.EnsureDir(writePath, 0755) err := tmos.EnsureDir(writePath, 0o755)
if err != nil { if err != nil {
return err return err
} }
err = tmos.WriteFile(file, contents, 0644) err = tmos.WriteFile(file, contents, 0o644)
if err != nil { if err != nil {
return err return err
} }

View File

@ -16,13 +16,11 @@ func init() {
infoCmd.Flags().Bool(flagLong, false, "Print full information") infoCmd.Flags().Bool(flagLong, false, "Print full information")
} }
var ( var infoCmd = &cobra.Command{
infoCmd = &cobra.Command{ Use: "info",
Use: "info", Short: "Print version info",
Short: "Print version info", RunE: func(_ *cobra.Command, _ []string) error {
RunE: func(_ *cobra.Command, _ []string) error { fmt.Println(version.Version())
fmt.Println(version.Version()) return nil
return nil },
}, }
}
)

View File

@ -183,7 +183,6 @@ type appCreator struct {
// newApp is an appCreator // newApp is an appCreator
func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { func (a appCreator) newApp(logger tmlog.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
var cache sdk.MultiStorePersistentCache var cache sdk.MultiStorePersistentCache
if cast.ToBool(appOpts.Get(sdkserver.FlagInterBlockCache)) { if cast.ToBool(appOpts.Get(sdkserver.FlagInterBlockCache)) {
@ -238,7 +237,6 @@ func (a appCreator) appExport(
logger tmlog.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, logger tmlog.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string,
appOpts servertypes.AppOptions, appOpts servertypes.AppOptions,
) (servertypes.ExportedApp, error) { ) (servertypes.ExportedApp, error) {
var ethermintApp *app.EthermintApp var ethermintApp *app.EthermintApp
homePath, ok := appOpts.Get(flags.FlagHome).(string) homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" { if !ok || homePath == "" {

View File

@ -59,7 +59,8 @@ ignore:
- "*.md" - "*.md"
- "cmd" - "cmd"
- "**/*.pb.go" - "**/*.pb.go"
- "**/*.pb.gw.go"
- "types/*.pb.go" - "types/*.pb.go"
- "x/**/*.pb.gw.go"
- "tests/*" - "tests/*"
- "x/**/*.pb.go"
- "scripts/" - "scripts/"

View File

@ -194,7 +194,7 @@ func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error {
// prior to verification. // prior to verification.
// //
// CONTRACT: The signature should be in [R || S] format. // CONTRACT: The signature should be in [R || S] format.
func (pubKey PubKey) VerifySignature(msg []byte, sig []byte) bool { func (pubKey PubKey) VerifySignature(msg, sig []byte) bool {
if len(sig) == crypto.SignatureLength { if len(sig) == crypto.SignatureLength {
// remove recovery ID (V) if contained in the signature // remove recovery ID (V) if contained in the signature
sig = sig[:len(sig)-1] sig = sig[:len(sig)-1]

View File

@ -38,7 +38,6 @@ func EthSecp256k1Option() keyring.Option {
options.SupportedAlgos = SupportedAlgorithms options.SupportedAlgos = SupportedAlgorithms
options.SupportedAlgosLedger = SupportedAlgorithmsLedger options.SupportedAlgosLedger = SupportedAlgorithmsLedger
} }
} }
var ( var (
@ -48,8 +47,7 @@ var (
EthSecp256k1 = ethSecp256k1Algo{} EthSecp256k1 = ethSecp256k1Algo{}
) )
type ethSecp256k1Algo struct { type ethSecp256k1Algo struct{}
}
// Name returns eth_secp256k1 // Name returns eth_secp256k1
func (s ethSecp256k1Algo) Name() hd.PubKeyType { func (s ethSecp256k1Algo) Name() hd.PubKeyType {
@ -58,7 +56,7 @@ func (s ethSecp256k1Algo) Name() hd.PubKeyType {
// Derive derives and returns the eth_secp256k1 private key for the given mnemonic and HD path. // Derive derives and returns the eth_secp256k1 private key for the given mnemonic and HD path.
func (s ethSecp256k1Algo) Derive() hd.DeriveFn { func (s ethSecp256k1Algo) Derive() hd.DeriveFn {
return func(mnemonic string, bip39Passphrase, path string) ([]byte, error) { return func(mnemonic, bip39Passphrase, path string) ([]byte, error) {
hdpath, err := accounts.ParseDerivationPath(path) hdpath, err := accounts.ParseDerivationPath(path)
if err != nil { if err != nil {
return nil, err return nil, err
@ -97,7 +95,7 @@ func (s ethSecp256k1Algo) Derive() hd.DeriveFn {
// Generate generates a eth_secp256k1 private key from the given bytes. // Generate generates a eth_secp256k1 private key from the given bytes.
func (s ethSecp256k1Algo) Generate() hd.GenerateFn { func (s ethSecp256k1Algo) Generate() hd.GenerateFn {
return func(bz []byte) cryptotypes.PrivKey { return func(bz []byte) cryptotypes.PrivKey {
var bzArr = make([]byte, ethsecp256k1.PrivKeySize) bzArr := make([]byte, ethsecp256k1.PrivKeySize)
copy(bzArr, bz) copy(bzArr, bz)
return &ethsecp256k1.PrivKey{Key: bzArr} return &ethsecp256k1.PrivKey{Key: bzArr}

View File

@ -182,7 +182,6 @@ func (e *EVMBackend) EthBlockFromTendermint(
block *tmtypes.Block, block *tmtypes.Block,
fullTx bool, fullTx bool,
) (map[string]interface{}, error) { ) (map[string]interface{}, error) {
gasUsed := uint64(0) gasUsed := uint64(0)
ethRPCTxs := []interface{}{} ethRPCTxs := []interface{}{}
@ -388,7 +387,7 @@ func (e *EVMBackend) GetLogs(blockHash common.Hash) ([][]*ethtypes.Log, error) {
return nil, err return nil, err
} }
var blockLogs = [][]*ethtypes.Log{} blockLogs := [][]*ethtypes.Log{}
for _, txLog := range res.TxLogs { for _, txLog := range res.TxLogs {
blockLogs = append(blockLogs, txLog.EthLogs()) blockLogs = append(blockLogs, txLog.EthLogs())
} }

View File

@ -18,7 +18,6 @@ import (
// setTxDefaults populates tx message with default values in case they are not // setTxDefaults populates tx message with default values in case they are not
// provided on the args // provided on the args
func (e *EVMBackend) setTxDefaults(args types.SendTxArgs) (types.SendTxArgs, error) { func (e *EVMBackend) setTxDefaults(args types.SendTxArgs) (types.SendTxArgs, error) {
if args.GasPrice == nil { if args.GasPrice == nil {
// TODO: Suggest a gas price based on the previous included txs // TODO: Suggest a gas price based on the previous included txs
args.GasPrice = (*hexutil.Big)(new(big.Int).SetUint64(e.RPCGasCap())) args.GasPrice = (*hexutil.Big)(new(big.Int).SetUint64(e.RPCGasCap()))

View File

@ -63,14 +63,14 @@ func NewAPI(
// and returns them as a JSON object. // and returns them as a JSON object.
func (a *API) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfig) (interface{}, error) { func (a *API) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfig) (interface{}, error) {
a.logger.Debug("debug_traceTransaction", "hash", hash) a.logger.Debug("debug_traceTransaction", "hash", hash)
//Get transaction by hash // Get transaction by hash
transaction, err := a.backend.GetTxByEthHash(hash) transaction, err := a.backend.GetTxByEthHash(hash)
if err != nil { if err != nil {
a.logger.Debug("tx not found", "hash", hash) a.logger.Debug("tx not found", "hash", hash)
return nil, err return nil, err
} }
//check if block number is 0 // check if block number is 0
if transaction.Height == 0 { if transaction.Height == 0 {
return nil, errors.New("genesis is not traceable") return nil, errors.New("genesis is not traceable")
} }
@ -97,13 +97,12 @@ func (a *API) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfig) (
} }
traceResult, err := a.queryClient.TraceTx(rpctypes.ContextWithHeight(transaction.Height), &traceTxRequest) traceResult, err := a.queryClient.TraceTx(rpctypes.ContextWithHeight(transaction.Height), &traceTxRequest)
if err != nil { if err != nil {
return nil, err return nil, err
} }
//Response format is unknown due to custom tracer config param // Response format is unknown due to custom tracer config param
//More information can be found here https://geth.ethereum.org/docs/dapp/tracing-filtered // More information can be found here https://geth.ethereum.org/docs/dapp/tracing-filtered
var decodedResult interface{} var decodedResult interface{}
err = json.Unmarshal(traceResult.Data, &decodedResult) err = json.Unmarshal(traceResult.Data, &decodedResult)
if err != nil { if err != nil {

View File

@ -14,7 +14,8 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//+build go1.5 //go:build go1.5
// +build go1.5
package debug package debug

View File

@ -14,7 +14,8 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//+build !go1.5 //go:build !go1.5
// +build !go1.5
// no-op implementation of tracing methods for Go < 1.5. // no-op implementation of tracing methods for Go < 1.5.

View File

@ -69,7 +69,6 @@ func NewPublicAPI(
clientCtx.Input, clientCtx.Input,
hd.EthSecp256k1Option(), hd.EthSecp256k1Option(),
) )
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -195,7 +194,7 @@ func (e *PublicAPI) BlockNumber() (hexutil.Uint64, error) {
} }
// GetBalance returns the provided account's balance up to the provided block number. // GetBalance returns the provided account's balance up to the provided block number.
func (e *PublicAPI) GetBalance(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Big, error) { // nolint: interfacer func (e *PublicAPI) GetBalance(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (*hexutil.Big, error) {
e.logger.Debug("eth_getBalance", "address", address.String(), "block number or hash", blockNrOrHash) e.logger.Debug("eth_getBalance", "address", address.String(), "block number or hash", blockNrOrHash)
blockNum, err := e.getBlockNumber(blockNrOrHash) blockNum, err := e.getBlockNumber(blockNrOrHash)
@ -221,7 +220,7 @@ func (e *PublicAPI) GetBalance(address common.Address, blockNrOrHash rpctypes.Bl
} }
// GetStorageAt returns the contract storage at the given address, block number, and key. // GetStorageAt returns the contract storage at the given address, block number, and key.
func (e *PublicAPI) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) { // nolint: interfacer func (e *PublicAPI) GetStorageAt(address common.Address, key string, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) {
e.logger.Debug("eth_getStorageAt", "address", address.Hex(), "key", key, "block number or hash", blockNrOrHash) e.logger.Debug("eth_getStorageAt", "address", address.Hex(), "key", key, "block number or hash", blockNrOrHash)
blockNum, err := e.getBlockNumber(blockNrOrHash) blockNum, err := e.getBlockNumber(blockNrOrHash)
@ -301,7 +300,7 @@ func (e *PublicAPI) GetUncleCountByBlockNumber(blockNum rpctypes.BlockNumber) he
} }
// GetCode returns the contract code at the given address and block number. // GetCode returns the contract code at the given address and block number.
func (e *PublicAPI) GetCode(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) { // nolint: interfacer func (e *PublicAPI) GetCode(address common.Address, blockNrOrHash rpctypes.BlockNumberOrHash) (hexutil.Bytes, error) {
e.logger.Debug("eth_getCode", "address", address.Hex(), "block number or hash", blockNrOrHash) e.logger.Debug("eth_getCode", "address", address.Hex(), "block number or hash", blockNrOrHash)
blockNum, err := e.getBlockNumber(blockNrOrHash) blockNum, err := e.getBlockNumber(blockNrOrHash)
@ -733,7 +732,7 @@ func (e *PublicAPI) GetUncleByBlockHashAndIndex(hash common.Hash, idx hexutil.Ui
} }
// GetUncleByBlockNumberAndIndex returns the uncle identified by number and index. Always returns nil. // GetUncleByBlockNumberAndIndex returns the uncle identified by number and index. Always returns nil.
func (e *PublicAPI) GetUncleByBlockNumberAndIndex(number hexutil.Uint, idx hexutil.Uint) map[string]interface{} { func (e *PublicAPI) GetUncleByBlockNumberAndIndex(number, idx hexutil.Uint) map[string]interface{} {
return nil return nil
} }

View File

@ -110,7 +110,7 @@ func (api *PrivateAccountAPI) ListAccounts() ([]common.Address, error) {
// LockAccount will lock the account associated with the given address when it's unlocked. // LockAccount will lock the account associated with the given address when it's unlocked.
// It removes the key corresponding to the given address from the API's local keys. // It removes the key corresponding to the given address from the API's local keys.
func (api *PrivateAccountAPI) LockAccount(address common.Address) bool { // nolint: interfacer func (api *PrivateAccountAPI) LockAccount(address common.Address) bool {
api.logger.Debug("personal_lockAccount", "address", address.String()) api.logger.Debug("personal_lockAccount", "address", address.String())
api.logger.Info("personal_lockAccount not supported") api.logger.Info("personal_lockAccount not supported")
// TODO: Not supported. See underlying issue https://github.com/99designs/keyring/issues/85 // TODO: Not supported. See underlying issue https://github.com/99designs/keyring/issues/85
@ -141,7 +141,7 @@ func (api *PrivateAccountAPI) NewAccount(password string) (common.Address, error
// UnlockAccount will unlock the account associated with the given address with // UnlockAccount will unlock the account associated with the given address with
// the given password for duration seconds. If duration is nil it will use a // the given password for duration seconds. If duration is nil it will use a
// default of 300 seconds. It returns an indication if the account was unlocked. // default of 300 seconds. It returns an indication if the account was unlocked.
func (api *PrivateAccountAPI) UnlockAccount(_ context.Context, addr common.Address, _ string, _ *uint64) (bool, error) { // nolint: interfacer func (api *PrivateAccountAPI) UnlockAccount(_ context.Context, addr common.Address, _ string, _ *uint64) (bool, error) {
api.logger.Debug("personal_unlockAccount", "address", addr.String()) api.logger.Debug("personal_unlockAccount", "address", addr.String())
// TODO: Not supported. See underlying issue https://github.com/99designs/keyring/issues/85 // TODO: Not supported. See underlying issue https://github.com/99designs/keyring/issues/85
return false, nil return false, nil

View File

@ -3,6 +3,7 @@ package types
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math" "math"
"math/big" "math/big"
@ -73,7 +74,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
} }
blckNum, err := hexutil.DecodeUint64(input) blckNum, err := hexutil.DecodeUint64(input)
if err == hexutil.ErrMissingPrefix { if errors.Is(err, hexutil.ErrMissingPrefix) {
blckNum = cast.ToUint64(input) blckNum = cast.ToUint64(input)
} else if err != nil { } else if err != nil {
return err return err

View File

@ -2,9 +2,10 @@ package types
import ( import (
"fmt" "fmt"
"testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"testing"
) )
func TestUnmarshalBlockNumberOrHash(t *testing.T) { func TestUnmarshalBlockNumberOrHash(t *testing.T) {
@ -98,5 +99,4 @@ func TestUnmarshalBlockNumberOrHash(t *testing.T) {
require.Error(t, err) require.Error(t, err)
} }
} }
} }

View File

@ -22,7 +22,7 @@ type QueryClient struct {
} }
// NewQueryClient creates a new gRPC query client // NewQueryClient creates a new gRPC query client
func NewQueryClient(clientCtx client.Context) *QueryClient { // nolint: interfacer func NewQueryClient(clientCtx client.Context) *QueryClient {
return &QueryClient{ return &QueryClient{
ServiceClient: tx.NewServiceClient(clientCtx), ServiceClient: tx.NewServiceClient(clientCtx),
QueryClient: evmtypes.NewQueryClient(clientCtx), QueryClient: evmtypes.NewQueryClient(clientCtx),

View File

@ -35,7 +35,7 @@ func RawTxToEthTx(clientCtx client.Context, txBz tmtypes.Tx) (*evmtypes.MsgEther
// NewTransaction returns a transaction that will serialize to the RPC // NewTransaction returns a transaction that will serialize to the RPC
// representation, with the given location metadata set (if available). // representation, with the given location metadata set (if available).
func NewTransaction(tx *ethtypes.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction { func NewTransaction(tx *ethtypes.Transaction, blockHash common.Hash, blockNumber, index uint64) *RPCTransaction {
// Determine the signer. For replay-protected transactions, use the most permissive // Determine the signer. For replay-protected transactions, use the most permissive
// signer, because we assume that signers are backwards-compatible with old // signer, because we assume that signers are backwards-compatible with old
// transactions. For non-protected transactions, the homestead signer signer is used // transactions. For non-protected transactions, the homestead signer signer is used
@ -242,7 +242,6 @@ func NewTransactionFromData(
txHash, blockHash common.Hash, txHash, blockHash common.Hash,
blockNumber, index uint64, blockNumber, index uint64,
) (*RPCTransaction, error) { ) (*RPCTransaction, error) {
if txHash == (common.Hash{}) { if txHash == (common.Hash{}) {
txHash = ethtypes.EmptyRootHash txHash = ethtypes.EmptyRootHash
} }

View File

@ -2,6 +2,7 @@ package rpc
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@ -67,7 +68,7 @@ type websocketsServer struct {
} }
func NewWebsocketsServer(logger log.Logger, tmWSClient *rpcclient.WSClient, rpcAddr, wsAddr string) WebsocketsServer { func NewWebsocketsServer(logger log.Logger, tmWSClient *rpcclient.WSClient, rpcAddr, wsAddr string) WebsocketsServer {
logger = logger.With("module", "websocket-server") logger = logger.With("api", "websocket-server")
return &websocketsServer{ return &websocketsServer{
rpcAddr: rpcAddr, rpcAddr: rpcAddr,
wsAddr: wsAddr, wsAddr: wsAddr,
@ -93,7 +94,7 @@ func (s *websocketsServer) Start() {
} }
func (s *websocketsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *websocketsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var upgrader = websocket.Upgrader{ upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
return true return true
}, },
@ -235,7 +236,7 @@ func (s *websocketsServer) readLoop(wsConn *wsConn) {
// tcpGetAndSendResponse connects to the rest-server over tcp, posts a JSON-RPC request, and sends the response // tcpGetAndSendResponse connects to the rest-server over tcp, posts a JSON-RPC request, and sends the response
// to the client over websockets // to the client over websockets
func (s *websocketsServer) tcpGetAndSendResponse(wsConn *wsConn, mb []byte) error { func (s *websocketsServer) tcpGetAndSendResponse(wsConn *wsConn, mb []byte) error {
req, err := http.NewRequest("POST", "http://"+s.rpcAddr, bytes.NewBuffer(mb)) req, err := http.NewRequestWithContext(context.Background(), "POST", "http://"+s.rpcAddr, bytes.NewBuffer(mb))
if err != nil { if err != nil {
return errors.Wrap(err, "Could not build request") return errors.Wrap(err, "Could not build request")
} }
@ -329,8 +330,8 @@ func (api *pubSubAPI) unsubscribe(id rpc.ID) bool {
} }
func (api *pubSubAPI) subscribeNewHeads(wsConn *wsConn) (rpc.ID, error) { func (api *pubSubAPI) subscribeNewHeads(wsConn *wsConn) (rpc.ID, error) {
var query = "subscribeNewHeads" query := "subscribeNewHeads"
var subID = rpc.NewID() subID := rpc.NewID()
sub, _, err := api.events.SubscribeNewHeads() sub, _, err := api.events.SubscribeNewHeads()
if err != nil { if err != nil {
@ -542,8 +543,8 @@ func (api *pubSubAPI) subscribeLogs(wsConn *wsConn, extra interface{}) (rpc.ID,
return rpc.ID(""), err return rpc.ID(""), err
} }
var query = "subscribeLogs" + string(critBz) query := "subscribeLogs" + string(critBz)
var subID = rpc.NewID() subID := rpc.NewID()
sub, _, err := api.events.SubscribeLogs(crit) sub, _, err := api.events.SubscribeLogs(crit)
if err != nil { if err != nil {
@ -637,8 +638,8 @@ func (api *pubSubAPI) subscribeLogs(wsConn *wsConn, extra interface{}) (rpc.ID,
} }
func (api *pubSubAPI) subscribePendingTransactions(wsConn *wsConn) (rpc.ID, error) { func (api *pubSubAPI) subscribePendingTransactions(wsConn *wsConn) (rpc.ID, error) {
var query = "subscribePendingTransactions" query := "subscribePendingTransactions"
var subID = rpc.NewID() subID := rpc.NewID()
sub, _, err := api.events.SubscribePendingTxs() sub, _, err := api.events.SubscribePendingTxs()
if err != nil { if err != nil {

View File

@ -29,9 +29,7 @@ const (
DefaultGasCap uint64 = 25000000 DefaultGasCap uint64 = 25000000
) )
var ( var evmTracers = []string{DefaultEVMTracer, "markdown", "struct", "access_list"}
evmTracers = []string{DefaultEVMTracer, "markdown", "struct", "access_list"}
)
// GetDefaultAPINamespaces returns the default list of JSON-RPC namespaces that should be enabled // GetDefaultAPINamespaces returns the default list of JSON-RPC namespaces that should be enabled
func GetDefaultAPINamespaces() []string { func GetDefaultAPINamespaces() []string {

View File

@ -18,7 +18,7 @@ import (
) )
// StartJSONRPC starts the JSON-RPC server // StartJSONRPC starts the JSON-RPC server
func StartJSONRPC(ctx *server.Context, clientCtx client.Context, tmRPCAddr string, tmEndpoint string, config config.Config) (*http.Server, chan struct{}, error) { func StartJSONRPC(ctx *server.Context, clientCtx client.Context, tmRPCAddr, tmEndpoint string, config config.Config) (*http.Server, chan struct{}, error) {
tmWsClient := ConnectTmWS(tmRPCAddr, tmEndpoint, ctx.Logger) tmWsClient := ConnectTmWS(tmRPCAddr, tmEndpoint, ctx.Logger)
rpcServer := ethrpc.NewServer() rpcServer := ethrpc.NewServer()

View File

@ -444,6 +444,6 @@ func openTraceWriter(traceWriterFile string) (w io.Writer, err error) {
return os.OpenFile( return os.OpenFile(
traceWriterFile, traceWriterFile,
os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.O_WRONLY|os.O_APPEND|os.O_CREATE,
0666, 0o666,
) )
} }

View File

@ -104,7 +104,7 @@ package importer
// }() // }()
// } // }
// // nolint: interfacer //
// func createAndTestGenesis(t *testing.T, cms sdk.CommitMultiStore, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper, evmKeeper *evmkeeper.Keeper) { // func createAndTestGenesis(t *testing.T, cms sdk.CommitMultiStore, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper, evmKeeper *evmkeeper.Keeper) {
// genBlock := ethcore.DefaultGenesisBlock() // genBlock := ethcore.DefaultGenesisBlock()
// ms := cms.CacheMultiStore() // ms := cms.CacheMultiStore()

View File

@ -581,7 +581,6 @@ func TestEth_GetTransactionReceipt_ContractDeployment(t *testing.T) {
require.NotEqual(t, common.Address{}.String(), receipt["contractAddress"].(string)) require.NotEqual(t, common.Address{}.String(), receipt["contractAddress"].(string))
require.NotNil(t, receipt["logs"]) require.NotNil(t, receipt["logs"])
} }
func getTransactionReceipt(t *testing.T, hash hexutil.Bytes) map[string]interface{} { func getTransactionReceipt(t *testing.T, hash hexutil.Bytes) map[string]interface{} {

View File

@ -2,6 +2,7 @@ package rpc
import ( import (
"bytes" "bytes"
"context"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
@ -35,9 +36,7 @@ type Response struct {
Result json.RawMessage `json:"result,omitempty"` Result json.RawMessage `json:"result,omitempty"`
} }
var ( var HOST = os.Getenv("HOST")
HOST = os.Getenv("HOST")
)
func GetAddress() ([]byte, error) { func GetAddress() ([]byte, error) {
rpcRes, err := CallWithError("eth_accounts", []string{}) rpcRes, err := CallWithError("eth_accounts", []string{})
@ -69,12 +68,11 @@ func Call(t *testing.T, method string, params interface{}) *Response {
var rpcRes *Response var rpcRes *Response
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
/* #nosec */
if HOST == "" { if HOST == "" {
HOST = "http://localhost:8545" HOST = "http://localhost:8545"
} }
res, err := http.Post(HOST, "application/json", bytes.NewBuffer(req)) // nolint:gosec res, err := http.NewRequestWithContext(context.Background(), "POST", HOST, bytes.NewBuffer(req))
require.NoError(t, err) require.NoError(t, err)
decoder := json.NewDecoder(res.Body) decoder := json.NewDecoder(res.Body)
@ -97,12 +95,11 @@ func CallWithError(method string, params interface{}) (*Response, error) {
var rpcRes *Response var rpcRes *Response
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
/* #nosec */
if HOST == "" { if HOST == "" {
HOST = "http://localhost:8545" HOST = "http://localhost:8545"
} }
res, err := http.Post(HOST, "application/json", bytes.NewBuffer(req)) // nolint:gosec res, err := http.NewRequestWithContext(context.Background(), "POST", HOST, bytes.NewBuffer(req))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -273,7 +273,7 @@ func New(t *testing.T, cfg Config) *Network {
nodeDir := filepath.Join(network.BaseDir, nodeDirName, "ethermintd") nodeDir := filepath.Join(network.BaseDir, nodeDirName, "ethermintd")
gentxsDir := filepath.Join(network.BaseDir, "gentxs") gentxsDir := filepath.Join(network.BaseDir, "gentxs")
require.NoError(t, os.MkdirAll(filepath.Join(nodeDir, "config"), 0755)) require.NoError(t, os.MkdirAll(filepath.Join(nodeDir, "config"), 0o755))
tmCfg.SetRoot(nodeDir) tmCfg.SetRoot(nodeDir)
tmCfg.Moniker = nodeDirName tmCfg.Moniker = nodeDirName

View File

@ -1,3 +1,4 @@
//go:build norace
// +build norace // +build norace
package network_test package network_test

View File

@ -218,7 +218,6 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error {
} }
func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string) error { func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string) error {
// set the accounts in the genesis state // set the accounts in the genesis state
var authGenState authtypes.GenesisState var authGenState authtypes.GenesisState
cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[authtypes.ModuleName], &authGenState) cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[authtypes.ModuleName], &authGenState)
@ -265,14 +264,14 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance
return nil return nil
} }
func writeFile(name string, dir string, contents []byte) error { func writeFile(name, dir string, contents []byte) error {
writePath := filepath.Join(dir) writePath := filepath.Join(dir)
file := filepath.Join(writePath, name) file := filepath.Join(writePath, name)
err := tmos.EnsureDir(writePath, 0755) err := tmos.EnsureDir(writePath, 0o755)
if err != nil { if err != nil {
return err return err
} }
return tmos.WriteFile(file, contents, 0644) return tmos.WriteFile(file, contents, 0o644)
} }

View File

@ -21,10 +21,8 @@ const (
BaseDenomUnit = 18 BaseDenomUnit = 18
) )
var ( // PowerReduction defines the default power reduction value for staking
// PowerReduction defines the default power reduction value for staking var PowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(BaseDenomUnit), nil))
PowerReduction = sdk.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 sdk.Int amount.
// The function will panic if the provided amount is negative. // The function will panic if the provided amount is negative.

View File

@ -17,7 +17,7 @@ import (
func InitGenesis( func InitGenesis(
ctx sdk.Context, ctx sdk.Context,
k *keeper.Keeper, k *keeper.Keeper,
accountKeeper types.AccountKeeper, // nolint: interfacer accountKeeper types.AccountKeeper,
data types.GenesisState, data types.GenesisState,
) []abci.ValidatorUpdate { ) []abci.ValidatorUpdate {
k.WithContext(ctx) k.WithContext(ctx)

View File

@ -58,7 +58,6 @@ func (suite *EvmTestSuite) SetupTest() {
suite.signer = tests.NewSigner(privKey) suite.signer = tests.NewSigner(privKey)
suite.ethSigner = ethtypes.LatestSignerForChainID(suite.chainID) suite.ethSigner = ethtypes.LatestSignerForChainID(suite.chainID)
suite.from = common.BytesToAddress(privKey.PubKey().Address().Bytes()) suite.from = common.BytesToAddress(privKey.PubKey().Address().Bytes())
} }
func TestEvmTestSuite(t *testing.T) { func TestEvmTestSuite(t *testing.T) {

View File

@ -123,7 +123,6 @@ func (k Keeper) ValidatorAccount(c context.Context, req *types.QueryValidatorAcc
} }
return &res, nil return &res, nil
} }
// Balance implements the Query/Balance gRPC method // Balance implements the Query/Balance gRPC method
@ -261,12 +260,11 @@ func (k Keeper) BlockLogs(c context.Context, req *types.QueryBlockLogsRequest) (
return false, nil return false, nil
}) })
if err != nil { if err != nil {
return nil, status.Error(codes.Internal, err.Error()) return nil, status.Error(codes.Internal, err.Error())
} }
var txsLogs = []types.TransactionLogs{} txsLogs := []types.TransactionLogs{}
for _, txHash := range mapOrder { for _, txHash := range mapOrder {
if len(logs[txHash]) > 0 { if len(logs[txHash]) > 0 {
txsLogs = append(txsLogs, types.TransactionLogs{Hash: txHash, Logs: logs[txHash]}) txsLogs = append(txsLogs, types.TransactionLogs{Hash: txHash, Logs: logs[txHash]})
@ -481,7 +479,6 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ
ethCfg := params.ChainConfig.EthereumConfig(k.eip155ChainID) ethCfg := params.ChainConfig.EthereumConfig(k.eip155ChainID)
signer := ethtypes.MakeSigner(ethCfg, big.NewInt(ctx.BlockHeight())) signer := ethtypes.MakeSigner(ethCfg, big.NewInt(ctx.BlockHeight()))
coreMessage, err := req.Msg.AsMessage(signer) coreMessage, err := req.Msg.AsMessage(signer)
if err != nil { if err != nil {
return nil, status.Error(codes.Internal, err.Error()) return nil, status.Error(codes.Internal, err.Error())
} }
@ -489,8 +486,8 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ
switch { switch {
case req.TraceConfig != nil && req.TraceConfig.Tracer != "": case req.TraceConfig != nil && req.TraceConfig.Tracer != "":
timeout := defaultTraceTimeout timeout := defaultTraceTimeout
//TODO change timeout to time.duration // TODO change timeout to time.duration
//Used string to comply with go ethereum // Used string to comply with go ethereum
if req.TraceConfig.Timeout != "" { if req.TraceConfig.Timeout != "" {
if timeout, err = time.ParseDuration(req.TraceConfig.Timeout); err != nil { if timeout, err = time.ParseDuration(req.TraceConfig.Timeout); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "timeout value: %s", err.Error()) return nil, status.Errorf(codes.InvalidArgument, "timeout value: %s", err.Error())
@ -530,7 +527,6 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ
k.SetTxIndexTransient(uint64(req.TxIndex)) k.SetTxIndexTransient(uint64(req.TxIndex))
res, err := k.ApplyMessage(evm, coreMessage, ethCfg, true) res, err := k.ApplyMessage(evm, coreMessage, ethCfg, true)
if err != nil { if err != nil {
return nil, status.Error(codes.Internal, err.Error()) return nil, status.Error(codes.Internal, err.Error())
} }
@ -538,7 +534,7 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ
// Depending on the tracer type, format and return the trace result data. // Depending on the tracer type, format and return the trace result data.
switch tracer := tracer.(type) { switch tracer := tracer.(type) {
case *vm.StructLogger: case *vm.StructLogger:
//TODO Return proper returnValue // TODO Return proper returnValue
result := types.ExecutionResult{ result := types.ExecutionResult{
Gas: res.GasUsed, Gas: res.GasUsed,
Failed: res.Failed(), Failed: res.Failed(),

View File

@ -20,7 +20,7 @@ import (
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
) )
//Not valid Ethereum address // Not valid Ethereum address
const invalidAddress = "0x0000" const invalidAddress = "0x0000"
func (suite *KeeperTestSuite) TestQueryAccount() { func (suite *KeeperTestSuite) TestQueryAccount() {
@ -101,7 +101,8 @@ func (suite *KeeperTestSuite) TestQueryCosmosAccount() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"invalid address", {
"invalid address",
func() { func() {
expAccount = &types.QueryCosmosAccountResponse{ expAccount = &types.QueryCosmosAccountResponse{
CosmosAddress: sdk.AccAddress(common.Address{}.Bytes()).String(), CosmosAddress: sdk.AccAddress(common.Address{}.Bytes()).String(),
@ -178,7 +179,8 @@ func (suite *KeeperTestSuite) TestQueryBalance() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"invalid address", {
"invalid address",
func() { func() {
expBalance = "0" expBalance = "0"
req = &types.QueryBalanceRequest{ req = &types.QueryBalanceRequest{
@ -236,7 +238,8 @@ func (suite *KeeperTestSuite) TestQueryStorage() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"invalid address", {
"invalid address",
func() { func() {
req = &types.QueryStorageRequest{ req = &types.QueryStorageRequest{
Address: invalidAddress, Address: invalidAddress,
@ -291,7 +294,8 @@ func (suite *KeeperTestSuite) TestQueryCode() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"invalid address", {
"invalid address",
func() { func() {
req = &types.QueryCodeRequest{ req = &types.QueryCodeRequest{
Address: invalidAddress, Address: invalidAddress,
@ -346,7 +350,8 @@ func (suite *KeeperTestSuite) TestQueryTxLogs() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"empty hash", {
"empty hash",
func() { func() {
req = &types.QueryTxLogsRequest{ req = &types.QueryTxLogsRequest{
Hash: common.Hash{}.String(), Hash: common.Hash{}.String(),
@ -354,7 +359,8 @@ func (suite *KeeperTestSuite) TestQueryTxLogs() {
}, },
false, false,
}, },
{"logs not found", {
"logs not found",
func() { func() {
hash := common.BytesToHash([]byte("hash")) hash := common.BytesToHash([]byte("hash"))
req = &types.QueryTxLogsRequest{ req = &types.QueryTxLogsRequest{
@ -423,7 +429,8 @@ func (suite *KeeperTestSuite) TestQueryBlockLogs() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"empty hash", {
"empty hash",
func() { func() {
req = &types.QueryBlockLogsRequest{ req = &types.QueryBlockLogsRequest{
Hash: common.Hash{}.String(), Hash: common.Hash{}.String(),
@ -431,7 +438,8 @@ func (suite *KeeperTestSuite) TestQueryBlockLogs() {
}, },
false, false,
}, },
{"logs not found", {
"logs not found",
func() { func() {
hash := common.BytesToHash([]byte("hash")) hash := common.BytesToHash([]byte("hash"))
req = &types.QueryBlockLogsRequest{ req = &types.QueryBlockLogsRequest{
@ -443,7 +451,6 @@ func (suite *KeeperTestSuite) TestQueryBlockLogs() {
{ {
"success", "success",
func() { func() {
hash := common.BytesToHash([]byte("block_hash")) hash := common.BytesToHash([]byte("block_hash"))
expLogs = []types.TransactionLogs{ expLogs = []types.TransactionLogs{
{ {
@ -533,7 +540,8 @@ func (suite *KeeperTestSuite) TestQueryBlockBloom() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"bad height", {
"bad height",
func() { func() {
req = &types.QueryBlockBloomRequest{Height: -2} req = &types.QueryBlockBloomRequest{Height: -2}
}, },
@ -550,7 +558,8 @@ func (suite *KeeperTestSuite) TestQueryBlockBloom() {
}, },
true, true,
}, },
{"bloom not found for height", {
"bloom not found for height",
func() { func() {
req = &types.QueryBlockBloomRequest{Height: 100} req = &types.QueryBlockBloomRequest{Height: 100}
bloom := ethtypes.BytesToBloom([]byte("bloom")) bloom := ethtypes.BytesToBloom([]byte("bloom"))
@ -614,7 +623,8 @@ func (suite *KeeperTestSuite) TestQueryValidatorAccount() {
malleate func() malleate func()
expPass bool expPass bool
}{ }{
{"invalid address", {
"invalid address",
func() { func() {
expAccount = &types.QueryValidatorAccountResponse{ expAccount = &types.QueryValidatorAccountResponse{
AccountAddress: sdk.AccAddress(common.Address{}.Bytes()).String(), AccountAddress: sdk.AccAddress(common.Address{}.Bytes()).String(),
@ -761,7 +771,7 @@ func (suite *KeeperTestSuite) TestEstimateGas() {
func (suite *KeeperTestSuite) TestTraceTx() { func (suite *KeeperTestSuite) TestTraceTx() {
ctx := sdk.WrapSDKContext(suite.ctx) ctx := sdk.WrapSDKContext(suite.ctx)
//TODO deploy contract that triggers internal transactions // TODO deploy contract that triggers internal transactions
var ( var (
txMsg *types.MsgEthereumTx txMsg *types.MsgEthereumTx
traceConfig *types.TraceConfig traceConfig *types.TraceConfig
@ -795,10 +805,10 @@ func (suite *KeeperTestSuite) TestTraceTx() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
suite.SetupTest() suite.SetupTest()
//Deploy contract // Deploy contract
contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt()) contractAddr := suite.DeployTestContract(suite.T(), suite.address, sdk.NewIntWithDecimal(1000, 18).BigInt())
suite.Commit() suite.Commit()
//Generate token transfer transaction // 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"), sdk.NewIntWithDecimal(1, 18).BigInt())
suite.Commit() suite.Commit()
@ -818,5 +828,4 @@ func (suite *KeeperTestSuite) TestTraceTx() {
} }
}) })
} }
} }

View File

@ -8,9 +8,7 @@ import (
"github.com/tharsis/ethermint/x/evm/types" "github.com/tharsis/ethermint/x/evm/types"
) )
var ( var _ types.EvmHooks = MultiEvmHooks{}
_ types.EvmHooks = MultiEvmHooks{}
)
// MultiEvmHooks combine multiple evm hooks, all hook functions are run in array sequence // MultiEvmHooks combine multiple evm hooks, all hook functions are run in array sequence
type MultiEvmHooks []types.EvmHooks type MultiEvmHooks []types.EvmHooks

View File

@ -66,7 +66,6 @@ func NewKeeper(
ak types.AccountKeeper, bankKeeper types.BankKeeper, sk types.StakingKeeper, ak types.AccountKeeper, bankKeeper types.BankKeeper, sk types.StakingKeeper,
tracer string, debug bool, tracer string, debug bool,
) *Keeper { ) *Keeper {
// ensure evm module account is set // ensure evm module account is set
if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { if addr := ak.GetModuleAddress(types.ModuleName); addr == nil {
panic("the EVM module account has not been set") panic("the EVM module account has not been set")
@ -241,7 +240,7 @@ func (k Keeper) GetAllTxLogs(ctx sdk.Context) []types.TransactionLogs {
defer iter.Close() defer iter.Close()
mapOrder := []string{} mapOrder := []string{}
var mapLogs = make(map[string][]*types.Log) mapLogs := make(map[string][]*types.Log)
for ; iter.Valid(); iter.Next() { for ; iter.Valid(); iter.Next() {
var txLog types.Log var txLog types.Log
k.cdc.MustUnmarshal(iter.Value(), &txLog) k.cdc.MustUnmarshal(iter.Value(), &txLog)
@ -272,7 +271,7 @@ func (k Keeper) GetTxLogs(txHash common.Hash) []*ethtypes.Log {
// We store the logs with key equal to txHash.Bytes() | sdk.Uint64ToBigEndian(uint64(log.Index)), // We store the logs with key equal to txHash.Bytes() | sdk.Uint64ToBigEndian(uint64(log.Index)),
// therefore, we set the end boundary(excluded) to txHash.Bytes() | uint64.Max -> []byte // therefore, we set the end boundary(excluded) to txHash.Bytes() | uint64.Max -> []byte
var end = txHash.Bytes() end := txHash.Bytes()
end = append(end, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}...) end = append(end, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}...)
iter := store.Iterator(txHash.Bytes(), end) iter := store.Iterator(txHash.Bytes(), end)
@ -293,7 +292,7 @@ func (k Keeper) SetLogs(txHash common.Hash, logs []*ethtypes.Log) {
store := prefix.NewStore(k.Ctx().KVStore(k.storeKey), types.KeyPrefixLogs) store := prefix.NewStore(k.Ctx().KVStore(k.storeKey), types.KeyPrefixLogs)
for _, log := range logs { for _, log := range logs {
var key = txHash.Bytes() key := txHash.Bytes()
key = append(key, sdk.Uint64ToBigEndian(uint64(log.Index))...) key = append(key, sdk.Uint64ToBigEndian(uint64(log.Index))...)
txIndexLog := types.NewLogFromEth(log) txIndexLog := types.NewLogFromEth(log)
bz := k.cdc.MustMarshal(txIndexLog) bz := k.cdc.MustMarshal(txIndexLog)
@ -305,7 +304,7 @@ func (k Keeper) SetLogs(txHash common.Hash, logs []*ethtypes.Log) {
func (k Keeper) SetLog(log *ethtypes.Log) { func (k Keeper) SetLog(log *ethtypes.Log) {
store := prefix.NewStore(k.Ctx().KVStore(k.storeKey), types.KeyPrefixLogs) store := prefix.NewStore(k.Ctx().KVStore(k.storeKey), types.KeyPrefixLogs)
var key = log.TxHash.Bytes() key := log.TxHash.Bytes()
key = append(key, sdk.Uint64ToBigEndian(uint64(log.Index))...) key = append(key, sdk.Uint64ToBigEndian(uint64(log.Index))...)
txIndexLog := types.NewLogFromEth(log) txIndexLog := types.NewLogFromEth(log)
@ -319,7 +318,7 @@ func (k Keeper) DeleteTxLogs(ctx sdk.Context, txHash common.Hash) {
// We store the logs with key equal to txHash.Bytes() | sdk.Uint64ToBigEndian(uint64(log.Index)), // We store the logs with key equal to txHash.Bytes() | sdk.Uint64ToBigEndian(uint64(log.Index)),
// therefore, we set the end boundary(excluded) to txHash.Bytes() | uint64.Max -> []byte // therefore, we set the end boundary(excluded) to txHash.Bytes() | uint64.Max -> []byte
var end = txHash.Bytes() end := txHash.Bytes()
end = append(end, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}...) end = append(end, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}...)
iter := store.Iterator(txHash.Bytes(), end) iter := store.Iterator(txHash.Bytes(), end)
@ -361,7 +360,6 @@ func (k Keeper) GetAccountStorage(ctx sdk.Context, address common.Address) (type
storage = append(storage, types.NewState(key, value)) storage = append(storage, types.NewState(key, value))
return false return false
}) })
if err != nil { if err != nil {
return types.Storage{}, err return types.Storage{}, err
} }

View File

@ -215,7 +215,7 @@ func (suite *KeeperTestSuite) DeployTestContract(t require.TestingT, owner commo
return crypto.CreateAddress(suite.address, nonce) return crypto.CreateAddress(suite.address, nonce)
} }
func (suite *KeeperTestSuite) TransferERC20Token(t require.TestingT, contractAddr common.Address, from common.Address, to common.Address, amount *big.Int) *types.MsgEthereumTx { func (suite *KeeperTestSuite) TransferERC20Token(t require.TestingT, contractAddr, from, to common.Address, amount *big.Int) *types.MsgEthereumTx {
ctx := sdk.WrapSDKContext(suite.ctx) ctx := sdk.WrapSDKContext(suite.ctx)
chainID := suite.app.EvmKeeper.ChainID() chainID := suite.app.EvmKeeper.ChainID()

View File

@ -51,7 +51,6 @@ func (suite *KeeperTestSuite) TestGetHashFn() {
"case 1.3: hash calculated from Tendermint header", "case 1.3: hash calculated from Tendermint header",
uint64(suite.ctx.BlockHeight()), uint64(suite.ctx.BlockHeight()),
func() { func() {
suite.ctx = suite.ctx.WithBlockHeader(header) suite.ctx = suite.ctx.WithBlockHeader(header)
suite.app.EvmKeeper.WithContext(suite.ctx) suite.app.EvmKeeper.WithContext(suite.ctx)
}, },

View File

@ -484,7 +484,6 @@ func (k *Keeper) Suicide(addr common.Address) bool {
// setSuicided sets a single byte to the transient store and marks the address as suicided // setSuicided sets a single byte to the transient store and marks the address as suicided
func (k Keeper) setSuicided(ctx sdk.Context, addr common.Address) { func (k Keeper) setSuicided(ctx sdk.Context, addr common.Address) {
store := prefix.NewStore(ctx.TransientStore(k.transientKey), types.KeyPrefixTransientSuicided) store := prefix.NewStore(ctx.TransientStore(k.transientKey), types.KeyPrefixTransientSuicided)
store.Set(addr.Bytes(), []byte{1}) store.Set(addr.Bytes(), []byte{1})
} }
@ -585,7 +584,7 @@ func (k *Keeper) AddressInAccessList(addr common.Address) bool {
} }
// SlotInAccessList checks if the address and the slots are registered in the transient store // SlotInAccessList checks if the address and the slots are registered in the transient store
func (k *Keeper) SlotInAccessList(addr common.Address, slot common.Hash) (addressOk bool, slotOk bool) { func (k *Keeper) SlotInAccessList(addr common.Address, slot common.Hash) (addressOk, slotOk bool) {
addressOk = k.AddressInAccessList(addr) addressOk = k.AddressInAccessList(addr)
slotOk = k.addressSlotInAccessList(addr, slot) slotOk = k.addressSlotInAccessList(addr, slot)
return addressOk, slotOk return addressOk, slotOk

View File

@ -178,7 +178,6 @@ func (suite *KeeperTestSuite) TestGetNonce() {
nonce := suite.app.EvmKeeper.GetNonce(tc.address) nonce := suite.app.EvmKeeper.GetNonce(tc.address)
suite.Require().Equal(tc.expectedNonce, nonce) suite.Require().Equal(tc.expectedNonce, nonce)
}) })
} }
} }
@ -248,7 +247,6 @@ func (suite *KeeperTestSuite) TestGetCodeHash() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
hash := suite.app.EvmKeeper.GetCodeHash(tc.address) hash := suite.app.EvmKeeper.GetCodeHash(tc.address)
@ -296,7 +294,6 @@ func (suite *KeeperTestSuite) TestSetCode() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
prev := suite.app.EvmKeeper.GetCode(tc.address) prev := suite.app.EvmKeeper.GetCode(tc.address)
suite.app.EvmKeeper.SetCode(tc.address, tc.code) suite.app.EvmKeeper.SetCode(tc.address, tc.code)
post := suite.app.EvmKeeper.GetCode(tc.address) post := suite.app.EvmKeeper.GetCode(tc.address)
@ -338,7 +335,6 @@ func (suite *KeeperTestSuite) TestRefund() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
tc.malleate() tc.malleate()
if tc.expPanic { if tc.expPanic {
@ -374,7 +370,6 @@ func (suite *KeeperTestSuite) TestState() {
for _, tc := range testCases { for _, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
suite.app.EvmKeeper.SetState(suite.address, tc.key, tc.value) suite.app.EvmKeeper.SetState(suite.address, tc.key, tc.value)
value := suite.app.EvmKeeper.GetState(suite.address, tc.key) value := suite.app.EvmKeeper.GetState(suite.address, tc.key)
suite.Require().Equal(tc.value, value) suite.Require().Equal(tc.value, value)
@ -385,9 +380,9 @@ func (suite *KeeperTestSuite) TestState() {
func (suite *KeeperTestSuite) TestCommittedState() { func (suite *KeeperTestSuite) TestCommittedState() {
suite.SetupTest() suite.SetupTest()
var key = common.BytesToHash([]byte("key")) key := common.BytesToHash([]byte("key"))
var value1 = common.BytesToHash([]byte("value1")) value1 := common.BytesToHash([]byte("value1"))
var value2 = common.BytesToHash([]byte("value2")) value2 := common.BytesToHash([]byte("value2"))
suite.app.EvmKeeper.SetState(suite.address, key, value1) suite.app.EvmKeeper.SetState(suite.address, key, value1)
@ -474,10 +469,9 @@ func (suite *KeeperTestSuite) TestEmpty() {
} }
func (suite *KeeperTestSuite) TestSnapshot() { func (suite *KeeperTestSuite) TestSnapshot() {
key := common.BytesToHash([]byte("key"))
var key = common.BytesToHash([]byte("key")) value1 := common.BytesToHash([]byte("value1"))
var value1 = common.BytesToHash([]byte("value1")) value2 := common.BytesToHash([]byte("value2"))
var value2 = common.BytesToHash([]byte("value2"))
testCases := []struct { testCases := []struct {
name string name string

View File

@ -133,7 +133,6 @@ func (suite *KeeperTestSuite) TestCheckSenderBalance() {
} else { } else {
suite.Require().Error(err, "invalid test %d passed", i) suite.Require().Error(err, "invalid test %d passed", i)
} }
}) })
} }
} }
@ -206,7 +205,6 @@ func (suite *KeeperTestSuite) TestDeductTxCostsFromUserBalance() {
} }
for i, tc := range testCases { for i, tc := range testCases {
suite.Run(tc.name, func() { suite.Run(tc.name, func() {
suite.SetupTest() suite.SetupTest()
suite.app.EvmKeeper.AddBalance(suite.address, hundredInt.BigInt()) suite.app.EvmKeeper.AddBalance(suite.address, hundredInt.BigInt())
@ -251,7 +249,6 @@ func (suite *KeeperTestSuite) TestDeductTxCostsFromUserBalance() {
suite.Require().Error(err, "invalid test %d passed", i) suite.Require().Error(err, "invalid test %d passed", i)
suite.Require().Nil(fees, "invalid test %d passed. fees value must be nil", i) suite.Require().Nil(fees, "invalid test %d passed. fees value must be nil", i)
} }
}) })
} }
} }

View File

@ -9,9 +9,7 @@ import (
proto "github.com/gogo/protobuf/proto" proto "github.com/gogo/protobuf/proto"
) )
var ( var ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
)
type ( type (
ExtensionOptionsEthereumTxI interface{} ExtensionOptionsEthereumTxI interface{}

View File

@ -14,7 +14,6 @@ type caseAny struct {
} }
func TestPackTxData(t *testing.T) { func TestPackTxData(t *testing.T) {
testCases := []struct { testCases := []struct {
name string name string
txData TxData txData TxData

View File

@ -32,9 +32,7 @@ const (
codeErrInvalidBaseFee codeErrInvalidBaseFee
) )
var ( var ErrPostTxProcessing = errors.New("failed to execute post processing")
ErrPostTxProcessing = errors.New("failed to execute post processing")
)
var ( var (
// ErrInvalidState returns an error resulting from an invalid Storage State. // ErrInvalidState returns an error resulting from an invalid Storage State.
@ -92,7 +90,7 @@ var (
// NewExecErrorWithReason unpacks the revert return bytes and returns a wrapped error // NewExecErrorWithReason unpacks the revert return bytes and returns a wrapped error
// with the return reason. // with the return reason.
func NewExecErrorWithReason(revertReason []byte) *RevertError { func NewExecErrorWithReason(revertReason []byte) *RevertError {
var result = common.CopyBytes(revertReason) result := common.CopyBytes(revertReason)
reason, errUnpack := abi.UnpackRevert(result) reason, errUnpack := abi.UnpackRevert(result)
err := errors.New("execution reverted") err := errors.New("execution reverted")
if errUnpack == nil { if errUnpack == nil {

View File

@ -1,16 +1,16 @@
package types package types
import ( import (
"testing"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/status-im/keycard-go/hexutils" "github.com/status-im/keycard-go/hexutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"testing"
) )
var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4] var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
func TestNewExecErrorWithReason(t *testing.T) { func TestNewExecErrorWithReason(t *testing.T) {
testCases := []struct { testCases := []struct {
name string name string
errorMessage string errorMessage string

View File

@ -31,7 +31,6 @@ func TestGenesisTestSuite(t *testing.T) {
} }
func (suite *GenesisTestSuite) TestValidateGenesisAccount() { func (suite *GenesisTestSuite) TestValidateGenesisAccount() {
testCases := []struct { testCases := []struct {
name string name string
genesisAccount GenesisAccount genesisAccount GenesisAccount
@ -84,7 +83,6 @@ func (suite *GenesisTestSuite) TestValidateGenesisAccount() {
} }
func (suite *GenesisTestSuite) TestValidateGenesis() { func (suite *GenesisTestSuite) TestValidateGenesis() {
testCases := []struct { testCases := []struct {
name string name string
genState *GenesisState genState *GenesisState

View File

@ -11,7 +11,7 @@ import (
) )
// NewTransactionLogs creates a new NewTransactionLogs instance. // NewTransactionLogs creates a new NewTransactionLogs instance.
func NewTransactionLogs(hash common.Hash, logs []*Log) TransactionLogs { // nolint: interfacer func NewTransactionLogs(hash common.Hash, logs []*Log) TransactionLogs {
return TransactionLogs{ return TransactionLogs{
Hash: hash.String(), Hash: hash.String(),
Logs: logs, Logs: logs,
@ -19,7 +19,7 @@ func NewTransactionLogs(hash common.Hash, logs []*Log) TransactionLogs { // noli
} }
// NewTransactionLogsFromEth creates a new NewTransactionLogs instance using []*ethtypes.Log. // NewTransactionLogsFromEth creates a new NewTransactionLogs instance using []*ethtypes.Log.
func NewTransactionLogsFromEth(hash common.Hash, ethlogs []*ethtypes.Log) TransactionLogs { // nolint: interfacer func NewTransactionLogsFromEth(hash common.Hash, ethlogs []*ethtypes.Log) TransactionLogs {
return TransactionLogs{ return TransactionLogs{
Hash: hash.String(), Hash: hash.String(),
Logs: NewLogsFromEth(ethlogs), Logs: NewLogsFromEth(ethlogs),

View File

@ -37,7 +37,6 @@ func NewTx(
gasLimit uint64, gasPrice *big.Int, input []byte, accesses *ethtypes.AccessList, gasLimit uint64, gasPrice *big.Int, input []byte, accesses *ethtypes.AccessList,
) *MsgEthereumTx { ) *MsgEthereumTx {
return newMsgEthereumTx(chainID, nonce, to, amount, gasLimit, gasPrice, input, accesses) return newMsgEthereumTx(chainID, nonce, to, amount, gasLimit, gasPrice, input, accesses)
} }
// NewTxContract returns a reference to a new Ethereum transaction // NewTxContract returns a reference to a new Ethereum transaction

View File

@ -58,7 +58,7 @@ func (s State) Validate() error {
} }
// NewState creates a new State instance // NewState creates a new State instance
func NewState(key, value common.Hash) State { // nolint: interfacer func NewState(key, value common.Hash) State {
return State{ return State{
Key: key.String(), Key: key.String(),
Value: value.String(), Value: value.String(),

View File

@ -68,11 +68,10 @@ func UnwrapEthereumMsg(tx *sdk.Tx) (*MsgEthereumTx, error) {
} }
// BinSearch execute the binary search and hone in on an executable gas limit // BinSearch execute the binary search and hone in on an executable gas limit
func BinSearch(lo uint64, hi uint64, executable func(uint64) (bool, *MsgEthereumTxResponse, error)) (uint64, error) { func BinSearch(lo, hi uint64, executable func(uint64) (bool, *MsgEthereumTxResponse, error)) (uint64, error) {
for lo+1 < hi { for lo+1 < hi {
mid := (hi + lo) / 2 mid := (hi + lo) / 2
failed, _, err := executable(mid) failed, _, err := executable(mid)
// If the error is not nil(consensus error), it means the provided message // If the error is not nil(consensus error), it means the provided message
// call or transaction will never be accepted no matter how much gas it is // call or transaction will never be accepted no matter how much gas it is
// assigned. Return the error directly, don't struggle any more. // assigned. Return the error directly, don't struggle any more.

View File

@ -14,7 +14,6 @@ func InitGenesis(
k keeper.Keeper, k keeper.Keeper,
data types.GenesisState, data types.GenesisState,
) []abci.ValidatorUpdate { ) []abci.ValidatorUpdate {
k.SetParams(ctx, data.Params) k.SetParams(ctx, data.Params)
k.SetBaseFee(ctx, data.BaseFee.BigInt()) k.SetBaseFee(ctx, data.BaseFee.BigInt())
k.SetBlockGasUsed(ctx, data.BlockGas) k.SetBlockGasUsed(ctx, data.BlockGas)

View File

@ -25,7 +25,6 @@ type Keeper struct {
func NewKeeper( func NewKeeper(
cdc codec.BinaryCodec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, cdc codec.BinaryCodec, storeKey sdk.StoreKey, paramSpace paramtypes.Subspace,
) Keeper { ) Keeper {
// set KeyTable if it has not already been set // set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() { if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())