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

Increase decay precision #454

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft

Increase decay precision #454

wants to merge 5 commits into from

Conversation

Corantin
Copy link
Contributor

@Corantin Corantin commented Oct 4, 2024

No description provided.

kafann and others added 3 commits October 3, 2024 20:29
Change precision for CVParams from 10 ** 7 to 10 ** 14 + fixed helpers accordingly + fixed tests and constants

# Conflicts:
#	pkg/contracts/out/Allo.sol/Allo.json
#	pkg/contracts/out/CVStrategyHelpers.sol/CVStrategyHelpers.json
#	pkg/contracts/out/CVStrategyV0_0.sol/CVStrategyV0_0.json
#	pkg/contracts/out/CVStrategyV0_0.sol/IPointStrategy.json
#	pkg/contracts/out/CVStrategyV0_1.sol/CVStrategyV0_1.json
#	pkg/contracts/out/ERC20.sol/ERC20.json
#	pkg/contracts/out/ERC20/IERC20.sol/IERC20.json
#	pkg/contracts/out/FAllo.sol/FAllo.json
#	pkg/contracts/out/GV2ERC20.sol/GV2ERC20.json
#	pkg/contracts/out/IAllo.sol/IAllo.json
#	pkg/contracts/out/IArbitrator.sol/IArbitrator.json
#	pkg/contracts/out/IERC20.sol/IERC20.json
#	pkg/contracts/out/IERC20Metadata.sol/IERC20Metadata.json
#	pkg/contracts/out/IERC20Permit.sol/IERC20Permit.json
#	pkg/contracts/out/IERC20Upgradeable.sol/IERC20Upgradeable.json
#	pkg/contracts/out/IRegistry.sol/IRegistry.json
#	pkg/contracts/out/IRegistryFactory.sol/IRegistryFactory.json
#	pkg/contracts/out/ISafe.sol/Enum.json
#	pkg/contracts/out/ISafe.sol/ISafe.json
#	pkg/contracts/out/ISafe.sol/SafeProxyFactory.json
#	pkg/contracts/out/MockERC20.sol/MockERC20.json
#	pkg/contracts/out/PassportScorer.sol/PassportScorer.json
#	pkg/contracts/out/Registry.sol/Registry.json
#	pkg/contracts/out/RegistryCommunityV0_0.sol/RegistryCommunityV0_0.json
#	pkg/contracts/out/RegistryCommunityV0_1.sol/RegistryCommunityV0_1.json
#	pkg/contracts/out/RegistryFactoryDiamond.sol/RegistryFactoryDiamond.json
#	pkg/contracts/out/RegistryFactoryFacet.sol/RegistryFactoryFacet.json
#	pkg/contracts/out/RegistryFactoryV0_0.sol/RegistryFactoryV0_0.json
#	pkg/contracts/out/RegistryFactoryV0_1.sol/RegistryFactoryV0_1.json
#	pkg/contracts/out/SafeArbitrator.sol/SafeArbitrator.json
#	pkg/contracts/out/SafeERC20.sol/SafeERC20.json
Copy link

vercel bot commented Oct 4, 2024

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

Name Status Preview Comments Updated (UTC)
gardens-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 5:25pm

@Corantin Corantin marked this pull request as draft October 4, 2024 00:59
Copy link

github-actions bot commented Oct 4, 2024

Gemini Code Review encountered an error. Here is the step log:


Copy link
Collaborator

@Mati0x Mati0x left a comment

Choose a reason for hiding this comment

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

Testing by creating some pools and compare with spreadsheet.
I have one discrepancy in the decay

@Corantin Corantin marked this pull request as draft October 9, 2024 23:09
@Corantin
Copy link
Contributor Author

!ai

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

## Pull Request Review: Improve calculation precision and fix activation bug

This pull request brings valuable improvements to calculation precision and fixes a security vulnerability. However, some points need clarification and further adjustments.

Positive Changes:

  • Increased Precision: Increasing CV_SCALE_PRECISION_DECIMALS from 7 to 14 in apps/web/utils/numbers.ts significantly improves calculation accuracy. The consistent update of the D constant to 10**14 across CVStrategyV0_0.sol and CVStrategyHelpersV0_0.sol further enhances this.
  • Enhanced Security: Restricting the activateMemberInStrategy function in RegistryCommunityV0_0.sol to the onlyStrategyAddress modifier significantly improves security by preventing unauthorized member activations.

