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

refactor: migrate bridge token data and update metadata alias #749

Merged
merged 1 commit into from
Oct 17, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Oct 17, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced cross-chain functionality with the addition of a new method to aggregate keeper instances.
    • Introduction of migration tools for managing token migrations and handling IBC denomination traces.
  • Bug Fixes

    • Context in tests now correctly includes the chain ID.
  • Refactor

    • Significant restructuring of the erc20 module for improved configuration and migration support.
  • Chores

    • Updated import statements and function calls to streamline operations and maintain compatibility.

Copy link

coderabbitai bot commented Oct 17, 2024

Walkthrough

The pull request introduces several enhancements to the application, primarily focusing on cross-chain functionalities. A new method, ToSlice, is added to the CrossChainKeepers struct, allowing it to return a slice of various keeper instances. The AppKeepers struct is updated to include CrossChainKeepers. Additionally, the erc20 module's instantiation is modified to incorporate new parameters, reflecting a shift in configuration. Other changes include the introduction of migration-related functions and updates to context handling in tests.

Changes

File Change Summary
app/keepers/keepers.go Added method ToSlice to CrossChainKeepers and included CrossChainKeepers in AppKeepers.
app/modules.go Updated erc20.NewAppModule instantiation to include additional parameters.
app/upgrade_test.go Modified newContext to set the chain ID in the context.
app/upgrades/v8/upgrade.go Added updateMetadata function and new imports for strings and bankkeeper.
x/crosschain/keeper/legacy.go Introduced deprecated method LegacyGetDenomBridgeToken.
x/erc20/migrations/v8/legacy.go Added method LegacyIsNativeERC20 to check native ERC20 tokens.
x/erc20/migrations/v8/migrate.go Introduced Migrator struct and methods for token migration.
x/erc20/migrations/v8/migrations.go Added Migrator struct and methods for handling migrations from version 3 to 4.
x/erc20/migrations/v8/token.go Introduced functions for handling IBC denomination traces and bridge tokens.
x/erc20/module.go Restructured AppModule to include new fields and updated NewAppModule constructor.

Possibly related PRs

🐇 In the fields so green and wide,
CrossChainKeepers now abide.
With slices neat, they gather round,
New migrations, joy abound!
Erc20's path, a twist and turn,
In code we hop, and brightly learn! 🌟


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

@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 (6)
x/crosschain/keeper/legacy.go (2)

9-10: Enhance the deprecation notice.

While the current deprecation notice is clear, it could be more informative. Consider expanding it to include:

  1. The reason for deprecation
  2. Alternative method(s) to use instead
  3. The exact version when it will be removed (if known)

For example:

// Deprecated: This function will be removed in v8 due to [reason].
// Use [alternative method] instead.
// Will be removed in v8.0.0.

10-20: LGTM: Function implementation is correct, consider adding input validation.

The LegacyGetDenomBridgeToken function correctly implements the legacy lookup for bridge tokens. It appropriately handles cases where no data is found and returns a pointer to BridgeToken which is suitable for potentially large structs.

However, consider adding input validation for the denom parameter to ensure it's not empty or malformed before using it to generate the key. This could prevent potential issues with invalid inputs.

Example:

if denom == "" {
    return nil, false
}
// Optionally, add more specific validation based on your denom format
x/erc20/migrations/v8/token.go (2)

9-60: LGTM: IBC denomination trace maps are well-structured.

The separation of testnet and mainnet IBC denomination traces is a good practice. The comments providing information about the source chains are helpful.

Consider adding a brief comment explaining the purpose of these maps at the beginning of each map declaration. For example:

// testnetIBCDenomTrace maps IBC denominations to their corresponding channel identifiers for the testnet environment
testnetIBCDenomTrace := map[string]string{
    // ... (existing entries)
}

// mainnetIBCDenomTrace maps IBC denominations to their corresponding channel identifiers for the mainnet environment
mainnetIBCDenomTrace := map[string]string{
    // ... (existing entries)
}

This would provide immediate context for developers working with these maps.


62-65: LGTM: Testnet excluded bridge token map is defined correctly.

The testnetExcludeBridgeToken map provides a way to exclude specific tokens from bridge operations in the testnet environment, which is a good practice for network-specific configurations.

