8000 chore(werc20): Add wrapper ERC20 precompile by Vvaradinov · Pull Request #2943 · evmos/evmos · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

chore(werc20): Add wrapper ERC20 precompile #2943

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

Merged
merged 75 commits into from
Nov 13, 2024
Merged

Conversation

Vvaradinov
Copy link
Contributor
@Vvaradinov Vvaradinov commented Oct 15, 2024

Description

This PR introduces the werc20 precompile to be used with registered native precompiles addresses. The implementation extend the already existing erc20 precompile adding the methods for the wrapping logic.

Te instantiation logic of the dynamic precompiles has been updated to load werc20 or erc20 depending on the address.

Other minor changes introduced in the PR are:

  • The configuration of Hardhat has been changed to support different compiler so that WEVMOS contract can be compiled. This allows to remove the contract from the /contracts folder and keep it only in the precompiles directory.
  • The BankKeeper field in the erc20 precompile is now public allowing the werc20 to use it without adding another pointer to in the struct.
  • Emit event to match original implementation of the wrapped contract.
  • Changed the signature for the IsTransfer function of precompiles to use the abi.Method instead of Method.Name. This is required to handle fallback and receive special functions.

Summary by CodeRabbit

  • New Features

    • Introduced a new Wrapped ERC20 token interface (IWERC20) for managing native EVM tokens.
    • Added deposit and withdrawal functionalities for the WERC20 token.
    • Enhanced the changelog with categories for unreleased changes, improvements, and bug fixes.
    • Implemented a new JSON artifact for the WEVMOS9 contract, detailing its functions and events.
    • Added a new contract (WEVMOS9TestCaller) for testing deposit functionalities with revert scenarios.
    • Introduced a utility function to load the WEVMOS9TestCaller contract from JSON.
    • Added support for multiple Solidity compiler versions in the Hardhat configuration.
  • Bug Fixes

    • Resolved issues with default denominations in CLI and fixed free delegated amounts on grants.
  • Documentation

    • Updated CHANGELOG.md to reflect recent changes and improvements.
  • Tests

    • Added comprehensive tests for WERC20 precompile functionalities, ensuring correct event emissions and contract interactions.
    • Established integration tests for the WEVMOS precompiled contract, validating various interactions and expected behaviors.
    • Introduced a test suite for the werc20 precompile, focusing on event emissions and contract behavior.
    • Enhanced test cases to utilize the new abi.Method type for improved type safety.

Summary by CodeRabbit

  • New Features

    • Introduced a new Wrapped ERC20 token interface (IWERC20) for managing native EVM tokens.
    • Added deposit and withdrawal functionalities for the new WERC20 token standard.
    • Enhanced the gas management and transaction handling for EVM interactions.
    • Added a new command-line option to specify additional Solidity contracts for compilation.
    • Introduced a new JSON artifact for the WEVMOS9 smart contract, including its ABI and metadata.
    • Added a new test caller contract (WEVMOS9TestCaller) for interacting with the WERC20 token.
  • Improvements

    • Updated the handling of ERC20 precompile instances to distinguish between native and standard versions.
    • Improved error handling and state management for deposit and withdrawal operations.
    • Enhanced integration tests for the WEVMOS precompiled contract to validate functionality under various conditions.
    • Updated the genesis state handling based on chain ID for more accurate testing configurations.
  • Bug Fixes

    • Resolved issues with gas limits and transaction handling for various methods.
    • Fixed errors related to the evmosd testnet init-files command.
  • Documentation

    • Updated CHANGELOG.md to reflect recent changes and improvements across the project.

@Vvaradinov Vvaradinov requested a review from a team as a code owner October 15, 2024 12:52
@Vvaradinov Vvaradinov requested review from hanchon and MalteHerrmann and removed request for a team October 15, 2024 12:52
Copy link
Contributor
coderabbitai bot commented Oct 15, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces significant changes across various modules, including the addition of a new Wrapped ERC20 token interface (IWERC20), updates to the handling of EVM coins with varying decimal precision, and modifications to the state machine. Key changes include the removal of EthAccount, the introduction of BaseAccount, and the refactoring of gas price handling in JSON-RPC. Additionally, new test cases and configuration updates enhance the testing framework and Solidity compiler support.

Changes

File Path Change Summary
CHANGELOG.md Updated with new entries for breaking changes, improvements, and bug fixes.
precompiles/werc20/IWERC20.sol Added interface for Wrapped ERC20 token with deposit and withdrawal functions.
precompiles/werc20/abi.json Introduced ABI for IWERC20 contract, detailing events and functions.
precompiles/werc20/tx.go Added deposit and withdrawal methods for WERC20 token management.
precompiles/werc20/werc20.go Implemented WERC20 precompile contract with initialization and method execution logic.
contracts/compiled_contracts/WEVMOS.json Removed ABI and binary code for WEVMOS contract.
contracts/hardhat.config.js Updated to support multiple Solidity compiler versions.
contracts/wevmos.go Removed implementation for WEVMOS smart contract.
precompiles/erc20/erc20.go Changed visibility of bankKeeper to BankKeeper and updated method signatures.
precompiles/erc20/query.go Updated references to bankKeeper to BankKeeper.
precompiles/erc20/tx.go Updated message server instantiation to use BankKeeper.
precompiles/erc20/types.go Removed constants for WEVMOSContractMainnet and WEVMOSContractTestnet.
precompiles/werc20/events.go Added event emission functionality for deposits and withdrawals.
precompiles/werc20/events_test.go Introduced unit tests for event emissions in WERC20 precompile.
precompiles/werc20/integration_test.go Added integration tests for WERC20 precompiled contract interactions.
precompiles/werc20/testdata/WEVMOS9.json Added JSON artifact for WEVMOS9 contract with metadata and ABI.
precompiles/werc20/testdata/WEVMOS9.sol Introduced WEVMOS9 contract with deposit functionality.
precompiles/werc20/testdata/wevmos9_test_caller.go Added function to load WEVMOS9TestCaller contract from JSON.
x/erc20/keeper/precompiles.go Updated ERC20 precompile methods to handle native and wrapped precompiles.
x/erc20/types/params.go Added mapping for WEVMOS contract addresses based on chain ID.
x/evm/keeper/call_evm_test.go Updated test cases to reflect new expected outcomes.
x/evm/keeper/keeper.go Minor comment correction in Keeper struct.
precompiles/bank/bank.go Updated transaction identification methods to use abi.Method.
precompiles/common/precompile.go Modified RunSetup to accept abi.Method pointers.
precompiles/distribution/distribution.go Updated transaction handling to use abi.Method instead of strings.
precompiles/gov/gov.go Updated transaction identification to use abi.Method.
tests/nix_tests/hardhat/hardhat.config.js Updated to include new compiler version and changed string syntax.
tests/solidity/suites/precompiles/hardhat.config.js Added new compiler version and standardized formatting.
testutil/integration/evmos/network/chain_id_modifiers.go Introduced functions for modifying genesis state based on chain ID.
testutil/integration/evmos/network/setup.go Updated genesis state functions to use new chain ID modifiers.
.github/workflows/super-linter.yml Added environment variable to control JavaScript validation.

Possibly related PRs

Suggested labels

proto, CLI

Suggested reviewers

  • GAtom22
  • hanchon
  • ramacarlucho

🐇 In the fields of code we hop,
With WERC20, we won't stop!
New contracts bloom, old ones fade,
In this dance of code, our plans are laid.
With every change, our vision grows,
In the world of tokens, our spirit flows! 🌟


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

🧹 Outside diff range and nitpick comments (10)
precompiles/werc20/tx.go (3)

6-13: LGTM: Constants are well-defined and documented.

The constants DepositMethod and WithdrawMethod are appropriately named and documented. Using constants for method names is a good practice for maintainability.

Consider adding a package-level comment explaining the purpose of these constants in the context of the WERC20 implementation. This would provide more context for developers unfamiliar with the WERC20 concept.


15-20: LGTM: Deposit method implemented as described.

The Deposit method is correctly implemented as a no-op function, consistent with the comment's explanation.

Consider expanding the comment to explain why a no-op implementation is sufficient in this context. For example:

// Deposit is a no-op mock function that provides the same interface as the
// WETH contract. It supports equality between the native coin and its wrapped
// ERC-20 (e.g., EVMOS and WEVMOS). A no-op is sufficient because the actual
// wrapping logic is handled elsewhere in the Evmos system, and this precompile
// serves as an interface compatibility layer.

This additional context would help developers understand the design decision behind this implementation.


22-27: LGTM: Withdraw method implemented as described, with suggestions for improvement.

The Withdraw method is correctly implemented as a no-op function, consistent with the comment's explanation and the Deposit method's implementation.

  1. Consider updating the comment to be specific to the Withdraw method, similar to the suggestion for the Deposit method.

  2. Since both Deposit and Withdraw methods have identical implementations, consider refactoring to reduce duplication:

type noOpFunc func() ([]byte, error)

func noOp() ([]byte, error) {
    return nil, nil
}

// Deposit is a no-op mock function that provides the same interface as the
// WETH contract. It supports equality between the native coin and its wrapped
// ERC-20 (e.g., EVMOS and WEVMOS). A no-op is sufficient because the actual
// wrapping logic is handled elsewhere in the Evmos system, and this precompile
// serves as an interface compatibility layer.
func (p Precompile) Deposit() noOpFunc {
    return noOp
}

// Withdraw is a no-op mock function with the same purpose and behavior as Deposit,
// but for the withdrawal operation.
func (p Precompile) Withdraw() noOpFunc {
    return noOp
}

This refactoring would make the code more DRY and easier to maintain if the implementation needs to change in the future.

precompiles/werc20/IWERC20.sol (2)

4-9: LGTM: Well-documented interface with a minor suggestion.

The interface is well-documented using NatSpec comments, providing clear information about its purpose and authorship. This follows good practices for code documentation.

Consider adding a @notice tag to provide a brief, one-line description of the interface. This can improve documentation generation tools' output. For example:

/**
 * @notice Interface for a wrapped ERC20 token representing the native EVM token
 * @author Evmos Team
 * @title Wrapped ERC20 Interface
 * @dev Interface for representing the native EVM token as ERC20 standard.
 */

26-37: LGTM: Well-defined deposit and withdraw functions with a minor suggestion.

The deposit and withdraw functions are properly defined with appropriate visibility and parameters. The documentation provides clear information about their expected behavior and effects.

For consistency, consider aligning the documentation style of both functions. The withdraw function includes a @param tag, while the deposit function doesn't have any parameters to document. You could add a @notice tag to the deposit function for consistency:

/// @notice Deposits native tokens in exchange for wrapped ERC20 token.
/// @dev After execution of this function the SetBalance function
/// @dev burns the tokens and increases the contract balance of the ERC20 tokens.
/// @dev Emits a Deposit Event.
function deposit() external payable;

This change would make the documentation style more consistent across both functions.

precompiles/werc20/werc20.go (5)

38-41: Define gas cost constants with consistent naming.

Consider following a consistent naming convention for the gas cost constants to improve code readability. For example, you can use either DepositRequiredGas and WithdrawRequiredGas or RequiredGasDeposit and RequiredGasWithdraw.

Apply this diff to update the constants:

-	DepositRequiredGas uint64 = 23_878
-	WithdrawRequiredGas uint64 = 9207
+	RequiredGasDeposit uint64 = 23_878
+	RequiredGasWithdraw uint64 = 9_207

46-48: Handle error when loading ABI more precisely.

In the LoadABI function, consider wrapping the error with additional context to make debugging easier.

Modify the function to include context in the error:

 func LoadABI() (abi.ABI, error) {
-	return cmn.LoadABI(f, abiPath)
+	abi, err := cmn.LoadABI(f, abiPath)
+	if err != nil {
+		return abi, fmt.Errorf("failed to load ABI from %s: %w", abiPath, err)
+	}
+	return abi, nil
 }

58-61: Check for nil before returning error.

After calling LoadABI(), it's good practice to check if the returned ABI is valid before proceeding.

Ensure the ABI is valid:

 if err != nil {
     return nil, err
 }
+if newABI == nil {
+    return nil, fmt.Errorf("ABI loaded is nil")
+}

68-70: Assign ABI directly to the ERC20 precompile.

Since erc20Precompile embeds Precompile, you can assign the ABI directly to erc20Precompile.ABI for clarity.

Apply this diff:

-	// use the IWERC20 ABI
-	erc20Precompile.Precompile.ABI = newABI
+	// Use the IWERC20 ABI
+	erc20Precompile.ABI = newABI

146-154: Leverage embedded IsTransaction method consistently.

In the IsTransaction method, after checking for DepositMethod and WithdrawMethod, the default case calls p.Precompile.IsTransaction(methodName). Since Precompile embeds erc20.Precompile, which may already handle these methods, consider whether the explicit checks are necessary.

If erc20.Precompile does not handle DepositMethod and WithdrawMethod, it's fine to keep the explicit checks. Otherwise, you can simplify the method:

 func (p Precompile) IsTransaction(methodName string) bool {
-	switch methodName {
-	case DepositMethod, WithdrawMethod:
-		return true
-	default:
-		return p.Precompile.IsTransaction(methodName)
-	}
+	return p.Precompile.IsTransaction(methodName)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b523bb1 and 1366276.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • precompiles/werc20/IWERC20.sol (1 hunks)
  • precompiles/werc20/abi.json (1 hunks)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
  • x/evm/keeper/static_precompiles.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (17)
precompiles/werc20/tx.go (1)

1-4: LGTM: Copyright, license, and package declaration are correct.

The copyright notice, SPDX license identifier, and package declaration are properly formatted and appropriate for this file.

precompiles/werc20/IWERC20.sol (2)

1-2: LGTM: Appropriate license and Solidity version.

The LGPL-3.0-only license is suitable for an open-source project, and the Solidity version (>=0.8.18) is recent, ensuring access to the latest language features and security improvements.


10-18: LGTM: Well-defined and documented events.

The Deposit and Withdrawal events are properly defined with appropriate parameters. The use of indexed for address parameters is a good practice for efficient event filtering. The documentation for each event is clear and informative, following good NatSpec conventions.

precompiles/werc20/abi.json (5)

1-5: LGTM: Contract metadata is correctly defined.

The contract metadata is properly structured and includes the correct contract name "IWERC20" and source file path. This follows the standard format for Hardhat artifacts.


6-43: LGTM: Event definitions are correct and follow best practices.

The "Deposit" and "Withdrawal" events are properly defined with appropriate parameters:

  1. Both events use an indexed address parameter for efficient event filtering.
  2. The "wad" parameter (representing the amount) is correctly defined as a non-indexed uint256.

These definitions align with standard practices for wrapped token contracts.


44-71: LGTM: Function definitions are correct and follow WERC20 standards.

The function definitions are properly structured and include:

  1. Payable fallback and receive functions, allowing the contract to accept native tokens.
  2. A payable deposit() function with no parameters, enabling users to wrap native tokens.
  3. A nonpayable withdraw(uint256 wad) function, allowing users to unwrap tokens.

These definitions align with the expected functionality of a wrapped token contract.


73-76: LGTM: Bytecode and link references are correctly empty.

The bytecode and link references are empty, which is expected for an interface contract like IWERC20. This is correct because:

  1. Interface contracts don't contain implementation code.
  2. There are no external libraries to link for this contract.

1-77: LGTM: WERC20 ABI is correctly defined and follows best practices.

The abi.json file successfully defines the Application Binary Interface (ABI) for the IWERC20 contract. It includes:

  1. Correct contract metadata.
  2. Properly defined "Deposit" and "Withdrawal" events.
  3. Appropriate function definitions for deposit(), withdraw(uint256), and payable fallback/receive functions.
  4. Correctly empty bytecode and link references.

This ABI definition provides a solid foundation for interacting with the WERC20 precompile in the Evmos ecosystem.

CHANGELOG.md (5)

Line range hint 42-47: State Machine Breaking changes look significant and well-documented.

The changes for v16.0.0 include several state machine breaking updates, such as:

  • Adding a new precompile for the secp256r1 curve
  • Introducing new custom transactions for distribution and staking modules
  • Adding a bech32 conversion precompile
  • Restricting transaction fee tokens

These changes are clearly explained and include references to the relevant pull requests, which is good practice for changelogs.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 49-77: Improvements section is comprehensive and well-organized.

The improvements section for v16.0.0 covers a wide range of updates, including:

  • Refactoring of various modules (vesting, inflation, incentives, claims, revenue)
  • Updates to dependencies and Go version
  • Additions to CLI functionality
  • Improvements to testing and CI processes

The entries are concise yet informative, and include pull request references. This follows good changelog practices.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 79-85: Bug Fixes section is present and well-documented.

The bug fixes section for v16.0.0 includes several important fixes, such as:

  • Updating Ledger supported algorithms
  • Fixing CLI issues
  • Addressing performance concerns

Each fix is clearly described and includes a reference to the relevant pull request.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 1-85: Overall changelog structure and formatting is consistent and follows best practices.

The changelog:

  • Uses reverse chronological order
  • Categorizes changes (State Machine Breaking, API Breaking, Improvements, Bug Fixes)
  • Includes version numbers and release dates
  • Provides concise descriptions of changes
  • Includes pull request references

This structure makes it easy for users and developers to understand the evolution of the project.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 1-1161: The CHANGELOG.md file is well-maintained and informative.

This changelog effectively documents the evolution of the Evmos project:

  • It follows a consistent structure across versions
  • Changes are categorized clearly (State Machine Breaking, API Breaking, Improvements, Bug Fixes)
  • Entries are concise yet informative
  • Pull request references are included for traceability
  • The most recent changes (v16.0.0) are well-documented, highlighting significant updates and breaking changes

The maintenance of this changelog demonstrates a commitment to clear communication with users and developers about the project's progress and changes.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)

precompiles/werc20/werc20.go (1)

83-85: ⚠️ Potential issue

Verify and update the hardcoded gas values.

The gas values for DepositRequiredGas and WithdrawRequiredGas are currently placeholders obtained from Remix. The TODO comment indicates that we should execute the transactions on the Evmos testnet to ensure parity in the values.

Please verify these gas values by executing the transactions on the Evmos testnet and update the constants accordingly.

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

25-27: Proper Addition of Imports for WERC20 Precompile

The new imports for werc20 and erc20types are correctly added to support the WERC20 precompile integration.


100-110: Correct Initialization of Wevmos Precompile

The wevmosPrecompile is properly instantiated with the tokenPair and necessary keepers (bankKeeper, authzKeeper, transferKeeper). Error handling is consistent with existing patterns, panicking on instantiation failure.


122-122: Ensure Unique Address for wevmosPrecompile

Verify that wevmosPrecompile.Address() does not conflict with existing precompile addresses in the precompiles map to prevent unintended overwriting.

Run the following script to check for duplicate addresses:

✅ Verification successful

Verification Successful: wevmosPrecompile.Address() is Unique

The address for wevmosPrecompile is added only once to the precompiles map, ensuring no conflicts with existing precompile addresses.

  • static_precompiles.go: precompiles[wevmosPrecompile.Address()]
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Ensure that wevmosPrecompile's address is unique in the precompiles map.

# Command: Search for all addresses added to the precompiles map.
rg --type go 'precompiles\[.*\.Address\(\)\]' -o

# Expected Result: Each address should be unique. Confirm that `wevmosPrecompile.Address()` is not duplicated elsewhere.

Length of output: 731

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

🧹 Outside diff range and nitpick comments (12)
precompiles/werc20/tx.go (3)

6-13: LGTM: Well-defined constants with clear documentation.

The constants DepositMethod and WithdrawMethod are well-named and their purpose is clearly documented. Using constants for method names is a good practice for maintainability.

Consider adding a brief comment above the const block to explain the purpose of these constants in the context of the WERC20 precompile. This would provide a quick overview for developers new to the file.


15-20: LGTM: Deposit method implemented as described.

The Deposit method is correctly implemented as a no-op function, matching the description in the comments. It provides the expected interface compatibility with the WETH contract.

Consider adding a TODO comment within the function body to indicate that this is a placeholder implementation. This can help future developers understand that the function might need to be updated in the future. For example:

func (p Precompile) Deposit() ([]byte, error) {
    // TODO: Implement actual deposit logic if needed in the future
    return nil, nil
}

22-27: LGTM: Withdraw method implemented as described.

The Withdraw method is correctly implemented as a no-op function, matching the description in the comments. It provides the expected interface compatibility with the WETH contract.

Similar to the Deposit method, consider adding a TODO comment within the function body:

func (p Precompile) Withdraw() ([]byte, error) {
    // TODO: Implement actual withdraw logic if needed in the future
    return nil, nil
}

Additionally, since both Deposit and Withdraw methods have identical implementations, you might want to consider adding a comment explaining why they are separate methods despite having the same behavior. This could help prevent future confusion or accidental merging of the methods.

precompiles/werc20/IWERC20.sol (1 10000 )

4-9: LGTM: Well-documented interface with a minor suggestion.

The interface is well-documented using NatSpec comments, providing clear information about its purpose. This follows good practices for code documentation.

Consider adding a @notice tag to provide a brief explanation of the interface's functionality, which can be useful for automatic documentation generation:

/**
 * @author Evmos Team
 * @title Wrapped ERC20 Interface
 * @dev Interface for representing the native EVM token as ERC20 standard.
 * @notice This interface defines the contract for wrapping and unwrapping native EVM tokens to ERC20 tokens.
 */
precompiles/werc20/abi.json (2)

5-43: LGTM: Event definitions are correct and follow best practices.

The "Deposit" and "Withdrawal" events are properly defined with appropriate parameters. The use of indexed addresses allows for efficient event filtering.

Consider adding a comment in the source Solidity file to explain that "wad" represents the amount in the smallest unit of the token (e.g., Wei for Ether).


44-71: LGTM: Function definitions are correct and cover essential WERC20 operations.

The fallback, deposit, withdraw, and receive functions are properly defined with appropriate mutability. This allows for wrapping and unwrapping of native tokens as expected in a WERC20 contract.

Consider adding a balanceOf function to allow users to check their WERC20 token balance. This is a common feature in WERC20 implementations and improves usability.

{
  "inputs": [{"internalType": "address", "name": "account", "type": "address"}],
  "name": "balanceOf",
  "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}],
  "stateMutability": "view",
  "type": "function"
}
CHANGELOG.md (4)

Line range hint 42-93: Comprehensive "Unreleased" section with room for improvement

The "Unreleased" section provides a detailed overview of upcoming changes, which is excellent for keeping users informed. It's well-organized into "State Machine Breaking", "Improvements", and "Bug Fixes" subsections.

To further enhance this section:

  1. Consider adding a brief summary at the beginning of the "Unreleased" section to highlight the most significant changes.
  2. For each entry, it would be helpful to add a short explanation of the impact or benefit of the change, especially for non-technical users.
🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 95-160: Well-documented v15.0.0 release with significant changes

The v15.0.0 release section provides a comprehensive list of changes, including API breaking and state machine breaking changes. This level of detail is crucial for users upgrading from previous versions.

Suggestion for improvement:
Consider adding a migration guide or linking to one for this major version change. This would greatly assist users in navigating the breaking changes and ensuring a smooth upgrade process.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 162-235: Contrast in detail between v14.1.0 and v14.0.0 releases

The changelog effectively distinguishes between the minor v14.1.0 patch release and the major v14.0.0 release. The v14.0.0 section provides a comprehensive list of changes across different categories, which is commendable.

Suggestion for improvement:
For the v14.1.0 release, consider adding a brief note explaining why this specific bug fix warranted a new release. This context can help users understand the importance of the patch.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 237-1115: Comprehensive historical changelog with room for improved navigation

The inclusion of detailed changelogs for all previous versions, dating back to v0.1.0, is exemplary. This level of detail allows users to understand the project's evolution and helps with troubleshooting version-specific issues.

Suggestion for improvement:
To enhance readability and navigation, consider adding a table of contents at the beginning of the file with links to each version. This would allow users to quickly jump to the version they're interested in, especially useful in such a long changelog.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)

precompiles/werc20/werc20.go (2)

22-22: Ensure consistent naming of WERC20 throughout the code

There is an inconsistency in naming: both "WERC-20" and "WERC20" are used in comments. For clarity and consistency, please choose one naming convention and use it consistently throughout the code and comments.

Also applies to: 33-33


83-85: Address TODO comment regarding gas values

The TODO comment indicates that the gas values for DepositRequiredGas and WithdrawRequiredGas were obtained from Remix using WEVMOS9.sol. It is important to verify these gas values on the Evmos testnet to ensure they are accurate and prevent any mismatches in gas estimation.

Would you like assistance in verifying these gas values on the Evmos testnet? I can help outline the steps or open a GitHub issue to track this task.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b523bb1 and 1366276.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • precompiles/werc20/IWERC20.sol (1 hunks)
  • precompiles/werc20/abi.json (1 hunks)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
  • x/evm/keeper/static_precompiles.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (13)
precompiles/werc20/tx.go (2)

1-4: LGTM: Copyright, license, and package declaration are correct.

The file starts with the appropriate copyright notice, SPDX license identifier, and package declaration. This follows best practices for code organization and licensing.


1-27: Overall assessment: Well-structured and documented WERC20 precompile implementation.

This file introduces the necessary constants and methods for the WERC20 precompile. The code is well-structured, with clear documentation for each component. The no-op implementations of Deposit and Withdraw methods are consistent with the described behavior, providing interface compatibility with the WETH contract.

To ensure that this implementation is consistent with other parts of the codebase, please run the following verification script:

This script will help identify any potential inconsistencies or areas that might need attention in relation to the WERC20 precompile implementation.

precompiles/werc20/IWERC20.sol (3)

1-2: LGTM: Appropriate license and Solidity version.

The LGPL-3.0-only license is suitable for an open-source project, and the Solidity version (>=0.8.18) is recent, ensuring access to the latest language features and security improvements.


10-18: LGTM: Well-defined and documented events.

The Deposit and Withdrawal events are well-defined and follow standard naming conventions. The use of indexed parameters for addresses is appropriate for efficient event filtering. The NatSpec documentation clearly explains the purpose and parameters of each event.


1-38: Overall, well-structured interface with minor improvements suggested.

The IWERC20 interface provides a solid foundation for implementing a Wrapped ERC20 token. It's well-documented and follows good Solidity practices. To further improve the interface:

  1. Clarify the relationship with the SetBalance function mentioned in comments.
  2. Consider adding return values to deposit and withdraw functions.
  3. Ensure implementing contracts handle the behavior of fallback and receive functions as intended.

These improvements will enhance the clarity and usability of the interface for developers implementing or interacting with WERC20 tokens.

precompiles/werc20/abi.json (3)

1-4: LGTM: Contract metadata is correctly defined.

The contract metadata is properly structured and includes the necessary information such as the contract name and source file location.


73-76: LGTM: Bytecode and link references are correctly empty.

For an interface contract like IWERC20, it's expected and correct to have empty bytecode and link references.


1-77: Overall assessment: The IWERC20 ABI is well-defined and follows best practices.

The ABI correctly defines the interface for a WERC20 token, including essential functions (deposit, withdraw) and events (Deposit, Withdrawal). The contract metadata, function mutability, and event indexing are all properly set.

While the current implementation is solid, consider the following suggestions for further improvement:

  1. Add comments in the Solidity source file to explain terminology (e.g., "wad").
  2. Consider adding a balanceOf function to enhance usability.

These suggestions aside, the ABI is ready for use in its current form.

CHANGELOG.md (2)

Line range hint 1-1115: Well-structured and consistent changelog

The overall structure and consistency of the CHANGELOG.md file are commendable. Key strengths include:

  1. Consistent formatting across all versions
  2. Clear categorization of changes (e.g., "State Machine Breaking", "API Breaking", "Improvements", "Bug Fixes")
  3. Inclusion of links to relevant issues and pull requests for most entries

This structure makes it easy for users and developers to understand the evolution of the project and find specific changes they're interested in.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 1-1115: Summary: Well-maintained CHANGELOG.md with minor suggestions for improvement

Overall, the CHANGELOG.md file is exemplary in its detail, consistency, and structure. It provides a comprehensive history of the project's evolution, which is invaluable for users and developers alike. The suggested improvements, such as adding a table of contents and providing more context for certain changes, are minor and aimed at further enhancing an already strong document.

Key strengths:

  1. Detailed documentation of changes for each version
  2. Consistent structure and categorization
  3. Inclusion of links to relevant issues and pull requests

Suggested improvements:

  1. Add a table of contents for easier navigation
  2. Provide more context for significant changes, especially in major releases
  3. Consider adding brief summaries for "Unreleased" sections

These enhancements would further improve the user experience and the overall value of the changelog.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)

precompiles/werc20/werc20.go (1)

98-104: ⚠️ Potential issue

Define constants DepositMethod and WithdrawMethod

The constants DepositMethod and WithdrawMethod are used but not defined in this file. This will result in compilation errors. Please define these constants with the appropriate string values corresponding to the method names in the ABI.

You can run the following script to check if DepositMethod and WithdrawMethod are defined elsewhere in the codebase:

Also applies to: 122-123, 125-126, 149-150

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

25-27: Approved: Necessary imports added

The new import statements for werc20, erc20Keeper, and erc20types are appropriate and necessary for the added functionality.


122-122: Approved: Added wevmosPrecompile to precompiles map

The wevmosPrecompile is correctly added to the precompiles map, ensuring it's available for use in the EVM module.

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

🧹 Outside diff range and nitpick comments (9)
precompiles/werc20/tx.go (2)

6-13: LGTM: Well-defined constants with clear comments.

The constants DepositMethod and WithdrawMethod are appropriately named and documented. Using constants for method names is a good practice for maintainability.

Consider using backticks for the constant values to prevent any potential escaping issues:

-	DepositMethod = "deposit"
+	DepositMethod = `deposit`
-	WithdrawMethod = "withdraw"
+	WithdrawMethod = `withdraw`

15-27: LGTM: Well-implemented mock functions with clear explanations.

The Deposit and Withdraw methods are correctly implemented as no-op functions, aligning with their intended purpose as mock functions. The comments provide clear explanations of their role in supporting equality between the native coin and its wrapped ERC-20.

For consistency with Go's standard library and common practices, consider returning nil explicitly for both return values:

 func (p Precompile) Deposit() ([]byte, error) {
-	return nil, nil
+	return nil, nil
 }

 func (p Precompile) Withdraw() ([]byte, error) {
-	return nil, nil
+	return nil, nil
 }

This makes it clear that we're intentionally returning nil for both the byte slice and the error.

precompiles/werc20/IWERC20.sol (3)

4-9: LGTM: Well-documented interface with a minor suggestion.

The interface is well-documented using NatSpec comments, providing clear information about its purpose and authorship. This follows good documentation practices.

Consider adding a @notice tag to provide a brief, one-line description of the interface. This can improve documentation generation and readability. For example:

/**
 * @notice Interface for a Wrapped ERC20 token representing the native EVM token
 * @author Evmos Team
 * @title Wrapped ERC20 Interface
 * @dev Interface for representing the native EVM token as ERC20 standard.
 */

20-24: LGTM: Fallback and receive functions with a suggestion for clarity.

The inclusion of both fallback() and receive() functions ensures compatibility with different methods of sending Ether to the contract. This is a good practice for handling incoming transactions.

For improved clarity, consider updating the documentation to reflect that the interface doesn't implement the actual call to deposit(). You could modify the comments as follows:

/// @dev Default fallback payable function. Should call the deposit method in the implementation.
fallback() external payable;

/// @dev Default receive payable function. Should call the deposit method in the implementation.
receive() external payable;

This clarifies that the actual implementation of these functions should include the call to deposit().


26-37: LGTM: Well-defined deposit and withdraw functions with a minor suggestion.

The deposit() and withdraw(uint256) functions are well-defined and properly documented. The function signatures are appropriate for their intended use, and the documentation clearly explains the expected behavior, including interactions with the SetBalance function and event emissions.

For consistency with the Deposit event, consider renaming the wad parameter in the Withdrawal event to amount. This would make the terminology more uniform across the interface. For example:

event Withdrawal(address indexed src, uint256 amount);

And update the withdraw function accordingly:

function withdraw(uint256 amount) external;

This change would improve the consistency of the terminology used throughout the interface.

precompiles/werc20/abi.json (1)

44-71: LGTM: Functions are correctly defined, with a minor suggestion.

The fallback, receive, deposit, and withdraw functions are correctly defined and match the expected behavior of a Wrapped Ether (WETH) contract. The payable and non-payable modifiers are appropriately used.

Consider adding a balanceOf(address) function to the ABI to allow querying of wrapped token balances, which is a standard feature in WETH contracts.

CHANGELOG.md (1)

Line range hint 42-93: Consider adding more context to some changelog entries

The "Unreleased" section provides a good overview of the upcoming changes. However, some entries could benefit from additional context or explanation:

  1. In the "State Machine Breaking" subsection:

    • For the WERC20 precompile re-addition, it would be helpful to briefly explain why it was removed and why it's being re-added.
    • For the removal of automatic withdrawal of staking rewards, consider explaining the rationale behind this change and its potential impact on users.
  2. In the "Improvements" subsection:

    • For entries related to outposts (Stride and Osmosis), it would be beneficial to provide a brief explanation of what outposts are and their significance in the Evmos ecosystem.
  3. In the "Bug Fixes" subsection:

    • For the fix related to burned cosmos transactions fees metric, consider explaining the importance of this metric and how the fix improves it.

Adding this additional context would make the changelog more informative for users and developers.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)

precompiles/werc20/werc20.go (2)

23-23: Consider renaming abiPath for clarity

The constant abiPath is set to "abi.json", which is specific to the WERC20 precompile. Renaming it to werc20ABIPath can improve code readability and maintainability.

Apply this diff:

-const abiPath = "abi.json"
+const werc20ABIPath = "abi.json"

Remember to update all references to this constant within the file.


83-85: Update TODO comment to reference the correct contract

The TODO comment mentions WEVMOS9.sol, which may not be relevant for WERC20. Clarify the comment to reference the appropriate contract or file related to WERC20.

Apply this diff:

-// TODO: these values were obtained from Remix using the WEVMOS9.sol.
+// TODO: These gas values were obtained from Remix using the WERC20 contract.
 // We should execute the transactions from Evmos testnet
 // to ensure parity in the values.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b523bb1 and 1366276.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • precompiles/werc20/IWERC20.sol (1 hunks)
  • precompiles/werc20/abi.json (1 hunks)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
  • x/evm/keeper/static_precompiles.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (14)
precompiles/werc20/tx.go (2)

1-5: LGTM: Proper license and package declaration.

The file correctly starts with the copyright notice, SPDX license identifier, and appropriate package declaration.


1-27: Overall: Well-implemented WERC20 boilerplate.

This file successfully reintroduces the WERC20 boilerplate as intended in the PR objectives. The constants and mock functions provide a clear interface for interacting with a wrapped ERC-20 token, specifically designed to support equality between the native coin (EVMOS) and its wrapped counterpart (WEVMOS).

The code is well-structured, properly documented, and aligns with the goal of enhancing the functionality of available static precompiles in the Evmos blockchain framework.

To ensure this implementation doesn't conflict with any existing code, let's verify that these method names are unique within the project:

This will help us confirm that we're not overriding any existing functionality.

✅ Verification successful

Verification Complete: Deposit and Withdraw methods are unique.

The Deposit and Withdraw methods in precompiles/werc20/tx.go do not conflict with any existing implementations within the project. There are no duplicate or conflicting method names found, ensuring that the new methods function as intended without overriding existing functionalities.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any existing implementations of Deposit and Withdraw methods

echo "Checking for existing Deposit methods:"
rg --type go -A 5 'func.*Deposit\('

echo "Checking for existing Withdraw methods:"
rg --type go -A 5 'func.*Withdraw\('

Length of output: 2443

precompiles/werc20/IWERC20.sol (3) 8000

1-2: LGTM: Appropriate license and Solidity version.

The LGPL-3.0-only license is suitable for an open-source project, and the Solidity version (>=0.8.18) is recent, ensuring access to the latest language features and security improvements.


10-18: LGTM: Well-defined and documented events.

The Deposit and Withdrawal events are well-defined and properly documented. The use of indexed parameters for addresses allows for efficient event filtering, which is crucial for tracking token movements. The documentation clearly explains the purpose and parameters of each event.


1-38: Overall: Well-designed WERC20 interface with minor suggestions for improvement.

The IWERC20 interface is well-structured and provides a solid foundation for implementing a Wrapped ERC20 token. It includes all necessary functions and events, with clear documentation. The suggestions made throughout the review are minor and focus on improving clarity, consistency, and documentation. These changes would enhance the overall quality of the interface without altering its core functionality.

Great job on creating a comprehensive and well-documented interface for the WERC20 token!

precompiles/werc20/abi.json (3)

1-4: LGTM: Metadata section is correct and consistent.

The metadata section correctly defines the contract name as "IWERC20" and provides the appropriate source file path. The format "hh-sol-artifact-1" indicates this is a Hardhat artifact, which is suitable for defining the ABI of a precompiled contract.


5-43: LGTM: Events are well-defined and follow standard patterns.

The Deposit and Withdrawal events are correctly defined with appropriate parameters. The use of indexed addresses allows for efficient filtering of events. The naming convention (dst/src for addresses, wad for amounts) is consistent with common Ethereum practices.


73-77: LGTM: Bytecode and link references are correctly empty.

The empty bytecode and link references are appropriate for an interface or precompiled contract. This indicates that the actual implementation will be provided by the blockchain's precompiled contracts rather than deployed as a separate smart contract.

CHANGELOG.md (4)

Line range hint 95-139: LGTM: v15.0.0 release section is well-documented

The v15.0.0 release section is comprehensive and well-organized. It clearly outlines the API Breaking changes, State Machine Breaking changes, Improvements, and Bug Fixes. The information provided is sufficient for users and developers to understand the significant changes in this release.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 141-211: LGTM: v14.1.0 and v14.0.0 release sections are well-documented

The v14.1.0 and v14.0.0 release sections are well-organized and provide clear information about the changes:

  1. v14.1.0 correctly identifies a specific bug fix.
  2. v14.0.0 comprehensively covers State Machine Breaking changes, API Breaking changes, Improvements, and Bug Fixes.

The level of detail provided is appropriate for users and developers to understand the scope and impact of these releases.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 213-1034: LGTM: Historical release sections are well-maintained

The changelog sections for releases from v13.0.2 down to v0.1.0 are well-maintained and provide a comprehensive history of the project's evolution:

  1. Consistent structure across all releases, categorizing changes into appropriate sections (e.g., "State Machine Breaking", "Improvements", "Bug Fixes").
  2. Clear and concise descriptions of changes, often with links to relevant pull requests.
  3. Proper versioning, allowing users to easily track changes between releases.

This historical record is valuable for users and developers who need to understand the project's development over time or track down when specific features or fixes were introduced.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)


Line range hint 1-1034: LGTM: CHANGELOG.md structure and formatting follow best practices

The overall structure and formatting of the CHANGELOG.md file adhere to best practices:

  1. Follows the "Keep a Changelog" format, which is a widely accepted standard.
  2. Includes a helpful comment at the top explaining the principles and usage of the changelog.
  3. Releases are listed in reverse chronological order, making it easy to find the most recent changes.
  4. Each release section is clearly marked with a version number and release date.
  5. Changes are consistently categorized (e.g., "State Machine Breaking", "Improvements", "Bug Fixes").

This structure makes the changelog easy to read and maintain, benefiting both users and contributors of the project.

🧰 Tools
🪛 Markdownlint

45-45: Expected: 120; Actual: 136
Line length

(MD013, line-length)

precompiles/werc20/werc20.go (1)

117-117: Confirm correct usage of deferred HandleGasError

The defer cmn.HandleGasError(ctx, contract, initialGas, &err)() statement ensures that gas errors are handled gracefully. Verify that this usage aligns with the intended error handling strategy.

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

122-122: WEVMOS precompile added to available precompiles

The wevmosPrecompile is correctly added to the precompiles map, making it available as a static precompiled contract.

@fedekunze fedekunze marked this pull request as draft October 18, 2024 08:44
Copy link
Collaborator
@fedekunze fedekunze left a comment

Choose a reason for hiding this comment

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

please address the coderabbit comments

@Vvaradinov Vvaradinov marked this pull request as ready for review October 22, 2024 07:03
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1366276 and af01cc8.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • precompiles/werc20/IWERC20.sol (1 hunks)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG.md
  • precompiles/werc20/IWERC20.sol
  • precompiles/werc20/werc20.go
🧰 Additional context used
🔇 Additional comments (2)
precompiles/werc20/tx.go (2)

1-21: LGTM: Package structure and imports are well-defined

The package declaration, imports, and constants are appropriately structured and documented. The use of relevant Cosmos SDK and Ethereum packages aligns with the expected functionality of a WERC20 implementation.


23-41: 🛠️ Refactor suggestion

Verify the intended behavior of the Deposit function

The current implementation of Deposit sends the deposited coins back to the sender, which seems to contradict typical deposit behavior. While this aligns with a previous review comment, it's worth confirming if this is the intended functionality.

Additionally, consider emitting an event to track deposit attempts, which could be useful for monitoring and auditing purposes.

If the current behavior is intended, consider adding a comment explaining the rationale. If not, here's a suggested modification:

 func (p Precompile) Deposit(ctx sdk.Context, contract *vm.Contract) ([]byte, error) {
     // Get the deposited amount from the contract value
     depositedAmount := contract.Value()
 
     // Get the sender's address
     sender := common.BytesToAddress(contract.Caller().Bytes())
     senderAccAddress := sdk.AccAddress(sender.Bytes())
     precompileAccAddr := sdk.AccAddress(p.Address().Bytes())
 
-    // Send the coins back to the sender
-    err := p.bankKeeper.SendCoins(ctx, precompileAccAddr, senderAccAddress, sdk.NewCoins(sdk.NewCoin(types.GetEVMCoinDenom(), math.NewIntFromBigInt(depositedAmount))))
+    // Transfer the coins from the sender to the contract
+    err := p.bankKeeper.SendCoins(ctx, senderAccAddress, precompileAccAddr, sdk.NewCoins(sdk.NewCoin(types.GetEVMCoinDenom(), math.NewIntFromBigInt(depositedAmount))))
     if err != nil {
         return nil, err
     }
 
+    // Emit a deposit event
+    ctx.EventManager().EmitEvent(
+        sdk.NewEvent(
+            "werc20_deposit",
+            sdk.NewAttribute("sender", senderAccAddress.String()),
+            sdk.NewAttribute("amount", depositedAmount.String()),
+        ),
+    )
+
     return nil, nil
 }

This modification would make the Deposit function behave more like a typical deposit operation and include event emission for tracking.

Co-authored-by: MalteHerrmann <42640438+MalteHerrmann@users.noreply.github.com>
Signed-off-by: stepit <48993133+0xstepit@users.noreply.github.com>
Co-authored-by: MalteHerrmann <42640438+MalteHerrmann@users.noreply.github.com>
Signed-off-by: stepit <48993133+0xstepit@users.noreply.github.com>
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: 0

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

Line range hint 42-56: Critical: Parameter name mismatch causing compilation error

The function parameter is named hasWrappedMethods but the code uses isNative in the conditional check, causing compilation errors. The parameter name should be consistent throughout the function.

Apply this fix:

-func (k Keeper) InstantiateERC20Precompile(ctx sdk.Context, contractAddr common.Address, hasWrappedMethods bool) (vm.PrecompiledContract, error) {
+func (k Keeper) InstantiateERC20Precompile(ctx sdk.Context, contractAddr common.Address, isNative bool) (vm.PrecompiledContract, error) {

Also update the documentation to reflect the correct parameter name:

-// If the `hasWrappedMethods` boolean is true, the ERC20 instance returned
-// exposes methods for `withdraw` and `deposit` as it is common for wrapped tokens.
+// If the `isNative` boolean is true, the ERC20 instance returned will be
+// a wrapped token implementation with additional `withdraw` and `deposit` methods.
🧰 Tools
🪛 GitHub Check: build

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: test-unit-cover

[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative

🪛 GitHub Check: test-solidity

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: dependency-review

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: Run golangci-lint

[failure] 54-54:
undefined: isNative (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)


61-64: Enhance documentation clarity

The documentation could be more explicit about the types of precompiles. Consider clarifying the distinction between native and dynamic precompiles.

Suggested improvement:

-// The available ERC-20 precompiles consist of the dynamic precompiles and the native
-// ones.
+// The available ERC-20 precompiles are of two types:
+// 1. Native precompiles: Built-in token contracts that support wrapping functionality
+// 2. Dynamic precompiles: User-registered token contracts with standard ERC20 functionality
precompiles/werc20/tx.go (3)

36-38: Consider handling zero-value deposits

The function accepts deposits of any value, including zero. Consider adding a validation check for zero-value deposits to prevent unnecessary state updates and gas consumption.

 caller := contract.Caller()
 depositedAmount := contract.Value()
+if depositedAmount.Sign() == 0 {
+    return nil, fmt.Errorf("cannot deposit zero amount")
+}

71-74: Enhance mock implementation transparency

While the mock implementation is intentional (as documented), it would be beneficial to add logging to make it clear to users that this is a no-op function.

 // Withdraw is a no-op and mock function that provides the same interface as the
 // WETH contract to support equality between the native coin and its wrapped
 // ERC-20 (e.g. EVMOS and WEVMOS).
-func (p Precompile) Withdraw(ctx sdk.Context, contract *vm.Contract, stateDB vm.StateDB, args []interface{}) ([]byte, error) {
+func (p Precompile) Withdraw(ctx sdk.Context, contract *vm.Contract, stateDB vm.StateDB, args []interface{}) ([]byte, error) {
+    // Log that this is a mock implementation
+    p.Logger.Debug("executing mock withdraw function - no actual withdrawal will occur")

84-86: Optimize error message construction

The error message uses string formatting even when the error condition isn't met. Consider using errors.New for static messages or wrapping the formatting in a separate function to avoid unnecessary string concatenation.

-if nativeBalance.Amount.LT(amountInt) {
-    return nil, fmt.Errorf("account balance %v is lower than withdraw balance %v", nativeBalance.Amount, amountInt)
+if nativeBalance.Amount.LT(amountInt) {
+    return nil, p.insufficientBalanceError(nativeBalance.Amount, amountInt)
 }

+// Add this helper method to the Precompile struct
+func (p Precompile) insufficientBalanceError(balance, amount math.Int) error {
+    return fmt.Errorf("account balance %v is lower than withdraw balance %v", balance, amount)
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e3e4aaf and 2c9febd.

📒 Files selected for processing (4)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
  • x/erc20/keeper/precompiles.go (3 hunks)
  • x/erc20/types/params.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • precompiles/werc20/werc20.go
  • x/erc20/types/params.go
🧰 Additional context used
🪛 GitHub Check: build
x/erc20/keeper/precompiles.go

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: test-unit-cover
x/erc20/keeper/precompiles.go

[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative


[failure] 54-54:
undefined: isNative

🪛 GitHub Check: test-solidity
x/erc20/keeper/precompiles.go

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: dependency-review
x/erc20/keeper/precompiles.go

[failure] 54-54:
undefined: isNative

🪛 GitHub Check: Run golangci-lint
x/erc20/keeper/precompiles.go

[failure] 54-54:
undefined: isNative (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)


[failure] 54-54:
undefined: isNative) (typecheck)

🔇 Additional comments (3)
x/erc20/keeper/precompiles.go (3)

13-13: LGTM: Import added for wrapped ERC20 functionality

The werc20 import is correctly added to support the new wrapped token functionality.


24-35: LGTM: Improved control flow with early returns

The refactoring enhances readability and follows good practices:

  • Early return pattern for unavailable precompiles
  • Clear separation of concerns with proper vertical spacing
  • Explicit error wrapping for initialization failures

Line range hint 44-50: Verify token pair validation completeness

Let's ensure the token pair validation is comprehensive and secure.

✅ Verification successful

Based on the search results, I can see comprehensive validation of token pairs across the codebase. The key findings show:

  1. < 10000 p dir="auto">Token pair validation includes multiple checks:

    • ID existence check (if len(id) == 0)
    • Pair existence check (if !ok or if !found)
    • Error handling with detailed messages
    • Additional validation in IBC callbacks and proposals
  2. The precompile code in question follows the standard validation pattern used throughout the codebase:

    • Checks token pair ID existence
    • Verifies token pair existence
    • Returns appropriate error messages

The validation is consistent with other critical parts of the system like IBC callbacks, proposals, and queries. The implementation is secure and follows the established patterns.

Token pair validation is comprehensive and secure

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for additional validation on token pairs in the codebase

# Look for token pair validation patterns
rg -A 5 "GetTokenPair|ValidateTokenPair" 

# Check for potential security checks on token pairs
ast-grep --pattern 'func $_(pair $_, $_) {
  if $_ {
    return $_, $_
  }
  $$$
}'

Length of output: 25568

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (6)
x/erc20/keeper/precompiles.go (1)

Line range hint 38-57: LGTM: Clear separation of wrapped and regular token handling

The implementation correctly differentiates between wrapped and regular ERC20 tokens. The parameter name hasWrappedMethods is clear and self-documenting.

Consider a future refactoring to introduce an interface or abstract factory pattern for different token types, which could make it easier to add new token variants in the future.

precompiles/werc20/tx.go (1)

55-60: Optimize journal entries for contract calls

The balance change entries are only necessary when the precompile is called from another contract, not from an EOA. Consider optimizing this by checking the caller type.

+	// Add journal entries only for contract calls
+	if !stateDB.IsOrigin(caller) {
 		p.SetBalanceChangeEntries(
 			cmn.NewBalanceChangeEntry(caller, depositedAmount, cmn.Add),
 			cmn.NewBalanceChangeEntry(p.Address(), depositedAmount, cmn.Sub),
 		)
+	}
precompiles/werc20/integration_test.go (4)

485-487: Correct grammatical errors in test descriptions

In the DescribeTable entries, there are grammatical errors that can be improved for clarity:

  • Use "don't" instead of "dont"
  • Rephrase the descriptions for better readability

Apply this diff to correct the descriptions:

-Entry("it should not move funds and dont emit the event reverting before changing state", true, false),
+Entry("it should not move funds and doesn't emit the event when reverting before changing state", true, false),
-Entry("it should not move funds and dont emit the event reverting after changing state", false, true),
+Entry("it should not move funds and doesn't emit the event when reverting after changing state", false, true),

67-67: Consider using realistic gas limits in tests

The gas limit is set to an extremely high value (1_000_000_000_000). While this ensures that gas is not a bottleneck in tests, it may mask potential issues with gas consumption. Consider setting a realistic gas limit to help catch unexpected gas usage.


174-174: Use appropriate gas limits for contract deployment

Similarly, the gas limit for deploying contracts is set to a very high value. Adjusting it to a more practical value can improve test accuracy regarding gas consumption.


69-70: Check the Ret field in ethRes for execution results

After calling CallContractAndCheckLogs, it's good practice to check the Ret field in ethRes to verify that the contract execution returned the expected data.

🛑 Comments failed to post (2)
precompiles/werc20/tx.go (1)

30-35: 🛠️ Refactor suggestion

Remove unused parameter 'origin'

The origin parameter is not used in the function implementation. Consider removing it or documenting why it's needed for future use.

 func (p Precompile) Deposit(
 	ctx sdk.Context,
-	origin common.Address,
 	contract *vm.Contract,
 	stateDB vm.StateDB,
 ) ([]byte, error) {
📝 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.

func (p Precompile) Deposit(
	ctx sdk.Context,
	contract *vm.Contract,
	stateDB vm.StateDB,
) ([]byte, error) {
🧰 Tools
🪛 GitHub Check: Run golangci-lint

[failure] 32-32:
unused-parameter: parameter 'origin' seems to be unused, consider removing or renaming it as _ (revive)

precompiles/werc20/integration_test.go (1)

498-498: ⚠️ Potential issue

Safely convert big.Int to sdk.Int without overflow

Using transferAmount.Int64() may cause overflow if transferAmount is larger than the maximum value of int64. This could lead to incorrect token amounts being transferred.

Apply this diff to handle large transfer amounts safely:

-transferCoins := sdk.Coins{sdk.NewInt64Coin(is.wrappedCoinDenom, transferAmount.Int64())}
+transferCoins := sdk.Coins{sdk.NewCoin(is.wrappedCoinDenom, sdk.NewIntFromBigInt(transferAmount))}
📝 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.

				transferCoins := sdk.Coins{sdk.NewCoin(is.wrappedCoinDenom, sdk.NewIntFromBigInt(transferAmount))}

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

🧹 Outside diff range and nitpick comments (3)
x/erc20/keeper/precompiles.go (1)

Line range hint 44-59: Consider consistent error message formatting

The error messages use different formats:

  • "precompile id not found: %s"
  • "token pair not found: %s"

Consider standardizing the error message format for consistency.

-		return nil, fmt.Errorf("precompile id not found: %s", address)
+		return nil, fmt.Errorf("token pair ID not found: %s", address)
precompiles/werc20/tx.go (2)

27-65: Consider optimizing journal entries for EOA calls

The journal entries are only necessary when the precompile is called from another contract. Consider adding an optimization to skip these entries for EOA calls.

+ // Add the entries to the statedb journal only if caller is a contract
+ // since these entries are only needed for proper revert handling
+ if !stateDB.IsOrigin(caller) {
     p.SetBalanceChangeEntries(
         cmn.NewBalanceChangeEntry(caller, depositedAmount, cmn.Add),
         cmn.NewBalanceChangeEntry(p.Address(), depositedAmount, cmn.Sub),
     )
+ }

67-88: Enhance error message for insufficient balance

The error message for insufficient balance could be more user-friendly by including the denomination.

- return nil, fmt.Errorf("account balance %v is lower than withdraw balance %v", nativeBalance.Amount, amountInt)
+ return nil, fmt.Errorf("insufficient balance: account has %v%s, but tried to withdraw %v%s", 
+    nativeBalance.Amount, evmtypes.GetEVMCoinDenom(), 
+    amountInt, evmtypes.GetEVMCoinDenom())
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 43ddaa6 and 9f5d77d.

📒 Files selected for processing (4)
  • precompiles/werc20/integration_test.go (1 hunks)
  • precompiles/werc20/tx.go (1 hunks)
  • precompiles/werc20/werc20.go (1 hunks)
  • x/erc20/keeper/precompiles.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • precompiles/werc20/integration_test.go
  • precompiles/werc20/werc20.go
🔇 Additional comments (6)
x/erc20/keeper/precompiles.go (5)

13-13: LGTM: Import added for WERC20 precompile

The new import is correctly added and necessary for the wrapped ERC20 functionality.


24-35: LGTM: Improved control flow and readability

The refactoring enhances code clarity through:

  • Early return pattern for unavailable precompiles
  • Clear separation between availability check and instantiation
  • Proper vertical spacing

38-42: LGTM: Clear documentation and parameter naming

The method signature and documentation clearly indicate the purpose of the hasWrappedMethods parameter, making the code's intent obvious.


61-64: LGTM: Clear and accurate documentation

The documentation clearly explains the purpose and scope of available ERC20 precompiles.


54-56: Verify WERC20 precompile integration

Let's verify that all necessary WERC20 methods are properly exposed through the precompile.

precompiles/werc20/tx.go (1)

18-25: LGTM! Constants are well-defined and documented.

The ABI method names are clearly defined with appropriate documentation.

@0xstepit 0xstepit marked this pull request as draft November 13, 2024 10:26
auto-merge was automatically disabled November 13, 2024 10:26

Pull request was converted to draft

@0xstepit 0xstepit removed the request for review from fedekunze November 13, 2024 10:29
@0xstepit 0xstepit marked this pull request as ready for review November 13, 2024 10:29
@0xstepit 0xstepit requested review from fedekunze and removed request for fedekunze November 13, 2024 10:29
@Vvaradinov Vvaradinov requested a review from fedekunze November 13, 2024 10:30
@Vvaradinov Vvaradinov dismissed fedekunze’s stale review November 13, 2024 10:31

It's been reviewed by others already

@0xstepit 0xstepit removed the request for review from fedekunze November 13, 2024 10:31
@Vvaradinov Vvaradinov merged commit 8a595e2 into main Nov 13, 2024
49 of 51 checks passed
@Vvaradinov Vvaradinov deleted the Vvaradinov/re-add-werc20 branch November 13, 2024 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants
0