Skip to content

Conversation

@QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented May 22, 2025

Issue being fixed or feature implemented

This PR adds tests to verify the functionality of epoch-based token distribution for evonodes, ensuring that the distribution logic works as expected across multiple epochs.

What was done?

  • Added multiple test cases to check the correctness of token distribution for evonodes based on epoch-based rules.
  • Verified that the distribution calculations are accurate based on the number of blocks proposed in each epoch.

How Has This Been Tested?

The new tests were executed in the test suite, confirming that the epoch-based distribution logic behaves correctly under various scenarios, including different block counts and proposals.

Breaking Changes

None

Checklist

  • I have performed a self-review of my own code

  • I have commented my code, particularly in hard-to-understand areas

  • I have added or updated relevant unit/integration/functional/e2e tests

    For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • Bug Fixes

    • Improved error messages for hash mismatches by adding specific context to clarify the source of the error.
  • Tests

    • Added comprehensive tests for perpetual token distribution to evonodes using linear distribution functions, including scenarios with non-genesis starts and start offsets.
    • Enhanced test coverage for blockchain simulation, token claims, and chain continuation.
    • Updated test logic to support more flexible block height conditions for contract state transitions.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 22, 2025

Walkthrough

This update modifies panic messages for drive and platform state app hash mismatches in several handler files to add contextual suffixes. It also enhances test coverage by adding three new tests for perpetual token distribution under various conditions, and generalizes strategy logic for initial contract state transitions based on block height.

Changes

File(s) Change Summary
packages/rs-drive-abci/src/abci/handler/info.rs,
.../prepare_proposal.rs,
.../process_proposal.rs
Updated panic messages for drive/platform state app hash mismatches to include context-specific suffixes (e.g., "(info)", "(prepare proposal)", "(process proposal)"). No logic or control flow changes.
packages/rs-drive-abci/tests/strategy_tests/execution.rs,
.../strategy.rs
Generalized contract state transition logic: Added start_block_height parameter to state_transitions_for_block, updated function calls and logic to support flexible initial contract addition based on block height. Removed debug print.
packages/rs-drive-abci/tests/strategy_tests/token_tests.rs Added three comprehensive test functions for perpetual token distribution to evonodes using linear distribution, covering genesis/non-genesis starts and distribution offsets. Refactored and expanded test logic for chain continuation and balance assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Token Distribution Test
    participant Platform as Platform
    participant State as State/DB
    participant Identity as Identity

    Test->>Platform: Initialize chain with token contract & identities
    loop For each block
        Platform->>State: Process block, update state
    end
    Test->>Platform: Create token claim transition (with Identity)
    Platform->>State: Process claim, update token balances
    State-->>Test: Return updated balances
    Test->>Test: Assert balances and block proposals
    Note over Test: Repeat for chain continuation and<br>different distribution parameters
Loading

Possibly related PRs

Suggested reviewers

  • shumkov

Poem

In the meadow of code where tokens flow free,
Rabbits test distributions, as happy as can be.
With hashes now clearer—context in sight,
And contracts that start at the block that feels right.
New tests hop along, all balances align—
This patch is a carrot, crisp and divine! 🥕

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@QuantumExplorer QuantumExplorer changed the title test: add tests for epoch-based token distribution for evonodes test(drive-abci): add tests for epoch-based token distribution for evonodes May 22, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
packages/rs-drive-abci/tests/strategy_tests/token_tests.rs (4)

639-646: Comment/documentation and assertion diverge – update the math in the comment

The explanatory comment states the expected reward is 250, but the integer-division result used in the assertion is 222.
Keeping both in sync avoids future confusion for anyone adjusting the reward algorithm or test constants.

-// They should get 2 * 1000 * 4 / 36
-// This is equal to 250
+// They should get 2 * 1000 * 4 / 36
+// This equals 222 with integer division (floor)

740-744: verify_sum_trees disabled – confirm intent

Turning off verify_sum_trees speeds the tests up, but it also removes an integrity check that has previously caught state-root mismatches.
If the only goal is runtime reduction, consider parameterising this flag so “fast” and “full-verify” modes can be toggled centrally for all strategy tests instead of hard-coding per test.
Otherwise, please add a short comment clarifying why full verification is not required here.


2000-2012: Hard-coded expected balances make tests brittle

The expected token balances are derived from hand-rolled formulas scattered across comments.
If the distribution logic changes (or integer vs. fixed-point math is introduced) these literals will need manual updates.

Consider extracting the reward formula into a helper so you can compute the expected value programmatically:

