Skip to content

Account for natural precision loss in matching pool distribution#339

Merged
akaia-shadowfox merged 5 commits intomainfrom
fix/20250203-proportional-funding-payouts
Feb 4, 2025
Merged

Account for natural precision loss in matching pool distribution#339
akaia-shadowfox merged 5 commits intomainfrom
fix/20250203-proportional-funding-payouts

Conversation

@akaia-shadowfox
Copy link
Copy Markdown
Collaborator

@akaia-shadowfox akaia-shadowfox commented Feb 4, 2025

Summary by CodeRabbit

  • New Features

    • Improved payout displays convert large amounts into accurate, readable token values in voting results and leaderboards.
    • Enhanced vote pages now show dynamic loading indicators and clear messaging while vote data is being fetched.
    • Introduced a new method for handling conversions between big number representations and indivisible units.
  • Bug Fixes

    • Updated data handling in voting round components for better clarity and accuracy.
  • Style

    • Adjusted splash screen dimensions for a more compact and visually pleasing configuration experience.
  • Refactor

    • Modified data retrieval methods to streamline access and improve performance across voting round hooks.

@akaia-shadowfox akaia-shadowfox self-assigned this Feb 4, 2025
@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 4, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
potlock-next-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 4, 2025 9:04pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request refines the structure of various voting and payout hooks and components. It modifies the return structure of elections hooks to utilize a unified data property, updating destructuring and dependency arrays accordingly. New utility functions for handling big-number conversions and token payouts are introduced. Additionally, the logic for calculating voting round results is revised to include token metadata and a reducer for payout computation. Minor UI styling adjustments and export renaming enhance naming consistency across the codebase.

Changes

File(s) Change Summary
src/common/contracts/core/voting/hooks.ts
src/entities/pot/hooks/feature-flags.ts
src/entities/voting-round/hooks/rounds.ts
src/pages/pot/[potId]/history.tsx
src/pages/pot/[potId]/votes.tsx
Updated hooks to spread all query properties; return structure now uses a unified data field; adjusted dependency arrays and loading state management.
src/common/lib/format.ts
src/entities/voting-round/components/WinnerRow.tsx
src/entities/voting-round/components/leaderboard.tsx
Introduced new utility bigNumToIndivisible; updated payout formatting using indivisibleUnitsToFloat and imported constants (NATIVE_TOKEN_DECIMALS) to enhance display precision.
src/entities/voting-round/hooks/results.ts
src/entities/voting-round/model/results.ts
src/entities/voting-round/types.ts
Modified voting round results hook to use potContractHooks.useConfig; updated winner calculation with a reducer and incorporated token metadata; changed type for estimatedPayoutAmount from number to IndivisibleUnits.
src/features/proportional-funding/components/payout-manager.tsx
src/features/proportional-funding/model/effects.ts
Changed type import and variable naming; removed the tokenDecimals parameter and associated conversion, simplifying payout submission logic.
src/entities/voting-round/index.ts Renamed export from Leaderboard to leaderboard and commented out constants export for naming consistency.
src/features/pot-configuration/components/editor.tsx Updated the SplashScreen component’s class from "h-200" to "h-150", adjusting the component height styling.

Sequence Diagram(s)

sequenceDiagram
    participant UI as Component
    participant VRHook as VotingRoundResultsHook
    participant Config as potContractHooks.useConfig
    participant Validator as revalidate()
    
    UI->>VRHook: Request voting round results
    VRHook->>Config: Fetch pot configuration
    Config-->>VRHook: Return potConfig
    VRHook->>Validator: Process winners & calculate payouts with token metadata
    Validator-->>VRHook: Return computed results
    VRHook-->>UI: Provide updated voting round data
Loading
sequenceDiagram
    participant UI as Funding Component
    participant Manager as PayoutManager
    participant Submit as submitPayouts()
    
    UI->>Manager: Initiate payout submission
    Manager->>Submit: Call function with potId & recipients
    Submit-->>Manager: Return confirmation
    Manager-->>UI: Display payout result
Loading

Possibly related PRs

Poem

Oh, I hop through lines of code so bright,
With data flowing clear and light,
Hooks and tokens aligned in a neat parade,
Payouts and features gracefully displayed,
In every refactor, my heart does leap—
A bunny’s joy in code runs deep! 🐇

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 65ca12b and 374e72c.

