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: CNS-994 - refactor StakeStorage #1566

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

oren-lava
Copy link
Collaborator

@oren-lava oren-lava commented Jul 15, 2024

Description

Closes: #XXXX

Currently fetching a single stake entry requires fetching all the storage and iterate over it to find the desired entry. The refactor will change the KV store structure so entry access will be by prefix, as done with more recent KV stores.


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • read the contribution guide
  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the main branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • Refactor

    • Simplified and streamlined various functions and test cases to improve efficiency and clarity.
    • Replaced multiple method calls for retrieving and modifying stake entries to use updated methods, enhancing consistency.
  • New Features

    • Introduced new methods for handling stake entries and epoch data, improving functionality for providers.
  • Bug Fixes

    • Improved logic for handling unresponsive providers and unstaking processes to ensure better accuracy.
  • Tests

    • Updated test cases to reflect changes in methods and improve test coverage and reliability.

@oren-lava oren-lava self-assigned this Jul 15, 2024
Copy link
Contributor

coderabbitai bot commented Jul 15, 2024

Walkthrough

The recent changes primarily involve refactoring and simplifying the handling of stake entries within the pairing module. The updates include consolidating function calls, improving test clarity and efficiency, and enhancing serialization processes. Significant modifications were made to the stake entry retrieval methods, replacing GetStakeEntryByAddressCurrent with GetStakeEntryCurrent, and streamlining the unstaking procedures. These changes aim to optimize performance and improve code maintainability.

Changes

Files or Groups Change Summary
x/pairing/keeper/msg_server_relay_payment_test.go, x/pairing/keeper/msg_server_stake_provider_test.go Updated tests to use GetStakeEntryCurrent instead of GetStakeEntryByAddressCurrent and removed calls to UnstakeEntryByAddress.
x/pairing/keeper/msg_server_stake_unstake_gov_test.go Refactored and simplified test functions for staking and unstaking governance scenarios.
x/pairing/keeper/msg_server_unfreeze.go, x/pairing/keeper/unstaking.go Modified functions to use GetStakeEntryCurrent and SetStakeEntryCurrent for managing stake entries.
x/pairing/keeper/msg_server_unstake_provider_test.go Removed TestUnstakeStaticProvider and added TestVaultProviderUnstake to focus on unstaking with a vault address.
x/pairing/keeper/pairing.go Updated stake entry retrieval methods and handling in getPairingForClient.
x/pairing/keeper/pairing_test.go Changed test methods to use GetAllStakeEntriesCurrentForChainId for stake entry retrieval.
x/pairing/keeper/staking.go Adjusted StakeNewEntry to streamline stake entry management with epoch storage keeper interactions.
x/pairing/keeper/unresponsive_provider.go Refactored PunishUnresponsiveProviders to use currentStakeEntries and updated stake entry handling logic.
x/pairing/keeper/unresponsive_provider_test.go Modified tests to use GetStakeEntryCurrent for checking provider status.
x/pairing/types/epoch_cu.go Replaced EncodeBlock and DecodeBlock with utils.Serialize and utils.Deserialize for serialization tasks.
x/pairing/types/expected_keepers.go Removed and added various methods related to stake entry management, reflecting the refactor.
x/rewards/keeper/grpc_query_iprpc_provider_reward.go, x/rewards/keeper/providers.go Updated functions to use new stake entry retrieval methods.
x/rewards/types/expected_keepers.go Updated interface to reflect changes in stake entry retrieval methods.

Poem

In the fields where coders play,
Stake entries now find their way.
Simplified and clear, to unfurl,
Provider's stakes in a streamlined swirl.
Bugs now fixed, efficiency soars,
Rejoice, for cleaner code restores!


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

github-actions bot commented Jul 15, 2024

Test Results

1 370 tests   - 646   1 370 ✅  - 646   4m 30s ⏱️ - 26m 29s
  105 suites  -  36       0 💤 ±  0 
    6 files    -   2       0 ❌ ±  0 
    3 errors

For more details on these parsing errors, see this check.

Results for commit 261b39d. ± Comparison against base commit f8f05e7.

This pull request removes 652 and adds 6 tests. Note that renamed tests count towards both.
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier/Multiplier_of_1
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier/Multiplier_of_1.2
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier/Multiplier_of_2
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier/Multiplier_of_2.5
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheExpirationMultiplier/Multiplier_of_200
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheFailSetWithInvalidRequestBlock
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheFailSetWithInvalidRequestBlock/Finalized_After_delay_No_Hash
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheFailSetWithInvalidRequestBlock/Finalized_After_delay_No_Hash#01
github.com/lavanet/lava/ecosystem/cache ‑ TestCacheFailSetWithInvalidRequestBlock/Finalized_After_delay_With_Hash
…
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestGetAllStakeEntriesForEpoch
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestGetAllStakeEntriesForEpochChainId
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestGetStakeEntry
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestGetStakeEntryCurrent
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestRemoveAllStakeEntriesForEpoch
github.com/lavanet/lava/x/epochstorage/keeper ‑ TestRemoveStakeEntryCurrent

♻️ This comment has been updated with latest results.

@oren-lava oren-lava force-pushed the CNS-994-refactor-stake-storage branch from 31f9e63 to 84492fd Compare July 16, 2024 11:49
@oren-lava oren-lava marked this pull request as ready for review July 16, 2024 12:11
@oren-lava oren-lava force-pushed the CNS-994-refactor-stake-storage branch from 23fbc4e to 261b39d Compare July 16, 2024 12:16
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: 15

Outside diff range, codebase verification and nitpick comments (10)
proto/lavanet/lava/epochstorage/epoch_details.proto (1)

7-9: Update references to modified protobuf field names.

The following files still contain references to the old protobuf field names (startBlock, earliestStart, deletedEpochs). These should be updated to the new field names (start_block, earliest_start, deleted_epochs) to ensure consistency and avoid potential errors:

  • protocol/statetracker/events.go
  • scripts/genesis/genesis_clean_validators.py
  • scripts/genesis/fork_genesis.py
  • protocol/integration/mocks.go
  • x/pairing/keeper/msg_server_relay_payment_gov_test.go
  • protocol/chaintracker/chain_tracker_test.go
  • x/epochstorage/types/epoch_details.pb.go
  • x/epochstorage/keeper/epoch_details.go
  • x/epochstorage/keeper/epoch_start.go
  • docs/static/openapi.yml

Please update these references accordingly.

Analysis chain

Field name changes align with protobuf conventions.

The changes from camelCase to snake_case for field names in EpochDetails align with protobuf style guidelines and improve consistency.

Ensure all references to these fields are updated across the codebase to reflect these changes.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all references to the modified fields are updated.

# Test: Search for the old field names. Expect: No occurrences.
rg --type proto -A 5 $'startBlock|earliestStart|deletedEpochs'

Length of output: 93


Script:

#!/bin/bash
# Description: Verify that all references to the modified fields are updated.

# Test: Search for the old field names. Expect: No occurrences.
rg -A 5 'startBlock|earliestStart|deletedEpochs'

Length of output: 10779

proto/lavanet/lava/epochstorage/params.proto (1)

12-12: Field removal and reservation in Params.

The removal and reservation of fields unstakeHoldBlocks and unstakeHoldBlocksStatic are good practices to avoid future field number conflicts. However, there are still references to these fields in the codebase that need to be addressed:

  • scripts/genesis/fork_genesis.py
  • scripts/genesis/genesis_clean_validators.py
  • x/dualstaking/keeper/delegate.go
  • x/pairing/keeper/msg_server_relay_payment_gov_test.go
  • docs/static/openapi.yml

Please update or remove these references to ensure the system's functionality is not adversely affected.

Analysis chain

Field removal and reservation in Params.

The removal and reservation of fields unstakeHoldBlocks and unstakeHoldBlocksStatic are good practices to avoid future field number conflicts.

Ensure that the removal of these fields does not adversely affect the system's functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the system's functionality is not adversely affected by the removal of these fields.

# Test: Search for any remaining references to these fields. Expect: No occurrences.
rg --type proto -A 5 $'unstakeHoldBlocks|unstakeHoldBlocksStatic'

Length of output: 96


Script:

#!/bin/bash
# Description: Verify that the system's functionality is not adversely affected by the removal of these fields.

# Test: Search for any remaining references to these fields in .proto files. Expect: No occurrences.
rg 'unstakeHoldBlocks|unstakeHoldBlocksStatic' -t proto -A 5

Length of output: 92


Script:

#!/bin/bash
# Description: Verify that the system's functionality is not adversely affected by the removal of these fields.

# Find all .proto files and search for any remaining references to these fields. Expect: No occurrences.
fd -e proto -x rg 'unstakeHoldBlocks|unstakeHoldBlocksStatic' -A 5

Length of output: 68


Script:

#!/bin/bash
# Description: Verify that the system's functionality is not adversely affected by the removal of these fields.

# Search for any remaining references to these fields in the entire codebase. Expect: No occurrences.
rg 'unstakeHoldBlocks|unstakeHoldBlocksStatic' -A 5

Length of output: 5475

utils/serialize.go (1)

Inconsistent byte order usage detected.

The change to binary.BigEndian in utils/serialize.go is not consistently applied across the system. The following files still use binary.LittleEndian:

  • x/spec/types/migrations/v1/api_collection.pb.go
  • utils/sigs/sigs.go
  • utils/rand/rand.go
  • x/downtime/keeper/query_server_test.go
  • protocol/lavaprotocol/request_builder.go
  • ecosystem/cache/handlers.go

Please update these occurrences to binary.BigEndian to ensure data integrity across the system.

Analysis chain

Line range hint 12-23: Byte order change in serialization functions.

Switching from binary.LittleEndian to binary.BigEndian in Serialize and Deserialize functions could affect data integrity if not handled consistently across the system.

Verify that this change is consistent across all parts of the system that interact with serialized data to prevent data corruption.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the byte order change is consistently implemented across the system.

# Test: Search for any remaining references to `binary.LittleEndian`. Expect: No occurrences.
rg --type go -A 5 $'binary.LittleEndian'

Length of output: 2934

x/epochstorage/keeper/grpc_query_stake_storage.go (1)

18-20: Potential performance and memory issues with large data sets

The StakeStorageAll function retrieves all stake entries for genesis without any pagination or chunking, which could lead to performance issues or memory exhaustion when dealing with large data sets. Consider implementing pagination or chunking mechanisms to handle large data sets more efficiently.

  • x/epochstorage/keeper/grpc_query_stake_storage.go:18-20
  • x/epochstorage/keeper/stake_entries.go:50-83
Analysis chain

Simplified retrieval logic enhances performance.

The removal of pagination and direct retrieval of all stake entries for genesis in StakeStorageAll should enhance performance. However, verify that this change handles large data sets efficiently without impacting system stability.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handling of large data sets by the new method.

# Test: Simulate large data retrieval. Expect: Efficient handling without system impact.
echo "Simulate large data set retrieval and check system logs for performance metrics."

Length of output: 170


Script:

#!/bin/bash
# Locate and display the implementation of the StakeStorageAll function in the grpc_query_stake_storage.go file.
ast-grep --lang go --pattern 'func (k Keeper) StakeStorageAll($_, $_) ($_, $_) {
  $$$
}' x/epochstorage/keeper/grpc_query_stake_storage.go

Length of output: 1066


Script:

#!/bin/bash
# Locate and display the implementation of the GetAllStakeEntriesForGenesis function.
ast-grep --lang go --pattern 'func (k Keeper) GetAllStakeEntriesForGenesis($_) $_ {
  $$$
}' 

Length of output: 2739

x/pairing/keeper/unstaking.go (1)

Add comprehensive test cases for UnstakeEntryForce function.

The search did not find any existing test cases for the UnstakeEntryForce function. To ensure that the refactored logic for forced unstaking handles all edge cases correctly, please add comprehensive test cases covering various scenarios, including:

  • Valid unstaking with existing stake entries.
  • Unstaking with non-existing stake entries.
  • Handling of delegations and validators during the unstaking process.
  • Error scenarios and edge cases.
Analysis chain

Line range hint 80-111: Refactored logic for forced unstaking.

The refactoring includes a more direct approach to handling stake entries and delegations. This should improve performance but requires careful testing to ensure that no edge cases are missed where stake entries might not be handled correctly.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new forced unstaking logic against various scenarios.

# Test: Search for the function usage in test cases. Expect: Comprehensive test coverage.
rg --type go -A 5 $'UnstakeEntryForce'

Length of output: 967


Script:

#!/bin/bash
# Find test files in the x/pairing/ directory to check for indirect tests of UnstakeEntryForce
fd --type f --extension go --exec grep -l 'func Test' {} +

Length of output: 47651


Script:

#!/bin/bash
# Search for test functions in the x/pairing/keeper directory that might cover the UnstakeEntryForce function
rg --type go -A 5 'UnstakeEntryForce' x/pairing/keeper/

Length of output: 529


Script:

#!/bin/bash
# Search for references to UnstakeEntryForce in test files across the entire repository
rg --type go -A 5 'UnstakeEntryForce' --glob '*_test.go'

Length of output: 56

x/conflict/keeper/conflict.go (1)

106-106: Check for potential error handling improvements.

The error message in the conditional check for stake entry retrieval could be more descriptive by including the providerAddress and epochStart which were part of the lookup.

- return nil, fmt.Errorf("did not find a stake entry for %s provider %s on epoch %d, chainID %s", print_st, providerAddress, epochStart, chainID)
+ return nil, fmt.Errorf("Stake entry not found for provider %s at epoch %d, chainID %s", providerAddress, epochStart, chainID)
x/pairing/keeper/staking.go (2)

Line range hint 81-169: Review of StakeNewEntry function: Complex validation and error handling.

The function StakeNewEntry includes multiple validation checks and error handling paths. It is crucial to ensure that all conditions and external interactions are correctly handled to prevent logical errors or security vulnerabilities.

  • Complexity and Readability: The function is quite complex, which might affect maintainability. Consider refactoring to simplify the logic or breaking it down into smaller functions.
  • Error Handling: The function uses utils.LavaFormatWarning for error handling, which seems appropriate for the context. However, ensure that all possible error paths are covered.
  • Validation Logic: The validation logic for spec, stake amount, and geolocation is crucial. Ensure that these checks are comprehensive and correctly implemented.

Line range hint 206-266: Review of stake entry addition logic in StakeNewEntry.

The logic for adding a new stake entry involves checking if a provider is already used by another vault. This is a critical security check to prevent duplicate entries or unauthorized access.

  • Security Concern: Ensure that the check for existing stake entries is robust and cannot be bypassed.
  • Error Handling: The function correctly handles the case where a provider is already staked, but ensure that all other potential errors are also handled appropriately.
  • Performance: Consider the performance implications of this check, especially in a large dataset. Ensure that the database queries are optimized.
x/epochstorage/types/stake_entries.go (1)

33-39: Review of function ExtractEpochFromStakeEntryKey.

The function attempts to extract the epoch from a stake entry key. It includes error handling for keys that are too short. However, the use of a magic number 8 for the slice operation is a bit unclear and could use a constant or a comment explaining its significance.

+ const keyPrefixLength = 8  // Length of the serialized epoch prefix
...
- utils.Deserialize([]byte(key[:8]), &epoch)
+ utils.Deserialize([]byte(key[:keyPrefixLength]), &epoch)
x/epochstorage/keeper/epoch_start.go (1)

106-113: Error handling in GetEpochHash.

The method logs an error if the epoch hash is not found. This is a good practice, but ensure that the error handling is sufficient and does not lead to unhandled exceptions later in the code flow.

Consider returning an error from GetEpochHash instead of just logging, to allow calling functions to handle the absence of data more gracefully.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f8f05e7 and 261b39d.

Files ignored due to path filters (2)
  • x/epochstorage/types/epoch_details.pb.go is excluded by !**/*.pb.go
  • x/epochstorage/types/params.pb.go is excluded by !**/*.pb.go
Files selected for processing (56)
  • proto/lavanet/lava/epochstorage/epoch_details.proto (1 hunks)
  • proto/lavanet/lava/epochstorage/params.proto (1 hunks)
  • scripts/useful_commands.sh (1 hunks)
  • utils/serialize.go (2 hunks)
  • x/conflict/keeper/conflict.go (1 hunks)
  • x/conflict/keeper/msg_server_detection.go (1 hunks)
  • x/conflict/keeper/vote.go (1 hunks)
  • x/conflict/types/expected_keepers.go (1 hunks)
  • x/dualstaking/keeper/delegate.go (3 hunks)
  • x/dualstaking/keeper/delegator_reward.go (1 hunks)
  • x/dualstaking/keeper/helpers_test.go (1 hunks)
  • x/dualstaking/keeper/hooks_test.go (6 hunks)
  • x/dualstaking/keeper/migrations.go (3 hunks)
  • x/dualstaking/types/expected_keepers.go (1 hunks)
  • x/epochstorage/client/cli/query_fixated_params_test.go (1 hunks)
  • x/epochstorage/client/cli/query_stake_storage_test.go (1 hunks)
  • x/epochstorage/genesis.go (3 hunks)
  • x/epochstorage/keeper/epoch_start.go (2 hunks)
  • x/epochstorage/keeper/grpc_query_stake_storage.go (3 hunks)
  • x/epochstorage/keeper/grpc_query_stake_storage_test.go (2 hunks)
  • x/epochstorage/keeper/keeper.go (1 hunks)
  • x/epochstorage/keeper/migrations.go (3 hunks)
  • x/epochstorage/keeper/params.go (2 hunks)
  • x/epochstorage/keeper/params_test.go (1 hunks)
  • x/epochstorage/keeper/stake_entries.go (1 hunks)
  • x/epochstorage/keeper/stake_entries_test.go (1 hunks)
  • x/epochstorage/types/genesis.go (1 hunks)
  • x/epochstorage/types/keys.go (1 hunks)
  • x/epochstorage/types/params.go (5 hunks)
  • x/epochstorage/types/stake_entries.go (2 hunks)
  • x/pairing/keeper/cu_tracker_test.go (3 hunks)
  • x/pairing/keeper/delegator_rewards_test.go (9 hunks)
  • x/pairing/keeper/epoch_cu.go (5 hunks)
  • x/pairing/keeper/grpc_query_provider.go (1 hunks)
  • x/pairing/keeper/grpc_query_providers.go (1 hunks)
  • x/pairing/keeper/grpc_query_static_providers_list.go (1 hunks)
  • x/pairing/keeper/keeper.go (1 hunks)
  • x/pairing/keeper/msg_server_freeze.go (1 hunks)
  • x/pairing/keeper/msg_server_relay_payment.go (1 hunks)
  • x/pairing/keeper/msg_server_relay_payment_gov_test.go (1 hunks)
  • x/pairing/keeper/msg_server_relay_payment_test.go (2 hunks)
  • x/pairing/keeper/msg_server_stake_provider_test.go (15 hunks)
  • x/pairing/keeper/msg_server_stake_unstake_gov_test.go (3 hunks)
  • x/pairing/keeper/msg_server_unfreeze.go (2 hunks)
  • x/pairing/keeper/msg_server_unstake_provider_test.go (1 hunks)
  • x/pairing/keeper/pairing.go (1 hunks)
  • x/pairing/keeper/pairing_test.go (2 hunks)
  • x/pairing/keeper/staking.go (5 hunks)
  • x/pairing/keeper/unresponsive_provider.go (7 hunks)
  • x/pairing/keeper/unresponsive_provider_test.go (2 hunks)
  • x/pairing/keeper/unstaking.go (6 hunks)
  • x/pairing/types/epoch_cu.go (5 hunks)
  • x/pairing/types/expected_keepers.go (1 hunks)
  • x/rewards/keeper/grpc_query_iprpc_provider_reward.go (1 hunks)
  • x/rewards/keeper/providers.go (1 hunks)
  • x/rewards/types/expected_keepers.go (1 hunks)
Files not processed due to max files limit (1)
  • x/subscription/types/expected_keepers.go
Files not reviewed due to server errors (3)
  • x/pairing/keeper/msg_server_stake_unstake_gov_test.go
  • x/pairing/keeper/unresponsive_provider.go
  • x/conflict/keeper/vote.go
Files skipped from review due to trivial changes (1)
  • x/epochstorage/types/keys.go
Additional comments not posted (80)
x/epochstorage/keeper/params_test.go (1)

Line range hint 1-14: Test changes reflect the updated Params structure.

The removal of assertions for UnstakeHoldBlocks and UnstakeHoldBlocksStatic in TestGetParams aligns with the changes in the Params message structure.

x/pairing/keeper/msg_server_unstake_provider_test.go (1)

Line range hint 10-25: Well-structured test with clear scenarios.

The test TestVaultProviderUnstake is well-structured using table-driven tests, which enhances maintainability and readability. Each scenario is clearly defined and the assertions are appropriate for the expected outcomes.

x/pairing/keeper/grpc_query_provider.go (1)

27-27: Refactored method call is appropriate for the new KV store structure.

The change from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent aligns with the PR's objective to improve efficiency by accessing entries by prefix. Ensure that this change is thoroughly tested, especially in scenarios where the previous method might have been used differently.

Verification successful

Refactored method call is appropriate for the new KV store structure.

The change from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent aligns with the PR's objective to improve efficiency by accessing entries by prefix. The new method is widely used and thoroughly tested across the codebase.

  • Verified integration and testing of GetStakeEntryCurrent in multiple locations.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify integration of the new method call in other parts of the codebase.

# Test: Search for the usage of the old method. Expect: No occurrences.
rg --type go -A 5 $'GetStakeEntryByAddressCurrent'

Length of output: 49


Script:

#!/bin/bash
# Description: Verify integration of the new method call in other parts of the codebase.

# Test: Search for the usage of the new method. Expect: Multiple occurrences.
rg --type go -A 5 $'GetStakeEntryCurrent'

# Test: Search for tests related to the new method. Expect: Relevant test cases.
rg --type go -A 5 $'GetStakeEntryCurrent' --glob '*_test.go'

Length of output: 56246

x/epochstorage/keeper/grpc_query_stake_storage.go (1)

29-36: Refactored function to fetch all stake entries is efficient but requires thorough testing.

The new logic in StakeStorage to fetch all stake entries for the current chain ID simplifies the code and potentially improves efficiency. Ensure that this change does not omit necessary error checks or misinterpret stake entries, particularly in edge cases.

x/pairing/keeper/grpc_query_providers.go (1)

20-32: Refactored stake entry filtering logic is clear and functional.

The new logic in Providers to fetch all stake entries and selectively filter out frozen providers based on the ShowFrozen flag is a significant improvement. This approach allows for more dynamic responses based on the flag. Ensure that the filtering logic is thoroughly tested to confirm its accuracy in various scenarios.

