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(staking): migrate staking module #934

Merged
merged 1 commit into from
Jan 22, 2025
Merged

Conversation

zakir-code
Copy link
Contributor

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced staking module migration capabilities during system upgrade
    • Added coin swapping utility for token denomination transformations
  • Tests

    • Expanded test coverage for coin swapping functionality
    • Added validation checks for staking module migration process
  • Improvements

    • Improved error handling in upgrade migration process
    • Added comprehensive validation for staking module parameters and delegations

Copy link

coderabbitai bot commented Jan 21, 2025

Walkthrough

This pull request introduces enhancements to the upgrade process for a blockchain application, focusing on staking module migration and coin swapping functionality. The changes include adding a new migration function for the staking module, implementing a coin swapping mechanism, and extending upgrade testing capabilities. The modifications ensure proper handling of staking parameters, validator data, and provide additional testing coverage for coin transformation operations.

Changes

File Change Summary
app/upgrade_test.go Added call to nextversion.CheckStakingModule() in checkModulesData function
app/upgrades/v8/staking.go New file with migrateStakingModule() and CheckStakingModule() functions for staking module migration and validation
app/upgrades/v8/upgrade.go Updated migrateModulesData() to include staking module migration error handling
types/constant.go Added SwapCoins() function for batch coin transformation
types/constant_test.go Added TestSwapCoin() and TestSwapCoins() test functions

Sequence Diagram

sequenceDiagram
    participant Upgrade as Upgrade Process
    participant StakingKeeper as Staking Keeper
    participant Validator as Validators
    
    Upgrade->>StakingKeeper: Migrate Staking Module
    StakingKeeper->>StakingKeeper: Update Bond Denomination
    StakingKeeper->>Validator: Update Validator Tokens
    StakingKeeper->>Validator: Update Redelegations
    StakingKeeper->>Validator: Update Unbonding Delegations
    Upgrade->>StakingKeeper: Validate Migration
Loading

Possibly related PRs

Poem

🐰 Hopping through code with glee,
Staking modules now set free!
Coins transformed, upgrades take flight,
Blockchain dancing with delight!
Migration magic, test's embrace 🚀

✨ 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: 4

🧹 Nitpick comments (1)
app/upgrades/v8/staking.go (1)

41-55: Refactor duplicated code in iterations over delegations.

The logic for iterating and updating redelegations and unbonding delegations is similar. Consider refactoring this code into a reusable function to reduce duplication and improve maintainability.

For example, create a generic function to update delegation entries:

func updateDelegationEntries[T any](ctx sdk.Context, keeper *stakingkeeper.Keeper, iterateFunc func(sdk.Context, func(int64, T) bool) error, setFunc func(sdk.Context, T) error) error {
    var err error
    iterErr := iterateFunc(ctx, func(_ int64, delegation T) (stop bool) {
        // Update delegation entries...
        if setErr := setFunc(ctx, delegation); setErr != nil {
            err = setErr
            return true
        }
        return false
    })
    if iterErr != nil {
        return iterErr
    }
    if err != nil {
        return err
    }
    return nil
}

Then use this function for both redelegations and unbonding delegations.

Also applies to: 57-72

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4346856 and a492ebf.

📒 Files selected for processing (5)
  • app/upgrade_test.go (1 hunks)
  • app/upgrades/v8/staking.go (1 hunks)
  • app/upgrades/v8/upgrade.go (1 hunks)
  • types/constant.go (1 hunks)
  • types/constant_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (4)
types/constant.go (1)

113-119: Verify impact on staking module migration.

Since this PR is about migrating the staking module, please verify:

  1. The coin swap ratio (division by 100) aligns with staking module requirements
  2. All staking-related coin denominations are handled correctly
  3. Impact on existing staked amounts and validator power
app/upgrades/v8/staking.go (1)

76-99: LGTM: Staking module validation function is correctly implemented.

The CheckStakingModule function effectively validates staking parameters and ensures the integrity of delegations after migration. The implementation follows best practices and enhances the robustness of the upgrade process.

app/upgrade_test.go (1)

657-657: Add staking module check to module data validation.

The addition of nextversion.CheckStakingModule ensures that the staking module is validated during the upgrade tests. This step is crucial for verifying that staking data is correctly migrated and aligns with the expected state.

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

213-215: Include staking module migration in the upgrade process.

By calling migrateStakingModule within migrateModulesData, the upgrade now properly migrates staking module data. This addition ensures that all staking-related data is updated accordingly, maintaining consistency and data integrity during the upgrade.