fn expected_linear_reward(blocks: u64, proposed: u64, a: i64, start: i64) -> u64 {
    let total = a * blocks as i64 + start;
    (total * proposed as i64 / blocks as i64) as u64
}

This keeps tests self-documenting and resilient to parameter tweaks.

Also applies to: 2319-2333


80-90: Repeated boiler-plate could be extracted into helpers

Each test recreates nearly identical blocks for:

  1. Seeding RNG & signer
  2. Creating two identities and their transitions
  3. Building PlatformConfig / NetworkStrategy

Abstracting these into helper functions (e.g., build_basic_token_contract(...), base_platform_config(day_ms)) would shorten the test file and emphasise the unique parts of each scenario.

Also applies to: 237-247, 670-680, 1203-1215, 1800-1813

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e513863 and 6b5f8b4.

📒 Files selected for processing (6)
  • packages/rs-drive-abci/src/abci/handler/info.rs (1 hunks)
  • packages/rs-drive-abci/src/abci/handler/prepare_proposal.rs (1 hunks)
  • packages/rs-drive-abci/src/abci/handler/process_proposal.rs (1 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/execution.rs (1 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/strategy.rs (2 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/token_tests.rs (7 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: QuantumExplorer
PR: dashpay/platform#2257
File: packages/rs-drive-abci/src/mimic/test_quorum.rs:159-164
Timestamp: 2024-11-20T16:16:01.830Z
Learning: QuantumExplorer prefers not to receive auto-generated messages asking to post on social media.
packages/rs-drive-abci/tests/strategy_tests/execution.rs (1)
Learnt from: QuantumExplorer
PR: dashpay/platform#2215
File: packages/rs-drive-abci/src/execution/engine/run_block_proposal/mod.rs:119-120
Timestamp: 2024-10-06T16:18:07.994Z
Learning: In the `run_block_proposal` function in `packages/rs-drive-abci/src/execution/engine/run_block_proposal/mod.rs`, it's acceptable to pass `platform_state` to `perform_events_on_first_block_of_protocol_change`, even if `block_platform_state` has been updated.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Rust packages (drive-abci) / Check each feature
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (7)
packages/rs-drive-abci/src/abci/handler/prepare_proposal.rs (1)

75-77: Approve enhanced panic context
The panic message now includes “(prepare proposal)” to explicitly identify the handler phase when a hash mismatch occurs. This change improves debug clarity and is consistent with sibling handlers. No behavior is altered.

packages/rs-drive-abci/src/abci/handler/info.rs (1)

63-65: Approve enhanced panic context
Appending “(info)” clarifies that the app-hash mismatch is detected during the ABCI info handshake. This aligns with the updates in other handlers and preserves existing logic.

packages/rs-drive-abci/src/abci/handler/process_proposal.rs (1)

219-221: Approve enhanced panic context
Adding “(process proposal)” makes it clear which phase triggered the panic on hash mismatch. This mirrors the pattern in the other handlers without impacting functionality.

packages/rs-drive-abci/tests/strategy_tests/execution.rs (1)

1014-1014: Update method call to pass block_start parameter.

The call to strategy.state_transitions_for_block has been updated to pass the block_start parameter, aligning with the modified method signature in strategy.rs. This change is necessary to support the generalized approach for handling initial contract state transitions at different block heights.

packages/rs-drive-abci/tests/strategy_tests/strategy.rs (2)

1598-1598: Update method signature to support generalized block height handling.

The state_transitions_for_block method signature now includes a new parameter start_block_height, allowing the caller to specify when initial contract state transitions should be applied, rather than hardcoding this to block height 1.


1634-1648: Generalize initial contract state transitions logic.

The code now generalizes when initial contract state transitions are added:

  1. Initial contracts are added when the current block height equals the provided start_block_height (not just block 1) and there are existing identities
  2. Operation transitions are skipped only if it's the first block (height 1), preserving the original behavior

This change enables more flexible testing scenarios, particularly for tests that continue chains from non-genesis blocks or run across multiple epochs.

packages/rs-drive-abci/tests/strategy_tests/token_tests.rs (1)

780-788: Great defensive check on state-transition execution results

Iterating over every transition and asserting code == 0 gives immediate, fine-grained feedback if something fails mid-chain – nice touch!

@QuantumExplorer QuantumExplorer added this to the v2.0.0 milestone May 22, 2025
@QuantumExplorer QuantumExplorer merged commit fc295c3 into v2.0-dev May 22, 2025
27 checks passed
@QuantumExplorer QuantumExplorer deleted the testadd-epoch-based-distribution-tests branch May 22, 2025 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant