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

test(evm): more bank extension tests and EVM ABCI integration tests to prevent regressions #2122

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Unique-Divine
Copy link
Member

@Unique-Divine Unique-Divine commented Dec 11, 2024

Purpose / Abstract

    1. It looked like there was redundant gas subtraction in EthereumTx
    1. To take a closer look at (1), I added a test that uses the raw ABCI methods instead of only using the message server directly. There's now a test that uses raw EthereumTx bytes in abci.BeginBlock -> abci.DeliverTx -> abci.EndBlock and displays proper gas consumption. → In doing this, I found out that nothing in our current test suite prevents a regression if we subtract out the consume gas step after an EthereumTx.
    1. We were using a branched context for EthereumTx > ApplyEvmMsg unnecessarily. The BaseApp already uses a temporary context and passes it in for DeliverTx, so there's not need to worry about cleanup in ApplyEvmMsg.
    1. Clarifies TODO comments in the precompiles directory
    1. Further tests have been added for the NibiruBankKeeper to verify it's not going to bring about unexpected state changes

@Unique-Divine Unique-Divine requested a review from a team as a code owner December 11, 2024 22:19
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between 9848e72 and 7f343f1.

📒 Files selected for processing (5)
  • CHANGELOG.md (1 hunks)
  • x/evm/evmtest/evmante.go (1 hunks)
  • x/evm/evmtest/tx.go (1 hunks)
  • x/evm/keeper/msg_ethereum_tx_test.go (3 hunks)
  • x/evm/keeper/msg_server.go (5 hunks)
 __________________________________________________________
< Solving problems you didn't know you were about to have. >
 ----------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

Walkthrough

The pull request introduces several updates across multiple files, primarily focusing on enhancements to the Nibiru EVM. Key changes include updates to the CHANGELOG.md for better documentation of various bug fixes and feature additions. Modifications in the codebase enhance gas management, improve error handling, and add new utility functions. Notably, the TransferWei function has been refactored into a method of a new struct for better organization. Additionally, new tests have been introduced to improve coverage, particularly for bank extension functionalities and gas consumption invariants.

Changes

File Path Change Summary
CHANGELOG.md Updated with new entries detailing bug fixes, feature additions, and improvements, including gas consumption fixes and new tests.
eth/rpc/backend/account_info.go Formatting adjustments in the GetProof method and refined error handling in GetTransactionCount.
go.mod Dependency github.com/rs/zerolog v1.32.0 removed and re-added; updates to replace directives for github.com/CosmWasm/wasmd and github.com/cosmos/cosmos-sdk.
x/common/testutil/testapp/testapp.go Added FundFeeCollector function to fund the module account for gas fees.
x/evm/evmtest/tx.go Refactored TransferWei into a method of TxTransferWei struct, enhancing parameter organization and error handling.
x/evm/evmtest/tx_test.go Updated TestTransferWei to use the new TxTransferWei struct and its Run method for improved error handling and clarity.
x/evm/keeper/bank_extension.go Introduced zeroCostGasConfig for gas management in NibiruBankKeeper methods, enhancing gas consumption consistency.
x/evm/keeper/bank_extension_test.go Added TestStateDBReadonlyInvariant to ensure no side effects during query operations; enhanced gas consumption tests.
x/evm/keeper/grpc_query_test.go Updated test case name and logic to reflect deployment of ERC20 contracts instead of transfers.
x/evm/keeper/keeper_test.go Added logging to the test suite; introduced SetupTest method for logging setup messages.
x/evm/keeper/msg_ethereum_tx_test.go Adjusted funding amounts and gas limits in test cases for Ethereum transactions.
x/evm/keeper/msg_server.go Simplified error messages in the EthereumTx method; no changes to functionality.
x/evm/keeper/statedb_test.go Refactored TestStateDBBalance to use TxTransferWei struct for transfers, enhancing clarity.
x/evm/precompile/funtoken.go Enhanced methods for ERC20 token interactions, improving error handling and response structuring.
x/evm/precompile/funtoken_test.go Updated TestHappyPath to include funding for the fee collector; maintained structure in other tests.
x/evm/precompile/wasm.go Added comment in Run method indicating future event emission implementation; no changes to logic.
x/evm/statedb/journal_test.go Enhanced error reporting in the test case for dirty journal entries, providing more context on failures.

Possibly related PRs

Suggested reviewers

  • k-yang

Poem

