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(erc20): better handling of gas consumption within erc20 contract execution #2089

Merged
merged 5 commits into from
Oct 24, 2024

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Oct 22, 2024

Notes

err here is nil and the result of errors.Wrapf returned nil causing panic nil pointer dereference in the next methods which assume that if err is nil then evmResp is not nil.

if evmResp.Failed() {
	return nil, errors.Wrapf(err, "EVM execution failed: %s", evmResp.VmError)

Tests

Added 2 malicious erc20 smart contracts: TestERC20MaliciousName.sol and TestERC20MaliciousTransfer.sol to test behaviour of funtokens created with gas intensive methods name() and transfer()

Resolves

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced new ERC20 contracts (TestERC20MaliciousName and TestERC20MaliciousTransfer) with enhanced functionalities.
    • Added support for new RPC APIs and an in-memory EventBus for event distribution in EVM context.
  • Improvements

    • Enhanced error handling and clarity in the contract call process.
    • Updated changelog format for better readability and organization.
    • Improved handling of gas consumption within ERC20 contract execution.
    • Clarified terminology in comments for consistency across the codebase.
  • Bug Fixes

    • Resolved issues related to gas consumption and transaction handling in ERC20 contracts.
    • Fixed keyring import functions and ensured proper gas cap parameters for dynamic fee transactions.
  • Tests

    • Added tests for handling malicious ERC20 contracts to ensure robust error handling and system stability.

Copy link

codecov bot commented Oct 22, 2024

Codecov Report

Attention: Patch coverage is 81.25000% with 12 lines in your changes missing coverage. Please review.

Project coverage is 63.98%. Comparing base (3199ae5) to head (b99a20e).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/keeper/erc20.go 73.68% 8 Missing and 2 partials ⚠️
x/evm/keeper/msg_server.go 91.66% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2089      +/-   ##
==========================================
- Coverage   63.99%   63.98%   -0.02%     
==========================================
  Files         270      270              
  Lines       21116    21092      -24     
==========================================
- Hits        13513    13495      -18     
+ Misses       6664     6660       -4     
+ Partials      939      937       -2     
Files with missing lines Coverage Δ
x/evm/embeds/embeds.go 68.00% <100.00%> (+2.78%) ⬆️
x/evm/keeper/msg_server.go 71.25% <91.66%> (-0.23%) ⬇️
x/evm/keeper/erc20.go 76.66% <73.68%> (-0.13%) ⬇️

... and 2 files with indirect coverage changes

@onikonychev onikonychev marked this pull request as ready for review October 22, 2024 12:16
@onikonychev onikonychev requested a review from a team as a code owner October 22, 2024 12:16
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The pull request includes extensive updates to the Nibiru project's CHANGELOG.md, reflecting changes in various areas such as breaking changes, new features, improvements, bug fixes, and dependency updates. Additionally, new smart contracts TestERC20MaliciousName and TestERC20MaliciousTransfer are introduced, along with their respective JSON artifacts. Modifications to existing files enhance error handling, gas management, and testing scenarios, particularly for malicious ERC20 contracts. The changes aim to improve the clarity, functionality, and robustness of the project's codebase.

Changes

File Path Change Summary
CHANGELOG.md Updated format and content, including sections for breaking changes, features, improvements, bug fixes, and dependencies.
src/evm/msgs.go Added methods deductCreateFunTokenFee, GetSigners, and updated ValidateBasic for MsgCreateFunToken and MsgSend.
x/evm/embeds/artifacts/contracts/FunToken.sol/IFunToken.json Changed contract name from "FunToken" to "IFunToken"; ABI structure remains unchanged.
x/evm/embeds/artifacts/contracts/TestERC20MaliciousName.sol/TestERC20MaliciousName.json Introduced new JSON artifact for TestERC20MaliciousName with detailed ABI and bytecode.
x/evm/embeds/artifacts/contracts/TestERC20MaliciousTransfer.sol/TestERC20MaliciousTransfer.json New JSON artifact for TestERC20MaliciousTransfer with ABI and bytecode.
x/evm/embeds/contracts/TestERC20MaliciousName.sol Added TestERC20MaliciousName contract with gas-intensive operations.
x/evm/embeds/contracts/TestERC20MaliciousTransfer.sol Added TestERC20MaliciousTransfer contract with overridden transfer function.
x/evm/embeds/embeds.go Added embedded JSON for malicious contracts and initialized new CompiledEvmContract instances.
x/evm/embeds/embeds_test.go Updated tests to include loading new malicious contracts.
x/evm/keeper/erc20.go Modified CallContractWithInput for improved error handling and gas management; removed computeCommitGasLimit.
x/evm/keeper/funtoken_from_erc20_test.go Added tests for handling ERC20 contracts with malicious behavior.
x/evm/keeper/msg_server.go Simplified transaction receipt handling and updated event emission logic.
proto/eth/evm/v1/evm.proto Updated comments for consistency regarding "Bank Coin" terminology.
proto/eth/evm/v1/query.proto Updated comment for fun_token field in QueryFunTokenMappingResponse for clarity.
proto/eth/evm/v1/tx.proto Modified comments for clarity regarding UpdateParams, CreateFunToken, and MsgCreateFunToken.
proto/eth/types/v1/indexer.proto Clarified comments for tx_index and eth_tx_index fields in TxResult message.

Possibly related PRs

Poem

In the land of code where rabbits play,
New features hop in, brightening the day.
Malicious tokens, a test we embrace,
With gas-intensive antics, we quicken the pace.
Changelogs updated, clarity in sight,
Hooray for the changes, our future is bright! 🐇✨


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.

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: 10

🧹 Outside diff range and nitpick comments (18)
x/evm/embeds/embeds.go (2)

65-71: LGTM: New TestERC20MaliciousName contract added.

The addition of this contract aligns with the PR objectives and follows the existing code structure. The comment clearly describes its purpose.

Consider adding a brief note about how this contract is used in tests to the comment, for example:

 // SmartContract_TestERC20MaliciousName is a test contract
 // which simulates malicious ERC20 behavior by adding gas intensive operation
-// for function name() intended to attack funtoken creation
+// for function name() intended to attack funtoken creation.
+// This is used in tests to ensure proper handling of gas-intensive operations.

72-78: LGTM: New TestERC20MaliciousTransfer contract added.

The addition of this contract aligns with the PR objectives and follows the existing code structure. The comment clearly describes its purpose.

Consider adding a brief note about how this contract is used in tests to the comment, for example:

 // SmartContract_TestERC20MaliciousTransfer is a test contract
 // which simulates malicious ERC20 behavior by adding gas intensive operation
 // for function transfer() intended to attack funtoken conversion from erc20 to bank coin
+// This is used in tests to ensure proper handling of gas-intensive operations during token transfers.
x/evm/embeds/artifacts/contracts/TestERC20MaliciousName.sol/TestERC20MaliciousName.json (1)

1-302: Ensure proper isolation of the malicious test contract.

Given that this contract is intentionally designed to be gas-intensive and potentially malicious, it's crucial to:

  1. Clearly document its purpose and potential risks.
  2. Ensure it's only used in controlled test environments.
  3. Implement safeguards in the main contract to handle potential gas-intensive ERC20 tokens.
  4. Regularly review and update gas limits and handling mechanisms based on the results of tests with this contract.

Consider adding a comment in the main contract or relevant test files explaining how this malicious contract is used and what safeguards are in place to prevent similar exploits in production.

CHANGELOG.md (7)

138-139: Ensure consistency in PR reference format.

The format for referencing pull requests is inconsistent. Some use square brackets, while others use parentheses. Consider standardizing to one format throughout the changelog for better readability.


Line range hint 144-145: Consider expanding on the impact of this change.

The entry "feat(perp): better handling of gas consumption within erc20 contract execution" could benefit from a brief explanation of how this affects users or developers. What improvements can they expect?


Line range hint 146-149: Ensure consistency in entry formatting.

Some entries in this section have more detailed explanations, while others are very brief. Consider adding a short explanation to all entries for consistency and to provide more context to users.


Line range hint 151-151: Consider reviewing change categorization.

The Features section is currently empty. Some changes in other sections, particularly in "State Machine Breaking," might qualify as new features. Consider reviewing the categorization to ensure users can easily identify new functionality.


Line range hint 155-156: Consider adding more context to the change.

The entry "chore(proto): Add a buf.gen.rs.yaml and corresponding script to create Rust types for Wasm Stargate messages" could benefit from a brief explanation of why this change is important or how it affects developers.


Line range hint 180-207: LGTM: Well-documented dependency updates.

The Dependencies section clearly lists all updated dependencies with their old and new versions. This is very helpful for users and developers.

Consider grouping similar dependencies (e.g., all Docker-related updates) for even better readability.


Line range hint 209-1595: LGTM: Comprehensive historical changelog.

The entries for previous versions (v1.5.0 and earlier) provide a detailed history of changes, which is valuable for users and developers. The consistent structure across versions is commendable.

For future updates, consider adding a brief summary of major changes or themes for each version at the top of its section. This could help users quickly understand the significance of each release.

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

227-227: Enhance error message for gas addition failure

The error message "error adding transient gas used to block" could be more descriptive. Including details about the gasUsed value or the context in which the error occurred can aid in debugging and provide clearer insights into the issue.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 227-227: x/evm/keeper/erc20.go#L227
Added line #L227 was not covered by tests


237-245: Improve error messages for EVM execution failures

For better debugging and user experience, consider enhancing the error messages when the EVM execution fails. Providing more context, such as the reason for failure or relevant transaction details, can help developers quickly identify and resolve issues.


183-185: Increase test coverage for new code paths

The static analysis tools indicate that the newly added lines are not covered by tests:

  • Lines 223-224: Handling gasUsed when evmResp is nil
  • Line 227: Error handling after adding gas used to block
  • Line 232: Wrapping error from ApplyEvmMsg
  • Line 235: Checking if evmResp is nil

Adding tests for these scenarios will improve reliability and ensure that edge cases are handled correctly.

Would you like assistance in writing unit tests to cover these code paths?

Also applies to: 219-225, 227-227, 232-235

x/evm/keeper/funtoken_from_erc20_test.go (4)

280-283: Nitpick: Improve function documentation comments.

Consider updating the function comments to follow Go conventions for better readability and maintainability. Begin the comment with the function name and provide a clear description.

Apply this diff to enhance the comments:

-// TestCreateFunTokenFromERC20MaliciousName tries to create funtoken from a contract
-// with a malicious (gas intensive) name() function.
-// Fun token should fail creation with "out of gas"
+// TestCreateFunTokenFromERC20MaliciousName tests the creation of a FunToken from an ERC20 contract
+// with a malicious (gas-intensive) name() function.
+// The FunToken creation should fail with an "out of gas" error.
 func (s *FunTokenFromErc20Suite) TestCreateFunTokenFromERC20MaliciousName() {

298-301: Nitpick: Simplify EIP55 address initialization.

You can directly assign deployResp.ContractAddr to erc20Addr since it's already of type eth.EIP55Addr.

Apply this diff to simplify the code:

-erc20Addr := eth.EIP55Addr{
-    Address: deployResp.ContractAddr,
-}
+erc20Addr := deployResp.ContractAddr

320-323: Nitpick: Improve function documentation comments.

As before, updating the comments to match Go conventions enhances readability.

Apply this diff to refine the comments:

-// TestFunTokenFromERC20MaliciousTransfer creates a funtoken from a contract
-// with a malicious (gas intensive) transfer() function.
-// Fun token should be created but sending from erc20 to bank should fail with out of gas
+// TestFunTokenFromERC20MaliciousTransfer tests the creation of a FunToken from an ERC20 contract
+// with a malicious (gas-intensive) transfer() function.
+// The FunToken creation should succeed, but transferring tokens to the bank should fail with an "out of gas" error.

338-341: Nitpick: Simplify EIP55 address initialization.

As with the previous function, you can simplify the assignment of erc20Addr.

Apply this diff:

-erc20Addr := eth.EIP55Addr{
-    Address: deployResp.ContractAddr,
-}
+erc20Addr := deployResp.ContractAddr
x/evm/keeper/msg_server.go (1)

710-723: Well-encapsulated updateBlockBloom function

The addition of the updateBlockBloom function enhances modularity by encapsulating the logic for updating the block bloom filter and log size. This improves code readability and maintainability.

Consider adding unit tests for updateBlockBloom to ensure its correctness and to prevent future regressions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3199ae5 and 84ef0fa.

📒 Files selected for processing (11)
  • CHANGELOG.md (1 hunks)
  • x/evm/embeds/artifacts/contracts/FunToken.sol/IFunToken.json (1 hunks)
  • x/evm/embeds/artifacts/contracts/TestERC20MaliciousName.sol/TestERC20MaliciousName.json (1 hunks)
  • x/evm/embeds/artifacts/contracts/TestERC20MaliciousTransfer.sol/TestERC20MaliciousTransfer.json (1 hunks)
  • x/evm/embeds/contracts/TestERC20MaliciousName.sol (1 hunks)
  • x/evm/embeds/contracts/TestERC20MaliciousTransfer.sol (1 hunks)
  • x/evm/embeds/embeds.go (3 hunks)
  • x/evm/embeds/embeds_test.go (1 hunks)
  • x/evm/keeper/erc20.go (3 hunks)
  • x/evm/keeper/funtoken_from_erc20_test.go (1 hunks)
  • x/evm/keeper/msg_server.go (6 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
x/evm/keeper/erc20.go

[warning] 223-224: x/evm/keeper/erc20.go#L223-L224
Added lines #L223 - L224 were not covered by tests


[warning] 227-227: x/evm/keeper/erc20.go#L227
Added line #L227 was not covered by tests


[warning] 232-232: x/evm/keeper/erc20.go#L232
Added line #L232 was not covered by tests


[warning] 235-235: x/evm/keeper/erc20.go#L235
Added line #L235 was not covered by tests

🔇 Additional comments (25)
x/evm/embeds/embeds_test.go (1)

17-18: LGTM! The changes align well with the PR objectives.

The addition of TestERC20MaliciousName and TestERC20MaliciousTransfer to the TestLoadContracts function is a good enhancement. These new test cases align perfectly with the PR's goal of improving robustness against malicious ERC20 contracts.

x/evm/embeds/artifacts/contracts/FunToken.sol/IFunToken.json (1)

3-3: LGTM: Contract name updated to reflect interface nature.

The change from "FunToken" to "IFunToken" correctly indicates that this is now an interface rather than a concrete implementation. This aligns well with best practices for contract design and separation of concerns.

To ensure consistency across the codebase, please run the following script:

This will help identify any places where the renaming might have been missed or where further updates might be necessary.

✅ Verification successful

LGTM: All necessary references updated to IFunToken.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all references to FunToken have been updated to IFunToken where appropriate

# Test: Search for any remaining references to FunToken
rg -i 'funtoken' --type ts --type sol --type go

# Test: Confirm the presence of IFunToken references
rg -i 'ifuntoken' --type ts --type sol --type go

Length of output: 152


Script:

#!/bin/bash
# Description: Verify that all references to FunToken have been updated to IFunToken where appropriate

# Test: Search for any remaining references to FunToken
rg -i 'funtoken' -g '*.ts' -g '*.sol' -g '*.go'

# Test: Confirm the presence of IFunToken references
rg -i 'ifuntoken' -g '*.ts' -g '*.sol' -g '*.go'

Length of output: 53808

x/evm/embeds/embeds.go (3)

28-31: LGTM: New malicious ERC20 contract JSONs added.

The addition of these embedded JSON files for malicious ERC20 contracts aligns with the PR objectives and follows the existing naming conventions and embedding patterns.


87-88: LGTM: New contracts initialized in init function.

The addition of MustLoad() calls for the new malicious contracts ensures they are properly initialized. This change is consistent with the existing pattern for contract initialization.


Line range hint 28-88: Summary: Enhancements for testing malicious ERC20 behavior.

The changes in this file successfully introduce two new malicious ERC20 contracts for testing purposes. These additions align with the PR objectives and enhance the project's ability to test and handle gas-intensive operations in ERC20 interactions. The implementation follows existing code patterns and is well-documented.

To ensure these new contracts are properly referenced and utilized in tests, please run the following script:

This will help confirm that the new contracts are being utilized in the test suite as intended.

✅ Verification successful

Verification Successful: Malicious ERC20 contracts are properly utilized in tests.

The new contracts TestERC20MaliciousName and TestERC20MaliciousTransfer are referenced in embeds_test.go and funtoken_from_erc20_test.go, ensuring they are actively used in the test suite.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new malicious ERC20 contracts in tests

# Test: Search for references to the new contracts in test files
echo "Searching for TestERC20MaliciousName usage in tests:"
rg -n "TestERC20MaliciousName" --type go --glob "*_test.go"

echo "\nSearching for TestERC20MaliciousTransfer usage in tests:"
rg -n "TestERC20MaliciousTransfer" --type go --glob "*_test.go"

Length of output: 747

x/evm/embeds/artifacts/contracts/TestERC20MaliciousName.sol/TestERC20MaliciousName.json (3)

1-4: Contract metadata aligns with PR objectives.

The contract name "TestERC20MaliciousName" and its source file location are consistent with the PR's goal of introducing malicious ERC20 contracts for testing gas-intensive methods, specifically the name() function.


298-301: Bytecode present, consider security audit.

The file includes both deployment and runtime bytecode, confirming successful compilation. Given the contract's intended malicious nature for testing, it's advisable to ensure a thorough security audit has been performed, particularly focusing on the gas consumption patterns in the name() function implementation.

To verify if a security audit has been mentioned or performed, run the following script:


5-297: Verify the implementation of the name() function.

The ABI includes the name() function, which is likely the focus of the malicious behavior for gas consumption testing. While the ABI structure is correct, it's crucial to verify the actual implementation of the name() function in the source code to ensure it meets the gas-intensive testing requirements.

To verify the implementation of the name() function, run the following script:

x/evm/embeds/artifacts/contracts/TestERC20MaliciousTransfer.sol/TestERC20MaliciousTransfer.json (6)

1-302: Contract structure aligns with its testing purpose.

The TestERC20MaliciousTransfer contract implements standard ERC20 functions, which is appropriate for its role in testing the system's handling of malicious ERC20 tokens. The contract structure serves its purpose well.


5-296: Fully compliant with ERC20 standard.

The contract implements all required ERC20 functions and events, as well as optional functions like name, symbol, and decimals. This ensures that the test contract accurately represents a standard ERC20 token, which is essential for reliable testing.


244-266: Gas-intensive behavior aligns with testing objectives.

The contract name and PR objectives suggest that this contract implements gas-intensive operations, likely in its transfer function. This design is appropriate for testing the system's ability to handle malicious ERC20 contracts that may attempt to exploit gas limits.


298-302: Bytecode and deployment information are complete and appropriate.

The contract's bytecode is provided and appears to be complete. The absence of link references indicates that the contract is self-contained, which is suitable for a test contract. This ensures that the contract can be deployed consistently for testing purposes.


1-302: Well-designed test contract for malicious ERC20 behavior.

This TestERC20MaliciousTransfer contract artifact is well-structured and fully compliant with the ERC20 standard. It appropriately implements intentionally malicious behavior for testing purposes, likely focusing on gas-intensive operations during transfers. The contract's design aligns well with the PR objectives of improving handling of malicious ERC20 contracts.

Key points:

  1. Fully ERC20 compliant
  2. Implements intentional malicious behavior for testing
  3. Likely includes gas-intensive operations in the transfer function
  4. Self-contained with no external dependencies

Ensure that this contract is strictly isolated to testing environments to prevent any unintended interactions in production systems.


1-302: Ensure proper isolation of malicious test contract.

This contract is designed to exhibit malicious behavior for testing purposes. While this is valuable for ensuring system robustness, it's crucial to implement strict safeguards to prevent any accidental deployment or interaction with this contract in non-testing environments.

To verify proper isolation, run the following script:

✅ Verification successful

Malicious test contract is properly isolated.

All references to TestERC20MaliciousTransfer are confined to test and spec directories, ensuring that the malicious contract cannot be deployed or interacted with in non-testing environments.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any imports or uses of TestERC20MaliciousTransfer outside of test files

# Test: Search for imports or uses of TestERC20MaliciousTransfer
rg -g '!*test*' -g '!*spec*' 'TestERC20MaliciousTransfer'

Length of output: 897


Script:

#!/bin/bash
# Description: Check if embeds.go is referenced in non-test and non-spec files

# Search for references to embeds.go outside of test and spec directories
rg -g '!*test*' -g '!*spec*' 'embeds\.go' .

Length of output: 45


Script:

#!/bin/bash
# Description: Verify that embeds.go is not imported or used in any non-test and non-spec files

# Search for import statements referencing embeds.go outside of test and spec directories
rg -g '!(*test*|*spec*)' 'import\s+["'\''].*embeds\.go["'\'']' .

Length of output: 66

CHANGELOG.md (2)

140-140: LGTM: Clear categorization of changes.

The changes are well-categorized into "State Machine Breaking," "Features," "Improvements," "Bug Fixes," and "Dependencies." This organization helps users quickly identify the nature of each change.


Line range hint 157-157: LGTM: Clear and concise improvement.

The entry "chore(goreleaser): update wasmvm to v1.4.0" is clear and provides useful information about a dependency update.

x/evm/embeds/contracts/TestERC20MaliciousTransfer.sol (1)

12-15: ⚠️ Potential issue

Excessive gas consumption in transfer may cause transactions to fail

The _gasIntensiveOperation() in the transfer function runs a loop of 100,000 iterations, which may consume excessive gas and cause transactions to fail or be rejected due to gas limits.

Consider verifying whether the gas consumption stays within acceptable limits. If necessary, adjust the loop count to prevent out-of-gas errors.

x/evm/embeds/contracts/TestERC20MaliciousName.sol (2)

12-16: Function name() implementation looks good

The override of the name() function correctly includes the gas-intensive operation to simulate high computational cost, fulfilling its intended purpose for testing.


19-28: Verify the gas consumption of _gasIntensiveOperation()

The _gasIntensiveOperation() function runs a loop with 100,000 iterations performing multiple computations. This may consume substantial gas, potentially exceeding block gas limits and causing transactions to fail. Please verify that the gas consumption is acceptable for your testing scenarios.

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

219-225: Verify gas usage calculation when evmResp is nil

When evmResp is nil, gasUsed is assigned the value of ctx.GasMeter().Limit(). Please verify that this correctly represents the gas used in scenarios where the EVM response is unavailable. Incorrect gas accounting may lead to inconsistencies in gas tracking and potential issues with transaction processing.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 223-224: x/evm/keeper/erc20.go#L223-L224
Added lines #L223 - L224 were not covered by tests

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

87-87: Verify proper initialization of txConfig.LogIndex

In line 87, k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex)) is called with uint64(txConfig.LogIndex). Ensure that txConfig.LogIndex is correctly initialized to prevent potential issues due to type conversion or uninitialized values.


654-655: Avoid potential nil pointer dereference

The check if recipient != nil before accessing recipient.Hex() ensures that you avoid a nil pointer dereference, which enhances the stability of the code when recipient is nil (e.g., during contract creation).


682-682: Confirm correct transaction type formatting

Formatting txType using fmt.Sprintf("%d", txType) correctly converts the transaction type to a string for the event attribute. Ensure that txType accurately represents the transaction type and aligns with the expected values.


688-689: Correctly identify contract creation transactions

Checking if recipient == nil to determine if the transaction is a contract creation is appropriate. This logic aligns with Ethereum's handling of contract creation transactions, where the recipient address is nil.


640-645: Ensure all calls to EmitEthereumTxEvents are updated

The signature of EmitEthereumTxEvents has changed. Verify that all invocations of this function throughout the codebase have been updated to prevent potential runtime errors.

Run the following script to find all usages of EmitEthereumTxEvents:

✅ Verification successful

EmitEthereumTxEvents Invocations Verified Successfully

All calls to EmitEthereumTxEvents are updated according to the new signature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to EmitEthereumTxEvents and ensure parameters are updated.

# Search for the function usage. Expectation: All calls reflect the new signature.
rg 'EmitEthereumTxEvents\(' -A 2

Length of output: 442

Comment on lines +7 to +10
constructor(string memory name, string memory symbol, uint8 decimals_)
ERC20(name, symbol) {
_mint(msg.sender, 1000000 * 10**18);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused parameter decimals_ or utilize it to set token decimals

The decimals_ parameter in the constructor is not used, which may lead to confusion. If you intend to set a custom decimals value, consider overriding the decimals() function to return decimals_. Otherwise, remove the parameter to simplify the constructor.

Apply this diff to remove the unused parameter:

-    constructor(string memory name, string memory symbol, uint8 decimals_)
+    constructor(string memory name, string memory symbol)
     ERC20(name, symbol) {
         _mint(msg.sender, 1000000 * 10**18);
     }

Alternatively, override the decimals() function to set a custom decimals value:

     constructor(string memory name, string memory symbol, uint8 decimals_)
     ERC20(name, symbol) {
         _mint(msg.sender, 1000000 * 10 ** decimals_);
+        _decimals = decimals_;
     }

+    uint8 private _decimals;

+    function decimals() public view virtual override returns (uint8) {
+        return _decimals;
+    }

Committable suggestion was skipped due to low confidence.

Comment on lines +7 to +10
constructor(string memory name, string memory symbol, uint8 decimals_)
ERC20(name, symbol) {
_mint(msg.sender, 1000000 * 10**18);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused parameter decimals_ in constructor

The parameter decimals_ is declared in the constructor but not utilized within the function body. This can lead to confusion or potential errors. Consider removing it if it's not needed or using it appropriately.

Apply this diff to remove the unused parameter:

-constructor(string memory name, string memory symbol, uint8 decimals_)
+constructor(string memory name, string memory symbol)
    ERC20(name, symbol) {
        _mint(msg.sender, 1000000 * 10**18);
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constructor(string memory name, string memory symbol, uint8 decimals_)
ERC20(name, symbol) {
_mint(msg.sender, 1000000 * 10**18);
}
constructor(string memory name, string memory symbol)
ERC20(name, symbol) {
_mint(msg.sender, 1000000 * 10**18);
}

x/evm/keeper/erc20.go Outdated Show resolved Hide resolved
x/evm/keeper/erc20.go Outdated Show resolved Hide resolved
x/evm/keeper/erc20.go Outdated Show resolved Hide resolved
Comment on lines +284 to +297
deps := evmtest.NewTestDeps()

s.T().Log("Deploy ERC20MaliciousName")
metadata := keeper.ERC20Metadata{
Name: "erc20name",
Symbol: "TOKEN",
Decimals: 18,
}
deployResp, err := evmtest.DeployContract(
&deps, embeds.SmartContract_TestERC20MaliciousName,
metadata.Name, metadata.Symbol, metadata.Decimals,
)
s.Require().NoError(err)

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Issue: Add error handling after contract deployment.

If the deployment of the malicious ERC20 contract fails, subsequent steps may cause a panic. It's safer to check the error immediately after deployment.

Apply this diff to handle the error appropriately:

 deployResp, err := evmtest.DeployContract(
     &deps, embeds.SmartContract_TestERC20MaliciousName,
     metadata.Name, metadata.Symbol, metadata.Decimals,
 )
-s.Require().NoError(err)
+if err != nil {
+    s.T().Fatalf("Failed to deploy ERC20MaliciousName contract: %v", err)
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
deps := evmtest.NewTestDeps()
s.T().Log("Deploy ERC20MaliciousName")
metadata := keeper.ERC20Metadata{
Name: "erc20name",
Symbol: "TOKEN",
Decimals: 18,
}
deployResp, err := evmtest.DeployContract(
&deps, embeds.SmartContract_TestERC20MaliciousName,
metadata.Name, metadata.Symbol, metadata.Decimals,
)
s.Require().NoError(err)
deps := evmtest.NewTestDeps()
s.T().Log("Deploy ERC20MaliciousName")
metadata := keeper.ERC20Metadata{
Name: "erc20name",
Symbol: "TOKEN",
Decimals: 18,
}
deployResp, err := evmtest.DeployContract(
&deps, embeds.SmartContract_TestERC20MaliciousName,
metadata.Name, metadata.Symbol, metadata.Decimals,
)
if err != nil {
s.T().Fatalf("Failed to deploy ERC20MaliciousName contract: %v", err)
}

x/evm/keeper/funtoken_from_erc20_test.go Show resolved Hide resolved
@@ -130,7 +94,7 @@ func (k *Keeper) EthereumTx(
// reset the gas meter for current cosmos transaction
k.ResetGasMeterAndConsumeGas(ctx, totalGasUsed)

err = k.EmitEthereumTxEvents(ctx, tx, msg, evmResp, contractAddr)
err = k.EmitEthereumTxEvents(ctx, tx.To(), tx.Type(), msg, evmResp)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update function call to match new EmitEthereumTxEvents signature

The EmitEthereumTxEvents function now expects recipient *gethcommon.Address and txType uint8 as parameters. Ensure that tx.To() returns a *gethcommon.Address and that tx.Type() provides the correct transaction type according to the updated function signature.

Apply this diff if necessary to align the function call with the new signature:

-	err = k.EmitEthereumTxEvents(ctx, tx.To(), tx.Type(), msg, evmResp)
+	recipient := tx.To()
+	txType := tx.Type()
+	err = k.EmitEthereumTxEvents(ctx, recipient, txType, msg, evmResp)

Committable suggestion was skipped due to low confidence.

@NibiruChain NibiruChain deleted a comment from coderabbitai bot Oct 22, 2024
@NibiruChain NibiruChain deleted a comment from coderabbitai bot Oct 22, 2024
Copy link
Member

@Unique-Divine Unique-Divine left a comment

Choose a reason for hiding this comment

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

Looks good. I'll do a second review pass from inside the editor to get a closer look at msg_server.go

Copy link
Member

Choose a reason for hiding this comment

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

Test cases look great for the behavior you're trying to test 🎉

x/evm/keeper/erc20.go Show resolved Hide resolved
x/evm/keeper/erc20.go Outdated Show resolved Hide resolved
x/evm/keeper/erc20.go Outdated Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (4)
x/evm/keeper/msg_server.go (4)

Line range hint 34-39: Ensure deferred error wrapping handles nil errors safely

In the deferred function starting at line 35, wrapping err without checking if it's nil could overwrite a nil error with a non-nil one.

Consider modifying the deferred function to only wrap err if it's not nil:

 defer func() {
+    if err != nil {
         err = fmt.Errorf("EthereumTx error: %w", err)
+    }
 }()

45-45: Avoid variable shadowing of ctx

At line 45, ctx is reassigned when calling sdk.UnwrapSDKContext(goCtx).CacheContext(), which can cause confusion due to variable shadowing.

Consider renaming one of the variables or restructuring the code to prevent shadowing and improve code clarity.


71-76: Simplify gas refund calculation

The refund gas calculation can be simplified to improve readability.

Consider the following refactor:

refundGas := evmMsg.Gas() - evmResp.GasUsed
if evmResp.GasUsed > evmMsg.Gas() {
    refundGas = 0
}

709-721: Add missing function documentation for updateBlockBloom

The updateBlockBloom function introduced at lines 709-721 lacks documentation.

Consider adding a comment to describe the purpose and usage of this function for better code maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f96e001 and 041c9b7.

⛔ Files ignored due to path filters (4)
  • eth/indexer.pb.go is excluded by !**/*.pb.go
  • x/evm/evm.pb.go is excluded by !**/*.pb.go
  • x/evm/query.pb.go is excluded by !**/*.pb.go
  • x/evm/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (6)
  • proto/eth/evm/v1/evm.proto (2 hunks)
  • proto/eth/evm/v1/query.proto (1 hunks)
  • proto/eth/evm/v1/tx.proto (4 hunks)
  • proto/eth/types/v1/indexer.proto (1 hunks)
  • x/evm/keeper/erc20.go (3 hunks)
  • x/evm/keeper/msg_server.go (7 hunks)
✅ Files skipped from review due to trivial changes (4)
  • proto/eth/evm/v1/evm.proto
  • proto/eth/evm/v1/query.proto
  • proto/eth/evm/v1/tx.proto
  • proto/eth/types/v1/indexer.proto
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/evm/keeper/erc20.go
🔇 Additional comments (8)
x/evm/keeper/msg_server.go (8)

63-63: Verify correctness of ApplyEvmMsg parameters

The call to k.ApplyEvmMsg(ctx, evmMsg, nil, true, evmConfig, txConfig) passes nil as the tracer and true for the commit parameter. Confirm that passing nil as the tracer is acceptable, and that committing the StateDB at this point is intentional and doesn't cause unintended side effects.


82-82: Confirm correct update of block bloom filter

Ensure that the k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex)) call correctly updates the block bloom filter and that txConfig.LogIndex is the appropriate starting point for the logs.


89-90: Ensure accurate gas meter reset

Resetting the gas meter with k.ResetGasMeterAndConsumeGas(ctx, totalGasUsed) should accurately reflect the total gas used to maintain consistency.


92-92: Verify parameters for EmitEthereumTxEvents

The updated call to EmitEthereumTxEvents includes tx.To() and tx.Type(). Ensure that these parameters align with the updated function signature that expects recipient *gethcommon.Address and txType uint8.


100-102: Commit context only on successful transaction execution

The addition of commitCtx() within the if !evmResp.Failed() block ensures that the context is committed only when the transaction did not fail. This change helps prevent committing state changes from failed transactions.


638-639: Update function signature and ensure consistency

The function EmitEthereumTxEvents has been updated to accept recipient *gethcommon.Address and txType uint8 as parameters. Verify that all calls to this function have been updated accordingly and that the parameters are used consistently within the function.


652-653: Safely handle nil recipient when emitting events

In lines 652-653, the code checks if recipient != nil before setting eventEthereumTx.Recipient. This prevents potential nil pointer dereferences.


Line range hint 686-702: Accurate event emission based on transaction details

The conditional logic from lines 686 to 702 ensures that the correct events are emitted based on the transaction type (contract creation, contract execution, or value transfer).

x/evm/keeper/msg_server.go Show resolved Hide resolved
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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 041c9b7 and 9a6d35d.

📒 Files selected for processing (2)
  • x/evm/keeper/erc20.go (3 hunks)
  • x/evm/keeper/msg_server.go (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/evm/keeper/erc20.go
🔇 Additional comments (12)
x/evm/keeper/msg_server.go (12)

34-35: Clarify the usage of defer for enhanced error context

The added comment effectively explains the purpose of the defer statement, which improves code readability and maintainability.


45-46: Proper use of CacheContext for transactional state management

Introducing CacheContext allows for conditional state commitment, enhancing the reliability of state changes within the transaction lifecycle.


64-67: Verify the necessity of passing nil as the tracer

Passing nil as the tracer to ApplyEvmMsg relies on default tracer behavior. Ensure that this meets the tracing requirements for debugging and performance monitoring.

If custom tracing is needed, consider initializing a tracer before calling ApplyEvmMsg.


73-74: State changes are committed only upon successful execution

Calling commitCtx() only when the transaction has not failed ensures that state changes are persisted only when intended, preventing unintended state mutations on failure.


77-81: Accurate calculation of gas refund to match Ethereum behavior

The logic correctly refunds the unused gas, aligning with Ethereum's gas consumption model and ensuring fair gas accounting.


88-88: Block bloom filter updated to include transaction logs

Calling k.updateBlockBloom ensures that the block's bloom filter accurately reflects the logs from the transaction, which is crucial for log searches and event indexing.


95-95: Resetting gas meter to reflect total gas used

Using k.ResetGasMeterAndConsumeGas(ctx, totalGasUsed) maintains consistency with the actual gas consumption, ensuring accurate gas accounting in the context.


640-641: Updated function signature improves event emission clarity

The modified parameters in EmitEthereumTxEvents focus on directly passing the recipient address and transaction type, simplifying the function's usage and enhancing code readability.


654-655: Safely set recipient in Ethereum transaction events

The null check for recipient before setting eventEthereumTx.Recipient prevents potential nil pointer dereferences, ensuring robustness in the event emission process.


682-682: Correct formatting of transaction type in event attribute

Using fmt.Sprintf to format txType as a string ensures that the event attribute accurately represents the transaction type, which is essential for event consumers.


688-689: Accurate detection of contract creation transactions

By checking recipient == nil, the code correctly identifies contract creation scenarios and generates the contract address using crypto.CreateAddress, aligning with Ethereum standards.


710-723: Refactored updateBlockBloom improves code modularity

Encapsulating the block bloom filter update logic into updateBlockBloom enhances code maintainability and readability, promoting better separation of concerns.

x/evm/keeper/msg_server.go Show resolved Hide resolved
x/evm/keeper/msg_server.go Show resolved Hide resolved
x/evm/keeper/msg_server.go Show resolved Hide resolved
@Unique-Divine
Copy link
Member

@coderabbitai pause

Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

✅ Actions performed

Reviews paused.

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