Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: return proper error message on precompile #103

Merged
merged 1 commit into from
Nov 8, 2024
Merged

Conversation

beer-1
Copy link
Collaborator

@beer-1 beer-1 commented Nov 8, 2024

Description

Fix cosmos precompiles to return error message properly by returning vm.ErrExecutionRevert with output revert message.

Fix precompiles copied on every separate call to prevent StateDB conflict.


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Enhanced error handling with more descriptive revert messages in the Ethereum Virtual Machine (EVM).
    • Updated initialization processes for Cosmos and ERC20 precompiles to improve state management.
  • Bug Fixes

    • Adjusted error assertions in tests to ensure accurate validation of contract execution scenarios.
  • Documentation

    • Improved clarity of error messages returned during contract execution.
  • Chores

    • Streamlined dependency management to ensure compatibility and address security concerns.

@beer-1 beer-1 self-assigned this Nov 8, 2024
@beer-1 beer-1 requested a review from a team as a code owner November 8, 2024 07:09
Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request includes extensive updates to the go.mod files for both the main project and the integration tests, featuring dependency version changes and replacements, particularly for the Ethereum and Cosmos-related packages. Additionally, several modifications were made across various files in the x/evm package, including changes to contract bytecode, error handling improvements in contract execution, and adjustments to the Keeper struct and its methods. The updates enhance the EVM's configurability, streamline initialization processes, and improve error reporting mechanisms.

Changes

File Path Change Summary
go.mod Updated Go module version to go 1.22.5, modified multiple dependencies including github.com/ethereum/go-ethereum and replaced deprecated dgrijalva/jwt-go.
integration-tests/go.mod Updated github.com/ethereum/go-ethereum dependency to a new version, modified several dependencies to point to custom versions.
x/evm/contracts/counter/Counter.go Updated CounterMetaData bytecode; no changes to ABI or function signatures.
x/evm/contracts/counter/Counter.sol Changed revert message in execute_cosmos function to provide more clarity.
x/evm/keeper/context.go Introduced chainConfig variable, modified how precompiles are determined, updated method calls to be rule-dependent.
x/evm/keeper/context_test.go Enhanced error handling in tests, updated assertions for reverted execution.
x/evm/keeper/keeper.go Removed precompiles and precompileAddrs fields from Keeper struct, simplifying initialization.
x/evm/keeper/precompiles.go Replaced loadPrecompiles method with precompiles, introduced precompileAddrs method, streamlined precompile handling.
x/evm/keeper/precompiles_test.go Added new test function Test_PrecompileRevertError to validate EVM behavior on unauthorized access.
x/evm/precompiles/cosmos/contract.go Initialized erc20CosmosABI in init function, modified constructor to accept stateDB, enhanced error handling in ExtendedRun.
x/evm/precompiles/cosmos/contract_test.go Updated test functions to initialize CosmosPrecompile with stateDB.
x/evm/precompiles/erc20_registry/contract.go Initialized erc20RegistryABI in init, updated constructor to accept stateDB, changed error handling strategy.
x/evm/precompiles/erc20_registry/contract_test.go Modified test function to initialize ERC20RegistryPrecompile with stateDB.
x/evm/types/errors.go Enhanced error handling for revert reasons, introduced NewRevertReason function.
x/evm/types/expected_keeper.go Removed SetStateDB method from SetStateDB interface.

Possibly related PRs

  • feat: update slinky => connect/v2 #63: Updates to the go.mod file, specifically the dependency for github.com/ethereum/go-ethereum, indicating a direct relationship in managing dependencies.
  • fix: use snapshot to support revert #90: Introduces a new function for preparing the SDK context for EVM execution, relevant to changes in context.go that enhance context management for EVM operations.
  • bump geth to v1.14.11 #99: Updates the go.mod file to a new version of github.com/ethereum/go-ethereum, indicating a direct relationship in dependency management.
  • fix: handle upgrade empty params #101: Addresses error handling related to upgrades, aligning with changes in the upgrade.go file that improve error handling during the upgrade process.

Suggested reviewers

  • djm07073