🐰 In the meadow, changes bloom,
With gas fixed and tests in room.
A keeper's tale, both bright and clear,
For every bug, we shed a tear.
New functions dance, like rabbits play,
In Nibiru's world, we hop and stay! 🌼

Tip

You can disable the changed files summary in the walkthrough.

Disable the reviews.changed_files_summary setting in your project's settings in CodeRabbit to disable the changed files summary in the walkthrough.


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

@@ -269,7 +271,7 @@ func (k *Keeper) ApplyEvmMsg(ctx sdk.Context,
)

defer func() {
if commit && err == nil && resp != nil && !resp.Failed() {
Copy link
Member Author

Choose a reason for hiding this comment

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

It's perfectly valid to have err == nil while the vmError is not empty. That will still result in a valid transaction.

Copy link

codecov bot commented Dec 11, 2024

Codecov Report

Attention: Patch coverage is 75.55556% with 11 lines in your changes missing coverage. Please review.

Project coverage is 64.92%. Comparing base (debaa4d) to head (7f343f1).

Files with missing lines Patch % Lines
x/evm/evmtest/tx.go 75.00% 4 Missing and 1 partial ⚠️
x/evm/keeper/msg_server.go 60.00% 4 Missing ⚠️
x/evm/evmtest/evmante.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2122      +/-   ##
==========================================
+ Coverage   64.79%   64.92%   +0.12%     
==========================================
  Files         273      273              
  Lines       21636    21656      +20     
==========================================
+ Hits        14020    14061      +41     
+ Misses       6644     6620      -24     
- Partials      972      975       +3     
Files with missing lines Coverage Δ
eth/rpc/backend/account_info.go 55.00% <100.00%> (+1.15%) ⬆️
x/evm/keeper/bank_extension.go 100.00% <100.00%> (ø)
x/evm/precompile/funtoken.go 56.96% <ø> (ø)
x/evm/precompile/wasm.go 62.29% <ø> (ø)
x/evm/evmtest/evmante.go 0.00% <0.00%> (ø)
x/evm/keeper/msg_server.go 77.10% <60.00%> (+1.10%) ⬆️
x/evm/evmtest/tx.go 55.32% <75.00%> (+1.21%) ⬆️

... and 3 files with indirect coverage changes

Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (2)
x/evm/precompile/funtoken.go (1)

208-208: Implement EVM event emissions for balance changes

You've added a TODO comment to emit EVM events for balance changes of the sender and recipient. Implementing these events will enhance transparency and allow clients to listen and react to these balance changes effectively. Would you like assistance in generating the code for these events, or should I open a new GitHub issue to track this task?

x/evm/evmtest/tx.go (1)

Line range hint 219-247: Consider consolidating error wrapping patterns.

The error handling could be more consistent. Currently, there are two different error wrapping patterns:

  1. Line 240: Using fmt.Errorf("error while transferring wei: %w", err)
  2. Line 245: Using the same pattern but in a different block

Consider consolidating the error handling into a single pattern at the return:

 func (tx TxTransferWei) Run() (evmResp *evm.MsgEthereumTxResponse, err error) {
     // ... existing code ...
     ethTxMsg, err := NewEthTxMsgFromTxData(
         deps,
         gethcore.LegacyTxType,
         innerTxData,
         deps.NewStateDB().GetNonce(ethAcc.EthAddr),
         &to,
         amountWei,
         gasLimit,
         accessList,
     )
-    if err != nil {
-        return evmResp, fmt.Errorf("error while transferring wei: %w", err)
-    }
+    if err != nil {
+        return nil, err
+    }

     evmResp, err = deps.App.EvmKeeper.EthereumTx(sdk.WrapSDKContext(deps.Ctx), ethTxMsg)
-    if err != nil {
-        err = fmt.Errorf("error while transferring wei: %w", err)
-    }
-    return evmResp, err
+    if err != nil {
+        return nil, fmt.Errorf("error while transferring wei: %w", err)
+    }
+    return evmResp, nil
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between debaa4d and 9848e72.

📒 Files selected for processing (17)
  • CHANGELOG.md (1 hunks)
  • eth/rpc/backend/account_info.go (1 hunks)
  • go.mod (1 hunks)
  • x/common/testutil/testapp/testapp.go (2 hunks)
  • x/evm/evmtest/tx.go (2 hunks)
  • x/evm/evmtest/tx_test.go (1 hunks)
  • x/evm/keeper/bank_extension.go (2 hunks)
  • x/evm/keeper/bank_extension_test.go (2 hunks)
  • x/evm/keeper/grpc_query_test.go (1 hunks)
  • x/evm/keeper/keeper_test.go (2 hunks)
  • x/evm/keeper/msg_ethereum_tx_test.go (1 hunks)
  • x/evm/keeper/msg_server.go (6 hunks)
  • x/evm/keeper/statedb_test.go (2 hunks)
  • x/evm/precompile/funtoken.go (1 hunks)
  • x/evm/precompile/funtoken_test.go (2 hunks)
  • x/evm/precompile/wasm.go (1 hunks)
  • x/evm/statedb/journal_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • x/evm/precompile/wasm.go
👮 Files not reviewed due to content moderation or server errors (3)
  • x/evm/precompile/funtoken_test.go
  • x/evm/keeper/msg_server.go
  • x/evm/keeper/grpc_query_test.go
🔇 Additional comments (14)
x/evm/keeper/keeper_test.go (1)

Line range hint 6-23: LGTM!

The addition of logging in SetupTest enhances test traceability, and the implementation of the SetupTestSuite interface ensures proper setup for each test.

x/evm/evmtest/tx_test.go (1)

80-86: Refactoring enhances code maintainability

The refactoring to use the TxTransferWei struct with a Run method improves code organization and encapsulates the transaction logic, making it more maintainable and consistent with other test implementations.

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

48-52: Refactoring improves code clarity

The change to use the TxTransferWei struct for the transfer operation enhances code clarity by encapsulating parameters and logic within a structured approach.


65-69: Verify the correctness of the expected error message

In the test case where an insufficient wei amount is transferred, the expected error message is "wei amount is too small". Please verify that this error message matches the actual error produced by the TxTransferWei implementation.

You can confirm the error message by searching the codebase:

eth/rpc/backend/account_info.go (1)

86-90: LGTM! Improved code readability.

The parameters for GetProof are now properly formatted across multiple lines, enhancing code readability while maintaining the same functionality.

x/evm/keeper/msg_ethereum_tx_test.go (1)

41-41: LGTM! Improved numeric literal readability.

The change standardizes the formatting of large numbers using underscores as thousand separators (1_000_000 instead of 1000_000), following Go's conventions for improved readability.

x/common/testutil/testapp/testapp.go (1)

187-198: LGTM! Well-structured test helper function.

The new FundFeeCollector function is:

  • Well-documented
  • Follows existing patterns for funding helper functions
  • Properly utilizes app constants for token denomination
  • Provides a convenient abstraction for a common test setup task
x/evm/keeper/bank_extension.go (2)

93-114: LGTM: Gas handling implementation ensures deterministic gas consumption.

The implementation correctly manages gas consumption by:

  1. Capturing the initial gas state
  2. Using a deferred function to restore gas state
  3. Applying zero-cost gas config for operations
  4. Properly documenting the gas meter requirements

126-134: LGTM: Zero-cost gas configuration aligns with deterministic gas usage goal.

The zeroCostGasConfig variable is properly defined with all costs set to 0, which is consistent with the goal of ensuring deterministic gas consumption during state operations.

x/evm/statedb/journal_test.go (1)

110-110: LGTM: Enhanced error reporting in test.

The change improves test debugging by including the journal state in the failure message, making it easier to diagnose test failures.

x/evm/evmtest/tx.go (1)

212-217: LGTM: Well-structured parameter encapsulation.

The TxTransferWei struct provides a clean encapsulation of transfer parameters with clear field names and types.

go.mod (1)

64-64: LGTM: zerolog dependency addition

The addition of zerolog v1.32.0 is appropriate for structured logging capabilities.

CHANGELOG.md (2)

49-49: LGTM: Test entry follows changelog format

The new entry "- #2122 - test(evm): more bank extension tests" follows the established format of:

  • Using hyphen for list items
  • Including PR link
  • Using conventional commit type prefix

Line range hint 1-48: LGTM: Well-structured changelog header

The changelog header follows best practices:

  • Clear format guidelines
  • Explicit versioning scheme (Semantic Versioning)
  • Proper section organization
  • Markdown formatting

x/evm/keeper/bank_extension_test.go Show resolved Hide resolved
@Unique-Divine Unique-Divine changed the title test(evm): more bank extension tests test(evm): more bank extension tests and EVM ABCI integration tests to prevent regressions Dec 12, 2024
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.

1 participant