Points for Clarification and Adjustment:

  • _etherToFloat Conversion (pkg/contracts/test/CVStrategyHelpersV0_0.sol**):*
    • Issue: The change from dividing by 10**11 to 10**4 lacks context.
    • Suggestion: Provide a clear explanation for this change. What is the intended decimal representation? Consider adding unit tests to validate this conversion logic.
  • Missing calculateBlocksTo100 Context:
    • Issue: The change from 1e7 to 1e14 in calculateBlocksTo100 across various tests lacks explanation.
    • Suggestion: Add comments clarifying the reason for this change and how it relates to getDecay. This helps reviewers understand the logic and ensures maintainability.
  • Missing Test Completeness:
    • Issue: The provided code snippet for CVStrategyTest.t.sol ends abruptly.
    • Suggestion: Please provide the complete code for a comprehensive review.
  • Consider Unit Tests for calculateBlocksTo100:
    • Suggestion: Add specific unit tests focusing on calculateBlocksTo100. This ensures that the conviction decay calculation is accurate across different scenarios.

General Recommendations:

  • Code Comments: While the code itself shows improvement, additional comments explaining the reasoning behind specific choices, especially regarding the 1e14 adjustments, would be beneficial.

By addressing these points, you can significantly enhance the clarity, security, and maintainability of your codebase.

## Pull Request Review: Improve calculation precision and fix activation bug

This pull request makes several changes to improve the precision of calculations and fixes a bug related to member activation in strategies.

Summary of Changes:

  • Increased precision for CV calculations: The precision of Conviction Voting (CV) related calculations has been significantly enhanced to minimize rounding errors and ensure more accurate results.
  • Fixed strategy activation bug: Addressed an issue where any address could activate a member in a strategy, introducing a potential security risk. The code now enforces that only the strategy itself can perform this action.

Detailed Review:

File: apps/web/utils/numbers.ts

  • Good Practice: Defining constants like CV_PERCENTAGE_SCALE, UI_PERCENTAGE_FORMAT, and CV_SCALE_PRECISION with descriptive names significantly improves code readability and maintainability.
  • Improved Precision: Increasing CV_SCALE_PRECISION_DECIMALS from 7 to 14 significantly enhances the precision of CV calculations, reducing potential rounding errors and improving the accuracy of results.

File: pkg/contracts/src/CVStrategy/CVStrategyV0_0.sol

  • Improved Precision: Replacing the previous D constant (107) with a new value of 1014 directly improves the precision of calculations within the CV strategy contract.
  • Potential Issue: Consider adding a comment explaining the reasoning behind the specific value chosen for D. While increasing precision is generally beneficial, it's important to document any trade-offs or considerations involved.

File: pkg/contracts/src/RegistryCommunity/RegistryCommunityV0_0.sol

  • Security Improvement: Adding onlyStrategyAddress(msg.sender, _strategy) to activateMemberInStrategy is crucial for security. This ensures that only the intended strategy contract can activate members, preventing unauthorized manipulations.

File: pkg/contracts/test/CVStrategyHelpersV0_0.sol

  • Improved Precision: Updating the D constant to 10**14 here ensures consistency with the main contract and test accuracy.
  • Potential Issue: The change to _etherToFloat from dividing by 1011 to 104 might be incorrect depending on the intended precision and use case. This change should be carefully reviewed and potentially adjusted based on the desired decimal representation.

File: pkg/contracts/test/CVStrategyTest.t.sol

  • Incomplete Change: The provided diff ends abruptly. Please provide the complete code for review.

Overall:

This pull request introduces important improvements to code quality, security, and precision. However, the potential issue with _etherToFloat in CVStrategyHelpersV0_0.sol requires further attention. Ensure the conversion aligns with the intended decimal representation and provide adequate test coverage for this change.

Pull Request Review

This PR seems to focus on fixing the calculation of conviction decay over time. The changes consistently modify how the getDecay value is used in the calculateBlocksTo100 function.

File: contracts/test/CVStrategy.test.sol

Overall Feedback:

While the changes seem to address a specific calculation error, there are potential improvements for clarity and readability:

Detailed Comments:

  • Lines 982, 1090, 1268, 1394:
    • Issue: The change from 1e7 to 1e14 lacks context. It's unclear why this modification is necessary.
    • Suggestion: Add a comment explaining the reason for changing the exponent and how it relates to the getDecay value. This will improve readability and help reviewers understand the intended behavior.

Example:

--- a/contracts/test/CVStrategy.test.sol
+++ b/contracts/test/CVStrategy.test.sol
@@ -1268,7 +1268,9 @@ contract CVStrategyTest is Test, AlloSetup, RegistrySetupFull, CVStrategyHelpers
         }
 
         uint256 rollTo100 =
-            calculateBlocksTo100(ABDKMath64x64.divu(9999999, 1e7), ABDKMath64x64.divu(cv.getDecay(), 1e14));
+            calculateBlocksTo100(ABDKMath64x64.divu(9999999, 1e7), 
+                                 ABDKMath64x64.divu(cv.getDecay(), 1e14)); // 1e14 is used to adjust for the scaling difference
+                                                                             // between getDecay and the calculation in calculateBlocksTo100
 
         vm.roll(rollTo100 * 2);
         console.log("after block.number", block.number);

General Recommendations:

  • Unit Tests: Consider adding specific unit tests that focus on the calculateBlocksTo100 function, ensuring that the conviction decay calculation is accurate across different scenarios.
  • Code Comments: While the code itself might be functionally correct, clear and concise comments are crucial for maintainability and future development.

By addressing these points, you can improve the readability and maintainability of your codebase.

</details>

@Corantin
Copy link
Contributor Author

!ai

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

## Pull Request Review: Conviction Calculation and Decay Updates

This pull request seems to adjust the calculation for conviction decay and updates related tests. While the goal appears sound, the changes lack clarity and introduce potential issues in the test suite.

File: contracts/test/strategies/cv/CVStrategy.t.sol

Issue 1: Magic Number Obscures Intent

  • Lines: 974 (+), 982 (+), 1090 (+), 1268 (+), 1394 (+)

  • Description: The repeated use of 1e14 without explanation is confusing. While it likely scales the decay rate, its purpose remains unclear.

  • Suggestion:

    1. Define a named constant instead of using the magic number directly. This improves readability and allows for easier future adjustments.
    2. Add a clear comment explaining the constant's derivation and purpose within the decay calculation.

Issue 2: Brittle Tests Due to Block Reliance

  • Lines: 971-987 (+), 1087-1103 (+), 1265-1279 (+), 1391-1405 (+)

  • Description: Tests heavily depend on specific block numbers and durations (e.g., rollTo100 * 2). This tight coupling makes them brittle as minor logic or timing changes could cause failures unrelated to the core functionality.

  • Suggestion: Refactor tests to be less sensitive to exact block numbers.

    • Test against different decay stages: Verify conviction values after staking, at various decay percentages, and near complete decay.
    • Abstract time-dependent logic: If specific durations are essential, consider helper functions or test utilities to manage time-based operations in a more controlled and understandable way.

Minor Issue: Inconsistent Spacing (Line 974 (+))

While minor, the inconsistent spacing around / in the ABDKMath64x64.divu call on line 974 should be addressed for readability. Ensure consistent spacing throughout the codebase.

Summary:

This pull request needs improvement before merging. While addressing a conviction calculation issue, the lack of clarity in the introduced constant and the brittle nature of the tests raise concerns. Prioritize code readability and robust testing practices.

## Pull Request Review: Improve Numerical Precision and Security

This pull request introduces several changes aimed at improving numerical precision and enhancing security in the contracts and associated frontend code.

Summary:

  • Increased Precision in CV Calculations: Moves from a 7-decimal to a 14-decimal representation for CV calculations, significantly improving accuracy.
  • Consistent and Clear Constant Definitions: Refactors constant definitions for better readability and consistency by introducing decimal place variables.
  • Security Enhancement in activateMemberInStrategy: Adds a check to ensure only the strategy address itself can activate members, preventing unauthorized actions.

File-Specific Comments:

apps/web/utils/numbers.ts:

  • Positive: Replacing magic numbers with well-named constants like CV_PERCENTAGE_SCALE_DECIMALS, UI_PERCENTAGE_FORMAT_DECIMALS, and CV_SCALE_PRECISION_DECIMALS significantly improves readability and understanding of the code.
  • Suggestion: Consider adding comments explaining the purpose and context of each constant.

pkg/contracts/src/CVStrategy/CVStrategyV0_0.sol:

  • Positive: Increasing the precision of D from 10**7 to 10**14 drastically improves the accuracy of calculations, especially for smaller values, mitigating rounding errors.
  • Suggestion: Add a comment explaining the reasoning behind choosing 14 decimal places for D. Consider if this value needs to be configurable for future flexibility.

pkg/contracts/src/RegistryCommunity/RegistryCommunityV0_0.sol:

  • Positive: Adding onlyStrategyAddress(msg.sender, _strategy) in activateMemberInStrategy significantly enhances security by ensuring that only the designated strategy contract can activate members within itself, preventing potential misuse.

pkg/contracts/test/CVStrategyHelpersV0_0.sol:

  • Positive: Updating D to 10**14 maintains consistency with the main contract and ensures accuracy in test calculations.
  • Positive: The adjustment to _etherToFloat reflects the increased precision and ensures the test setup aligns with the updated contract logic.

pkg/contracts/test/CVStrategyTest.t.sol:

  • Issue: The code snippet provided is incomplete and breaks off mid-expression. Please provide the full context of the _calculateConviction function and its surrounding code for a complete review.

Overall:

This pull request demonstrates a good understanding of numerical precision in smart contracts and implements necessary improvements. The added security check is crucial and highlights a good eye for potential vulnerabilities.

However, providing more context for the incomplete test case is essential for a thorough review.

Pull Request Review: Conviction Calculation and Decay Updates

This pull request focuses on adjusting the conviction calculation and decay mechanisms within the CVStrategy contract. While the changes appear to address a specific issue, there are potential areas for improvement in terms of code clarity and testing.

File: contracts/test/strategies/cv/CVStrategy.t.sol

Issue 1: Magic Numbers

  • Lines: 974 (+), 982 (+), 1090 (+), 1268 (+), 1394 (+)

  • Description: The updated code introduces the constant 1e14 without clear explanation. While it likely relates to the decay calculation, a comment explaining its purpose and derivation would enhance readability.

  • Suggestion: Add a comment above the calculateBlocksTo100 calls explaining the significance of 1e14, e.g., "Divide by 1e14 to scale decay rate to the appropriate unit".

Issue 2: Test Case Specificity

  • Lines: 971-987 (+), 1087-1103 (+), 1265-1279 (+), 1391-1405 (+)

  • Description: The test cases rely heavily on specific block numbers and durations (e.g., rollTo100 * 2). This approach can make tests brittle to minor changes in logic or block times.

  • Suggestion: Consider refactoring the tests to be less reliant on exact block numbers. Instead, focus on testing the expected conviction values at different stages of decay (e.g., immediately after staking, after 50% decay, after near-full decay).

Minor Issue: Inconsistent Spacing

  • Line: 974 (+)

  • Description: The spacing around the / operator in the ABDKMath64x64.divu call is inconsistent with other occurrences in the same line. While minor, consistent spacing enhances readability.

  • Suggestion: Adjust spacing for consistency:

-        uint256 rollTo100 = calculateBlocksTo100(ABDKMath64x64.divu(9999999, 1e7), ABDKMath64x64.divu(cv.getDecay(), 1e14));
+        uint256 rollTo100 = calculateBlocksTo100(ABDKMath64x64.divu(9999999, 1e7), ABDKMath64x64.divu(cv.getDecay(), 1e14)); 

Summary:

Overall, this pull request addresses the conviction calculation issue but would benefit from improved code documentation and more robust testing. Adding comments to clarify the purpose of new constants and refactoring tests for greater flexibility will enhance the code's maintainability.

</details>

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.

3 participants