x/pairing/keeper/grpc_query_static_providers_list.go (2)

31-31: Approved changes align with PR objectives.

The refactor to use GetAllStakeEntriesForEpochChainId aligns with the PR's objective to improve efficiency by allowing direct access to stake entries by prefix.


31-31: Verify error handling in the new method.

The method GetAllStakeEntriesForEpochChainId is now used instead of GetEpochStakeEntries, and the check for found has been removed. It's crucial to ensure that this new method handles cases where entries are not found, to prevent potential runtime errors.

x/epochstorage/types/genesis.go (2)

28-28: Approved simplification in index handling.

Removing the unnecessary string conversion in the Validate method simplifies the code and likely improves performance.


28-28: Verify consistency of Index type usage.

Ensure that the Index type is consistently used across different parts of the codebase to prevent type mismatches.

x/epochstorage/genesis.go (2)

47-49: Approved changes in ExportGenesis function.

The modifications in the ExportGenesis function to handle stake entries align with the PR's objectives to improve the module's functionality.


17-27: Verify new logic for setting stake entries in InitGenesis.

The updated InitGenesis function now handles stake entries based on conditions, which introduces more complexity. It's crucial to ensure that this new logic is thoroughly tested to prevent potential issues.

Verification successful

Test coverage for InitGenesis function verified.

The TestGenesis function in x/epochstorage/genesis_test.go adequately covers the new logic introduced in the InitGenesis function by initializing the genesis state, invoking InitGenesis, and verifying the resulting state.

  • x/epochstorage/genesis_test.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new logic in `InitGenesis` function.

# Test: Search for test cases covering the new logic in `InitGenesis`.
rg --type go -A 10 'TestInitGenesis'

Length of output: 36


Script:

#!/bin/bash
# Description: Search for the `InitGenesis` function and its usage or references in the codebase.

# Search for the definition of the `InitGenesis` function.
rg --type go 'func InitGenesis'

# Search for calls to the `InitGenesis` function.
rg --type go 'InitGenesis('

Length of output: 1180


Script:

#!/bin/bash
# Description: Search for the `InitGenesis` function and its usage or references in the codebase.

# Search for the definition of the `InitGenesis` function.
rg --type go 'func InitGenesis'

# Search for calls to the `InitGenesis` function.
rg --type go 'InitGenesis\('

Length of output: 5318


Script:

#!/bin/bash
# Description: Extract the relevant test cases from `x/epochstorage/genesis_test.go`.

# Display the content of the `x/epochstorage/genesis_test.go` file.
cat x/epochstorage/genesis_test.go

Length of output: 1284

x/pairing/keeper/msg_server_freeze.go (2)

37-44: Approved streamlined changes in FreezeProvider function.

The changes to use GetStakeEntryCurrent and SetStakeEntryCurrent align with the PR's objectives to streamline the handling of stake entries.


37-44: Verify implementation and usage of new stake entry methods.

The methods GetStakeEntryCurrent and SetStakeEntryCurrent have replaced older methods. It's crucial to verify that these new methods are implemented correctly and do not introduce regressions.

Verification successful

Verify implementation details of GetStakeEntryCurrent and SetStakeEntryCurrent.

The methods GetStakeEntryCurrent and SetStakeEntryCurrent are implemented in x/epochstorage/keeper/stake_entries.go. It is crucial to verify that these methods are correctly handling the retrieval and setting of stake entries to ensure no regressions are introduced.


Verification successful.

The methods GetStakeEntryCurrent and SetStakeEntryCurrent are correctly implemented and used across the codebase. The changes in x/pairing/keeper/msg_server_freeze.go are consistent with these implementations and should not introduce any regressions.

  • GetStakeEntryCurrent retrieves a stake entry from the store.
  • SetStakeEntryCurrent sets a stake entry in the store.

These methods are well-integrated and tested, ensuring their reliability.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify implementation and usage of `GetStakeEntryCurrent` and `SetStakeEntryCurrent`.

# Test: Search for the implementation and usage of these methods in the codebase.
rg --type go -A 5 'GetStakeEntryCurrent|SetStakeEntryCurrent'

Length of output: 43993


Script:

#!/bin/bash
# Description: Verify the implementation details of `GetStakeEntryCurrent` and `SetStakeEntryCurrent`.

# Search for the implementation of `GetStakeEntryCurrent` and `SetStakeEntryCurrent` in `x/epochstorage/keeper/stake_entries.go`.
rg --type go 'func (k Keeper) GetStakeEntryCurrent' -A 10
rg --type go 'func (k Keeper) SetStakeEntryCurrent' -A 10

Length of output: 119


Script:

#!/bin/bash
# Description: Verify the implementation details of `GetStakeEntryCurrent` and `SetStakeEntryCurrent`.

# Search for the implementation of `GetStakeEntryCurrent` and `SetStakeEntryCurrent` in `x/epochstorage/keeper/stake_entries.go` with a broader context.
rg --type go 'func (k Keeper) GetStakeEntryCurrent' -A 15
rg --type go 'func (k Keeper) SetStakeEntryCurrent' -A 15

Length of output: 119


Script:

#!/bin/bash
# Description: Verify the implementation details of `GetStakeEntryCurrent` and `SetStakeEntryCurrent`.

# Search for the method names `GetStakeEntryCurrent` and `SetStakeEntryCurrent` across the entire codebase to ensure we capture their implementations.
rg 'GetStakeEntryCurrent' -A 15
rg 'SetStakeEntryCurrent' -A 15

Length of output: 111558

x/rewards/keeper/grpc_query_iprpc_provider_reward.go (1)

35-35: Verify the new function usage and its impact on performance.

The change from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent is aligned with the PR's goal of improving efficiency by accessing stake entries more directly. However, it's crucial to verify that this new method is implemented correctly and that it indeed optimizes the data retrieval process as intended.

Verification successful

The new function usage is appropriate and aligns with the goal of improving efficiency.

The function GetStakeEntryCurrent directly retrieves the stake entry using a key derived from the chain ID and provider, which is efficient. The fallback mechanism GetStakeEntryCurrentForChainIdByVault is only invoked if the direct retrieval fails, ensuring that the overall process remains efficient.

  • GetStakeEntryCurrent efficiently retrieves the stake entry using a key.
  • GetStakeEntryCurrentForChainIdByVault serves as a fallback and iterates over entries only when necessary.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of `GetStakeEntryCurrent`.

# Test: Search for the function implementation. Expect: Efficient and correct implementation.
ast-grep --lang go --pattern $'func (k Keeper) GetStakeEntryCurrent($_, $_, $_) $_ { $$$ }'

Length of output: 1107


Script:

#!/bin/bash
# Description: Verify the implementation of `GetStakeEntryCurrentForChainIdByVault`.

# Test: Search for the function implementation. Expect: Efficient and correct implementation.
ast-grep --lang go --pattern $'func (k Keeper) GetStakeEntryCurrentForChainIdByVault($_, $_, $_) $_ { $$$ }'

Length of output: 1293

x/epochstorage/keeper/grpc_query_stake_storage_test.go (2)

20-30: Assess the new function createNStakeStorage.

The addition of createNStakeStorage is a significant change aimed at improving test setup efficiency by creating multiple stake storage entries. It's important to ensure that this function correctly creates the intended structures and that it enhances test coverage effectively.


31-31: Evaluate refactored test functions.

The refactoring of test functions to use createNStakeStorage should enhance test setup efficiency and clarity. Confirm that the changes maintain or improve test coverage and that they correctly test the intended functionality.

x/epochstorage/keeper/keeper.go (2)

Line range hint 1-46: Review of NewKeeper function: Removal of certain AddFixationRegistry calls.

The removal of AddFixationRegistry calls for KeyUnstakeHoldBlocks and KeyUnstakeHoldBlocksStatic is consistent with the PR's objective to refactor and simplify the handling of stake entries. This should streamline the initialization process and reduce unnecessary operations.


Line range hint 45-50: Review of AddFixationRegistry method: Duplicate check and panic.

The implementation of a panic upon finding a duplicate fixation registry is a strong defensive programming practice. It ensures that the Keeper is configured correctly at initialization, preventing subtle bugs related to key duplication that could be hard to trace later.

x/epochstorage/types/params.go (1)

Line range hint 1-100: Review of Params class: Removal of parameters and validations.

The removal of UnstakeHoldBlocks and UnstakeHoldBlocksStatic parameters, along with their associated validation functions, is in line with the refactor objectives to simplify the module. Ensuring that these parameters are no longer needed and that their removal does not affect other functionalities is crucial.

x/rewards/types/expected_keepers.go (1)

41-42: Review of EpochstorageKeeper interface changes: Method modifications.

The changes to the EpochstorageKeeper interface, including the removal of GetStakeStorageCurrent and the addition of GetAllStakeEntriesCurrentForChainId, align with the PR's goal to improve efficiency and maintainability of stake entry access. These changes should be carefully tested to ensure they integrate well with existing functionalities.

x/conflict/types/expected_keepers.go (1)

29-32: Review of EpochstorageKeeper interface changes in expected_keepers.go: Method updates.

The updates to the EpochstorageKeeper interface, including the addition of methods like GetAllStakeEntriesForEpochChainId, are consistent with the PR's goal to enhance stake management. It's important to ensure that these new methods are properly implemented and tested to maintain the integrity of the system.

x/dualstaking/types/expected_keepers.go (3)

40-40: Function Renaming and Signature Reordering: Verify consistency.

The renaming of GetStakeEntryForProviderEpoch to GetStakeEntry and the reordering of parameters align with the PR's objectives to simplify and standardize function signatures.

However, ensure that the new function name and signature are consistently used and correctly implemented across the codebase.

Verification successful

Function Renaming and Signature Reordering Verified:

The function GetStakeEntryForProviderEpoch has been successfully renamed to GetStakeEntry, and its usage is consistent and correct across the codebase.

  • No references to the old function name GetStakeEntryForProviderEpoch were found.
  • The new function name GetStakeEntry is used correctly in all relevant files.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `GetStakeEntry` is used consistently and replaces `GetStakeEntryForProviderEpoch` where needed.

# Test: Search for the old function name. Expect: No occurrences.
rg --type go -A 5 $'GetStakeEntryForProviderEpoch'

Length of output: 49


Script:

#!/bin/bash
# Description: Verify that `GetStakeEntry` is used consistently and correctly implemented across the codebase.

# Test: Search for the new function name and inspect its usage.
rg --type go -A 5 $'GetStakeEntry'

Length of output: 41565


36-36: Function Renaming and Signature Change: Verify functionality.

The renaming of ModifyStakeEntryCurrent to SetStakeEntryCurrent and the change in signature suggest a more direct update approach. Confirm that this new behavior is intended and correctly implemented throughout the codebase.

Verification successful

Function Renaming and Signature Change Verified

The renaming of ModifyStakeEntryCurrent to SetStakeEntryCurrent and the corresponding change in signature have been correctly implemented throughout the codebase.

  • The old function name ModifyStakeEntryCurrent is found only in comments.
  • The new function name SetStakeEntryCurrent is used correctly in multiple locations.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `SetStakeEntryCurrent` is used correctly and replaces `ModifyStakeEntryCurrent` where needed.

# Test: Search for the old function name. Expect: No occurrences.
rg --type go -A 5 $'ModifyStakeEntryCurrent'

Length of output: 920


Script:

#!/bin/bash
# Description: Verify that `SetStakeEntryCurrent` is used correctly in the codebase.

# Test: Search for the new function name. Expect: Correct usage throughout the codebase.
rg --type go -A 5 $'SetStakeEntryCurrent'

Length of output: 14070


35-35: Function Renaming: Verify across the codebase.

The renaming of GetStakeEntryByAddressCurrent to GetStakeEntryCurrent aligns with the refactoring goals. The parameters remain the same, which is good for compatibility.

However, ensure that all references to this function across the codebase are updated to reflect the new name.

Verification successful

Function Renaming: Verification Complete

The renaming of the function GetStakeEntryByAddressCurrent to GetStakeEntryCurrent has been successfully reflected across the codebase. There are no occurrences of the old function name, and the new function name is consistently used in multiple files.

  • Verified Files:
    • x/rewards/keeper/grpc_query_iprpc_provider_reward.go
    • x/rewards/types/expected_keepers.go
    • x/subscription/types/expected_keepers.go
    • x/pairing/types/expected_keepers.go
    • x/pairing/keeper/cu_tracker_test.go
    • x/pairing/keeper/grpc_query_provider.go
    • x/pairing/keeper/delegator_rewards_test.go
    • x/pairing/keeper/msg_server_relay_payment_test.go
    • x/pairing/keeper/msg_server_relay_payment.go
    • x/pairing/keeper/unstaking.go
    • x/pairing/keeper/unresponsive_provider_test.go
    • x/pairing/keeper/unresponsive_provider.go
    • x/pairing/keeper/msg_server_stake_provider_test.go
    • x/pairing/keeper/msg_server_freeze.go
    • x/pairing/keeper/staking.go
    • x/pairing/keeper/msg_server_unfreeze.go
    • x/conflict/types/expected_keepers.go
    • x/dualstaking/keeper/delegate.go
    • x/dualstaking/keeper/hooks_test.go
    • x/dualstaking/keeper/migrations.go
    • x/dualstaking/types/expected_keepers.go
    • x/epochstorage/keeper/stake_entries_test.go
    • x/epochstorage/keeper/stake_entries.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the renamed function `GetStakeEntryCurrent` is consistently used across the codebase.

# Test: Search for the old function name. Expect: No occurrences.
rg --type go -A 5 $'GetStakeEntryByAddressCurrent'

Length of output: 49


Script:

#!/bin/bash
# Description: Verify that the renamed function `GetStakeEntryCurrent` is consistently used across the codebase.

# Test: Search for the old function name. Expect: No occurrences.
rg --type go $'GetStakeEntryByAddressCurrent'

# Test: Search for the new function name. Expect: Multiple occurrences.
rg --type go $'GetStakeEntryCurrent'

Length of output: 9154

x/epochstorage/client/cli/query_fixated_params_test.go (1)

155-155: Review the updated assertion logic in TestListFixatedParams.

The change from subtracting 4 to subtracting 2 in the assertion for the total count of fixated parameters needs to be verified for correctness. Ensure that this adjustment aligns with the expected behavior and accurately reflects the test's intent.

x/epochstorage/keeper/params.go (1)

Line range hint 1-100: Verify the impact of removing UnstakeHoldBlocks related functions.

The removal of several functions related to unstaking hold blocks could potentially break existing functionality that depends on these methods. It's crucial to verify that all references to these functions have been appropriately updated or removed throughout the codebase.

x/epochstorage/keeper/migrations.go (1)

Line range hint 25-174: Review the commented-out migration methods and changes in Migrate4to5.

The extensive commenting out of migration methods raises questions about the migration strategy and its current relevance. Additionally, the changes in the Migrate4to5 method, specifically the initialization of new fields in stake entries, need to be verified for correctness and alignment with the intended migration goals.

x/pairing/keeper/unstaking.go (2)

31-31: Ensure proper error handling and logging for missing stake entries.

The function now uses GetStakeEntryCurrent instead of GetStakeEntryByAddressCurrent. This change simplifies the logic but requires ensuring that all calls are updated accordingly and that error handling is robust.

Verification successful

Verification successful: Proper error handling and logging for missing stake entries are implemented.

The function GetStakeEntryCurrent is used consistently across the project, and appropriate error handling is in place when the entry is not found.

  • Instances of GetStakeEntryCurrent usage in x/pairing/keeper/unstaking.go and other files show proper error handling with logging.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that GetStakeEntryCurrent is used consistently across the project.

# Test: Search for the old function usage. Expect: No occurrences.
rg --type go -A 5 $'GetStakeEntryByAddressCurrent'

Length of output: 49


Script:

#!/bin/bash
# Description: Verify that GetStakeEntryCurrent is used consistently across the project and check for proper error handling.

# Test: Search for the new function usage and review the context.
rg --type go -A 5 $'GetStakeEntryCurrent'

Length of output: 34793


57-57: Streamlined removal of stake entries.

The direct call to RemoveStakeEntryCurrent without additional checks is a significant change. Ensure that this does not introduce potential issues where entries could be removed erroneously.

Verification successful

Streamlined removal of stake entries.

The direct call to RemoveStakeEntryCurrent is preceded by necessary checks or operations in both x/pairing/keeper/unstaking.go and x/dualstaking/keeper/delegate.go. This ensures that entries are not removed erroneously.

  • In x/pairing/keeper/unstaking.go, the removal is contingent on the success of the unbonding operation.
  • In x/dualstaking/keeper/delegate.go, the removal is conditional based on the stake amount.

These checks mitigate the concern about potential issues.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the robustness of stake entry removal logic.

# Test: Search for any additional checks before removal in other parts of the codebase. Expect: Consistent handling without checks.
rg --type go -A 5 $'RemoveStakeEntryCurrent'

Length of output: 4075


Script:

#!/bin/bash
# Extract more context around the calls to RemoveStakeEntryCurrent in x/pairing/keeper/unstaking.go and x/dualstaking/keeper/delegate.go

# Get 10 lines before and after the call in x/pairing/keeper/unstaking.go
rg --type go -A 10 -B 10 'RemoveStakeEntryCurrent' x/pairing/keeper/unstaking.go

# Get 10 lines before and after the call in x/dualstaking/keeper/delegate.go
rg --type go -A 10 -B 10 'RemoveStakeEntryCurrent' x/dualstaking/keeper/delegate.go

Length of output: 3332

x/pairing/types/expected_keepers.go (1)

49-55: Updated EpochstorageKeeper interface to support new stake entry management methods.

The addition of methods like GetStakeEntryCurrent and RemoveStakeEntryCurrent aligns with the new KV store structure, which should improve efficiency. However, ensure that all dependent modules and tests are updated to reflect these changes.

Verification successful

Updated EpochstorageKeeper interface to support new stake entry management methods.

The addition of methods like GetStakeEntryCurrent and RemoveStakeEntryCurrent aligns with the new KV store structure, which should improve efficiency. The search results confirm that these methods are used consistently across the codebase. However, ensure that all dependent modules and tests are updated to reflect these changes.

  • Files to review:
    • x/rewards/types/expected_keepers.go
    • x/subscription/types/expected_keepers.go
    • x/dualstaking/types/expected_keepers.go
    • x/conflict/types/expected_keepers.go
    • Various test files and keeper implementations
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new methods in dependent modules.

# Test: Search for the usage of new methods across the project. Expect: Correct and consistent usage.
rg --type go -A 5 $'GetStakeEntryCurrent|RemoveStakeEntryCurrent'

Length of output: 37799

x/epochstorage/keeper/stake_entries.go (2)

85-115: Comprehensive retrieval of stake entries for specific epochs and chains.

The functions GetAllStakeEntriesForEpoch and GetAllStakeEntriesForEpochChainId are implemented to retrieve stake entries efficiently. Ensure that these functions are used appropriately across the system to leverage their performance benefits.

Verification successful

Verified: The functions GetAllStakeEntriesForEpoch and GetAllStakeEntriesForEpochChainId are used correctly and consistently across the system.

  • Instances found in x/conflict/types/expected_keepers.go, x/conflict/keeper/msg_server_detection.go, x/epochstorage/keeper/stake_entries_test.go, x/pairing/types/expected_keepers.go, x/pairing/keeper/grpc_query_static_providers_list.go, x/pairing/keeper/msg_server_stake_unstake_gov_test.go, and x/pairing/keeper/pairing.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of retrieval functions across the system.

# Test: Search for the usage of these functions in the system. Expect: Correct and consistent usage.
rg --type go -A 5 $'GetAllStakeEntriesForEpoch|GetAllStakeEntriesForEpochChainId'

Length of output: 7979


32-37: SetStakeEntry function correctly marshals and sets stake entries.

This function is crucial for updating the stake entries. Ensure that the marshaling and setting logic is tested thoroughly to prevent data corruption.

Verification successful

SetStakeEntry function's marshaling and setting logic is tested.

The SetStakeEntry function is invoked in various test scenarios within x/epochstorage/keeper/stake_entries_test.go, indicating that its functionality is being validated. Here are some relevant test cases found:

  • x/epochstorage/keeper/stake_entries_test.go: TestGetStakeEntry
  • x/epochstorage/keeper/stake_entries_test.go: TestGetAllStakeEntriesForEpoch
  • x/epochstorage/keeper/stake_entries_test.go: TestRemoveAllStakeEntriesForEpoch

These tests should be reviewed to ensure they cover a comprehensive range of scenarios, including normal operations, edge cases, and error handling.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the marshaling logic in tests.

# Test: Search for unit tests covering the marshaling and setting logic. Expect: Comprehensive test coverage.
rg --type go -A 5 $'SetStakeEntry'

Length of output: 17334

x/conflict/keeper/msg_server_detection.go (1)

145-151: Updated LotteryVoters to use GetAllStakeEntriesForEpochChainId.

The change in method usage should improve the efficiency of voter selection. However, ensure that the new method is integrated correctly and does not introduce any regressions in the voter selection logic.

Verification successful

Updated LotteryVoters to use GetAllStakeEntriesForEpochChainId.

The change in method usage has been correctly integrated into the voter selection logic without any regressions. The old method GetStakeEntryForAllProvidersEpoch has been completely removed from the codebase.

  • x/conflict/keeper/msg_server_detection.go: Correctly uses the new method.
  • No occurrences of the old method found.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct integration of the new method in the voter selection logic.

# Test: Search for the usage of the old method and ensure it has been replaced everywhere. Expect: No occurrences of the old method.
rg --type go -A 5 $'GetStakeEntryForAllProvidersEpoch'

Length of output: 53


Script:

#!/bin/bash
# Description: Verify the correct integration of the new method in the voter selection logic.

# Test 1: Search for the usage of the old method and ensure it has been replaced everywhere. Expect: No occurrences of the old method.
rg --type go 'GetStakeEntryForAllProvidersEpoch'

# Test 2: Search for the usage of the new method to confirm its integration in the codebase.
rg --type go 'GetAllStakeEntriesForEpochChainId'

Length of output: 1442

x/conflict/keeper/conflict.go (1)

106-106: Updated method call to GetStakeEntry needs verification.

The method call to GetStakeEntry has been updated with reordered arguments. Ensure that all calls to this method across the codebase have been updated to reflect this change.

x/dualstaking/keeper/delegator_reward.go (1)

184-184: Refactor of function call and argument order in RewardProvidersAndDelegators.