📒 Files selected for processing (5)
  • src/entities/voting-round/components/ResultsTable.tsx (1 hunks)
  • src/entities/voting-round/components/leaderboard.tsx (3 hunks)
  • src/entities/voting-round/model/results.ts (4 hunks)
  • src/entities/voting-round/types.ts (2 hunks)
  • src/entities/voting-round/utils/weight.ts (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@akaia-shadowfox akaia-shadowfox marked this pull request as ready for review February 4, 2025 19:17
@akaia-shadowfox akaia-shadowfox removed the request for review from Ebube111 February 4, 2025 19:17
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (7)
src/entities/voting-round/model/results.ts (3)

62-63: Direct assignment of payoutTokenMetadata.
The assignment ensures consistent usage of the updated token metadata. Consider adding a null-check or fallback for edge cases.


154-195: Remainder-based allocation logic.
Granting leftover funds to the last candidate is a valid approach if that is the intended design. However, verify it aligns with stakeholder expectations—smaller rounding or distribution logic might require a different approach.


200-205: State update with new winners and payout token.
The store update is consistent with the newly computed winners and payoutTokenMetadata. Consider adding dedicated unit tests to ensure end-to-end validation of final state contents.

src/entities/pot/hooks/feature-flags.ts (1)

7-10: Renamed de-structured property.
Using data: elections keeps the code semantically clear, but confirm it's consistent throughout the project to avoid confusion in naming conventions.

src/common/lib/format.ts (1)

12-13: Consider improving type safety.

While the function correctly handles precision using Big.js, consider adding runtime validation to ensure the result is a valid IndivisibleUnits (non-negative integer string).

 export const bigNumToIndivisible = (amount: Big.Big, decimals: number): IndivisibleUnits =>
-  amount.mul(Big(10).pow(decimals)).toFixed().toString();
+  amount.mul(Big(10).pow(decimals)).toFixed(0).toString();
src/entities/voting-round/components/leaderboard.tsx (1)

87-91: LGTM! Improved token amount precision handling.

The change properly accounts for token decimals when displaying amounts, ensuring accurate representation of values.

Consider extracting the decimal places (2) to a constant to maintain consistency across the application:

+const DISPLAY_DECIMAL_PLACES = 2;
+
 caption={indivisibleUnitsToFloat(
   estimatedPayoutAmount,
   NATIVE_TOKEN_DECIMALS,
-  2,
+  DISPLAY_DECIMAL_PLACES,
 )}
src/features/proportional-funding/components/payout-manager.tsx (1)

33-34: Track the TODO comment about Pinata upload.

The TODO comment about uploading via Pinata should be tracked to ensure it's not forgotten.

Would you like me to create an issue to track this TODO item?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 968bec4 and 65ca12b.

📒 Files selected for processing (15)
  • src/common/contracts/core/voting/hooks.ts (2 hunks)
  • src/common/lib/format.ts (1 hunks)
  • src/entities/pot/hooks/feature-flags.ts (1 hunks)
  • src/entities/voting-round/components/WinnerRow.tsx (2 hunks)
  • src/entities/voting-round/components/leaderboard.tsx (2 hunks)
  • src/entities/voting-round/hooks/results.ts (4 hunks)
  • src/entities/voting-round/hooks/rounds.ts (1 hunks)
  • src/entities/voting-round/index.ts (1 hunks)
  • src/entities/voting-round/model/results.ts (4 hunks)
  • src/entities/voting-round/types.ts (2 hunks)
  • src/features/pot-configuration/components/editor.tsx (1 hunks)
  • src/features/proportional-funding/components/payout-manager.tsx (2 hunks)
  • src/features/proportional-funding/model/effects.ts (1 hunks)
  • src/pages/pot/[potId]/history.tsx (1 hunks)
  • src/pages/pot/[potId]/votes.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/features/pot-configuration/components/editor.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Fleek - broad-haze-5260
  • GitHub Check: Fleek - broad-haze-5260
🔇 Additional comments (21)
src/entities/voting-round/model/results.ts (5)

7-10: Imports look valid and consistent.
They're properly typed and grouped, aligning with the new metadata handling logic.


16-16: Schema version bump is correct.
Increasing the schema version to 3 ensures stored data is differentiated and avoids conflicts with the old structure.


23-29: Cache shape updated with new payout token metadata.
The addition of payoutTokenMetadata is consistent with the new calculations, but ensure all upstream references are updated accordingly.


38-38: Confirm presence of decimals in NativeTokenMetadata.
Because the union type can include NativeTokenMetadata, verify that it has a decimals property. Otherwise, runtime errors may occur during bigNumToIndivisible.

Would you like me to generate a shell script to check for fields in NativeTokenMetadata definitions across the codebase?


54-54: Parameter passthrough looks correct.
Forwarding matchingPoolTokenMetadata to local scope aligns with the new distribution logic. No issues noted.

src/entities/pot/hooks/feature-flags.ts (2)

15-15: Usage of optional chaining.
(elections?.length ?? 0) > 0 correctly ensures safe checks against undefined. Well done.


17-18: Dependency array updated for re-render control.
Including elections?.length ensures the memo recalculates when the number of elections changes. This prevents stale data.

src/entities/voting-round/index.ts (1)

8-8: File export casing check.
Confirm that the underlying file is indeed leaderboard.ts or leaderboard.tsx to avoid case-sensitivity issues on certain filesystems.

src/features/proportional-funding/model/effects.ts (1)

11-11: LGTM! Simplified payout submission by using pre-converted amounts.

The changes correctly handle precision by using estimatedPayoutAmount directly, as it's already in IndivisibleUnits format, eliminating the need for conversion and potential precision loss.

Also applies to: 17-17

src/entities/voting-round/hooks/rounds.ts (1)

13-16: LGTM! Improved hook return structure.

The changes correctly restructure the data return format while maintaining proper dependency tracking in the useMemo hooks.

Also applies to: 21-24, 30-32, 37-40

src/entities/voting-round/types.ts (1)

63-63: LGTM! Improved type safety for token amounts.

The change from number to IndivisibleUnits for estimatedPayoutAmount correctly enforces proper handling of token amounts and prevents precision loss.

src/pages/pot/[potId]/history.tsx (1)

20-21: LGTM! Clean destructuring of hook data.

The changes improve code clarity by explicitly showing the data structure returned by the hooks.

src/entities/voting-round/components/WinnerRow.tsx (1)

94-98: Verify decimal place consistency between caption and tooltip.

The caption shows 2 decimal places while the tooltip shows full precision (NATIVE_TOKEN_DECIMALS). This might be confusing when values don't match exactly.

Consider either:

  1. Using the same precision in both places
  2. Adding a comment explaining the intentional difference
  3. Adding "(approximate)" to the caption to indicate it's rounded
 caption={`~ ${indivisibleUnitsToFloat(
   estimatedPayoutAmount,
   NATIVE_TOKEN_DECIMALS,
-  2,
+  NATIVE_TOKEN_DECIMALS, // Match tooltip precision
 )}`}

Also applies to: 107-114

src/features/proportional-funding/components/payout-manager.tsx (1)

40-40: LGTM! Simplified payout submission.

The removal of tokenDecimals parameter aligns with the broader refactor for consistent token decimal handling across the application.

src/common/contracts/core/voting/hooks.ts (2)

116-127: LGTM! Consistent data property usage.

The refactoring improves consistency by using the data property pattern for query results.


129-143: LGTM! Consistent data property usage.

The refactoring aligns with the same pattern used in usePotElections.

src/entities/voting-round/hooks/results.ts (3)

6-8: LGTM! Improved token handling imports.

The new imports support better token metadata handling.

Also applies to: 11-11


23-33: Consider additional error handling for token metadata.

While the token handling is improved, consider adding error handling for cases where token metadata might be undefined or invalid.


91-97: Verify token decimals usage.

Ensure that NATIVE_TOKEN_DECIMALS is appropriate for the matching pool token.

Consider using the token's own decimals from metadata:

-          NATIVE_TOKEN_DECIMALS,
+          matchingPoolToken.metadata.decimals,
✅ Verification successful

I'll start by gathering more context around how NATIVE_TOKEN_DECIMALS is defined and how it's used alongside the matching pool token metadata. This will help verify if the constant is appropriate for the matching pool token or if the token-specific decimals should be used.


Action: Update matching pool balance conversion to use token-specific decimals.

The search confirms that while several components (e.g., in DonationSuccess.tsx) follow a pattern using the token’s metadata decimals (with a fallback to NATIVE_TOKEN_DECIMALS), the voting round results currently always use NATIVE_TOKEN_DECIMALS. Since matchingPoolToken.metadata is available, it would be more accurate and consistent to use its decimals property for the conversion rather than the generic native value.

Recommendations:

  • Replace the hardcoded NATIVE_TOKEN_DECIMALS in the call to indivisibleUnitsToBigNum with matchingPoolToken.metadata.decimals.
  • Optionally, add a fallback in case matchingPoolToken.metadata.decimals is missing (e.g., using the nullish coalescing operator).
-          NATIVE_TOKEN_DECIMALS,
+          matchingPoolToken.metadata.decimals ?? NATIVE_TOKEN_DECIMALS,
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts or web queries found


Script:

#!/bin/bash
# Search for how NATIVE_TOKEN_DECIMALS is defined and its occurrences
echo "Searching for definitions and usages of NATIVE_TOKEN_DECIMALS..."
rg "NATIVE_TOKEN_DECIMALS" -n .

# Search for matchingPoolToken metadata usages in the code
echo "Searching for usages of matchingPoolToken.metadata..."
rg "matchingPoolToken\.metadata" -n .

Length of output: 3094

src/pages/pot/[potId]/votes.tsx (2)

152-163: LGTM! Improved loading state feedback.

The addition of a loading state with appropriate visual feedback enhances user experience.


170-170: LGTM! Consistent title casing.

The title case update improves text consistency.

@akaia-shadowfox akaia-shadowfox merged commit dc15fdb into main Feb 4, 2025
@akaia-shadowfox akaia-shadowfox deleted the fix/20250203-proportional-funding-payouts branch February 4, 2025 21:03
Ebube111 added a commit that referenced this pull request Feb 17, 2025
* Reimplement wallet bindings & Introduce performance optimizations (#332)

Co-authored-by: Jiku Godwill Nsanwi <jikugodwill@yahoo.com>
Co-authored-by: Ebube111 <ebubeagwaze@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Account for natural precision loss in matching pool distribution (#339)

* fix: Unlock donation submit with default value (#340)

* Implement payout justification publishing (#342)

* Fix Campaign Issues (#341)

* campaign changes done

* implemented suggested changes

---------

Co-authored-by: Carina.Akaia.io <cvo.akaia@gmail.com>
Co-authored-by: Jiku Godwill Nsanwi <jikugodwill@yahoo.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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