🐰 "In the code where bunnies hop,
Dependencies updated, we won't stop.
With error messages clear and bright,
Our EVM shines, a true delight!
With each new change, we leap and bound,
In the world of code, joy is found!" 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@beer-1 beer-1 changed the title fix: revert error to return proper error message fix: return proper error message on precompile Nov 8, 2024
Copy link

codecov bot commented Nov 8, 2024

Codecov Report

Attention: Patch coverage is 63.93443% with 22 lines in your changes missing coverage. Please review.

Project coverage is 28.27%. Comparing base (883a73e) to head (5e12444).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/types/errors.go 17.64% 13 Missing and 1 partial ⚠️
x/evm/precompiles/cosmos/contract.go 76.92% 2 Missing and 1 partial ⚠️
x/evm/keeper/context.go 81.81% 1 Missing and 1 partial ⚠️
x/evm/keeper/precompiles.go 77.77% 2 Missing ⚠️
x/evm/precompiles/erc20_registry/contract.go 90.90% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #103      +/-   ##
==========================================
- Coverage   28.31%   28.27%   -0.04%     
==========================================
  Files         126      126              
  Lines       14016    14021       +5     
==========================================
- Hits         3968     3965       -3     
- Misses       9487     9494       +7     
- Partials      561      562       +1     
Files with missing lines Coverage Δ
x/evm/contracts/counter/Counter.go 0.00% <ø> (ø)
x/evm/keeper/keeper.go 71.42% <ø> (+0.20%) ⬆️
x/evm/precompiles/erc20_registry/contract.go 54.62% <90.90%> (+2.24%) ⬆️
x/evm/keeper/context.go 76.61% <81.81%> (-0.75%) ⬇️
x/evm/keeper/precompiles.go 76.92% <77.77%> (-5.43%) ⬇️
x/evm/precompiles/cosmos/contract.go 52.47% <76.92%> (+1.21%) ⬆️
x/evm/types/errors.go 15.00% <17.64%> (+15.00%) ⬆️

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (10)
x/evm/keeper/precompiles.go (2)

13-14: Consider adding parameter validation and improving documentation.

The function would benefit from:

  1. Documentation explaining the rules parameter and its impact
  2. Input validation for nil parameters
 // precompiles returns the precompiled contracts for the EVM.
+// The rules parameter determines which precompiles are active based on the current
+// chain configuration. The stateDB parameter is used to initialize stateful precompiles.
 func (k *Keeper) precompiles(rules params.Rules, stateDB types.StateDB) (vm.PrecompiledContracts, error) {
+    if stateDB == nil {
+        return nil, errors.New("stateDB cannot be nil")
+    }

42-45: Function naming and documentation improvements needed.

  1. The function name should be PrecompileAddrs to follow Go naming conventions for exported functions
  2. The documentation should explain what addresses are included in the returned slice
-// PrecompileAddrs returns the precompile addresses for the EVM.
+// PrecompileAddrs returns all active precompile addresses for the EVM based on
+// the provided rules, including both standard Ethereum precompiles and custom
+// precompiles (Cosmos and ERC20Registry).
-func (k *Keeper) precompileAddrs(rules params.Rules) []common.Address {
+func (k *Keeper) PrecompileAddrs(rules params.Rules) []common.Address {
x/evm/contracts/counter/Counter.sol (1)

46-46: LGTM! Consider adding a comment for clarity.

The more descriptive revert message improves error clarity for testing scenarios.

Consider adding a comment to document that this revert is specifically for testing error handling:

+    // Revert with a test message to verify error handling in cosmos precompiles
     revert("revert reason dummy value for test");
x/evm/precompiles/erc20_registry/contract_test.go (1)

Line range hint 75-165: Consider enhancing error handling test coverage.

While the test cases cover basic error scenarios like out-of-gas and read-only violations, consider adding test cases for:

  1. Invalid input data handling
  2. State conflicts
  3. Revert scenarios with custom error messages

This would align with the PR's objective of improving error handling in cosmos precompiles.

Would you like me to help generate additional test cases?

x/evm/keeper/precompiles_test.go (2)

222-240: Consider adding a comment explaining the test scenario.

The test setup is correct, but it would be helpful to add a comment explaining that we're intentionally using mismatched addresses to test the unauthorized access scenario.

 // call execute_cosmos with revert
+// Test scenario: Using mismatched addresses where the from_address in the message
+// doesn't match the actual caller, which should trigger an unauthorized error
 inputBz, err := parsed.Pack("execute_cosmos",

246-248: Consider adding a descriptive comment for balance verification.

The balance checks correctly verify that the state remains unchanged after a failed execution.

-// check balance
+// Verify that balances remain unchanged after the failed execution:
+// - Contract should retain its initial balance
+// - Target address should have zero balance as the transfer failed
 require.Equal(t, amount, input.BankKeeper.GetBalance(ctx, sdk.AccAddress(contractAddr.Bytes()), denom).Amount)
x/evm/precompiles/cosmos/contract.go (1)

108-114: Consider adding debug logging for errors.

To aid in debugging and monitoring, consider adding debug-level logging when converting Cosmos errors to EVM errors.

 if err != vm.ErrOutOfGas {
+    // Log the original error for debugging
+    e.stateDB.Logger().Debug("converting cosmos error to EVM error", "error", err)
     resBz = types.NewRevertReason(err)
     err = vm.ErrExecutionReverted
 }
go.mod (1)

Go version 1.22.5 should be downgraded to 1.22.1

The specified Go version 1.22.5 in go.mod appears to be a non-existent version, as Go 1.22.1 is currently the latest stable release. While the codebase does use modern Go features (like generics), it doesn't require any features specific to unreleased Go versions.

  • Update go.mod to use go 1.22.1 instead of the non-existent version 1.22.5
  • The codebase is compatible with Go 1.22.x as evidenced by the generic function usage in indexer/utils.go
🔗 Analysis chain

Line range hint 3-3: Verify Go version compatibility.

The specified Go version 1.22.5 appears to be beyond the current stable release (1.22.1 as of March 2024). This could lead to compatibility issues.


Let me gather more information about the Go version usage in the codebase.


Let me check the GitHub repository's release information to verify the Go version compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if any code uses features specific to Go 1.22.5

# Test: Search for potential usage of new Go 1.22+ features
rg -g '*.go' 'range over integer|range over func|clear\('

Length of output: 159


Script:

#!/bin/bash
# Check for go.mod files and their Go versions
fd -e mod -x cat {}

# Check for any build constraints or Go version requirements in Go files
rg -g '*.go' '^//\s*\+build|^//\s*go:build'

# Check GitHub workflow files for Go version specifications
fd -e yml -e yaml -p '\.github/workflows' -x cat {}

Length of output: 29187


Script:

#!/bin/bash
# Check repository information and releases
gh api repos/initia-labs/minievm --jq '.default_branch'
gh api repos/initia-labs/minievm/releases/latest --jq '.tag_name'

# Check if there are any Go files with version-specific syntax
rg -g '*.go' 'func\s+\w+\s*\[' # Check for type parameters (Go 1.18+)
rg -g '*.go' 'any\s*[{(]' # Check for 'any' type alias (Go 1.18+)

Length of output: 263

x/evm/contracts/counter/Counter.go (1)

Line range hint 1-1024: Consider implementing contract upgrade mechanism.

While the current implementation is solid, consider implementing a contract upgrade mechanism for future updates. This could be achieved through:

  1. Using a proxy pattern
  2. Implementing a version control system
  3. Adding proper migration handlers

This would make future updates to error handling or other features more manageable.

x/evm/precompiles/erc20_registry/contract.go (1)

20-26: Consider documenting the rationale for panic in init function

Using panic in the init function can cause the application to crash during startup if the ABI retrieval fails. Adding a comment to explain why panicking here is acceptable can improve code readability and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 883a73e and 5e12444.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • integration-tests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (15)
  • go.mod (1 hunks)
  • integration-tests/go.mod (1 hunks)
  • x/evm/contracts/counter/Counter.go (1 hunks)
  • x/evm/contracts/counter/Counter.sol (1 hunks)
  • x/evm/keeper/context.go (4 hunks)
  • x/evm/keeper/context_test.go (2 hunks)
  • x/evm/keeper/keeper.go (0 hunks)
  • x/evm/keeper/precompiles.go (2 hunks)
  • x/evm/keeper/precompiles_test.go (2 hunks)
  • x/evm/precompiles/cosmos/contract.go (4 hunks)
  • x/evm/precompiles/cosmos/contract_test.go (12 hunks)
  • x/evm/precompiles/erc20_registry/contract.go (2 hunks)
  • x/evm/precompiles/erc20_registry/contract_test.go (1 hunks)
  • x/evm/types/errors.go (2 hunks)
  • x/evm/types/expected_keeper.go (0 hunks)
💤 Files with no reviewable changes (2)
  • x/evm/keeper/keeper.go
  • x/evm/types/expected_keeper.go
🔇 Additional comments (28)
x/evm/keeper/precompiles.go (2)

4-11: LGTM! Imports are well-organized.

The imports are properly structured with external dependencies followed by internal packages.


Line range hint 13-39: LGTM! Improved error handling and precompile initialization.

The implementation properly addresses the PR objectives by:

  1. Returning proper error messages with nil contracts
  2. Fixing the issue of precompiles being copied on every call by using vm.ActivePrecompiledContracts
  3. Properly initializing precompiles with stateDB
x/evm/precompiles/erc20_registry/contract_test.go (1)

75-76: LGTM! The initialization change aligns with the PR objectives.

The modification to pass stateDB as the first argument to NewERC20RegistryPrecompile is correct and addresses the issue of precompiles being copied on every separate call. This change helps prevent conflicts with the StateDB.

x/evm/keeper/precompiles_test.go (3)

9-9: LGTM: Import additions align with PR objectives.

The new imports for sdkerrors and vm packages are necessary for proper error handling validation in the new test case.

Also applies to: 14-15


208-220: LGTM: Test setup follows established patterns.

The test setup and contract deployment follow the same pattern as other test functions, with proper error handling and validation.


242-244: LGTM: Comprehensive error validation.

The test properly validates both the EVM execution revert and the unauthorized access error, ensuring that the precompile correctly propagates both error types. This aligns with the PR's objective of improving error handling.

x/evm/precompiles/cosmos/contract.go (4)

27-36: LGTM! Performance improvement by caching ABI.

Moving the ABI initialization to init() prevents redundant parsing on each precompile instantiation. This is a good optimization that aligns with the PR's objective of fixing precompile copying issues.


80-82: LGTM! Simplified error handling.

Direct error return is appropriate here since ExtendedRun will handle the proper error wrapping and conversion to EVM errors.


108-114: Verify error message conversion behavior.

The error handling improvements look good:

  1. Proper conversion of Cosmos errors to EVM errors
  2. State reversion ensures atomicity
  3. Error message conversion using types.NewRevertReason

However, we should verify the behavior of types.NewRevertReason to ensure error messages are properly formatted for EVM clients.

#!/bin/bash
# Description: Check error message conversion implementation
# Look for NewRevertReason implementation and usage

echo "Checking NewRevertReason implementation:"
rg -A 10 "func.*NewRevertReason" --type go

echo "Checking other usages of NewRevertReason:"
rg "NewRevertReason" --type go

Line range hint 54-74: Verify StateDB lifecycle management across precompiles.

The addition of stateDB parameter to the constructor looks good and helps prevent precompile copying issues. However, we should verify that the StateDB is properly managed across all precompile instances.

✅ Verification successful

Let me gather more information about the StateDB usage and management across precompiles.


Let me do one final check to understand the complete precompile initialization flow.


StateDB management in precompiles is properly implemented

The verification shows that StateDB is correctly managed across precompiles:

  • StateDB is properly initialized in the Keeper's precompiles function and passed to each precompile constructor
  • Both ERC20Registry and Cosmos precompiles follow the same pattern for StateDB handling
  • StateDB operations (Snapshot, RevertToSnapshot, ContextOfSnapshot) are consistently used across precompiles for transaction safety
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper StateDB initialization and management across precompiles
# Look for other precompile constructors that should follow the same pattern

# Search for precompile constructors
echo "Checking precompile constructors:"
rg -A 5 "func New.*Precompile.*\(" --type go

# Search for StateDB usage in precompiles
echo "Checking StateDB usage:"
rg "stateDB.*types\.StateDB" --type go

Length of output: 1610


Script:

#!/bin/bash
# Search for all precompile struct definitions and their StateDB fields
echo "Checking precompile struct definitions:"
ast-grep --pattern 'type $_Precompile struct {
  $$$
}'

# Search for StateDB initialization in precompile constructors
echo "Checking StateDB initialization in constructors:"
ast-grep --pattern 'func New$_Precompile($$$) (*$_, error) {
  $$$
}'

# Search for any direct StateDB field access
echo "Checking StateDB field access:"
rg "\.stateDB\." --type go

Length of output: 1011


Script:

#!/bin/bash
# Check how precompiles are created and managed in the keeper
echo "Checking precompile initialization in keeper:"
rg -A 10 "func.*precompiles.*\(" --type go

# Check for any other StateDB-related operations
echo "Checking other StateDB operations:"
rg "Snapshot|RevertToSnapshot|ContextOfSnapshot" --type go

Length of output: 4459

integration-tests/go.mod (1)

274-274: LGTM! Verify the commit contains intended fixes.

The replace directive correctly points to the custom fork with the specific commit that addresses the error handling and precompile copying issues.

Let's verify the commit contains the intended fixes:

✅ Verification successful

✅ Commit changes align with the intended fixes

The commit modifies error handling in precompiled contracts to:

  • Return output and remaining gas even when errors occur (except for out-of-gas)
  • Add proper gas tracking through logger
  • Fix the specific issue where errors were causing all outputs to be discarded

This change directly addresses the error handling improvements mentioned in the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the commit contains the intended fixes for error handling and precompile copying.

# Test: Check commit message and changes
gh api repos/initia-labs/evm/commits/3d312736d7fb \
  --jq '.commit.message, .files[].filename' || \
echo "Note: Unable to verify commit. Please ensure the commit 3d312736d7fb exists in initia-labs/evm repository and contains the error handling and precompile copying fixes."

Length of output: 173


Script:

#!/bin/bash
# Let's examine the actual changes in the commit to verify the fixes
gh api repos/initia-labs/evm/commits/3d312736d7fb \
  --jq '.files[].patch' || \
echo "Unable to fetch patch details"

Length of output: 653

go.mod (2)

Line range hint 274-282: LGTM! Security-focused replacements.

Good security practices observed:

  1. Replacing deprecated dgrijalva/jwt-go with maintained golang-jwt/jwt/v4
  2. Updating gin-gonic/gin to fix GHSA-h395-qcrw-5vmq vulnerability
  3. Using a specific version of goleveldb to avoid simulation failures

291-291: LGTM! Custom EVM fork replacement.

The replacement of github.com/ethereum/go-ethereum with a custom fork aligns with the PR objectives to fix error handling in cosmos precompiles and address StateDB conflicts.

#!/bin/bash
# Description: Verify the custom EVM fork's commit hash matches the changes needed

# Test: Check if the specific commit contains relevant changes
gh api repos/initia-labs/evm/commits/3d312736d7fbf68af35df985b01536684bf6aafa \
  --jq '.commit.message' || echo "Failed to fetch commit details"
x/evm/keeper/context_test.go (2)

297-298: LGTM: Improved error assertion aligns with PR objectives

The updated error assertions properly verify both the EVM execution revert error and its accompanying reason message, which aligns with the PR's goal of returning proper error messages.


317-317: LGTM: Correct assertion for successful execution path

The NoError assertion is appropriate here as this test case verifies successful execution with valid parameters.

x/evm/precompiles/cosmos/contract_test.go (3)

67-68: LGTM: Consistent constructor changes across all test functions.

The addition of stateDB parameter to NewCosmosPrecompile constructor is consistently applied across all test functions, properly addressing the issue of precompiles being copied on every separate call.

Also applies to: 111-112, 155-156, 185-186, 215-216, 287-288, 373-374, 430-431, 470-471


279-281: LGTM: Improved error handling for unauthorized execution.

The error handling has been enhanced to:

  1. Return vm.ErrExecutionReverted for proper EVM error handling
  2. Include the original error message using types.NewRevertError

This change ensures that EVM contracts receive proper revert messages while maintaining the error context.


352-354: LGTM: Consistent error handling in ExecuteCosmosWithOptions.

The error handling changes maintain consistency with Test_ExecuteCosmos, ensuring uniform error handling behavior across different execution modes.

x/evm/contracts/counter/Counter.go (4)

35-35: LGTM: Contract bytecode update.

The updated bytecode aligns with the PR objectives to improve error handling in cosmos precompiles.


Line range hint 428-429: LGTM: Contract methods properly handle errors.

The contract methods, particularly execute_cosmos, execute_cosmos_with_options, and callback, have been properly updated to handle errors and return appropriate messages, which aligns with the PR objectives.

Also applies to: 445-446, 461-462


Line range hint 642-644: LGTM: Event handlers properly implemented.

The event handlers for callback_received, increased, and recursive_called events are well-implemented with proper type handling and error management.

Also applies to: 739-741, 836-838


Line range hint 1-1024: Verify error handling implementation across the codebase.

Let's verify that the error handling changes are consistently implemented across related files.

x/evm/precompiles/erc20_registry/contract.go (1)

34-35: Verify that all calls to NewERC20RegistryPrecompile include the new stateDB parameter

The constructor NewERC20RegistryPrecompile now requires stateDB as the first argument. Please ensure that all instances where this function is called have been updated accordingly to prevent compilation errors or unexpected behavior.

Run the following script to verify:

✅ Verification successful

Based on the search results, I can generate the final response as we have found all instances where NewERC20RegistryPrecompile is called in the codebase. The results show that all three occurrences (one definition and two calls) properly include the stateDB parameter:

All calls to NewERC20RegistryPrecompile correctly include the stateDB parameter

The function is called in two locations and both already include the stateDB parameter:

  • x/evm/precompiles/erc20_registry/contract_test.go: registry, err := precompiles.NewERC20RegistryPrecompile(stateDB, k)
  • x/evm/keeper/precompiles.go: erc20RegistryPrecompile, err := erc20registryprecompile.NewERC20RegistryPrecompile(stateDB, k.erc20StoresKeeper)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all calls to `NewERC20RegistryPrecompile` include the new `stateDB` parameter.

# Test: Search for all instances of `NewERC20RegistryPrecompile` and display the surrounding lines.
rg 'NewERC20RegistryPrecompile\(' -A 2

Length of output: 865

x/evm/keeper/context.go (5)

196-196: Pass correct parameters to vm.NewEVMWithPrecompiles

The updated code correctly passes chainConfig, vmConfig, and precompiles to vm.NewEVMWithPrecompiles. This ensures that the EVM instance is initialized with the appropriate configuration and precompiled contracts, which is essential for accurate EVM behavior.

Also applies to: 198-198


243-243: Update Prepare method with rule-based precompile addresses

In EVMStaticCallWithTracer, the evm.StateDB.Prepare method now uses k.precompileAddrs(rules) to obtain precompile addresses based on the current EVM rules. This change ensures that state preparation accurately reflects the active precompiles for the given block context.


281-281: Consistent use of rule-based precompile addresses in EVMCallWithTracer

Similarly, EVMCallWithTracer now uses k.precompileAddrs(rules) in the Prepare method. This maintains consistency across different EVM call methods and ensures that precompile addresses are correctly determined based on the current chain rules.


375-375: Use rule-based precompile addresses in EVMCreateWithTracer

The Prepare method in EVMCreateWithTracer now includes k.precompileAddrs(rules). This ensures that contract creation operations consider the appropriate precompile addresses according to the current EVM rules, enhancing correctness in contract deployment.


184-189: Confirm appropriate use of default chain configuration

The code initializes chainConfig using types.DefaultChainConfig(ctx). Ensure that this default configuration aligns with the chain's actual settings, especially if there are custom chain configurations or upgrades that might affect EVM execution.

You can run the following script to check for any custom chain configurations and where they are used:

x/evm/types/errors.go Show resolved Hide resolved
x/evm/precompiles/erc20_registry/contract.go Show resolved Hide resolved
Copy link
Contributor

@djm07073 djm07073 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants