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

feat: pre-compilation get ERC20 token #949

Merged
merged 1 commit into from
Jan 24, 2025
Merged

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Jan 24, 2025

Summary by CodeRabbit

  • New Features

    • Added functionality to retrieve ERC20 token information by denomination
    • Introduced a new method to get ERC20 token address and enabled status
    • Enhanced crosschain contract with ERC20 token support
  • Improvements

    • Updated precompiled contract to include ERC20 token management
    • Extended keeper interfaces to support ERC20 token queries

Copy link

coderabbitai bot commented Jan 24, 2025

Walkthrough

This pull request introduces a comprehensive enhancement to the crosschain ERC20 token functionality across multiple files. The changes primarily focus on adding a new method GetERC20Token that allows retrieving an ERC20 token's address and enabled status based on a denomination. The implementation spans both Go and Solidity codebases, involving updates to precompiled contracts, interfaces, and test suites to support this new feature.

Changes

File Change Summary
app/keepers/keepers.go Added Erc20Keeper as a parameter in NewAppKeeper function
contract/crosschain.go Introduced GetERC20TokenArgs type with Denom validation
contract/crosschain_precompile.go Added GetERC20Token method to CrosschainPrecompileKeeper
precompiles/crosschain/contract.go Updated NewPrecompiledContract to include erc20Keeper
precompiles/crosschain/keeper.go Added erc20Keeper field to Keeper struct
precompiles/types/expected_keepers.go Added GetERC20Token method to Erc20Keeper interface
solidity/contracts/interfaces/ICrosschain.sol Added getERC20Token function to interface

Sequence Diagram

sequenceDiagram
    participant Client
    participant CrosschainContract
    participant Keeper
    participant Erc20Keeper

    Client->>CrosschainContract: getERC20Token(denom)
    CrosschainContract->>Keeper: GetERC20Token(context, args)
    Keeper->>Erc20Keeper: GetERC20Token(baseDenom)
    Erc20Keeper-->>Keeper: Return Token Details
    Keeper-->>CrosschainContract: Return Token Address & Enable Status
    CrosschainContract-->>Client: Token Information
Loading

Possibly related PRs

Poem

🐰 In the realm of tokens, a rabbit's delight,
ERC20 now dances with crosschain might!
A denom whispered, a contract's embrace,
New methods leaping with algorithmic grace.
Blockchain magic, coded with care! 🌉✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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

🧹 Nitpick comments (9)
solidity/contracts/interfaces/ICrosschain.sol (1)

31-34: Consider documenting the _enable return value.
Though the new getERC20Token function extends the interface effectively, it might be helpful to include comments or NatSpec annotations clarifying what _enable signifies (e.g., whether the token is active, tradable, etc.).

precompiles/crosschain/keeper.go (1)

19-21: Add clarity on usage of erc20Keeper.
Introducing erc20Keeper in Keeper is beneficial for integrating ERC20 logic. Consider adding a docstring or comment explaining the purpose of this field and how interactions differ from the existing bankKeeper.

precompiles/crosschain/contract.go (2)

28-28: Document the erc20Keeper parameter.
When extending NewPrecompiledContract to accept erc20Keeper, consider updating the function’s docstring or inline comment to clarify how this keeper is used for ERC20 integration.


32-34: Maintain order or alignment for consistent readability.
The Keeper fields are arranged in a logical order. While not critical, you might keep all keeper references (e.g., bankKeeper and then erc20Keeper) grouped together consistently throughout the codebase.

precompiles/crosschain/get_erc20_token_test.go (3)

16-20: Rename the test function.
The function name TestCrosschainGetERC20Tokwn seems to contain a minor spelling mistake in the word "Tokwn." Consider renaming it to TestCrosschainGetERC20Token for clarity and consistency.

-func TestCrosschainGetERC20Tokwn(t *testing.T) {
+func TestCrosschainGetERC20Token(t *testing.T) {

28-44: Add a test scenario for Enabled = true.
The current test covers setting Enabled to false. To fully validate functionality, consider adding a test that sets Enabled to true and confirms its behavior.


56-67: Consider asserting error messages for negative scenarios.
While the test confirms whether an error occurred, you might also want to assert the exact error message or error code to ensure correctness and maintainability.

testutil/helpers/crosschain_precompile_suite.go (1)

61-65: Return the error for flexible handling.
This method enforces error handling internally via requireError. For scenarios that need nuanced error handling, consider returning the error to the caller to allow finer control over test assertions.

-func (s CrosschainPrecompileSuite) GetERC20Token(ctx context.Context, args contract.GetERC20TokenArgs) (common.Address, bool) {
+func (s CrosschainPrecompileSuite) GetERC20Token(ctx context.Context, args contract.GetERC20TokenArgs) (common.Address, bool, error) {
  token, enable, err := s.CrosschainPrecompileKeeper.GetERC20Token(ctx, args)
  s.requireError(err)
  return token, enable
}
solidity/contracts/test/CrosschainTest.sol (1)

124-128: Add NatSpec documentation to enhance maintainability

While this function is straightforward, adding NatSpec comments can help other developers understand its purpose and expected behavior.

 function getERC20Token(
     bytes32 _denom
 ) external view returns (address _token, bool _enable) {
+    /**
+     * @notice Retrieves the ERC20 token address and whether it's enabled for the specified denom.
+     * @dev Calls into the crosschain precompile at CROSS_CHAIN_ADDRESS
+     * @param _denom Bytes32 representation of the token denomination
+     * @return _token Address of the ERC20 token
+     * @return _enable Boolean indicating whether the token is enabled
+     */
     return ICrosschain(CROSS_CHAIN_ADDRESS).getERC20Token(_denom);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e72fe47 and 39a2445.

📒 Files selected for processing (13)
  • app/keepers/keepers.go (1 hunks)
  • contract/crosschain.go (1 hunks)
  • contract/crosschain_precompile.go (1 hunks)
  • contract/icrosschain.sol.go (2 hunks)
  • precompiles/crosschain/contract.go (1 hunks)
  • precompiles/crosschain/get_erc20_token.go (1 hunks)
  • precompiles/crosschain/get_erc20_token_test.go (1 hunks)
  • precompiles/crosschain/keeper.go (1 hunks)
  • precompiles/types/expected_keepers.go (1 hunks)
  • solidity/contracts/interfaces/ICrosschain.sol (1 hunks)
  • solidity/contracts/test/CrosschainTest.sol (1 hunks)
  • tests/contract/crosschain_test.sol.go (2 hunks)
  • testutil/helpers/crosschain_precompile_suite.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (13)
precompiles/crosschain/get_erc20_token.go (1)

1-76: Thoroughly review input validation and potential error handling paths.

  1. The method Run (lines 36-48) gracefully returns an error if UnpackInput fails or GetERC20Token fails, which is good. Consider adding (or clarifying) logs or error details where beneficial, especially for debugging potential input data issues.
  2. The gas requirement is fixed at 1,000 (lines 28-30). Ensure this static cost is sufficient for typical usage and that it remains stable over time.
  3. PackOutput (lines 74-76) returns the packed data directly. Consider including checks or logs if the token address is zero or if any unexpected state arises.
precompiles/crosschain/contract.go (1)

42-42: Great addition of NewGetERC20TokenMethod(keeper).
Adding this method to the contract expands functionality effectively. Validate test coverage to confirm all success and failure scenarios are handled.

precompiles/crosschain/get_erc20_token_test.go (2)

22-27: Good structure for test cases array.
Defining multiple scenarios using a slice of structures is a clean, scalable way to handle test variants.


45-53: Well-handled error scenario.
This test case properly verifies the error path when the token is not found.

contract/crosschain.go (1)

128-133: Validation approach looks good.
The Validate method correctly checks for an empty Denom. This aligns with the rest of the argument-validation pattern.

precompiles/types/expected_keepers.go (1)

95-95: Ensure interface naming consistency and clarity

This new interface method aligns well with existing patterns, but verify that other code references consistently use GetERC20Token and handle the returned error.

app/keepers/keepers.go (1)

373-373: Verify the non-nil initialization of Erc20Keeper

You're passing appKeepers.Erc20Keeper to the precompiled contract. Ensure it is properly initialized and never nil to avoid runtime panics.

✅ Verification successful

Erc20Keeper initialization verified as safe and properly handled

The Erc20Keeper is properly initialized during app setup with all required dependencies and used safely throughout the codebase with proper error handling. The initialization happens before its usage in precompiled contracts and is well-tested.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify all references to appKeepers.Erc20Keeper are guarded or properly initialized
rg --context 5 'Erc20Keeper'

Length of output: 59055

tests/contract/crosschain_test.sol.go (2)

34-35: Auto-generated ABI and bytecode fields

These lines reflect auto-generated contract metadata. No issues identified.


267-311: Confirm correct usage of ABIGen-style bindings

This auto-generated getter for getERC20Token appears valid and consistent with the contract. Make sure to cover this in your tests to validate the correct data is retrieved.

contract/icrosschain.sol.go (4)

34-34: Ensure consistency in ABI versioning.

Double-check that the updated ABI is in sync with any relevant contract updates. If the Solidity contract changes again, remember to regenerate these bindings to maintain accuracy.


214-237: Validate error handling for _ICrosschain.contract.Call.

While this code appears auto-generated and conventional for Go-Ethereum bindings, ensure there's adequate error handling and logging around contract calls in higher-level logic. If an error is returned here, confirm upstream callers handle it gracefully (e.g., logging, fallback flows).


239-248: Confirm usage of session-based calls.

This session-based GetERC20Token method leverages preset call options (e.g., Context, BlockNumber). Verify that these session parameters are correctly set before usage to avoid unexpected behaviors in production.


249-258: Check consistency in caller session logic.

As with the other session-based function, ensure that any user-specified CallOpts for the session remain consistent across your integration’s environment. This includes confirming that proper addresses, contexts, or override blocks are set in tests and production.

contract/crosschain_precompile.go Show resolved Hide resolved
@fx0x55 fx0x55 merged commit 8e9620e into main Jan 24, 2025
18 checks passed
@fx0x55 fx0x55 deleted the nulnut/precompile-erc20-token branch January 24, 2025 05:10
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.

3 participants