Skip to content

fix: improve observer emissions distribution#3904

Merged
kingpinXD merged 8 commits intodevelopfrom
sherlock-309
May 27, 2025
Merged

fix: improve observer emissions distribution#3904
kingpinXD merged 8 commits intodevelopfrom
sherlock-309

Conversation

@kingpinXD
Copy link
Member

@kingpinXD kingpinXD commented May 22, 2025

Description

Closes : https://github.com/zeta-chain/protocol-private/issues/247

Improve reward pool utilization to distribute all rewards allocated for emissions to the observers .

Older logic
The portion of rewards allocated to the observers who are being slashed was retained by the protocol.

Newer logic
The portion of rewards allocated to the observers who are being slashed is distributed to the other observers therby increasing thier earning slightly

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

  • Bug Fixes

    • Improved the distribution mechanism for observer emissions to maximize pool utilization and ensure rewards are allocated only for correct votes.
    • Adjusted reward calculations so that only observers with correct votes receive added emissions, while those with incorrect or missing votes are penalized appropriately.
  • Documentation

    • Enhanced in-code comments to clarify the observer reward and penalty scheme and the logic behind reward distribution.
  • Tests

    • Updated test cases to reflect the corrected reward allocation logic for observers, ensuring accuracy in emissions distribution validation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 22, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This update refines the observer emissions reward distribution mechanism. The reward calculation logic is clarified and made more explicit, with improved separation between reward unit accumulation and final allocation. Related tests are updated to match the new logic, and method signatures are adjusted for clarity and correctness. Extensive comments are added to enhance maintainability.

Changes

File(s) Change Summary
changelog.md Added a fix entry describing the improved observer emissions distribution mechanism for maximizing pool utilization.
x/emissions/abci.go Refactored distributeRewardsForMaturedBallots to clarify and separate reward unit accumulation from allocation, added comprehensive comments, and improved reward/slash logic for observers.
x/observer/types/ballot.go Changed BuildRewardsDistribution to no longer return total reward units; now directly updates the rewards map and has a void return type.
x/observer/types/ballot_test.go Updated tests to remove assertions on the removed return value from BuildRewardsDistribution; now only checks the rewards map. Minor readability improvement.
x/emissions/abci_test.go Renamed test case for clarity, adjusted expected reward values to reflect the new logic, and removed a trailing blank line.

Sequence Diagram(s)

sequenceDiagram
    participant EmissionsModule
    participant Ballot
    participant Observer

    EmissionsModule->>Ballot: BuildRewardsDistribution(rewardsMap)
    Ballot-->>EmissionsModule: updates rewardsMap (no return value)
    EmissionsModule->>EmissionsModule: Calculate total positive reward units
    EmissionsModule->>EmissionsModule: Compute reward per unit
    loop For each Observer
        EmissionsModule->>Observer: Distribute reward or apply slash based on reward units
    end
Loading

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.

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.

@codecov
Copy link

codecov bot commented May 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 64.88%. Comparing base (d0a1466) to head (0a62e04).
Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #3904   +/-   ##
========================================
  Coverage    64.87%   64.88%           
========================================
  Files          470      470           
  Lines        34400    34408    +8     
========================================
+ Hits         22316    22324    +8     
  Misses       11051    11051           
  Partials      1033     1033           
Files with missing lines Coverage Δ
x/emissions/abci.go 94.97% <100.00%> (+0.29%) ⬆️
x/observer/types/ballot.go 97.53% <100.00%> (-0.06%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kingpinXD kingpinXD marked this pull request as ready for review May 22, 2025 20:35
@kingpinXD kingpinXD requested a review from a team as a code owner May 22, 2025 20:35
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 (2)
x/emissions/abci.go (2)

188-201: Move the explanatory block into proper GoDoc or a standalone design note

The new comment block is very helpful, yet it sits in-line inside the critical loop.
Consider extracting these explanations into:

  1. A package-level comment in doc.go, or
  2. A well-named helper that carries its own GoDoc (e.g. applyBallotRewards).

This keeps the core loop compact and prevents future drift between code and commentary.


215-217: Unallocated remainder silently stays in the pool – decide on an explicit policy

Integer division (Quo) guarantees the contract never over-allocates, but it also leaves a residual amount % totalRewardsUnits undistributed.
Over time, these dust amounts can accumulate to noticeable sums and distort accounting.

Options:

  1. Carry the remainder forward into the next block’s UndistributedObserverRewardsPool (explicitly log the rollover).
  2. Distribute the remainder to the observers with the highest positive units (deterministically, e.g. first in sortedKeys).
  3. Burn it if the protocol economics allow.

Whichever approach you choose, codify it so the intention is clear and auditable.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b06813 and cb0a2da.

📒 Files selected for processing (5)
  • changelog.md (1 hunks)
  • x/emissions/abci.go (2 hunks)
  • x/emissions/abci_test.go (2 hunks)
  • x/observer/types/ballot.go (1 hunks)
  • x/observer/types/ballot_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

**/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

  • x/observer/types/ballot_test.go
  • x/emissions/abci_test.go
  • x/observer/types/ballot.go
  • x/emissions/abci.go
🧬 Code Graph Analysis (1)
x/observer/types/ballot.go (1)
testutil/sample/observer.go (1)
  • Ballot (21-34)
🔇 Additional comments (7)
changelog.md (1)

52-52: Well-formatted changelog entry.

The changelog entry clearly communicates the purpose of this PR - improving observer emissions distribution to maximize pool utilization.

x/observer/types/ballot_test.go (2)

441-441: Improved test readability.

The added blank line enhances code readability by visually separating the test case fields.


555-556: Test correctly adapted to method signature change.

The test has been properly updated to reflect the new BuildRewardsDistribution method signature, which no longer returns a total reward count. The test now correctly focuses on verifying the map state changes.

x/emissions/abci_test.go (2)

463-463: Clearer test case name.

The updated test name more accurately describes the behavior being tested - that withdrawable emissions are added only for correct votes, rather than remaining unchanged when rewards and slashes are equal.


483-485: Updated expected values to match new distribution logic.

The test now correctly expects higher reward values (122 instead of 120) for observers with correct votes, reflecting the improved reward distribution mechanism where slashed amounts are redistributed to observers who voted correctly.

x/observer/types/ballot.go (2)

96-100: Improved method signature to focus on side effects.

The BuildRewardsDistribution method now appropriately focuses on its primary responsibility - updating the rewards map. Removing the return value clarifies the method's purpose and decouples reward unit accumulation from map updates, aligning with the single responsibility principle.


114-116: Enhanced code clarity with explicit comment.

The added comment clarifies that observers who did not vote (NotVoted) are penalized similarly to those who voted incorrectly. This makes the intention of the code explicit and improves maintainability.

@kingpinXD kingpinXD requested review from lumtis and skosito May 23, 2025 13:59
Copy link
Contributor

@ws4charlie ws4charlie left a comment

Choose a reason for hiding this comment

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

the new logic looks correct

@swift1337 swift1337 self-requested a review May 27, 2025 11:35
# Conflicts:
#	changelog.md
@kingpinXD kingpinXD enabled auto-merge May 27, 2025 15:01
@kingpinXD kingpinXD added this pull request to the merge queue May 27, 2025
Merged via the queue into develop with commit 71eafeb May 27, 2025
47 checks passed
@kingpinXD kingpinXD deleted the sherlock-309 branch May 27, 2025 17:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants