-
Notifications
You must be signed in to change notification settings - Fork 12
Mike/improve/pool logic #73
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
Conversation
- Add basic upward rounding division test for ray_div_up function - Test with small numbers (100, 3) and larger numbers (1000 RAY, 300 RAY) - Verify upward rounding behavior with expected values - Update imports to include ray_div_up function
- Add edge cases test for ray_div_up function - Test zero numerator handling (should return 0) - Test exact division scenarios (600 RAY / 200 RAY) - Test very small remainder cases (1000 RAY + 1 / 1000 RAY) - Verify upward rounding behavior in edge cases
- Add division by zero test for ray_div_up function - Test that ray_div_up(1000, 0) properly aborts with EDIVISION_BY_ZERO error - Verify error handling behavior for invalid input parameters - Use expected_failure annotation to test error conditions
- Add overflow test for ray_div_up function - Test that ray_div_up properly aborts with EOVERFLOW error when input is too large - Verify overflow handling behavior for extreme input parameters - Use expected_failure annotation to test overflow conditions
- Add basic downward rounding division test for ray_div_down function - Test with small numbers (100, 3) and larger numbers (1000 RAY, 300 RAY) - Verify downward rounding behavior with expected values - Update imports to include ray_div_down function
- Add edge cases test for ray_div_down function - Test zero numerator handling (should return 0) - Test exact division scenarios (600 RAY / 200 RAY) - Test very small remainder cases (1000 RAY + 1 / 1000 RAY) - Verify downward rounding behavior in edge cases
- Add division by zero test for ray_div_down function - Test that ray_div_down(1000, 0) properly aborts with EDIVISION_BY_ZERO error - Verify error handling behavior for invalid input parameters - Use expected_failure annotation to test error conditions
- Add directional comparison test for ray_div functions - Test that ray_div_up >= ray_div >= ray_div_down for same inputs - Verify proper ordering of rounding results (700 RAY / 300 RAY) - Ensure directional rounding maintains mathematical consistency
- Add basic upward rounding multiplication test for ray_mul_up function - Test with small numbers (100, 3) and larger numbers (500 RAY, 200 RAY) - Verify upward rounding behavior with expected values - Update imports to include ray_mul_up function
- Add edge cases test for ray_mul_up function - Test zero operand handling (should return 0) - Test exact multiplication scenarios (500 RAY * 200 RAY) - Verify upward rounding behavior in edge cases
- Add overflow test for ray_mul_up function - Test that ray_mul_up properly aborts with EOVERFLOW error when input is too large - Verify overflow handling behavior for extreme input parameters - Use expected_failure annotation to test overflow conditions
- Add basic downward rounding multiplication test for ray_mul_down function - Test with small numbers (100, 3) and larger numbers (500 RAY, 200 RAY) - Verify downward rounding behavior with expected values - Update imports to include ray_mul_down function
- Add edge cases test for ray_mul_down function - Test zero operand handling (should return 0) - Test exact multiplication scenarios (500 RAY * 200 RAY) - Verify downward rounding behavior in edge cases
- Add directional comparison test for ray_mul functions - Test that ray_mul_up >= ray_mul >= ray_mul_down for same inputs - Verify proper ordering of rounding results (700 RAY * 300 RAY) - Ensure directional rounding maintains mathematical consistency
- Add exact division consistency test for ray_div functions - Test that ray_div_up and ray_div_down give same result for exact division - Verify mathematical consistency when no rounding is needed (600 RAY / 200 RAY) - Ensure directional rounding functions behave correctly for exact cases
- Add comprehensive directional rounding consistency test - Test both division and multiplication with remainder scenarios - Verify ray_div_up > ray_div_down for non-exact division (700 RAY / 300 RAY) - Verify ray_mul_up == ray_mul_down for exact multiplication (700 RAY * 300 RAY) - Ensure directional rounding functions maintain expected mathematical behavior
- Add protocol safety test for directional rounding functions - Test small debt calculation scenario (should not round to zero) - Test collateral calculation scenario (should not overestimate) - Test interest calculation precision with exact rate multiplication - Verify directional rounding provides protocol safety benefits in real-world scenarios
- Add rounding_up parameter to token_base::mint_scaled - aToken uses round down (mint less, safer for protocol) - vToken uses round up (mint more debt, safer for protocol) - Add comprehensive inline comments explaining rounding strategy - Update token_base_tests to pass rounding parameter
- Add rounding_up parameter to token_base::burn_scaled - aToken uses round up (burn more, safer for protocol) - vToken uses round down (burn less debt, safer for protocol) - Add comprehensive inline comments explaining rounding strategy - Update token_base_tests to pass rounding parameter
- Use ray_mul_down instead of ray_mul in balance_of - Round down to count less asset balance (safer for protocol) - Add inline comment explaining rounding direction
…nting - Use ray_mul_down instead of ray_mul in total_supply - Round down to count less total supply (safer for protocol) - Add inline comment explaining rounding direction
…ctual transfer - Pre-calculate scaled amount using ray_div (same as token_base::transfer) - Ensures event accurately reports the actual transferred scaled amount - Add dust check to prevent assertion failure for tiny liquidation fees - Update comments to emphasize event consistency with on-chain state
- Add early return if amount is 0 to avoid unnecessary computation - Pre-calculate scaled amount using ray_div_down to check for dust - Skip minting if scaled amount is 0 to prevent assertion failure - Treasury accrued fees can be tiny (1-2 octa) which round down to 0 - Add comprehensive comments explaining two-layer check logic
…ve debt accounting - Use ray_mul_up instead of ray_mul in balance_of - Round up to count more debt balance (safer for protocol) - Add inline comment explaining rounding direction
…tive debt accounting - Use ray_mul_up instead of ray_mul in total_supply - Round up to count more total debt (safer for protocol) - Add inline comment explaining rounding direction
…void dust - Increase supply_amount: 1000 → 10000 - Increase user2_supply_amount: 2000 → 20000 - Increase borrow_amount: 500 → 5000 - Adapt test to ray_div_down in mint_to_treasury - Small amounts would round down to 0 (dust) and skip minting - Update test documentation explaining 10x increase rationale - Add inline comments about dust handling with ray_div_down
Apply directional rounding for conservative treasury accrual calculation. Changes in mint_to_treasury function: - When converting scaled treasury accrual to actual mintable amount, change from ray_mul (half-up) to ray_mul_down (round down) - Modified calculation: amount_to_mint = ray_mul_down(accrued_to_treasury, normalized_income) Rationale: - Prevents overestimation of treasury accrued value - Ensures protocol doesn't mint excessive tokens to treasury - Aligns with protocol safety principle (favor protocol) - Conservative rounding protects protocol from edge cases Impact: - Treasury receives slightly less tokens (by at most 1 minimum unit) - More conservative treasury allocation - No impact on user operations or core protocol functionality - Consistent with balance_of implementations using ray_mul_down
Apply directional rounding for balance consistency in transfer function.
Changes in transfer() function:
- Calculate from_balance_before using ray_mul_down instead of ray_mul
- Calculate to_balance_before using ray_mul_down instead of ray_mul
- Reuses pre-fetched index for atomic snapshot guarantee
Rationale:
- Matches a_token_factory::balance_of behavior (uses ray_mul_down)
- Ensures atomic consistency: all balance calculations use same index value
- Prevents race conditions where index changes between balance calculations
- Enables correct detection of full withdrawal and first-time receipt scenarios
- Manual calculation reuses pre-fetched index (also used by token_base::transfer
and balance transfer event), ensuring consistent state snapshot
Impact:
- Fixes collateral flag updates for full withdrawal and first receipt
- Guarantees atomic snapshot of user balances (critical for HF validation)
- Consistent with user-facing balance_of query results
- Gas optimized: single index fetch reused across all operations
- Aligns with Solidity Aave V3 implementation pattern
Security: Prevents non-atomic balance calculations that could lead to
inconsistent state and incorrect health factor validation
Apply directional rounding for conservative debt calculation. Changes: - Modified get_user_debt_in_base_currency function L37 - Changed ray_mul to ray_mul_up for debt index multiplication Rationale: - Debt should never be underestimated for protocol safety - Conservative calculation protects against liquidation edge cases - Aligns with Solidity Aave V3 implementation pattern Impact: - Health factor calculations become more conservative - Slight increase in debt amounts (~0.0001% per operation) - Better protection against dust debt scenarios
Apply ceiling division for conservative debt amount calculation. Changes: - Modified get_user_debt_in_base_currency function L42-45 - Changed regular division to ceil_div for price conversion - Simplified code by combining multiplication and division Rationale: - Prevents small debt × low price from rounding down to zero - Critical fix for test_issue_2 scenario - Ensures debt is always counted in base currency calculations Impact: - Fixes dust debt being ignored in health factor calculations - Small debt amounts will now be properly tracked - More accurate liquidation threshold determinations
Apply directional rounding for conservative collateral valuation. Changes: - Modified get_user_balance_in_base_currency function L62-70 - Changed ray_mul to ray_mul_down for collateral index multiplication Rationale: - Collateral should never be overestimated for protocol safety - Conservative calculation prevents over-leveraging - Consistent with a_token_factory::balance_of behavior Impact: - Health factor calculations become more conservative - Slight decrease in collateral value (~0.0001% per operation) - Better protection against liquidation edge cases
Apply directional rounding for conservative withdrawal balance calculation. Changes: - Calculate user_balance using ray_mul_down instead of ray_mul in withdraw function - Modified: supply_logic.move line 199-206 Rationale: - User withdrawal balance should never be overestimated for protocol safety - Conservative calculation prevents users from withdrawing more than actual balance - Consistent with a_token_factory::balance_of behavior - Aligns with Solidity Aave V3 implementation pattern Impact: - Withdrawal balance calculations become more conservative - User may need to query real-time balance for complete withdrawal - Better protection against over-withdrawal scenarios - Consistent with balance_of external API behavior
…rsion Apply directional rounding for conservative liquidation debt calculation. Changes: - Calculate user_reserve_debt_in_base_currency using ceil_div instead of normal division - Modified: execute_liquidation_call function (L627-640) - Keep collateral calculation with normal division (rounds down conservatively) Rationale: - Debt should never be underestimated during liquidation for protocol safety - Conservative calculation prevents liquidation amount errors - Ensures accurate liquidation bonus and collateral seizure calculations - Aligns with Solidity Aave V3 implementation pattern Impact: - Liquidation calculations become more conservative - Small debt amounts will not be rounded to zero (fixes potential dust debt issues) - Better protection against debt underestimation in liquidation scenarios - Consistent with generic_logic debt calculation approach
…lation Apply directional rounding for conservative flashloan liquidity calculation. Changes: - Calculate total_liquidity using ray_mul_down instead of ray_mul - Modified: handle_flash_loan_repayment function (L751-759) - Convert reserve_accrued_to_treasury to actual amount using conservative rounding Rationale: - Available flashloan liquidity should not be overestimated for protocol safety - Conservative calculation prevents lending more than actually available - Ensures treasury accrued balance doesn't inflate available liquidity - Aligns with mint_to_treasury's conservative approach Impact: - Flashloan availability becomes slightly more conservative (~0.0001%) - Prevents protocol from over-lending during high utilization - Better protection against liquidity miscalculation - Consistent with other directional rounding implementations
…rual Apply directional rounding for conservative flashloan treasury accumulation. Changes: - Calculate new_reserve_accrued_to_treasury using ray_div_down instead of ray_div - Modified: handle_flash_loan_repayment function (L767-776) - Convert premium_to_protocol from actual amount to scaled balance conservatively Rationale: - Protocol treasury should not accumulate optimistic amounts for safety - Conservative calculation prevents treasury from over-accruing fees - Ensures consistency with mint_to_treasury's conservative minting approach - Prevents long-term accumulation of rounding errors favoring treasury Impact: - Treasury accrual becomes slightly more conservative (~0.0001%) - Prevents protocol from recording more treasury fees than actually earned - Better alignment with dual-conservative approach (liquidity + treasury) - Consistent with other directional rounding implementations across protocol
…lation input Apply directional rounding for conservative interest rate strategy input. Changes: - Calculate total_variable_debt using ray_mul_up instead of ray_mul - Modified: update_interest_rates function (L95-102) - Convert scaled debt to actual amount conservatively for rate calculation Rationale: - Interest rate strategy requires accurate utilization rate calculation - Underestimated debt leads to lower calculated rates → higher protocol risk - Conservative debt estimation → higher rates → encourages repayment → safer protocol - This is input to interest rate strategy, not pure index calculation - Critical for accurate borrow_usage_ratio and supply_usage_ratio Impact: - Interest rates become slightly more conservative when utilization is high - Prevents debt underestimation that could lead to unsafe low borrowing rates - Ensures protocol maintains healthy incentive structure for borrowers - Consistent with directional rounding implementations across protocol
Apply directional rounding for conservative treasury accumulation in interest updates. Changes: - Calculate new_accrued_to_treasury using ray_div_down instead of ray_div - Modified: update_interest_rates function (L442-454) - Convert actual interest amount to scaled treasury balance conservatively - Adjust test_drop_reserve_one_year_interest amounts to avoid dust rounding Rationale: - Protocol treasury should not accumulate optimistic amounts for safety - Conservative calculation prevents treasury from recording unrealized revenue - Consistent with mint_to_treasury (ray_mul_down) and flashloan accrual (ray_div_down) - Double downward rounding (accumulation + minting) ensures treasury never over-mints - Test amounts increased 10x (10000/20000/5000) to avoid dust issues with dual rounding Impact: - Treasury revenue slightly reduced (~1%) from more conservative accumulation - Enhanced protocol security by preventing optimistic treasury balance - Maintains consistency with entire treasury flow (accrue → mint)
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #73 +/- ##
==========================================
- Coverage 97.70% 97.58% -0.13%
==========================================
Files 38 38
Lines 785 786 +1
==========================================
Hits 767 767
- Misses 18 19 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@matchv Can you please rebase against main as this PR contains some oracle changes I did and area already merged, so are npm changes in it to be seen. This way there will only be the relevant rounding changes in here. Please rebase in fact all of your PRs against main so pipelines are all green! |
update_interest_rates, total_variable_debt => ray_mul_up, counting up debt rate
update_interest_rates, total_accrued_to_treasury => may_div_down, counting down accrued to treasury