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

add validation for supported nstID #223

Merged
merged 7 commits into from
Nov 11, 2024

Conversation

leonz789
Copy link
Contributor

@leonz789 leonz789 commented Oct 21, 2024

Description

Restrict current implementation to support NSTETH only.

----

Closes #XXX

Summary by CodeRabbit

  • New Features

    • Enhanced handling of asset IDs for NSTETH with new constants and a mapping for maximum effective balances.
    • Introduced a new function to verify asset ID support for balance updates.
  • Bug Fixes

    • Corrected the error variable name for unsupported asset IDs, ensuring consistency and clarity in error handling.
    • Updated logic for deposit and withdrawal handling to improve accuracy in validator management.
  • Refactor

    • Improved structure and clarity in balance change processing methods, including the introduction of capped balance change handling.

Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The pull request introduces significant modifications to the native_token.go file in the keeper package. Key changes include the renaming of constants for NSTETH asset IDs, the addition of new variables for limited changes and maximum effective balances, and updates to methods for validating and processing balance changes. The code structure has been improved with comments for future enhancements, and new functions have been added to ensure robust handling of asset IDs and balance management.

Changes

File Path Change Summary
x/oracle/keeper/native_token.go - Renamed constants for NSTETH asset IDs to NSTETHAssetIDMainnet, NSTETHAssetIDLocalnet, NSTETHAssetIDHolesky, NSTETHAssetIDSepolia.
- Added variable limitedChangeNST.
- Added variable maxEffectiveBalances.
- Updated function signature from parseBalanceChange to parseBalanceChangeCapped.
- Added functions IsLimitedChangeNST(assetID string) bool and maxEffectiveBalance(assetID string) int.
- Enhanced logic in UpdateNSTValidatorListForStaker and UpdateNSTByBalanceChange methods.
x/oracle/types/errors.go - Renamed error variable from ErrNSTAssetNotSurpported to ErrNSTAssetNotSupported.

Possibly related PRs

Suggested labels

enhancement, C:Proto, C:CLI

Suggested reviewers

  • adu-web3
  • trestinlsd
  • MaxMustermann2
  • bwhour

🐇 In the code where constants play,
NSTETH finds its brighter day.
With balance checks and mappings clear,
A structured path, we hold so dear.
For every staker, every change,
Our code evolves, we rearrange! 🐰✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint

level=warning msg="The linter 'exportloopref' is deprecated (since v1.60.2) due to: Since Go1.22 (loopvar) this linter is no longer relevant. Replaced by copyloopvar."


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

🧹 Outside diff range and nitpick comments (6)
x/oracle/keeper/native_token.go (6)

24-26: Address TODOs and correct typos in comments

The comments at lines 24-26 contain TODOs indicating areas that need attention. Consider implementing the validation before invoking oracle-related functions instead of checking hardcoded IDs here. Additionally, there's a typo in line 26: "ralted" should be "related".

Would you like assistance in addressing these TODOs or correcting the typos?


172-172: Fix typo in comment

In the comment at line 173, "deopsit" should be "deposit".


186-187: Address TODO and correct grammar in comments

There's a TODO at line 186 suggesting to check if the validator has withdrawn all their assets before removing them from the staker's validator list. Implementing this check would enhance the accuracy of the validator list. Additionally, the comments contain grammatical errors:

  • "has withdraw all its asset" should be "has withdrawn all its assets".
  • "len(stkaerInfo.ValidatorPubkeyList)==0 shoule equal to newBalance.Balance<=0" should be "len(stakerInfo.ValidatorPubkeyList) == 0 should equal newBalance.Balance <= 0".

Would you like assistance in implementing this check and correcting the grammatical errors?


224-225: Correct error message grammar

The error message at line 225, "remove unexist validator", is grammatically incorrect. It should be "remove nonexistent validator" or "attempted to remove a validator that does not exist".

Apply this diff to correct the error message:

-return errors.New("remove unexist validator")
+return errors.New("attempted to remove a validator that does not exist")

336-336: Address TODO and correct grammar in comment

The comment at line 336 contains a TODO indicating that the conversion method may need upgrading for future changes. Also, there are grammatical errors:

  • "suites" should be "suits".
  • "need to be upgrade" should be "need to be upgraded".

Would you like assistance in addressing this TODO and correcting the comment?


269-269: Ensure proper handling of parseBalanceChangeCapped errors

At line 269, after calling parseBalanceChangeCapped, consider providing more context in the error handling to aid in debugging if an error occurs.

Apply this diff to enhance error reporting:

 if err != nil {
-	return err
+	return fmt.Errorf("failed to parse balance change: %w", err)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f7233c7 and 2490231.

📒 Files selected for processing (1)
  • x/oracle/keeper/native_token.go (10 hunks)
🧰 Additional context used
📓 Learnings (1)
x/oracle/keeper/native_token.go (2)
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-10-09T01:26:20.424Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-09-20T00:02:14.496Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
🔇 Additional comments (1)
x/oracle/keeper/native_token.go (1)

154-157: Check for missing assetID in getDecimal

In the call to k.getDecimal(ctx, assetID) at line 154, ensure that assetID is valid. If getDecimal returns an error due to a missing or invalid assetID, handle it appropriately.

x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Show resolved Hide resolved
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 (2)
x/oracle/keeper/native_token.go (2)

Line range hint 173-195: Consider simplifying the validator list update logic

The logic for updating the validator list could be simplified and made more explicit. Currently, it's not clear why we're only adding validators on deposit and not removing them on withdrawal in this part of the code.

Consider refactoring this section to make the logic more explicit:

if amountInt64 > 0 {
    // Deposit: add a new validator to the staker's validatorList if not already present
    if !contains(stakerInfo.ValidatorPubkeyList, validatorPubkey) {
        stakerInfo.ValidatorPubkeyList = append(stakerInfo.ValidatorPubkeyList, validatorPubkey)
    }
} else {
    // Withdrawal: remove the validator from the staker's validatorList
    stakerInfo.ValidatorPubkeyList = removeValidator(stakerInfo.ValidatorPubkeyList, validatorPubkey)
}

// Helper functions
func contains(list []string, item string) bool {
    for _, v := range list {
        if v == item {
            return true
        }
    }
    return false
}

func removeValidator(list []string, item string) []string {
    for i, v := range list {
        if v == item {
            return append(list[:i], list[i+1:]...)
        }
    }
    return list
}

This refactoring makes the logic more explicit and handles both deposit and withdrawal cases.


Line range hint 337-411: Consider simplifying and optimizing parseBalanceChangeCapped

The parseBalanceChangeCapped function is quite complex and may be difficult to maintain. Consider breaking it down into smaller, more manageable functions. Additionally, the bit manipulation could potentially be optimized.

Consider refactoring this function into smaller, more focused functions:

  1. A function to parse the index bitmap
  2. A function to extract the length value
  3. A function to extract the change value

This would make the code more readable and easier to maintain. For example:

func parseBalanceChangeCapped(rawData []byte, sl types.StakerList) (map[string]int, error) {
    indexes := parseIndexBitmap(rawData[:32])
    changes := rawData[32:]
    stakerChanges := make(map[string]int)

    for i, hasChange := range indexes {
        if hasChange {
            length, offset := extractLengthValue(changes, offset)
            change, offset := extractChangeValue(changes, offset, length)
            stakerChanges[sl.StakerAddrs[i]] = change
        }
    }

    return stakerChanges, nil
}

func parseIndexBitmap(data []byte) []bool {
    // Implementation
}

func extractLengthValue(data []byte, offset int) (int, int) {
    // Implementation
}

func extractChangeValue(data []byte, offset int, length int) (int, int) {
    // Implementation
}

This refactoring would make the function easier to understand and maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2490231 and c0fb31c.

📒 Files selected for processing (1)
  • x/oracle/keeper/native_token.go (10 hunks)
🧰 Additional context used
📓 Learnings (1)
x/oracle/keeper/native_token.go (2)
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-10-09T01:26:20.424Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-09-20T00:02:14.496Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
🔇 Additional comments (2)
x/oracle/keeper/native_token.go (2)

Line range hint 1-421: Overall impression: Good changes with room for optimization

The changes introduce support for multiple networks and implement balance limits for NSTETH assets, which is a good improvement. The new constants, variables, and functions are well-structured and implement the required functionality.

However, there are several areas where the code could be optimized and improved:

  1. Consider using more efficient data structures (e.g., maps instead of slices) for better performance.
  2. Unify the error handling approach throughout the file for better consistency.
  3. Simplify complex functions like parseBalanceChangeCapped for better maintainability.
  4. Ensure consistent naming conventions (e.g., fix typos in error names).

These optimizations would enhance the overall quality and performance of the code.


152-158: ⚠️ Potential issue

Correct typo in error name

There's a typo in the error name ErrNSTAssetNotSurpported. It should be ErrNSTAssetNotSupported.

Apply this diff to correct the typo:

-		return types.ErrNSTAssetNotSurpported
+		return types.ErrNSTAssetNotSupported

Likely invalid or redundant comment.

x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (4)
x/oracle/keeper/native_token.go (4)

27-29: Consider addressing TODO comments regarding validation

The TODO comments at lines 27-29 suggest that hardcoding asset IDs is not ideal and that validation should occur before invoking oracle-related functions. Prioritizing these tasks will enhance code maintainability and flexibility.


179-179: Correct typos in comments for clarity

In the comment at line 179, there are typographical errors. It should read: "one validator can only deposit once before it completes withdrawal, which removes its pubkey from this list. So there's no need to check duplication."


342-343: Plan to upgrade parseBalanceChangeCapped for future changes

The TODO comment at lines 342-343 indicates that parseBalanceChangeCapped has limitations for larger balance changes and may need upgrades if extended to other use cases. Consider creating a plan to address this for future scalability.

Would you like assistance in outlining the upgrades or opening a GitHub issue to track this task?


418-418: Improve function comment for better understanding

The function comment at line 418 can be made clearer. Consider rephrasing it to:

// IsLimitedChangeNST checks if the given assetID corresponds to an asset with a capped balance change limit

This enhances readability and understanding of the function's purpose.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c0fb31c and 6be46e3.

📒 Files selected for processing (2)
  • x/oracle/keeper/native_token.go (11 hunks)
  • x/oracle/types/errors.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • x/oracle/types/errors.go
🧰 Additional context used
📓 Learnings (1)
x/oracle/keeper/native_token.go (3)
Learnt from: leonz789
PR: ExocoreNetwork/exocore#223
File: x/oracle/keeper/native_token.go:175-175
Timestamp: 2024-10-22T08:56:02.545Z
Learning: In `x/oracle/keeper/native_token.go`, duplicate entries in `ValidatorPubkeyList` are not possible because a validator can only deposit once before withdrawal, and the public key is removed upon withdrawal.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-09-20T00:02:14.496Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-10-09T01:26:20.424Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.

Comment on lines +230 to 231
if amountInt64 <= 0 {
return errors.New("remove unexist validator")
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 the error message for clarity

The error message at line 231 reads "remove unexist validator." Consider changing it to "remove nonexistent validator" for better readability.

Apply this diff to correct the error message:

-return errors.New("remove unexist validator")
+return errors.New("remove nonexistent validator")
📝 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
if amountInt64 <= 0 {
return errors.New("remove unexist validator")
if amountInt64 <= 0 {
return errors.New("remove nonexistent validator")

x/oracle/keeper/native_token.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (3)
x/oracle/keeper/native_token.go (3)

179-179: Correct typo in comment

In the comment at line 179, there's a typo: "which remove its pubkey form this list" should be "which removes its pubkey from this list."

Apply this diff to correct the typo:

-// one validator can only deposit once before it completed withdraw which remove its pubkey form this list. So there's no need to check duplication
+// One validator can only deposit once before it completes withdrawal, which removes its pubkey from this list. So there's no need to check duplication.

230-231: Ensure error message clarity

The error message at line 231 reads "remove unexist validator." For clarity and proper grammar, consider changing it to "remove nonexistent validator."

Apply this diff to correct the error message:

-return errors.New("remove unexist validator")
+return errors.New("remove nonexistent validator")

342-343: Reminder: Address the TODO comment

The TODO comment at lines 342-343 indicates that parseBalanceChangeCapped may need upgrades to support larger value changes and other chains. Prioritizing this will ensure future compatibility and scalability.

Would you like assistance in implementing these upgrades or opening a GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6be46e3 and 1999d24.

📒 Files selected for processing (1)
  • x/oracle/keeper/native_token.go (11 hunks)
🧰 Additional context used
📓 Learnings (1)
x/oracle/keeper/native_token.go (3)
Learnt from: leonz789
PR: ExocoreNetwork/exocore#223
File: x/oracle/keeper/native_token.go:175-175
Timestamp: 2024-10-22T08:56:02.545Z
Learning: In `x/oracle/keeper/native_token.go`, duplicate entries in `ValidatorPubkeyList` are not possible because a validator can only deposit once before withdrawal, and the public key is removed upon withdrawal.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-09-20T00:02:14.496Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.
Learnt from: leonz789
PR: ExocoreNetwork/exocore#189
File: x/oracle/keeper/native_token.go:0-0
Timestamp: 2024-10-09T01:26:20.424Z
Learning: The function `UpdateNativeTokenByDepositOrWithdraw` is invoked through the assets module, and data validation is properly handled there.

x/oracle/keeper/native_token.go Show resolved Hide resolved
@leonz789 leonz789 merged commit 150fb0e into ExocoreNetwork:develop Nov 11, 2024
19 checks passed
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.

5 participants