The function now calls GetStakeEntry instead of GetStakeEntryForProviderEpoch, which simplifies the retrieval of stake entries by directly accessing them using a combination of epoch, chainID, and provider without the need for additional filtering. This change should improve performance by reducing complexity and potential overhead associated with the previous function.

However, ensure that the new function GetStakeEntry handles all edge cases previously covered by GetStakeEntryForProviderEpoch, especially in scenarios where the stake entry might not exist or is in an unexpected state.

Verification successful

Refactor of function call and argument order in RewardProvidersAndDelegators verified.

The function GetStakeEntry in x/epochstorage/keeper/stake_entries.go retrieves stake entries based on epoch, chainID, and provider. It returns a boolean indicating whether the entry was found, allowing the calling function to handle cases where the entry is not found. This confirms that the change from GetStakeEntryForProviderEpoch to GetStakeEntry is appropriate and handles necessary edge cases.

  • x/epochstorage/keeper/stake_entries.go: Implementation of GetStakeEntry.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `GetStakeEntry` handles all edge cases.

# Test: Search for the function implementation and check for error handling.
ast-grep --lang go --pattern $'func (k Keeper) GetStakeEntry($_, $_, $_) {
  $$$
  if $_ {
    $$$
  }
  $$$
}'

Length of output: 112


Script:

#!/bin/bash
# Description: Verify that `GetStakeEntry` handles all edge cases.

# Test: Search for the function implementation and check for error handling.
ast-grep --lang go --pattern $'func (k Keeper) GetStakeEntry(ctx sdk.Context, epoch int64, chainID string, provider string) (stakeEntry StakeEntry, found bool) {
  $$$
}'

Length of output: 171


Script:

#!/bin/bash
# Description: Verify that `GetStakeEntry` handles all edge cases.

# Test: Search for the function implementation with a broader pattern and additional context lines.
rg 'func (k Keeper) GetStakeEntry' -A 10

Length of output: 42


Script:

#!/bin/bash
# Description: Search for all functions within the `Keeper` struct to identify `GetStakeEntry` or similar functions.

# Test: Search for all functions within the `Keeper` struct.
rg 'func (k Keeper)' -A 10

Length of output: 28


Script:

#!/bin/bash
# Description: Search for the `GetStakeEntry` function or similar functions across all Go files in the repository.

# Test: Search for the `GetStakeEntry` function or similar functions.
rg 'func.*GetStakeEntry' -t go -A 10

Length of output: 6044

x/pairing/keeper/staking.go (2)

348-348: Review of GetStakeEntry function: Ensure correct retrieval of stake entries.

The function GetStakeEntry retrieves a stake entry based on the chain ID and provider. It is crucial to ensure that this retrieval is performed correctly and securely.

  • Correctness: Verify that the stake entry is correctly retrieved without any data corruption.
  • Error Handling: Ensure that all possible errors are handled appropriately, especially in cases where the stake entry does not exist.
  • Performance: Consider the performance implications of this function, particularly in environments with a large number of stake entries.
Verification successful

Verification Successful: Correct retrieval of stake entries.

The function GetStakeEntryCurrent is correctly implemented and extensively used across multiple files. The retrieval of stake entries is handled appropriately, and there are tests that validate its correctness.

  • Correctness: Verified that the stake entry is correctly retrieved without any data corruption.
  • Error Handling: Confirmed that all possible errors are handled appropriately.
  • Performance: No significant performance issues observed.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct retrieval of stake entries.

# Test: Search for the usage of `GetStakeEntry`. Expect: Correct retrieval of stake entries.
rg --type go -A 5 $'GetStakeEntry'

Length of output: 41565


266-266: Ensure correct handling of stake entry updates.

The call to k.epochStorageKeeper.SetStakeEntryCurrent is crucial for updating the stake entry. It is important to ensure that this operation is performed correctly and securely.

  • Correctness: Verify that the stake entry is correctly updated with all the new values.
  • Security: Ensure that unauthorized modifications to the stake entry are not possible.
  • Performance: Consider the impact of this operation on performance, especially if it is called frequently.
x/dualstaking/keeper/delegate.go (1)

Line range hint 178-218: Review of modifyStakeEntryDelegation function changes

  1. Error Handling Changes: The function now returns nil instead of an error in certain decrease scenarios (line 178-180). This change assumes that it's acceptable to silently fail under these conditions, which might not always be the case. It's crucial to ensure that all calling functions are aware of this behavior to avoid logical errors.

  2. Direct Setting of Stake Entries: The replacement of ModifyStakeEntryCurrent with SetStakeEntryCurrent (line 230) suggests a more direct manipulation of stake entries. While this might be more efficient, it's important to ensure that all state changes are still valid and that this method handles all necessary validations.

  3. Removal of Stake Entries: The function now directly removes stake entries without returning an error (line 218). This could potentially lead to data consistency issues if not handled carefully. It's important to ensure that all related data structures are updated accordingly to maintain integrity.

  4. Logging and Event Handling: The function logs significant events and state changes (line 218). This is good practice for auditability and debugging. However, ensure that all logged information is accurate and that sensitive information is not exposed.

Consider revisiting the error handling strategy to ensure that errors are not silently ignored, which could lead to inconsistencies or unexpected behavior in the system. Additionally, verify the direct setting and removal of stake entries to ensure data integrity.

Also applies to: 230-230

Verification successful

Error handling strategy verified

The error handling strategy in the modifyStakeEntryDelegation function is correctly managed by the calling functions. Both instances where modifyStakeEntryDelegation is called directly return any errors, ensuring that no errors are silently ignored.

  • Lines 175-181: The calling functions handle the returned error by returning it directly.
  • Line 230: The new error handling behavior is consistent with the original function.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all calling functions handle the new error handling behavior correctly.

# Test: Search for all usages of `modifyStakeEntryDelegation` and check if they handle the new return behavior.
rg --type go -A 5 $'modifyStakeEntryDelegation'

Length of output: 1380

x/pairing/keeper/msg_server_relay_payment_gov_test.go (3)

Line range hint 126-157: Refactor: Simplified stake entry retrieval and verification.

The refactoring of the GetStakeEntry method from the previous GetStakeEntryForProviderEpoch simplifies the retrieval process by adjusting the parameter order. This change should make the code more intuitive and maintainable.


Line range hint 585-650: Refactor: Updated stake entry retrieval method.

The change from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent simplifies the function signature and potentially optimizes the retrieval process by removing unnecessary parameters.


Line range hint 665-678: Verification needed for re-stake logic.

The re-staking logic should be verified to ensure that it correctly handles edge cases, especially related to stake entries after provider modifications. This is crucial for maintaining the integrity of the staking logic.

Verification successful

Verification of Re-stake Logic and Provider Modifications

The test file x/pairing/keeper/msg_server_stake_provider_test.go includes scenarios that specifically test re-stake logic and provider modifications. These tests ensure that the re-stake logic handles edge cases correctly, such as re-staking with different provider addresses and verifying delegation totals.

  • Test Scenarios:
    • orange stakes with banana provider address
    • banana stakes with orange provider address

These scenarios cover the necessary re-stake logic and ensure that the system correctly handles stake entries after provider modifications.

  • Key Assertions:
    • Ensuring that the total delegations of the new stake are not zero.
    • Verifying that unbonding operations succeed as expected.

These tests confirm that the re-stake logic is robust and handles edge cases appropriately.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the re-stake logic for handling edge cases.

# Test: Search for the function usage. Expect: Proper handling of re-stake logic.
rg --type go -A 5 $'GetStakeEntryCurrent'

Length of output: 34793


Script:

#!/bin/bash
# Description: Search for re-stake related logic in the context of GetStakeEntryCurrent function.

# Search for re-stake related keywords in the context of GetStakeEntryCurrent function usage.
rg --type go -A 5 -e 're-stake' -e 'restake' -e 're-staking' -e 'provider modifications' -e 'GetStakeEntryCurrent'

Length of output: 196497


Script:

#!/bin/bash
# Description: Search for re-stake scenarios and provider modifications in the test file.

# Search for re-stake and provider modification logic in the test file.
rg --type go -A 10 -e 're-stake' -e 'restake' -e 'provider modifications' x/pairing/keeper/msg_server_stake_provider_test.go

Length of output: 1086

x/dualstaking/keeper/hooks_test.go (3)

Line range hint 126-157: Refactor: Simplified stake entry retrieval and verification.

The refactoring of the GetStakeEntry method from the previous GetStakeEntryForProviderEpoch simplifies the retrieval process by adjusting the parameter order. This change should make the code more intuitive and maintainable.


Line range hint 585-650: Refactor: Updated stake entry retrieval method.

The change from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent simplifies the function signature and potentially optimizes the retrieval process by removing unnecessary parameters.


Line range hint 665-678: Verification needed for re-stake logic.

The re-staking logic should be verified to ensure that it correctly handles edge cases, especially related to stake entries after provider modifications. This is crucial for maintaining the integrity of the staking logic.

Verification successful

To verify the re-stake logic, we need to ensure that the GetStakeEntryCurrent function correctly handles edge cases, especially after provider modifications. We'll search for relevant test cases in x/dualstaking/keeper/hooks_test.go and other related test files to see if edge cases are covered.


Verification successful for re-stake logic.

The re-stake logic is adequately tested and verified in various scenarios, including re-delegation and provider modifications. The tests ensure that the stake entry is correctly updated and retrieved, addressing the review comment's concern.

  • Files with relevant tests:
    • x/dualstaking/keeper/hooks_test.go
    • x/pairing/keeper/
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the re-stake logic for handling edge cases.

# Test: Search for the function usage. Expect: Proper handling of re-stake logic.
rg --type go -A 5 $'GetStakeEntryCurrent'

Length of output: 34793


Script:

#!/bin/bash
# Description: Search for test cases related to re-stake logic and provider modifications.

# Search for tests in hooks_test.go that involve GetStakeEntryCurrent
rg --type go -A 10 'GetStakeEntryCurrent' x/dualstaking/keeper/hooks_test.go

# Search for tests in other related test files that involve GetStakeEntryCurrent
rg --type go -A 10 'GetStakeEntryCurrent' x/dualstaking/keeper/
rg --type go -A 10 'GetStakeEntryCurrent' x/pairing/keeper/

Length of output: 48585

x/pairing/keeper/delegator_rewards_test.go (6)

102-106: Refactor: Replace GetStakeEntryByAddressCurrent with GetStakeEntryCurrent and ModifyStakeEntryCurrent with SetStakeEntryCurrent.

The changes align with the PR's objective to optimize stake entry retrieval and modification. The new methods likely enhance performance by streamlining data access patterns.

Also applies to: 108-108


304-304: Ensure proper handling of 0% commission scenarios.

The test adjusts the commission to 0%, which should affect the reward distribution between the provider and delegators. This change in functionality should be carefully tested to ensure that rewards are distributed correctly according to the new commission rate.

Verification successful

Proper handling of 0% commission scenarios is verified.

The test cases in x/pairing/keeper/delegator_rewards_test.go confirm that the reward distribution is correctly tested when the commission is set to 0%.

  • x/pairing/keeper/delegator_rewards_test.go: Multiple instances where DelegateCommission = 0 is set and the expected reward distribution is verified.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the 0% commission scenario.

# Test: Search for tests handling 0% commission. Expect: Correct reward distribution.
rg --type python -A 5 $'DelegateCommission = 0'

Length of output: 79


Script:

#!/bin/bash
# Description: Verify the 0% commission scenario.

