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

ensure we use the correct zone denom where evaluating pool claims #1721

Merged
merged 1 commit into from
Sep 26, 2024

Conversation

joe-bowman
Copy link
Contributor

@joe-bowman joe-bowman commented Sep 26, 2024

1. Summary

Osmosis Pools (legacy + CL) attempt to validate the denom for a claim against the zone, by checking the chain_id of the denom vs the chain_id of the zone. Given that the chain_id of a qAsset/asset pool will be the same for both denoms, the denom selected will be based on the order of the denoms in the slice - and not always validate the correct denom.

This change ensures we use the correct denom as listed for that qAsset on osmosis by the ProtocolDataAllowedLiquidToken.

2.Type of change

  • Bug fix (non-breaking change which fixes an issue)

3. Implementation details

Instead of checking whether denom X has chain_id Y (to match the zone), we lookup the local_denom of the zone, cross reference against the ProtocolDataAllowedLiquidToken list for osmosis (via the OsmosisParams PD chain_id), to ascertain whether we match on the denom. This is always guaranteed to yield the correct answer.

This introduces a contract that all claimable assets in a pool MUST exist in the ProtocolDataAllowedLiquidToken list - however, I cannot foresee any instance where this isn't desirable.

Summary by CodeRabbit

  • New Features

    • Introduced a new method to retrieve applicable denominations for specific zones, enhancing claim validation.
    • Updated functions to accept additional parameters for improved token determination based on pool denominations.
  • Bug Fixes

    • Improved error handling in token validation processes to enhance clarity and robustness.
  • Refactor

    • Streamlined logic in existing functions to remove redundancy and simplify processing.

Copy link

vercel bot commented Sep 26, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
quicksilver ❌ Failed (Inspect) Sep 26, 2024 0:21am

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The pull request introduces modifications to several functions related to token determination in pools within the Osmosis project. Key changes include the addition of a poolDenom parameter to the DetermineApplicableTokensInPool and DetermineApplicableTokensInClPool functions, streamlining logic by removing unnecessary loops. New error handling and logging features enhance clarity. Additionally, a new method, ApplicableDenomForZone, is introduced to improve the claim validation process by determining applicable denominations based on zones.

Changes

Files Change Summary
third-party-chains/osmosis-types/validation.go - Updated DetermineApplicableTokensInPool and DetermineApplicableTokensInClPool to accept poolDenom as a parameter, removing redundant logic and enhancing error messages.
x/airdrop/keeper/claim_handler.go - Modified verifyPoolAndGetAmount to call DetermineApplicableTokensInPool with an additional "UNUSED" parameter.
x/participationrewards/keeper/submodule_osmosis.go - Updated ValidateClaim to include a check for applicable denomination using ApplicableDenomForZone, enhancing claim validation before calling DetermineApplicableTokensInPool.
x/participationrewards/keeper/submodule_osmosiscl.go - Introduced ApplicableDenomForZone method to retrieve applicable denominations for zones, modifying ValidateClaim to utilize this method before calling DetermineApplicableTokensInClPool.

Possibly related PRs

Suggested reviewers

  • faddat
  • minhngoc274
  • TropicalDog17
  • tuantran1702

Poem

🐇 In the meadow where tokens play,
Changes hop in a bright new way.
With poolDenom now in sight,
Claims are clearer, futures bright!
A leap for logic, a bound for cheer,
In the world of Osmosis, we hold dear! 🌼


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 (3)
third-party-chains/osmosis-types/validation.go (3)

24-24: LGTM! Consider enhancing error handling.

The changes to the function signature and the use of poolDenom align well with the PR objectives. This modification addresses the issue of incorrect denom selection and simplifies the logic.

Consider adding a check at the beginning of the function to ensure that poolDenom is not empty:

if poolDenom == "" {
    return sdk.ZeroInt(), errors.New("poolDenom cannot be empty")
}

This would provide an early exit and clearer error message if an invalid poolDenom is passed.


Line range hint 81-119: Verify poolDenom against ProtocolDataAllowedLiquidToken list.

The PR objectives mention a new requirement: "all claimable assets in a pool must exist in the ProtocolDataAllowedLiquidToken list". However, the current implementation doesn't include this check.

Consider adding a verification step to ensure that the poolDenom exists in the ProtocolDataAllowedLiquidToken list. This could be implemented as follows:

// Add this near the beginning of the function, after obtaining the protocol data
osmosisParams, ok := prKeeper.GetProtocolData(ctx, participationrewardstypes.ProtocolDataTypeOsmosisParams, "")
if !ok {
    return sdk.ZeroInt(), errors.New("unable to obtain Osmosis params protocol data")
}

params, err := participationrewardstypes.UnmarshalProtocolData(participationrewardstypes.ProtocolDataTypeOsmosisParams, osmosisParams.Data)
if err != nil {
    return sdk.ZeroInt(), fmt.Errorf("failed to unmarshal Osmosis params: %w", err)
}

osmosisParamsData, ok := params.(*participationrewardstypes.OsmosisParamsProtocolData)
if !ok {
    return sdk.ZeroInt(), errors.New("invalid Osmosis params data type")
}