Consider adding a brief comment explaining the purpose of this map. For example:

// testnetExcludeBridgeToken maps token addresses to a boolean indicating whether they should be excluded from bridge operations in the testnet environment
testnetExcludeBridgeToken := map[string]bool{
    // ... (existing entry)
}

This would provide immediate context for developers working with this map.

x/erc20/migrations/v8/migrate.go (1)

16-43: Handle potential cases where no tokens are migrated

In the MigrateToken function, after processing the denom metadata, there might be scenarios where no tokens are added due to the conditions in your loops and if-statements. Consider adding logging or error handling to account for situations where tokens are expected to be migrated but none are added. This will help in debugging and ensuring the migration process completes as intended.

x/erc20/module.go (1)

88-95: Consider using a more descriptive parameter name in NewAppModule

The parameter cks in the NewAppModule function could be renamed to crossChainKeepers for clarity and consistency with the struct field name.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bff5bda and 3cfaf73.

📒 Files selected for processing (10)
  • app/keepers/keepers.go (1 hunks)
  • app/modules.go (1 hunks)
  • app/upgrade_test.go (1 hunks)
  • app/upgrades/v8/upgrade.go (3 hunks)
  • x/crosschain/keeper/legacy.go (1 hunks)
  • x/erc20/migrations/v8/legacy.go (1 hunks)
  • x/erc20/migrations/v8/migrate.go (1 hunks)
  • x/erc20/migrations/v8/migrations.go (1 hunks)
  • x/erc20/migrations/v8/token.go (1 hunks)
  • x/erc20/module.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (14)
x/crosschain/keeper/legacy.go (1)

1-7: LGTM: Package declaration and imports are appropriate.

The package declaration and imports are correct and relevant for the functionality implemented in this file.

x/erc20/migrations/v8/legacy.go (1)

3-9: LGTM: Imports are appropriate and concise.

The imported packages are relevant to the function's implementation, and there are no unused imports.

x/erc20/migrations/v8/migrations.go (3)

1-11: LGTM: Package declaration and imports are appropriate.

The package is correctly named v8, aligning with the migration version. The imports include necessary Cosmos SDK types and custom types from fx-core, which are appropriate for the migration task.


13-19: LGTM: Migrator struct is well-defined.

The Migrator struct encapsulates all necessary dependencies for the migration process, including store key, codec, keeper, bank keeper, and cross-chain keepers. The use of a slice for crossChainKeepers allows for multiple cross-chain integrations, which is a flexible design choice.


21-29: LGTM: NewMigrator constructor is well-implemented.

The NewMigrator function provides a clean way to create a Migrator instance. It follows dependency injection principles by accepting all necessary dependencies as parameters. This approach enhances testability and flexibility of the code.

app/upgrade_test.go (1)

83-83: Verify the necessity of explicitly setting the chain ID

The addition of ctx = ctx.WithChainID(chainId) ensures that the chain ID is explicitly set in the context. While this improves clarity and consistency, it's worth noting that the chain ID is already set in the header used to create the context.

Could you clarify if this addition addresses any specific issues? If not, consider whether this explicit setting is necessary given the existing header setup.

To verify the impact of this change, you can run the following script:

This will help identify if there are places in the codebase where the chain ID is accessed directly from the context, which would justify this addition.

✅ Verification successful

Consistent usage of WithChainID across the codebase

The use of ctx.WithChainID(chainId) in app/upgrade_test.go aligns with similar implementations in app/keepers/keepers.go and app/export_test.go. This ensures consistent handling of the chain ID within the context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any occurrences where the chain ID might be accessed directly from the context
# rather than through the header, which could justify this addition.

rg --type go 'ctx\.ChainID\(\)' app
rg --type go 'WithChainID' app

Length of output: 289

x/erc20/migrations/v8/token.go (3)

1-7: LGTM: Package declaration and imports are appropriate.

The package declaration and imports are correct and align with the file's location and purpose.


67-74: LGTM: getIBCDenomTrace function is well-implemented.

The function correctly differentiates between testnet and mainnet environments using the chain ID from the context. It provides a clean way to retrieve the channel identifier for a given IBC denomination.

The implementation is concise and follows Go's idiomatic return style for map lookups.


76-81: LGTM with a question: Verify mainnet behavior for getExcludeBridgeToken.

The function correctly differentiates between testnet and mainnet environments using the chain ID from the context. For the testnet, it checks if the token should be excluded from bridge operations.

Please confirm if the current implementation for mainnet (always returning false) is intentional. If it is, consider adding a comment explaining why no tokens are excluded in the mainnet environment. If not, you might want to add a mainnetExcludeBridgeToken map similar to the testnet one.

To verify the usage of this function, you can run the following script:

This will help ensure that the function is being used as intended across the codebase.

✅ Verification successful

Verified mainnet behavior for getExcludeBridgeToken.

The function is only used in migrate.go and intentionally returns false for mainnet environments, ensuring no tokens are excluded during production operations. Consider adding a comment to clarify this behavior for future reference.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any usage of getExcludeBridgeToken function in the codebase

# Test: Search for function calls to getExcludeBridgeToken
rg --type go "getExcludeBridgeToken\s*\(" .

Length of output: 218

app/keepers/keepers.go (2)

102-107: LGTM: Useful addition for cross-chain keeper aggregation.

The ToSlice method is a valuable addition to the CrossChainKeepers struct. It provides a convenient way to access all cross-chain keepers as a slice, which can be beneficial for operations that need to iterate over or process all keepers collectively.


108-108: Verify initialization of embedded CrossChainKeepers.

The inclusion of CrossChainKeepers in the AppKeepers struct is a good way to organize related keepers. However, ensure that the CrossChainKeepers is properly initialized in the NewAppKeeper function. This initialization is not visible in the provided code snippet and should be verified.

To confirm the proper initialization, please run the following script:

This will help us verify that CrossChainKeepers is being set up correctly when creating a new AppKeepers instance.

app/upgrades/v8/upgrade.go (2)

44-45: Integration of metadata update within upgrade handler

The addition of updateMetadata(cacheCtx, app.BankKeeper) correctly integrates the metadata update process into the upgrade handler.


84-102: 🛠️ Refactor suggestion

⚠️ Potential issue

Ensure complete update of denomination units

The updateMetadata function currently modifies only the first denomination unit (md.DenomUnits[0]). To ensure consistency across all units, consider iterating over all DenomUnits to remove aliases and update denominations.

Here is a suggested refactor:

func updateMetadata(ctx sdk.Context, bankKeeper bankkeeper.Keeper) {
    mds := bankKeeper.GetAllDenomMetaData(ctx)
    for _, md := range mds {
        if md.Base == fxtypes.DefaultDenom || len(md.DenomUnits) == 0 || len(md.DenomUnits[0].Aliases) == 0 {
            continue
        }
        // remove aliases from all denom units
-       md.DenomUnits[0].Aliases = []string{}
+       for i := range md.DenomUnits {
+           md.DenomUnits[i].Aliases = []string{}
+       }

        // update base denom
        newBase := strings.ToLower(md.Symbol)
        if md.Base != newBase {
            oldBase := md.Base
            md.Base = newBase
            // update denom in all denom units that match the old base
-           md.DenomUnits[0].Denom = newBase
+           for i := range md.DenomUnits {
+               if md.DenomUnits[i].Denom == oldBase {
+                   md.DenomUnits[i].Denom = newBase
+               }
+           }
        }

        bankKeeper.SetDenomMetaData(ctx, md)
    }
}

Verify impact of base denomination changes

Changing md.Base and updating denom units may have implications elsewhere in the codebase where the original base denominations are referenced. Please ensure that all dependencies and references to the old base denominations are updated accordingly to prevent inconsistencies.

x/erc20/module.go (1)

114-117: Ensure crossChainKeepers is properly initialized before migration

Please verify that am.crossChainKeepers is properly initialized before it's used in the migration. An uninitialized or nil crossChainKeepers may lead to runtime errors during the migration process.

x/erc20/migrations/v8/legacy.go Show resolved Hide resolved
x/erc20/migrations/v8/migrations.go Show resolved Hide resolved
app/modules.go Show resolved Hide resolved
x/erc20/migrations/v8/migrate.go Show resolved Hide resolved
x/erc20/migrations/v8/migrate.go Show resolved Hide resolved
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