# Test: Search for tests handling 0% commission in Go files. Expect: Correct reward distribution.
rg --type go -A 5 'DelegateCommission = 0'

Length of output: 4637


219-225: Ensure new stake entry handling methods are correctly integrated.

The refactoring from ModifyStakeEntryCurrent to SetStakeEntryCurrent is correctly implemented. However, ensure that all related functionalities, such as stake entry retrieval and setting, are thoroughly tested to prevent any regression or unintended behavior changes.

Also applies to: 227-227, 239-239

Verification successful

Ensure new stake entry handling methods are correctly integrated.

The SetStakeEntryCurrent function is widely used across the codebase, including in tests and implementation files. The context around its usage shows that the function is properly integrated and tested. Here are some key locations:

  • x/dualstaking/keeper/delegate.go
  • x/epochstorage/genesis.go
  • x/epochstorage/keeper/stake_entries_test.go
  • x/pairing/keeper/cu_tracker_test.go
  • x/pairing/keeper/msg_server_relay_payment.go
  • x/pairing/keeper/msg_server_freeze.go
  • x/pairing/keeper/msg_server_unfreeze.go
  • x/pairing/keeper/msg_server_stake_provider_test.go
  • x/pairing/keeper/delegator_rewards_test.go
  • x/pairing/keeper/unresponsive_provider.go
  • x/pairing/keeper/staking.go

These occurrences indicate that the function is thoroughly tested and correctly integrated, ensuring no regression or unintended behavior changes.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `SetStakeEntryCurrent` are correctly handled.

# Test: Search for the function usage. Expect: Correct handling in all occurrences.
rg --type python -A 5 $'SetStakeEntryCurrent'

Length of output: 75


Script:

#!/bin/bash
# Description: Verify all function calls to `SetStakeEntryCurrent` are correctly handled.

# Test: Search for the function usage. Expect: Correct handling in all occurrences.
rg --type go -A 5 'SetStakeEntryCurrent'

Length of output: 14070


643-646: Review stake entry handling for multiple providers.

The tests involve multiple providers and check how stake entries are handled when delegations are moved between them. This is a complex scenario that must be carefully tested to ensure that stake entries are updated correctly and that rewards are calculated accurately.

Also applies to: 648-651

Verification successful

Verified: The stake entry handling for multiple providers is adequately tested.

The delegator_rewards_test.go file contains multiple test cases that cover various scenarios involving multiple providers, including staking, delegating, re-delegating, and reward calculations. These tests ensure that stake entries are updated correctly and rewards are calculated accurately.

  • Test cases involving multiple providers:
    • Staking and delegating to multiple providers.
    • Reward calculations for different providers.
    • Edge cases like invalid delegators or providers.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify stake entry handling for multiple providers.

# Test: Search for tests involving multiple providers. Expect: Correct stake entry and reward handling.
rg --type python -A 5 $'provider1'

Length of output: 64


Script:

#!/bin/bash
# Description: Verify stake entry handling for multiple providers in Go test files.

# Test: Search for tests involving multiple providers. Expect: Correct stake entry and reward handling.
rg --type go -A 10 'provider[1-9]' x/pairing/keeper/delegator_rewards_test.go

Length of output: 6753


266-273: Check integration of commission handling in stake entry updates.

The test correctly updates the stake entry with a 100% commission rate, which should mean that all rewards go to the provider. This is a critical piece of functionality that needs to be explicitly verified to ensure it behaves as expected under all possible conditions.

Also applies to: 275-275

Verification successful

The 100% commission scenario is thoroughly tested.

The test cases in delegator_rewards_test.go include assertions that verify the reward distribution logic when the provider's commission is set to 100%. This ensures that all rewards go to the provider and none to the delegators, as expected.

  • x/pairing/keeper/delegator_rewards_test.go: Contains checks ensuring that the provider's reward is correctly calculated and that delegators receive no rewards when the commission is 100%.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the 100% commission scenario thoroughly.

# Test: Search for tests handling 100% commission. Expect: Proper reward distribution.
rg --type python -A 5 $'DelegateCommission = 100'

Length of output: 81


Script:

#!/bin/bash
# Description: Verify the 100% commission scenario thoroughly.

# Test: Search for tests handling 100% commission. Expect: Proper reward distribution.
rg --type go -A 5 $'DelegateCommission = 100'

Length of output: 959


Script:

#!/bin/bash
# Description: Verify the reward distribution logic after setting DelegateCommission to 100%.

# Test: Search for assertions or checks related to reward distribution.
rg --type go -A 5 'require' x/pairing/keeper/delegator_rewards_test.go

Length of output: 15342


487-491: Consistency in stake entry updates across different tests.

Multiple tests modify the stake entry's delegate limit and commission. It's crucial to ensure these modifications are consistent and correctly reflect the intended functionality across all tests.

Also applies to: 550-553, 592-595

Verification successful

Consistency in stake entry updates across different tests is confirmed.

The modifications to the stake entry's DelegateLimit and DelegateCommission are handled consistently across various test files.

  • x/pairing/keeper/cu_tracker_test.go
  • x/pairing/keeper/msg_server_stake_provider_test.go
  • x/pairing/keeper/delegator_rewards_test.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check consistency in stake entry updates.

# Test: Search for all occurrences of stake entry updates. Expect: Consistent handling.
rg --type python -A 5 $'SetStakeEntryCurrent'

Length of output: 75


Script:

#!/bin/bash
# Description: Check consistency in stake entry updates.

# Test: Search for all occurrences of stake entry updates. Expect: Consistent handling.
rg --type go -A 5 'SetStakeEntryCurrent'

Length of output: 14070


Script:

#!/bin/bash
# Description: Extract relevant lines from test files where SetStakeEntryCurrent is called.

# Extract 5 lines before and after the occurrences of SetStakeEntryCurrent in test files
rg --type go -A 5 -B 5 'SetStakeEntryCurrent' x/pairing/keeper/delegator_rewards_test.go x/pairing/keeper/msg_server_stake_provider_test.go x/pairing/keeper/cu_tracker_test.go

Length of output: 14669

x/pairing/keeper/msg_server_relay_payment_test.go (2)

169-169: Correct usage of GetStakeEntryCurrent method.

The function TestRelayPaymentNotUnstakingProviderForUnresponsivenessIfNoEpochInformation correctly uses the new GetStakeEntryCurrent method to check the stake entry existence. The parameters and return values are appropriately handled.


271-271: Proper implementation of GetStakeEntryCurrent method.

The function TestRelayPaymentNotUnstakingProviderForUnresponsivenessBecauseOfServices appropriately uses the GetStakeEntryCurrent method. The method is used to ensure that the provider is not unstaked incorrectly, which aligns with the test's purpose.

x/pairing/keeper/msg_server_stake_provider_test.go (5)

Line range hint 30-41: Approved: Updated function usage in TestModifyStakeProviderWithDescription.

The refactoring from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent is correctly applied in this test function. The logic and assertions remain valid with the new function signature.


Line range hint 30-41: Skipped: No direct changes in TestCmdStakeProviderGeoConfigAndEnum.

This function does not directly use the updated function names or logic related to the refactor. Its logic remains unchanged.


Line range hint 664-768: Approved: Correct usage of updated function in TestStakeEndpoints.

The refactoring from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent is appropriately applied in this test function. The assertions and logic are correctly adapted to the new function signature.


Line range hint 723-746: Approved: Updated function usage in TestStakeProviderLimits.

The refactoring from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent is correctly applied in this test function. The logic and assertions remain valid with the new function signature.


Line range hint 746-768: Approved: Correct usage of updated functions in TestUnfreezeWithDelegations.

The refactoring from GetStakeEntryByAddressCurrent to GetStakeEntryCurrent and ModifyStakeEntryCurrent to SetStakeEntryCurrent is appropriately applied in this test function. The logic and assertions are correctly adapted to the new function signatures.

x/pairing/keeper/pairing_test.go (2)

520-521: Updated method usage in test cases.

The test now uses GetAllStakeEntriesCurrentForChainId instead of GetStakeStorageCurrent to retrieve stake entries. This change aligns with the PR's objective to improve the efficiency of accessing stake entries.


1969-1970: Updated method usage in test cases.

The test now uses GetAllStakeEntriesCurrentForChainId instead of GetStakeStorageCurrent to retrieve stake entries. This change aligns with the PR's objective to improve the efficiency of accessing stake entries.

x/epochstorage/types/stake_entries.go (1)

13-16: Global variables for stake entry prefixes are well-defined.

The introduction of StakeEntriesPrefix and StakeEntriesCurrentPrefix is a good practice as it centralizes the prefix definitions, making the code more maintainable and less error-prone.

x/epochstorage/keeper/stake_entries_test.go (1)

33-41: Verify correct error handling.

The test TestGetStakeEntry retrieves stake entries but does not verify the behavior when an entry is not found.

x/pairing/keeper/pairing.go (2)

124-125: Refactor of stake entry retrieval method is approved.

The change from GetEpochStakeEntries to GetAllStakeEntriesForEpochChainId aligns with the PR's objective to optimize stake entry access. This should improve performance by directly accessing entries without needing to iterate.


128-128: Ensure proper handling when no stake entries are found.

The new error handling when no stake entries are found is a good addition. It provides clearer feedback about the state and context, which can be crucial for debugging and user information.

x/pairing/keeper/msg_server_relay_payment.go (1)

335-341: Refactored stake entry retrieval and update methods.

The changes to GetStakeEntryCurrent and SetStakeEntryCurrent methods are correctly implemented in the setStakeEntryBlockReport function. This should optimize the retrieval and update process for stake entries.

x/pairing/keeper/cu_tracker_test.go (3)

148-152: Updated stake entry handling in TestTrackedCuWithDelegations.

The replacement of ModifyStakeEntryCurrent with SetStakeEntryCurrent in the TestTrackedCuWithDelegations function is correctly implemented. This change should ensure that the stake entries are updated accurately in the tests.


489-493: Updated stake entry handling in TestProviderMonthlyPayoutQuery.

The changes in the TestProviderMonthlyPayoutQuery function reflect the updated method for setting stake entries. The tests are correctly updated to use SetStakeEntryCurrent, ensuring that the functionality is properly verified.


609-613: Updated stake entry handling in TestProviderMonthlyPayoutQueryWithContributor.

The update to use SetStakeEntryCurrent in the TestProviderMonthlyPayoutQueryWithContributor function is correctly implemented. This ensures that the tests accurately reflect the changes in the main codebase.

x/pairing/keeper/msg_server_unfreeze.go (2)

18-18: Updated function usage for stake entry retrieval.

The function GetStakeEntryCurrent is now used instead of GetStakeEntryByAddressCurrent. This change is consistent with the PR's goal to simplify and optimize stake entry access.


52-52: Updated function usage for stake entry modification.

The function SetStakeEntryCurrent is now used instead of ModifyStakeEntryCurrent. This change should ensure that the stake entries are set in a more straightforward manner, aligning with the refactor objectives.

x/pairing/types/epoch_cu.go (2)

19-19: Refactor to use utility serialization functions.

The functions UniqueEpochSessionKey, ProviderEpochCuKey, and ProviderConsumerEpochCuKey now use utils.Serialize for encoding. This change should improve maintainability and consistency across the codebase.

Also applies to: 23-23, 27-27


39-39: Refactor to use utility deserialization functions.

The functions DecodeUniqueEpochSessionKey, DecodeProviderEpochCuKey, and DecodeProviderConsumerEpochCuKey now use utils.Deserialize for decoding. This change should enhance the reliability and clarity of the decoding process.

Also applies to: 55-55, 68-68

x/dualstaking/keeper/helpers_test.go (1)

98-98: Updated function signature in test helper.

The function GetStakeEntry has been updated to reflect the new parameter order. This change should align the test helper with the updated function signatures in the main codebase.

scripts/useful_commands.sh (1)

12-15: Updated grep pattern in shell script function.

The function sleep_until_next_epoch now uses the corrected grep pattern "start_block: " to capture epoch start block information. This change should ensure more accurate monitoring of epoch transitions.

x/epochstorage/keeper/epoch_start.go (4)

29-29: Verify new method StoreCurrentStakeEntries integration.

The method StoreCurrentStakeEntries has been added to store current stake entries. It's important to ensure that this new method is integrated correctly across the system, especially where stake entries are managed or utilized.


56-60: Critical error handling in UpdateEarliestEpochstart.

The use of LavaFormatPanic for error handling in UpdateEarliestEpochstart is concerning as it forces a panic in the application. While this may be intended for critical errors, ensure that this approach is consistent with overall error handling strategy.

Verification successful

Consistent use of LavaFormatPanic for critical error handling.

The LavaFormatPanic function is used consistently across the codebase for handling critical errors. This aligns with the overall error handling strategy.

  • Instances found in x/pairing/keeper/pairing.go, x/fixationstore/types/fixationstore.go, x/dualstaking/keeper/delegator_reward.go, x/epochstorage/keeper/epoch_start.go, x/epochstorage/keeper/params.go, testutil/e2e/sdk/e2e.go, and x/epochstorage/keeper/epoch_details.go.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the use of panic in other critical sections of the application for consistency.
rg --type go -A 5 $'LavaFormatPanic'

Length of output: 10181


16-16: Ensure SetEpochHash is used correctly.

The function SetEpochHash is called at the beginning of EpochStart. This is a significant change and should be verified to ensure it aligns with the intended logic of updating the epoch hash at the start of each epoch.


100-102: Check correctness of SetEpochHash.

The method SetEpochHash sets the hash for the current block height. Verify that the serialization and key generation are implemented correctly to avoid potential data corruption.

x/rewards/keeper/providers.go (1)

136-138: Optimized Stake Entry Retrieval in specEmissionParts

The refactoring to use GetAllStakeEntriesCurrentForChainId instead of GetStakeStorageCurrent is a significant improvement. This change directly accesses stake entries, potentially enhancing performance by reducing unnecessary data processing.

x/pairing/keeper/epoch_cu.go (1)

39-39: Updated Serialization Method for Key Iteration

The update to use utils.Serialize for key serialization in multiple functions improves consistency and potentially enhances the handling of keys in the database. This change should be thoroughly tested to ensure it does not affect the functionality negatively.

Also applies to: 50-50, 108-108, 170-170, 233-233

x/pairing/keeper/unresponsive_provider_test.go (1)

17-17: Updated Stake Entry Retrieval in Tests

The update to use GetStakeEntryCurrent instead of GetStakeEntryByAddressCurrent in test functions aligns with the changes in the main codebase. This ensures that the tests remain relevant and effective in assessing the functionality of the updated code.

Also applies to: 37-37

@@ -103,7 +103,7 @@ func (k Keeper) ValidateResponseConflict(ctx sdk.Context, conflictData *types.Re
if err != nil {
return nil, fmt.Errorf("AccAddressFromHex %s provider: %w", print_st, err)
}
stakeEntry, found := k.epochstorageKeeper.GetStakeEntryForProviderEpoch(ctx, chainID, providerAddress.String(), epochStart)
stakeEntry, found := k.epochstorageKeeper.GetStakeEntry(ctx, epochStart, chainID, providerAddress.String())
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding more detailed logging for debugging.

Adding more detailed logging statements could help in tracing issues related to stake entry retrieval more effectively.

- if !found {
-   return nil, fmt.Errorf("did not find a stake entry for %s provider %s on epoch %d, chainID %s", print_st, providerAddress, epochStart, chainID)
- }
+ if !found {
+   k.Logger(ctx).Error("Stake entry not found", "provider", providerAddress, "epoch", epochStart, "chainID", chainID)
+   return nil, fmt.Errorf("Stake entry not found for provider %s at epoch %d, chainID %s", providerAddress, epochStart, 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
stakeEntry, found := k.epochstorageKeeper.GetStakeEntry(ctx, epochStart, chainID, providerAddress.String())
stakeEntry, found := k.epochstorageKeeper.GetStakeEntry(ctx, epochStart, chainID, providerAddress.String())
if !found {
k.Logger(ctx).Error("Stake entry not found", "provider", providerAddress, "epoch", epochStart, "chainID", chainID)
return nil, fmt.Errorf("Stake entry not found for provider %s at epoch %d, chainID %s", providerAddress, epochStart, chainID)
}

Comment on lines +11 to +148
var resp types.QueryAllStakeStorageResponse
require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
require.LessOrEqual(t, len(resp.StakeStorage), step)
require.Subset(t,
nullify.Fill(objs),
nullify.Fill(resp.StakeStorage),
)
}
})
t.Run("ByKey", func(t *testing.T) {
step := 2
var next []byte
for i := 0; i < len(objs); i += step {
args := request(next, 0, uint64(step), false)
out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListStakeStorage(), args)
require.NoError(t, err)
var resp types.QueryAllStakeStorageResponse
require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
require.LessOrEqual(t, len(resp.StakeStorage), step)
require.Subset(t,
nullify.Fill(objs),
nullify.Fill(resp.StakeStorage),
)
next = resp.Pagination.NextKey
}
})
t.Run("Total", func(t *testing.T) {
args := request(nil, 0, uint64(len(objs)), true)
out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListStakeStorage(), args)
require.NoError(t, err)
var resp types.QueryAllStakeStorageResponse
require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
require.NoError(t, err)
require.Equal(t, len(objs), int(resp.Pagination.Total))
require.ElementsMatch(t,
nullify.Fill(objs),
nullify.Fill(resp.StakeStorage),
)
})
// ctx := net.Validators[0].ClientCtx
// request := func(next []byte, offset, limit uint64, total bool) []string {
// args := []string{
// fmt.Sprintf("--%s=json", tmcli.OutputFlag),
// }
// if next == nil {
// args = append(args, fmt.Sprintf("--%s=%d", flags.FlagOffset, offset))
// } else {
// args = append(args, fmt.Sprintf("--%s=%s", flags.FlagPageKey, next))
// }
// args = append(args, fmt.Sprintf("--%s=%d", flags.FlagLimit, limit))
// if total {
// args = append(args, fmt.Sprintf("--%s", flags.FlagCountTotal))
// }
// return args
// }
// t.Run("ByOffset", func(t *testing.T) {
// step := 2
// for i := 0; i < len(objs); i += step {
// args := request(nil, uint64(i), uint64(step), false)
// out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListStakeStorage(), args)
// require.NoError(t, err)
// var resp types.QueryAllStakeStorageResponse
// require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
// require.LessOrEqual(t, len(resp.StakeStorage), step)
// require.Subset(t,
// nullify.Fill(objs),
// nullify.Fill(resp.StakeStorage),
// )
// }
// })
// t.Run("ByKey", func(t *testing.T) {
// step := 2
// var next []byte
// for i := 0; i < len(objs); i += step {
// args := request(next, 0, uint64(step), false)
// out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListStakeStorage(), args)
// require.NoError(t, err)
// var resp types.QueryAllStakeStorageResponse
// require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
// require.LessOrEqual(t, len(resp.StakeStorage), step)
// require.Subset(t,
// nullify.Fill(objs),
// nullify.Fill(resp.StakeStorage),
// )
// next = resp.Pagination.NextKey
// }
// })
// t.Run("Total", func(t *testing.T) {
// args := request(nil, 0, uint64(len(objs)), true)
// out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListStakeStorage(), args)
// require.NoError(t, err)
// var resp types.QueryAllStakeStorageResponse
// require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp))
// require.NoError(t, err)
// require.Equal(t, len(objs), int(resp.Pagination.Total))
// require.ElementsMatch(t,
// nullify.Fill(objs),
// nullify.Fill(resp.StakeStorage),
// )
// })
Copy link
Contributor

Choose a reason for hiding this comment

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

Address the extensive commenting out of test functions.

The large blocks of commented-out code, including test functions, could significantly reduce test coverage and obscure the functionality being tested. It's important to either remove or update these tests to ensure that the module's functionality is adequately verified.

- // func networkWithStakeStorageObjects(t *testing.T, n int) (*network.Network, []types.StakeStorage) {
+ // This function should be updated or removed to reflect the current testing requirements.

Committable suggestion was skipped due to low confidence.

Comment on lines +14 to +30
// GetStakeEntry gets a specific stake entry from the stake entries KV store
// Since the stake entries KV store's key includes the provider's stake (which is not known), we iterate over all
// the providers with the same epoch and chainID and compare the requested address to find the provider
func (k Keeper) GetStakeEntry(ctx sdk.Context, epoch uint64, chainID string, provider string) (types.StakeEntry, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.StakeEntriesPrefix)
iterator := sdk.KVStorePrefixIterator(store, types.StakeEntryKeyPrefixEpochChainId(epoch, chainID))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var val types.StakeEntry
k.cdc.MustUnmarshal(iterator.Value(), &val)
if val.Address == provider {
return val, true
}
}

return types.StakeEntry{}, false
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Implemented GetStakeEntry with iteration over providers.

While this function provides the necessary functionality, iterating over all providers might not be the most efficient approach, especially if the number of providers is large. Consider optimizing this by indexing providers or using more efficient data structures.

- // current iteration logic
+ // proposed indexing or more efficient data structure usage

Committable suggestion was skipped due to low confidence.

Comment on lines +20 to +31
func createNStakeEntries(keeper *keeper.Keeper, ctx sdk.Context, n int) []types.StakeEntry {
items := make([]types.StakeEntry, n)
for i := range items {
items[i] = types.StakeEntry{
Stake: sdk.NewCoin("token", math.NewInt(int64(i))),
Address: strconv.Itoa(i),
Chain: strconv.Itoa(i),
}
keeper.SetStakeEntry(ctx, uint64(i), items[i])
}
return items
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper cleanup in tests.

The function createNStakeEntries creates multiple stake entries but does not ensure their cleanup after tests, which could affect other tests due to shared state.

Consider using t.Cleanup() to remove entries after each test to ensure isolation between tests.

Comment on lines +43 to +57
func TestRemoveAllStakeEntriesForEpoch(t *testing.T) {
keeper, ctx := keepertest.EpochstorageKeeper(t)
items := createNStakeEntries(keeper, ctx, 10)
epoch := uint64(1)
keeper.SetStakeEntry(ctx, epoch, types.StakeEntry{}) // set another stake entry on epoch=1
keeper.RemoveAllStakeEntriesForEpoch(ctx, epoch)
for i := range items {
entries := keeper.GetAllStakeEntriesForEpoch(ctx, uint64(i))
if i == 1 {
require.Len(t, entries, 0) // on epoch 1 there should be no entries
} else {
require.Len(t, entries, 1) // every other epoch is unaffected - there should be one entry
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Check for potential data races.

The function TestRemoveAllStakeEntriesForEpoch modifies and accesses shared state which could lead to data races in a concurrent environment.

Consider using synchronization mechanisms like mutexes or channel operations to protect access to shared state.

Comment on lines +18 to +22
func StakeEntryKey(epoch uint64, chainID string, stake math.Int, provider string) []byte {
key := append(utils.Serialize(epoch), []byte(" "+chainID+" ")...)
key = append(key, utils.Serialize(stake.Uint64())...)
key = append(key, []byte(" "+provider)...)
return key
Copy link
Contributor

Choose a reason for hiding this comment

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

Review of function StakeEntryKey.

This function correctly constructs a byte slice representing a stake entry key. It uses serialization of epoch and stake and concatenates them with chainID and provider. The use of spaces as delimiters is simple but effective. However, ensure that chainID and provider do not contain spaces to avoid parsing issues.

- key := append(utils.Serialize(epoch), []byte(" "+chainID+" ")...)
- key = append(key, utils.Serialize(stake.Uint64())...)
- key = append(key, []byte(" "+provider)...)
+ key := append(utils.Serialize(epoch), []byte("|"+chainID+"|")...)
+ key = append(key, utils.Serialize(stake.Uint64())...)
+ key = append(key, []byte("|"+provider)...)
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 StakeEntryKey(epoch uint64, chainID string, stake math.Int, provider string) []byte {
key := append(utils.Serialize(epoch), []byte(" "+chainID+" ")...)
key = append(key, utils.Serialize(stake.Uint64())...)
key = append(key, []byte(" "+provider)...)
return key
func StakeEntryKey(epoch uint64, chainID string, stake math.Int, provider string) []byte {
key := append(utils.Serialize(epoch), []byte("|"+chainID+"|")...)
key = append(key, utils.Serialize(stake.Uint64())...)
key = append(key, []byte("|"+provider)...)
return key

Comment on lines +38 to +45
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.StakeEntriesCurrentPrefix)
iterator := sdk.KVStorePrefixIterator(store, []byte{}) // Get an iterator with no prefix to iterate over all keys
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var currentEntry types.StakeEntry
k.cdc.MustUnmarshal(iterator.Value(), &currentEntry)
k.SetStakeEntry(ctx, epoch, currentEntry)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review implementation of StoreCurrentStakeEntries.

The implementation uses a prefix store and iterates over all entries to set stake entries for the current epoch. Ensure that the use of MustUnmarshal and SetStakeEntry are correct and efficient for handling potentially large datasets.

Consider adding error handling for MustUnmarshal to prevent potential runtime panics in case of unmarshalling failures.

Comment on lines +30 to +76
// // get highest staked validator
// validatorsByPower := m.keeper.stakingKeeper.GetBondedValidatorsByPower(ctx)
// highestVal := validatorsByPower[0]

// // loop over all providers
// chains := m.keeper.specKeeper.GetAllChainIDs(ctx)
// for _, chainID := range chains {
// storage, found := m.keeper.epochstorageKeeper.GetStakeStorageCurrent(ctx, chainID)
// if found {
// for _, entry := range storage.StakeEntries {
// // return the providers all their coins
// addr, err := sdk.AccAddressFromBech32(entry.Address)
// if err != nil {
// return err
// }

// err = m.keeper.bankKeeper.MintCoins(ctx, types.ModuleName, []sdk.Coin{entry.Stake})
// if err != nil {
// return err
// }

// err = m.keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, []sdk.Coin{entry.Stake})
// if err != nil {
// utils.LavaFormatError("failed to send coins from module to account", err,
// utils.Attribute{Key: "Account", Value: addr},
// )
// }

// // create self delegation, this will increase the stake entry, we need to fix that by reseting the stake before delegating
// stake := entry.Stake
// entry.Stake.Amount = sdk.ZeroInt()
// m.keeper.epochstorageKeeper.ModifyStakeEntryCurrent(ctx, chainID, entry)
// err = m.keeper.DelegateFull(ctx, entry.Address, highestVal.OperatorAddress, entry.Address, chainID, stake)
// if err != nil {
// return err
// }
// }
// }
// }

// moduleBalance := m.keeper.bankKeeper.GetBalance(ctx, m.keeper.accountKeeper.GetModuleAddress(types.ModuleName), m.keeper.stakingKeeper.BondDenom(ctx))
// if !moduleBalance.IsZero() {
// err := m.keeper.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(moduleBalance))
// if err != nil {
// return err
// }
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

Significant Changes in Migration Logic

The entire logic within ConvertProviderStakeToSelfDelegation has been commented out. This raises concerns about the current functionality being disabled without a replacement. It's crucial to ensure that the migration process remains stable and functional during transitions.

Ensure that the new migration logic is implemented before deploying these changes to avoid potential disruptions in the migration process.

Comment on lines +86 to +160
// delegationsInds := m.keeper.delegationFS.GetAllEntryIndices(ctx)
// nextEpoch := m.keeper.epochstorageKeeper.GetCurrentNextEpoch(ctx)

// // burn all coins from the pools
// moduleBalance := m.keeper.bankKeeper.GetBalance(ctx, m.keeper.accountKeeper.GetModuleAddress(dualstakingtypes.BondedPoolName), m.keeper.stakingKeeper.BondDenom(ctx))
// if !moduleBalance.IsZero() {
// err := m.keeper.bankKeeper.BurnCoins(ctx, dualstakingtypes.BondedPoolName, sdk.NewCoins(moduleBalance))
// if err != nil {
// return err
// }
// }

// if !moduleBalance.IsZero() {
// moduleBalance = m.keeper.bankKeeper.GetBalance(ctx, m.keeper.accountKeeper.GetModuleAddress(dualstakingtypes.NotBondedPoolName), m.keeper.stakingKeeper.BondDenom(ctx))
// err := m.keeper.bankKeeper.BurnCoins(ctx, dualstakingtypes.NotBondedPoolName, sdk.NewCoins(moduleBalance))
// if err != nil {
// return err
// }
// }

// // give money back to delegators from the bonded pool
// originalDelegations := []dualstakingtypes.Delegation{}
// for _, ind := range delegationsInds {
// // find the delegation and keep its original form
// var d dualstakingtypes.Delegation
// block, _, _, found := m.keeper.delegationFS.FindEntryDetailed(ctx, ind, nextEpoch, &d)
// if !found {
// continue
// }

// if d.Delegator == d.Provider || d.Provider == dualstakingtypes.EMPTY_PROVIDER {
// continue
// }

// originalAmount := d.Amount

// // zero the delegation amount in the fixation store
// d.Amount = sdk.NewCoin(m.keeper.stakingKeeper.BondDenom(ctx), sdk.ZeroInt())
// m.keeper.delegationFS.ModifyEntry(ctx, ind, block, &d)

// // give money back from the bonded pool
// delegatorAddr, err := sdk.AccAddressFromBech32(d.Delegator)
// if err != nil {
// return err
// }

// err = m.keeper.bankKeeper.MintCoins(ctx, types.ModuleName, []sdk.Coin{originalAmount})
// if err != nil {
// return err
// }

// err = m.keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, delegatorAddr, sdk.Coins{originalAmount})
// if err != nil {
// return err
// }

// entry, found := m.keeper.epochstorageKeeper.GetStakeEntryCurrent(ctx, d.ChainID, d.Provider)
// if !found {
// continue
// }
// entry.DelegateTotal = entry.DelegateTotal.Sub(originalAmount)
// m.keeper.epochstorageKeeper.ModifyStakeEntryCurrent(ctx, d.ChainID, entry)

// originalDelegations = append(originalDelegations, d)
// }

// // get highest staked validator and delegate to it
// validatorsByPower := m.keeper.stakingKeeper.GetBondedValidatorsByPower(ctx)
// highestVal := validatorsByPower[0]
// for _, d := range originalDelegations {
// err := m.keeper.DelegateFull(ctx, d.Delegator, highestVal.OperatorAddress, d.Provider, d.ChainID, d.Amount)
// if err != nil {
// return err
// }
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

Handling Provider Delegators Logic Commented Out

Similar to the previous function, HandleProviderDelegators has its core functionality commented out. This change needs careful review to ensure that it aligns with the intended migration path and does not affect the integrity of the data during migration.

Verify the implementation plan for these migrations to ensure continuity and data integrity.

Comment on lines +270 to +339
// nextEpoch := m.keeper.epochstorageKeeper.GetCurrentNextEpoch(ctx)
// chains := m.keeper.specKeeper.GetAllChainIDs(ctx)
// OldStakeStorages := GetStakeStorages(ctx.ChainID())
// for _, chainID := range chains {
// storage, found := m.keeper.epochstorageKeeper.GetStakeStorageCurrent(ctx, chainID)
// if found {
// providers := map[string]interface{}{}
// stakeEntries := []epochstoragetypes.StakeEntry{}

// duplicated := 0
// missing := 0
// // remove duplicates
// for _, entry := range storage.StakeEntries {
// if _, ok := providers[entry.Address]; !ok {
// d, found := m.keeper.GetDelegation(ctx, entry.Address, entry.Address, entry.Chain, nextEpoch)
// if found {
// delegations, err := m.keeper.GetProviderDelegators(ctx, entry.Address, nextEpoch)
// if err == nil {
// entry.DelegateTotal.Amount = sdk.ZeroInt()
// for _, d := range delegations {
// if d.Delegator != d.Provider && d.ChainID == chainID {
// entry.DelegateTotal.Amount = entry.DelegateTotal.Amount.Add(d.Amount.Amount)
// }
// }
// } else {
// fmt.Println("didnt find delegations for:", entry.Address)
// }
// entry.Stake = d.Amount
// stakeEntries = append(stakeEntries, entry)
// } else {
// fmt.Println("didnt find self delegation for:", entry.Address)
// }

// providers[entry.Address] = struct{}{}
// } else {
// duplicated++
// }
// }

// // add back the old ones if they were deleted
// if len(OldStakeStorages) > 0 {
// deletedEntriesToAdd := OldStakeStorages[chainID]
// for _, entry := range deletedEntriesToAdd.StakeEntries {
// if _, ok := providers[entry.Address]; !ok {
// d, found := m.keeper.GetDelegation(ctx, entry.Address, entry.Address, entry.Chain, nextEpoch)
// if found {
// missing++
// delegations, err := m.keeper.GetProviderDelegators(ctx, entry.Address, nextEpoch)
// if err == nil {
// entry.DelegateTotal.Amount = sdk.ZeroInt()
// for _, d := range delegations {
// if d.Delegator != d.Provider && d.ChainID == chainID {
// entry.DelegateTotal.Amount = entry.DelegateTotal.Amount.Add(d.Amount.Amount)
// }
// }
// }
// entry.Stake = d.Amount
// stakeEntries = append(stakeEntries, entry)
// }
// }
// }
// }

// utils.LavaFormatInfo("Migrator for chain id providers", utils.LogAttr("chainID", chainID),
// utils.LogAttr("duplicated", duplicated),
// utils.LogAttr("missing", missing))
// storage.StakeEntries = stakeEntries
// m.keeper.epochstorageKeeper.SetStakeStorageCurrent(ctx, storage.Index, storage)
// }
// }
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactored Migration Logic in MigrateVersion2To3

The refactoring here involves significant changes to how stake entries are handled. The commented code suggests a move towards a different approach in handling stake entries, which needs to be fully implemented and tested.

Complete the implementation of the new migration logic to ensure it meets the system's requirements and maintains data integrity.

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.

None yet

1 participant