if !osmosisParamsData.IsAllowedLiquidToken(poolDenom) {
    return sdk.ZeroInt(), fmt.Errorf("poolDenom %s is not in the ProtocolDataAllowedLiquidToken list", poolDenom)
}

This addition ensures that the poolDenom is verified against the ProtocolDataAllowedLiquidToken list, as specified in the PR objectives.


Line range hint 1-119: Summary: Changes align with PR objectives, but additional improvements suggested.

The modifications to both DetermineApplicableTokensInPool and DetermineApplicableTokensInClPool functions address the core issue of incorrect denom selection. The addition of the poolDenom parameter and its direct usage simplify the logic and reduce the potential for errors.

However, there are two areas for improvement:

  1. Enhanced error handling in DetermineApplicableTokensInPool to check for empty poolDenom.
  2. Implementation of the requirement to verify the poolDenom against the ProtocolDataAllowedLiquidToken list in DetermineApplicableTokensInClPool.

Addressing these points will further strengthen the implementation and fully meet the PR objectives.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ff35015 and b41f72d.

📒 Files selected for processing (4)
  • third-party-chains/osmosis-types/validation.go (3 hunks)
  • x/airdrop/keeper/claim_handler.go (1 hunks)
  • x/participationrewards/keeper/submodule_osmosis.go (1 hunks)
  • x/participationrewards/keeper/submodule_osmosiscl.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
x/participationrewards/keeper/submodule_osmosiscl.go

[failure] 135-135:
ST1003: method parameter chainId should be chainID (stylecheck)

🔇 Additional comments (2)
third-party-chains/osmosis-types/validation.go (1)

81-83: LGTM! Improved logging enhances debuggability.

The changes to the function signature and the use of poolDenom align well with the PR objectives. The added logging statements at lines 84 and 107 will greatly improve debuggability. The updated error message at line 115 provides more context, which is helpful.

Also applies to: 84-84, 107-108, 115-115

x/airdrop/keeper/claim_handler.go (1)

310-310: Approved, but clarification needed on the new parameter.

The addition of the "UNUSED" parameter to the DetermineApplicableTokensInPool function call is a non-breaking change. However, there are a few points that need clarification:

  1. What is the purpose of the "UNUSED" parameter? It's not clear how this relates to the PR objectives of ensuring the correct zone denom is used for evaluating pool claims.

  2. How does this change align with the PR objective of referencing the ProtocolDataAllowedLiquidToken? The current implementation doesn't seem to directly address this.

  3. Is this a temporary solution or a preparation for future changes?

To better understand the context and impact of this change, let's check how the DetermineApplicableTokensInPool function is defined and used elsewhere in the codebase:

Consider adding a comment to explain the purpose of the "UNUSED" parameter:

 func (k *Keeper) verifyPoolAndGetAmount(ctx sdk.Context, lock osmosislockuptypes.PeriodLock, cr types.ClaimRecord) (sdkmath.Int, error) {
+    // TODO: Explain the purpose of the "UNUSED" parameter
     return osmosistypes.DetermineApplicableTokensInPool(ctx, k.prKeeper, lock, cr.ChainId, "UNUSED")
 }

Comment on lines +143 to +146
denom, found := k.ApplicableDenomForZone(ctx, msg.Zone)
if !found {
return math.ZeroInt(), errors.New("no applicable denom found for zone")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use sdk.ZeroInt() instead of math.ZeroInt() for error return

In line 145, you return math.ZeroInt(), whereas elsewhere in the code, sdk.ZeroInt() is used for returning zero Int values. For consistency and to avoid potential issues, consider replacing math.ZeroInt() with sdk.ZeroInt().

Apply this diff to fix the inconsistency:

-			return math.ZeroInt(), errors.New("no applicable denom found for zone")
+			return sdk.ZeroInt(), errors.New("no applicable denom found for zone")
📝 Committable suggestion

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

Suggested change
denom, found := k.ApplicableDenomForZone(ctx, msg.Zone)
if !found {
return math.ZeroInt(), errors.New("no applicable denom found for zone")
}
denom, found := k.ApplicableDenomForZone(ctx, msg.Zone)
if !found {
return sdk.ZeroInt(), errors.New("no applicable denom found for zone")
}

return math.ZeroInt(), errors.New("no applicable denom found for zone")
}

sdkAmount, err := osmosistypes.DetermineApplicableTokensInPool(ctx, k, lock, msg.Zone, denom)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Incomplete Update of DetermineApplicableTokensInPool Calls

The call in x/airdrop/keeper/claim_handler.go is passing "UNUSED" as the denom parameter. This appears to be a placeholder and should be updated to use a valid denomination to prevent potential runtime errors.

🔗 Analysis chain

Ensure all calls to DetermineApplicableTokensInPool include the new denom parameter

The function DetermineApplicableTokensInPool now requires an additional denom parameter. Please verify that all other calls to this function in the codebase have been updated to include the new parameter to prevent any runtime errors.

Run the following script to find any usages of DetermineApplicableTokensInPool that may need updating:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find calls to `DetermineApplicableTokensInPool` without the `denom` parameter
# Expected: No occurrences of calls with missing parameters

rg --type go 'DetermineApplicableTokensInPool\(' -A5

Length of output: 1464


Script:

#!/bin/bash
# Description: Verify if the 'denom' parameter is intentionally set to "UNUSED" in claim_handler.go
# Expected: Identify any comments or TODOs indicating the purpose of "UNUSED"

rg --type go 'DetermineApplicableTokensInPool\(' x/airdrop/keeper/claim_handler.go -A2

Length of output: 189


Script:

#!/bin/bash
# Description: Search for definitions and usages of "UNUSED" in the codebase
# Expected: Identify if "UNUSED" is defined as a constant or used in multiple contexts

rg '"UNUSED"' --no-filename -C2

Length of output: 273

@@ -126,3 +131,32 @@
func (*OsmosisClModule) KeyPool(poolID uint64) []byte {
return osmocl.KeyPool(poolID)
}

func (k *Keeper) ApplicableDenomForZone(ctx sdk.Context, chainId string) (denom string, found bool) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct parameter name to follow Go naming conventions

According to Go naming conventions, acronyms should be capitalized. Therefore, chainId should be renamed to chainID.

Apply this diff to correct the parameter name:

-func (k *Keeper) ApplicableDenomForZone(ctx sdk.Context, chainId string) (denom string, found bool) {
+func (k *Keeper) ApplicableDenomForZone(ctx sdk.Context, chainID string) (denom string, found bool) {

Also, update all instances of chainId within the function:

-	zone, found := k.icsKeeper.GetZone(ctx, chainId)
+	zone, found := k.icsKeeper.GetZone(ctx, chainID)
📝 Committable suggestion

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

Suggested change
func (k *Keeper) ApplicableDenomForZone(ctx sdk.Context, chainId string) (denom string, found bool) {
func (k *Keeper) ApplicableDenomForZone(ctx sdk.Context, chainID string) (denom string, found bool) {
🧰 Tools
🪛 GitHub Check: lint

[failure] 135-135:
ST1003: method parameter chainId should be chainID (stylecheck)

Comment on lines +152 to +153
liquidToken, _ := types.UnmarshalProtocolData(types.ProtocolDataTypeLiquidToken, data.Data)
liquidTokenData := liquidToken.(*types.LiquidAllowedDenomProtocolData)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors during unmarshalling and type assertion

The error returned by UnmarshalProtocolData is being ignored, and the unchecked type assertion could result in a runtime panic if the assertion fails. It's important to handle these errors to prevent potential runtime issues.

Consider modifying the code to handle the error and safely perform the type assertion:

-		liquidToken, _ := types.UnmarshalProtocolData(types.ProtocolDataTypeLiquidToken, data.Data)
-		liquidTokenData := liquidToken.(*types.LiquidAllowedDenomProtocolData)
+		liquidToken, err := types.UnmarshalProtocolData(types.ProtocolDataTypeLiquidToken, data.Data)
+		if err != nil {
+			// Handle the error appropriately, possibly log and continue
+			return false
+		}
+		liquidTokenData, ok := liquidToken.(*types.LiquidAllowedDenomProtocolData)
+		if !ok {
+			// Handle the unexpected type
+			return false
+		}
📝 Committable suggestion

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

Suggested change
liquidToken, _ := types.UnmarshalProtocolData(types.ProtocolDataTypeLiquidToken, data.Data)
liquidTokenData := liquidToken.(*types.LiquidAllowedDenomProtocolData)
liquidToken, err := types.UnmarshalProtocolData(types.ProtocolDataTypeLiquidToken, data.Data)
if err != nil {
// Handle the error appropriately, possibly log and continue
return false
}
liquidTokenData, ok := liquidToken.(*types.LiquidAllowedDenomProtocolData)
if !ok {
// Handle the unexpected type
return false
}

@joe-bowman joe-bowman merged commit b41f72d into main Sep 26, 2024
16 of 19 checks passed
Copy link

codecov bot commented Sep 26, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 14 lines in your changes missing coverage. Please review.

Project coverage is 63.41%. Comparing base (ff35015) to head (b41f72d).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...participationrewards/keeper/submodule_osmosiscl.go 52.17% 8 Missing and 3 partials ⚠️
x/participationrewards/keeper/submodule_osmosis.go 50.00% 1 Missing and 1 partial ⚠️
x/airdrop/keeper/claim_handler.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1721      +/-   ##
==========================================
- Coverage   63.44%   63.41%   -0.03%     
==========================================
  Files         194      194              
  Lines       13411    13436      +25     
==========================================
+ Hits         8508     8521      +13     
- Misses       4089     4097       +8     
- Partials      814      818       +4     
Flag Coverage Δ
unittests 63.41% <50.00%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
x/airdrop/keeper/claim_handler.go 60.69% <0.00%> (ø)
x/participationrewards/keeper/submodule_osmosis.go 53.40% <50.00%> (-0.71%) ⬇️
...participationrewards/keeper/submodule_osmosiscl.go 41.57% <52.17%> (+4.25%) ⬆️

@joe-bowman joe-bowman deleted the ensure-we-validate-against-correct-pools branch October 24, 2024 19:57
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.

1 participant