Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: many to one test #705

Merged
merged 2 commits into from
Sep 29, 2024
Merged

test: many to one test #705

merged 2 commits into from
Sep 29, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Sep 29, 2024

Summary by CodeRabbit

  • New Features

    • Introduced methods for enhanced token minting and balance management.
    • Added functionality to check balances for specific tokens and accounts.
    • New methods for creating and managing bridge tokens and coin conversions.
    • Implemented a method to query ERC20 contract balances.
  • Tests

    • Added comprehensive unit tests for various token operations and conversions, ensuring robust validation of functionalities.

Copy link

coderabbitai bot commented Sep 29, 2024

Walkthrough

The changes enhance the token minting and balance management functionalities within the Cosmos SDK. Several methods in the BaseSuite struct have been updated or added to support variadic parameters for minting tokens, checking balances, and creating new coins. Additionally, a new test suite for the Keeper functionality in the crosschain module has been introduced, validating various token conversion and bridge operations.

Changes

Files Change Summary
testutil/helpers/suite.go Updated MintToken to accept variadic amounts. Added methods for minting tokens to modules, checking balances, and creating new coins.
x/crosschain/keeper/many_to_one_test.go Introduced unit tests for various token conversion and bridge operations, validating expected behaviors and error handling.

Poem

🐰 In the garden of code, changes bloom bright,
With tokens and balances dancing in light.
Minting and checking, all in a row,
A symphony of functions, watch them all grow!
Hopping along, with tests oh so neat,
In the world of Cosmos, our work is complete! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f0de550 and f72681b.

📒 Files selected for processing (2)
  • testutil/helpers/suite.go (3 hunks)
  • x/crosschain/keeper/many_to_one_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • testutil/helpers/suite.go
  • x/crosschain/keeper/many_to_one_test.go

Warning

Review ran into problems

🔥 Problems

Error running Gitleaks: Cloning the repository previously failed.


Error running golangci-lint: Command failed with exit code 4: jk_cp -o -f -k -j /cache/54/6300ea40-43e2-43c0-8800-d997902910bb /dev/null /dev/urandom /usr/bin/ast-grep /usr/bin/curl /usr/bin/diff /usr/bin/dirname /usr/bin/env /usr/bin/fd /usr/bin/gawk /usr/bin/gh /usr/bin/jq /usr/bin/patch /usr/bin/rg /usr/bin/shellcheck /usr/bin/tokei /usr/bin/tree /usr/bin/uniq /usr/bin/xargs /etc/ssl/certs /etc/passwd /etc/group /home/jailuser/ast-grep-rules

ERROR: /usr/bin/ast-grep does not exist

Usage: /usr/sbin/jk_cp -j [OPTIONS]

-h --help : this help screen
-j, --jail : the jail to copy to
-v, --verbose : show what is being copied
-f, --force : overwrite existing files
-k, --hardlink : use hardlinks if possible
-o, --owner : retain file ownership and group
-s, --setuid : retain file setuid/setgid bits

Note: if no jail is specified, the first argument is
considered to be the jail


Error running semgrep: Cloning the repository previously failed.


Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review.


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

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

40-40: Add a comment explaining the method's purpose.

To improve code readability and maintainability, consider adding a comment that explains the purpose of the ERC20BalanceOf method and its parameters.

Here's a suggested comment:

// ERC20BalanceOf queries the balance of the specified address for the given ERC20 contract.
// It returns the balance as a *big.Int and an error if the query fails.
x/crosschain/keeper/keeper_v1_test.go (3)

168-174: LGTM: SetToken() method is well-implemented, with a minor suggestion.

The SetToken() method is a good wrapper for testing purposes. It correctly handles the special case for the default denomination and checks for errors.

Consider adding a comment explaining the purpose of this method and why the default denomination is treated differently. This would improve the code's readability and maintainability.

 func (suite *KeeperTestSuite) SetToken(symbol string, bridgeDenoms ...string) {
+	// SetToken is a test helper that sets up a token with the given symbol and bridge denominations.
+	// The default denomination (fxtypes.DefaultDenom) is treated as a special case with no bridge denominations.
 	if symbol == fxtypes.DefaultDenom {
 		bridgeDenoms = []string{}
 	}
 	err := suite.Keeper().SetToken(suite.Ctx, "Test Token", symbol, 18, bridgeDenoms...)
 	suite.NoError(err)
 }

176-182: LGTM with suggestions: AddTokenPair() method could be improved.

The AddTokenPair() method is a useful helper for testing. However, there are a few areas where it could be improved:

  1. The use of a hardcoded hex address (helpers.GenHexAddress()) might not be suitable for all test scenarios. Consider parameterizing this.
  2. The method doesn't check for errors when adding the token pair. It's generally good practice to handle potential errors, even in test code.

Consider refactoring the method as follows:

-func (suite *KeeperTestSuite) AddTokenPair(denom string, isNative bool) {
+func (suite *KeeperTestSuite) AddTokenPair(denom string, isNative bool, erc20Address string) error {
 	contractOwner := erc20types.OWNER_EXTERNAL
 	if isNative {
 		contractOwner = erc20types.OWNER_MODULE
 	}
-	suite.App.Erc20Keeper.AddTokenPair(suite.Ctx, erc20types.TokenPair{Erc20Address: helpers.GenHexAddress().String(), Denom: denom, Enabled: true, ContractOwner: contractOwner})
+	if erc20Address == "" {
+		erc20Address = helpers.GenHexAddress().String()
+	}
+	return suite.App.Erc20Keeper.AddTokenPair(suite.Ctx, erc20types.TokenPair{
+		Erc20Address: erc20Address,
+		Denom: denom,
+		Enabled: true,
+		ContractOwner: contractOwner,
+	})
 }

This refactoring allows for more flexible testing scenarios and proper error handling.


184-188: LGTM with suggestions: AddBridgeToken() method could be more flexible.

The AddBridgeToken() method is a useful helper for testing bridge token functionality. However, it could be made more flexible to accommodate various test scenarios:

Consider refactoring the method to allow for more customization:

-func (suite *KeeperTestSuite) AddBridgeToken(contractAddr string, symbol string) {
+func (suite *KeeperTestSuite) AddBridgeToken(contractAddr, name, symbol string, decimals uint32) {
 	bridgeTokenClaim := &types.MsgBridgeTokenClaim{
 		TokenContract: contractAddr,
-		Name: "Test Token",
+		Name: name,
 		Symbol: symbol,
-		Decimals: 18,
+		Decimals: decimals,
 		ChainName: suite.chainName,
 	}
 	err := suite.Keeper().AddBridgeTokenExecuted(suite.Ctx, bridgeTokenClaim)
 	suite.Require().NoError(err)
 }

This refactoring allows for more flexible testing scenarios by parameterizing the token name and decimals. You might also consider adding a comment explaining the purpose of this method and its relationship to the AddBridgeTokenExecuted function.

x/crosschain/keeper/many_to_one_test.go (1)

64-91: Enhance test coverage with additional edge cases in TestManyToOne

Currently, TestManyToOne covers basic success scenarios. Consider adding test cases for:

  • Invalid ConvertDenom values that are neither base nor bridge denoms.
  • Unsupported Target values.
  • Empty strings for ConvertDenom or Target.

This will ensure that the function behaves correctly under all possible inputs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 548c396 and f0de550.

📒 Files selected for processing (6)
  • testutil/helpers/suite.go (3 hunks)
  • x/crosschain/keeper/bridge_call_out_v1_test.go (1 hunks)
  • x/crosschain/keeper/keeper_v1_test.go (4 hunks)
  • x/crosschain/keeper/many_to_one.go (7 hunks)
  • x/crosschain/keeper/many_to_one_test.go (1 hunks)
  • x/evm/keeper/erc20.go (1 hunks)
🔇 Additional comments (18)
x/crosschain/keeper/bridge_call_out_v1_test.go (1)

84-84: LGTM! Verify the CheckBalanceOf method implementation.

The change from suite.checkBalanceOf to suite.CheckBalanceOf appears to be part of a refactoring effort. The functionality seems to remain the same, which is good for maintaining test integrity.

To ensure the refactoring was done correctly, please run the following script to verify the CheckBalanceOf method implementation:

x/crosschain/keeper/keeper_v1_test.go (2)

13-13: LGTM: Import statements are appropriate.

The new import statements are relevant to the added functionality and existing code. They are correctly formatted and placed.

Also applies to: 25-30


120-123: LGTM: ModuleAddress() method is correctly implemented.

The ModuleAddress() method correctly uses authtypes.NewModuleAddress() to generate the module address based on the chainName. This is a standard approach in Cosmos SDK.

testutil/helpers/suite.go (7)

131-134: Updated MintToken function allows minting multiple coins

The modification correctly updates the MintToken function to accept a variadic parameter, enabling minting of multiple coins to a single address.


145-147: Balance function correctly retrieves all balances

The Balance function properly retrieves all balances for the given account using GetAllBalances.


149-154: CheckBalance function accurately verifies individual balances

The function iterates over the expected balances and verifies that each denomination matches the actual balance.


156-159: CheckAllBalance function effectively compares total balances

The function compares the expected and actual total balances, ensuring they match exactly.


161-165: CheckBalanceOf function properly checks ERC20 token balances

The function correctly retrieves the ERC20 token balance and asserts its equality with the expected balance.


167-174: NewCoin function generates coins with specified or random amounts

The function creates a new coin with a random denomination and amount, or uses the provided amount if specified.


176-184: NewBridgeCoin function creates bridge coins associated with a module

The function generates a new bridge coin and corresponding token address, facilitating cross-chain interactions.

x/crosschain/keeper/many_to_one.go (8)

56-58: Handle default denomination in DepositBridgeToken.

The added condition checks if bridgeToken.Denom is the default denomination (fxtypes.DefaultDenom). If so, it directly sends the coins from the module to the account holder without additional processing. This ensures that the default token is handled appropriately.


76-77: Introduce WithdrawBridgeToken function.

The WithdrawBridgeToken function has been added or renamed from ClaimBridgeToken. This function manages the withdrawal of bridge tokens to the crosschain module. Ensure that its implementation correctly handles all necessary logic and that any renaming does not affect the functionality.


81-83: Ensure correct handling of default denomination in WithdrawBridgeToken.

An early return has been added for cases where bridgeToken.Denom equals fxtypes.DefaultDenom. This implies no further processing is needed for the default denomination. Verify that this logic is correct and that skipping additional steps is appropriate in this context.


118-120: Simplify conversion logic in ManyToOne.

The condition checks if baseDenom is the default denomination or if no target is specified. If either is true, it returns baseDenom immediately. This optimization avoids unnecessary conversions and simplifies the function's logic when conversion isn't needed.


153-155: Optimize ConversionCoin for default denomination.

An early return has been added when coin.Denom is the default denomination in ConversionCoin. This prevents unnecessary processing and reflects that no conversion is required for the default token.


92-93: Verify skipping coin burning for native ERC20 tokens.

In WithdrawBridgeToken, the function now returns early if tokenPair.IsNativeERC20() is true, bypassing the coin burning step. Confirm that this behavior is intentional and appropriate, as it affects the total supply of tokens. Skipping the burning process for native ERC20 tokens might be necessary, but it's important to ensure this aligns with the overall token management strategy.

To review where IsNativeERC20 influences logic, run:

#!/bin/bash
# Description: Find all instances where `IsNativeERC20` affects control flow.

rg --type go 'IsNativeERC20\(' -A 5

36-44: Confirm the use of WithdrawBridgeToken in BaseCoinToBridgeToken.

The function BaseCoinToBridgeToken now calls WithdrawBridgeToken instead of ClaimBridgeToken. Ensure that WithdrawBridgeToken correctly replaces ClaimBridgeToken and that it handles all necessary withdrawal logic for bridge tokens. Verify that any changes in behavior are intentional and that all dependent code operates as expected.

To check for correct usage, you can search for all references to WithdrawBridgeToken:


17-20: Update tokenAddr parameter type and ensure consistent handling.

The tokenAddr parameter in BridgeTokenToBaseCoin has been changed from common.Address to string. This simplifies address handling but requires that all usages of tokenAddr within this function and any downstream functions correctly handle the string type. Also, verify that all callers of BridgeTokenToBaseCoin have been updated to pass a string instead of a common.Address.

To ensure consistency, run the following script to find all calls to BridgeTokenToBaseCoin and check that they pass a string as tokenAddr:

✅ Verification successful

✅ Verification Successful: tokenAddr is consistently handled as a string across all usages.

  • All calls to BridgeTokenToBaseCoin pass a string for the tokenAddr parameter.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to `BridgeTokenToBaseCoin` to verify parameter types.

rg --type go 'BridgeTokenToBaseCoin\(' -A 1

Length of output: 717


Script:

#!/bin/bash
# Description: Find the definition of `TokenAddr` in `many_to_one_test.go` to verify its type.

rg --type go 'TokenAddr\s*:' x/crosschain/keeper/many_to_one_test.go

Length of output: 189

x/evm/keeper/erc20.go Show resolved Hide resolved
testutil/helpers/suite.go Outdated Show resolved Hide resolved
x/crosschain/keeper/many_to_one_test.go Outdated Show resolved Hide resolved
x/crosschain/keeper/many_to_one_test.go Show resolved Hide resolved
x/crosschain/keeper/many_to_one_test.go Show resolved Hide resolved
x/crosschain/keeper/many_to_one_test.go Show resolved Hide resolved
Co-authored-by: nulnut <151493716+nulnut@users.noreply.github.com>
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