Comment on lines +60 to +64
func TestSwapCoins(t *testing.T) {
coins := sdk.NewCoins(sdk.NewCoin(FXDenom, sdkmath.NewInt(100)))
swapCoins := SwapCoins(coins)
assert.NotEqual(t, swapCoins.String(), coins.String())
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for SwapCoins function.

The current test is limited to a single coin and only verifies string representation. Consider adding:

  1. Test cases with multiple coins (mix of FX and non-FX denominations)
  2. Explicit verification of individual coin amounts
  3. Edge cases (empty coins, nil coins)
 func TestSwapCoins(t *testing.T) {
-    coins := sdk.NewCoins(sdk.NewCoin(FXDenom, sdkmath.NewInt(100)))
-    swapCoins := SwapCoins(coins)
-    assert.NotEqual(t, swapCoins.String(), coins.String())
+    testCases := []struct {
+        name     string
+        coins    sdk.Coins
+        expected sdk.Coins
+    }{
+        {
+            name: "mixed denominations",
+            coins: sdk.NewCoins(
+                sdk.NewCoin(FXDenom, sdkmath.NewInt(100)),
+                sdk.NewCoin("other", sdkmath.NewInt(100)),
+            ),
+            expected: sdk.NewCoins(
+                sdk.NewCoin(FXDenom, sdkmath.NewInt(1)),
+                sdk.NewCoin("other", sdkmath.NewInt(100)),
+            ),
+        },
+        {
+            name:     "empty coins",
+            coins:    sdk.Coins{},
+            expected: sdk.Coins{},
+        },
+        {
+            name:     "nil coins",
+            coins:    nil,
+            expected: sdk.Coins{},
+        },
+    }
+
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
+            result := SwapCoins(tc.coins)
+            assert.Equal(t, tc.expected, result)
+        })
+    }
 }
📝 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 TestSwapCoins(t *testing.T) {
coins := sdk.NewCoins(sdk.NewCoin(FXDenom, sdkmath.NewInt(100)))
swapCoins := SwapCoins(coins)
assert.NotEqual(t, swapCoins.String(), coins.String())
}
func TestSwapCoins(t *testing.T) {
testCases := []struct {
name string
coins sdk.Coins
expected sdk.Coins
}{
{
name: "mixed denominations",
coins: sdk.NewCoins(
sdk.NewCoin(FXDenom, sdkmath.NewInt(100)),
sdk.NewCoin("other", sdkmath.NewInt(100)),
),
expected: sdk.NewCoins(
sdk.NewCoin(FXDenom, sdkmath.NewInt(1)),
sdk.NewCoin("other", sdkmath.NewInt(100)),
),
},
{
name: "empty coins",
coins: sdk.Coins{},
expected: sdk.Coins{},
},
{
name: "nil coins",
coins: nil,
expected: sdk.Coins{},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := SwapCoins(tc.coins)
assert.Equal(t, tc.expected, result)
})
}
}

Comment on lines +54 to +58
func TestSwapCoin(t *testing.T) {
coin := sdk.NewCoin(FXDenom, sdkmath.NewInt(100))
swapCoin := SwapCoin(coin)
assert.NotEqual(t, swapCoin.String(), coin.String())
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for SwapCoin function.

The current test only verifies that the string representation changes. Consider adding:

  1. Explicit verification that amount is divided by 100 for FXDenom
  2. Test case for non-FXDenom coins (should remain unchanged)
  3. Edge cases (zero amount, max int amount)
 func TestSwapCoin(t *testing.T) {
-    coin := sdk.NewCoin(FXDenom, sdkmath.NewInt(100))
-    swapCoin := SwapCoin(coin)
-    assert.NotEqual(t, swapCoin.String(), coin.String())
+    testCases := []struct {
+        name     string
+        coin     sdk.Coin
+        expected sdk.Coin
+    }{
+        {
+            name:     "FXDenom coin",
+            coin:     sdk.NewCoin(FXDenom, sdkmath.NewInt(100)),
+            expected: sdk.NewCoin(FXDenom, sdkmath.NewInt(1)),
+        },
+        {
+            name:     "non-FXDenom coin",
+            coin:     sdk.NewCoin("other", sdkmath.NewInt(100)),
+            expected: sdk.NewCoin("other", sdkmath.NewInt(100)),
+        },
+        {
+            name:     "zero amount",
+            coin:     sdk.NewCoin(FXDenom, sdkmath.ZeroInt()),
+            expected: sdk.NewCoin(FXDenom, sdkmath.ZeroInt()),
+        },
+    }
+
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
+            result := SwapCoin(tc.coin)
+            assert.Equal(t, tc.expected, result)
+        })
+    }
 }
📝 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 TestSwapCoin(t *testing.T) {
coin := sdk.NewCoin(FXDenom, sdkmath.NewInt(100))
swapCoin := SwapCoin(coin)
assert.NotEqual(t, swapCoin.String(), coin.String())
}
func TestSwapCoin(t *testing.T) {
testCases := []struct {
name string
coin sdk.Coin
expected sdk.Coin
}{
{
name: "FXDenom coin",
coin: sdk.NewCoin(FXDenom, sdkmath.NewInt(100)),
expected: sdk.NewCoin(FXDenom, sdkmath.NewInt(1)),
},
{
name: "non-FXDenom coin",
coin: sdk.NewCoin("other", sdkmath.NewInt(100)),
expected: sdk.NewCoin("other", sdkmath.NewInt(100)),
},
{
name: "zero amount",
coin: sdk.NewCoin(FXDenom, sdkmath.ZeroInt()),
expected: sdk.NewCoin(FXDenom, sdkmath.ZeroInt()),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := SwapCoin(tc.coin)
assert.Equal(t, tc.expected, result)
})
}
}

Comment on lines +113 to +119
func SwapCoins(coins sdk.Coins) sdk.Coins {
swapCoins := sdk.Coins{}
for _, coin := range coins {
swapCoins.Add(SwapCoin(coin))
}
return swapCoins
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential issues in SwapCoins implementation.

The current implementation has several issues:

  1. Using Add method modifies the receiver in-place
  2. Missing nil input handling
  3. No pre-allocation for better performance
  4. Missing validation for empty coins
 func SwapCoins(coins sdk.Coins) sdk.Coins {
+    if coins == nil {
+        return sdk.Coins{}
+    }
+    if len(coins) == 0 {
+        return sdk.Coins{}
+    }
-    swapCoins := sdk.Coins{}
+    swapCoins := make(sdk.Coins, 0, len(coins))
     for _, coin := range coins {
-        swapCoins.Add(SwapCoin(coin))
+        swapCoins = append(swapCoins, SwapCoin(coin))
     }
     return swapCoins
 }

Additionally, consider adding documentation to explain the purpose and behavior of this function.

+// SwapCoins applies the SwapCoin transformation to each coin in the input collection.
+// For coins with FXDenom, the amount is divided by 100, while other denominations remain unchanged.
+// Returns a new Coins collection containing the transformed coins.
 func SwapCoins(coins sdk.Coins) sdk.Coins {
📝 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 SwapCoins(coins sdk.Coins) sdk.Coins {
swapCoins := sdk.Coins{}
for _, coin := range coins {
swapCoins.Add(SwapCoin(coin))
}
return swapCoins
}
// SwapCoins applies the SwapCoin transformation to each coin in the input collection.
// For coins with FXDenom, the amount is divided by 100, while other denominations remain unchanged.
// Returns a new Coins collection containing the transformed coins.
func SwapCoins(coins sdk.Coins) sdk.Coins {
if coins == nil {
return sdk.Coins{}
}
if len(coins) == 0 {
return sdk.Coins{}
}
swapCoins := make(sdk.Coins, 0, len(coins))
for _, coin := range coins {
swapCoins = append(swapCoins, SwapCoin(coin))
}
return swapCoins
}

Comment on lines +41 to +55
iterErr := keeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
for i := 0; i < len(red.Entries); i++ {
red.Entries[i].InitialBalance = fxtypes.SwapAmount(red.Entries[i].InitialBalance)
}
if err = keeper.SetRedelegation(ctx, red); err != nil {
return true
}
return false
})
if iterErr != nil {
return iterErr
}
if err != nil {
return err
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid variable shadowing and ensure correct error handling.

In the closures for IterateRedelegations and IterateUnbondingDelegations, the variable err is assigned within the closure, which may shadow the outer err variable and lead to unintended behavior. To prevent this, declare a new variable inside the closure to capture errors, and handle them appropriately outside.

Apply this diff to fix the error handling in IterateRedelegations:

 for _, validator := range validators {
     // ...
 }
 
-iterErr := keeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
+iterErr := keeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
+    var setErr error
     for i := 0; i < len(red.Entries); i++ {
         red.Entries[i].InitialBalance = fxtypes.SwapAmount(red.Entries[i].InitialBalance)
     }
-    if err = keeper.SetRedelegation(ctx, red); err != nil {
+    if setErr = keeper.SetRedelegation(ctx, red); setErr != nil {
+        err = setErr
         return true
     }
     return false
 })
 if iterErr != nil {
     return iterErr
 }
-if err != nil {
+if err != nil {
     return err
 }

Similarly, fix the error handling in IterateUnbondingDelegations:

 iterErr = keeper.IterateUnbondingDelegations(ctx, func(index int64, ubd stakingtypes.UnbondingDelegation) (stop bool) {
+    var setErr error
     for i := 0; i < len(ubd.Entries); i++ {
         ubd.Entries[i].Balance = fxtypes.SwapAmount(ubd.Entries[i].Balance)
         ubd.Entries[i].InitialBalance = fxtypes.SwapAmount(ubd.Entries[i].InitialBalance)
     }
-    if err = keeper.SetUnbondingDelegation(ctx, ubd); err != nil {
+    if setErr = keeper.SetUnbondingDelegation(ctx, ubd); setErr != nil {
+        err = setErr
         return true
     }
     return false
 })
 if iterErr != nil {
     return iterErr
 }
-if err != nil {
+if err != nil {
     return err
 }

Committable suggestion skipped: line range outside the PR's diff.

@fx0x55 fx0x55 merged commit 3c22219 into main Jan 22, 2025
13 checks passed
@fx0x55 fx0x55 deleted the zakir/migrate-staking branch January 22, 2025 01:43
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