Skip to content

feat: implement XYCSwapStrictAdditive with fee reinvestment and add c…#63

Draft
ifelsedeveloper wants to merge 18 commits intomainfrom
feature/Strict-Additive-Fees-Reinvested-Inside-Pricing
Draft

feat: implement XYCSwapStrictAdditive with fee reinvestment and add c…#63
ifelsedeveloper wants to merge 18 commits intomainfrom
feature/Strict-Additive-Fees-Reinvested-Inside-Pricing

Conversation

@ifelsedeveloper
Copy link
Contributor

@ifelsedeveloper ifelsedeveloper commented Jan 26, 2026

Strict Additive Fee AMM with Reinvestment Inside Pricing

Implement x^α * y = K AMM formula with strict additive fee model and corresponding tests.

  • Introduced XYCSwapStrictAdditive contract for AMM with strict additive fee model
  • Added StrictAdditiveMath library for calculations related to the new swap model
  • Created tests for XYCSwapStrictAdditive covering basic swaps, edge cases, and numerical examples from the associated paper
  • Updated Opcodes to include the new _xycSwapStrictAdditiveXD instruction
  • Added documentation in the form of a PDF outlining the fee reinvestment strategy

Change Summary

What does this PR change?

This PR introduces a new AMM swap instruction implementing the x^α * y = K invariant with strict additive fees reinvested inside pricing. Unlike standard Uniswap-style fees which break split invariance, this model ensures that swap(a+b) = swap(b) ∘ swap(a) — meaning the final state is deterministic regardless of how trades are split.

Key formulas:

  • ExactIn: Δy = y * (1 - (x / (x + Δx))^α)
  • ExactOut: Δx = x * ((y / (y - Δy))^(1/α) - 1)

Where α ∈ (0, 1] controls the fee:

  • α = 1.0 → No fee (standard constant product)
  • α = 0.997 → ~0.3% equivalent fee
  • α = 0.95 → ~5% equivalent fee

Related Issue/Ticket:

PT1-322

Files Changed

New Files

File Description
src/libs/StrictAdditiveMath.sol Math library with powRatio(), powRatioInverse(), calcExactIn(), calcExactOut()
src/instructions/XYCSwapStrictAdditive.sol New swap instruction implementing x^α * y = K
test/XYCSwapStrictAdditive.t.sol 15 comprehensive tests
docs/fee-reinvest-strict-additive.pdf Mathematical derivation and proofs

Modified Files

File Change
src/opcodes/Opcodes.sol Added XYCSwapStrictAdditive import and _xycSwapStrictAdditiveXD instruction

Testing & Verification

How was this tested?

  • Unit tests
  • Integration tests
  • Manual testing (describe steps)
  • Verified on staging

Test Results

All 15 new tests pass:

[PASS] test_XYCSwapStrictAdditive_AsymmetricPool()
[PASS] test_XYCSwapStrictAdditive_BasicSwap_HighFee()
[PASS] test_XYCSwapStrictAdditive_BasicSwap_NoFee()
[PASS] test_XYCSwapStrictAdditive_BasicSwap_WithFee()
[PASS] test_XYCSwapStrictAdditive_ExactOut_Basic()
[PASS] test_XYCSwapStrictAdditive_ExactOut_SplitInvariance()
[PASS] test_XYCSwapStrictAdditive_LargeAmounts()
[PASS] test_XYCSwapStrictAdditive_PaperExample()
[PASS] test_XYCSwapStrictAdditive_PaperExample_SplitInvariance()
[PASS] test_XYCSwapStrictAdditive_RoundingInvariants()
[PASS] test_XYCSwapStrictAdditive_RoundingInvariants_HighFee()
[PASS] test_XYCSwapStrictAdditive_SmallAmounts()
[PASS] test_XYCSwapStrictAdditive_SplitInvariance_CompareToStandardXYK()
[PASS] test_XYCSwapStrictAdditive_SplitInvariance_ManySwaps()
[PASS] test_XYCSwapStrictAdditive_SplitInvariance_TwoSwaps()

Key Property Verified: Strict Additivity (Split Invariance)

Single swap (100):     90649116889594508919
Split swap (40 + 60):  90649116889594508919
Difference:            0

Full test suite (616 tests) passes with no regressions.

Risk Assessment

Risk Level:

  • Low - Minor changes, no operational impact
  • Medium - Moderate changes, limited impact, standard rollback available
  • High - Significant changes, potential operational impact, complex rollback

Risks & Impact

  • No breaking changes: This is a new additive instruction; existing functionality is unaffected
  • New opcode slot used: Instruction added at index 50 in the opcodes array
  • Math precision: Uses Taylor series for ln/exp with 1e27 precision scale; tested with rounding invariants to ensure no accumulation exploits
  • Gas overhead: Higher gas than standard XYC swap due to logarithm/exponential calculations (expected for the mathematical complexity)

Usage Example

// Build program with strict additive swap
// Alpha = 997_000_000 means α = 0.997 (~0.3% fee)
bytes memory bytecode = bytes.concat(
    program.build(_dynamicBalancesXD, BalancesArgsBuilder.build(...)),
    program.build(_xycSwapStrictAdditiveXD, XYCSwapStrictAdditiveArgsBuilder.build(997_000_000))
);

…orresponding tests

- Introduced XYCSwapStrictAdditive contract for AMM with strict additive fee model.
- Added StrictAdditiveMath library for calculations related to the new swap model.
- Created tests for XYCSwapStrictAdditive covering basic swaps, edge cases, and numerical examples from the associated paper.
- Updated Opcodes to include the new XYCSwapStrictAdditive instruction.
- Added documentation in the form of a PDF outlining the fee reinvestment strategy.
@claude
Copy link

claude bot commented Jan 26, 2026

Claude finished @ifelsedeveloper's task —— View job


Code Review: XYCSwapStrictAdditive Implementation

I've completed my review of this PR that implements the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

The implementation is well-designed and mathematically sound. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model as described in the accompanying paper, maintaining the key property of split invariance.

🔍 Code Quality and Best Practices

StrictAdditiveMath.sol:

  • Good: High-precision fixed-point arithmetic using 1e27 scale
  • Good: Well-documented with clear mathematical formulas
  • Good: Proper error handling with custom errors
  • 🔶 Minor: Consider adding more explicit bounds checking in _ln and _exp functions to prevent edge cases

XYCSwapStrictAdditive.sol:

  • Good: Clean separation of concerns with math logic in separate library
  • Good: Comprehensive ASCII art documentation explaining the formula
  • Good: Proper validation of pool state (non-zero balances)

🐛 Potential Issues

  1. Precision Loss in Edge Cases: In StrictAdditiveMath._ln(), the Taylor series approximation might lose precision for very small or very large values. While the scaling logic helps, consider documenting the precision guarantees.

  2. Gas Optimization Opportunity: The powRatio and powRatioInverse functions compute ln and exp operations which are gas-intensive. The gas usage (227k-352k for basic swaps) is significantly higher than standard XYC swaps (~218k).

  3. Integer Overflow Protection: While _exp checks for overflow at line 166, the multiplication at line 191 (result = result << uint256(k)) could overflow for large k values even though k is checked to be ≤ 88.

⚡ Performance Considerations

  • Gas Usage: The implementation uses ~30-60% more gas than standard XYC swaps due to logarithm/exponential calculations
  • Rounding Invariant Tests: Very high gas usage (54M) suggests the implementation handles many edge cases correctly but at computational cost
  • Consider caching frequently used calculations if the same pool parameters are used repeatedly

🔒 Security Concerns

  1. ✅ No Reentrancy Risk: Pure functions with no external calls
  2. ✅ Proper Input Validation: Checks for zero balances and valid alpha range
  3. ✅ Floor/Ceiling Rounding: Correctly protects the maker by using floor division for output amounts and ceiling division for input amounts
  4. 🔶 Convergence Risk: The iterative algorithms in _ln and _exp have fixed iteration limits. While unlikely, non-convergence could lead to incorrect results. Consider adding explicit convergence checks.

🧪 Test Coverage

Excellent test coverage including:

  • ✅ Basic swap functionality with various fee levels
  • ✅ Split invariance verification (the key property)
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (small/large amounts, asymmetric pools)
  • ✅ Rounding invariants to prevent exploitation
  • ✅ Numerical examples matching the paper

Suggestions:

  • Add tests for extreme alpha values (very close to 0 and 1)
  • Test behavior when calculations approach precision limits
  • Consider fuzzing the mathematical functions for edge cases

📝 Additional Recommendations

  1. Documentation: Consider adding more inline comments in the math library explaining the Taylor series convergence properties and precision guarantees

  2. Gas Optimization: For production use, consider:

    • Pre-computing common alpha values (997_000_000, 990_000_000)
    • Using lookup tables for frequently used power calculations
    • Optimizing the Taylor series to use fewer iterations for common ranges
  3. Monitoring: Add events or logs for debugging convergence issues in the mathematical functions

✅ Summary

This is a high-quality implementation of a novel AMM design with strong mathematical foundations. The code is well-tested, properly documented, and correctly implements the strict additivity property. The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides.

Recommendation: Approve with minor suggestions for gas optimization and edge case handling.

…precision in calculations

- Updated StrictAdditiveMath library to implement Balancer-style optimizations, including precomputed constants and unrolled Taylor series for improved performance.
- Adjusted fixed-point arithmetic to utilize 18 decimal precision, enhancing accuracy in mathematical operations.
- Added comprehensive tests for precision analysis in XYCSwapStrictAdditive, covering various split scenarios and fee levels.
- Implemented gas comparison tests to evaluate performance against traditional XY=K models.
@claude
Copy link

claude bot commented Jan 26, 2026

Claude finished @ifelsedeveloper's task —— View job


🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code correctly implements the "Strict-Additive Fees Reinvested Inside Pricing" model as described in the accompanying paper, successfully maintaining the key property of split invariance (strict additivity).

🏗️ Code Quality and Best Practices

StrictAdditiveMath.sol:

  • Excellent: Uses Balancer-style optimized logarithm/exponential implementations with precomputed constants
  • Well-structured: Clear separation between public functions (powRatio, powRatioInverse) and internal math helpers
  • Good precision: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • Proper error handling: Custom errors for invalid inputs and overflow conditions

XYCSwapStrictAdditive.sol:

  • Clean design: Follows the established pattern of other swap instructions
  • Excellent documentation: Comprehensive ASCII art explaining the formula and its properties
  • Proper validation: Checks for zero balances and detects recompute attempts

🐛 Potential Issues

  1. Precision at Extremes (src/libs/StrictAdditiveMath.sol:126-128):

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    The bounds [0.9, 1.1] for high-precision ln may not cover all cases where precision is critical. Consider expanding or documenting the precision guarantees.

  2. Unchecked Bit Shift (src/libs/StrictAdditiveMath.sol:300):

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    While the exp bounds check prevents overflow, the final multiplication could theoretically overflow for edge cases. Consider using checked math or documenting the safety invariants.

⚡ Performance Considerations

  1. Gas Usage: Tests show 227k-352k gas for basic swaps vs ~218k for standard XYC swaps. The ~30-60% overhead is expected due to:

    • Multiple ln/exp calculations requiring Taylor series expansions
    • Unrolled loops (good optimization choice)
    • Precomputed constants (excellent optimization)
  2. Optimization Opportunities:

    • Consider caching powRatio results for common alpha values (997_000_000, 990_000_000)
    • The Taylor series could potentially use fewer terms for common input ranges
    • Consider a lookup table for frequently used power calculations

🔒 Security Analysis

  1. ✅ No Reentrancy: Pure functions with no external calls
  2. ✅ Input Validation: Proper checks for zero balances, alpha range, and output bounds
  3. ✅ Rounding Direction: Correctly uses floor for output (protects maker) and ceiling for input
  4. ✅ Overflow Protection: Explicit bounds checking in _exp function

Minor Concern: The iterative Taylor series have fixed iteration counts but no explicit convergence checks. While the unrolled design prevents infinite loops, consider adding debug assertions for convergence in development builds.

🧪 Test Coverage

Excellent coverage including:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 5%)
  • ✅ Split invariance verification (the key property) - thoroughly tested with multiple splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (small amounts: 1e12, large amounts: 500e18)
  • ✅ Rounding invariants to prevent value extraction
  • ✅ Numerical validation matching paper examples
  • ✅ Asymmetric pools

Test Quality Highlights:

  • The split invariance tests are particularly well-designed, testing 2-way, 3-way, up to 100-way splits
  • Precision analysis across different fee levels and swap sizes
  • Good use of relative tolerance (1e15) for floating-point comparisons

📚 Documentation

  • ✅ Comprehensive inline documentation explaining the mathematical model
  • ✅ PDF paper provides rigorous mathematical proofs
  • ✅ Clear examples in tests demonstrating usage

💡 Suggestions for Improvement

  1. Constants Documentation: Add comments explaining why specific Taylor series term counts were chosen (6 terms for ln, 12 for exp)

  2. Alpha Helper Constants: Consider adding named constants for common alpha values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;    // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;     // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;       // 1% fee
  3. Gas Profiling Comments: Add comments showing typical gas usage for different operations to help users make informed choices

  4. Precision Guarantees: Document the maximum relative error for the ln/exp approximations

✅ Summary

This is a well-implemented, mathematically sound addition to the swap-vm opcodes. The code successfully achieves its goal of implementing a strict-additive AMM with fees reinvested inside pricing. The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides.

The implementation follows best practices, has comprehensive test coverage, and properly handles edge cases. The use of Balancer-style optimizations shows good research and adaptation of existing efficient implementations.

Recommendation: ✅ Approve - This is production-ready code with only minor suggestions for enhancement.

- Refactored rounding invariant tests to utilize the RoundingInvariants library with appropriate tolerances for strict additive swaps.
- Added comprehensive tests for fee reinvestment analysis, demonstrating the impact of different fee levels on pool reserves and K growth.
- Implemented additional tests for pool reserve growth and exact fee calculations, comparing traditional and strict additive models.
- Improved logging for clarity in test outputs and results.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my detailed analysis:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity). The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Correct rounding: Floor for output (protects maker), ceiling for input

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. Consider whether this range should be expanded for better precision in edge cases.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Optimizations already in place: precomputed constants, unrolled loops
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • Potential lookup tables for frequently used calculations
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds, output limits
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol
  • Split invariance: Prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples
  • ✅ Asymmetric pools
  • ✅ Precision analysis showing sub-ppb differences

Test Quality Highlights:

  • Excellent precision analysis across different scenarios
  • Well-structured tests with clear documentation
  • Good use of console logging for debugging

📝 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure

The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides (deterministic final state regardless of trade splitting).

Verdict: ✅ Approve - This is high-quality code ready for production use.

…rounding invariants

- Improved the _xycSwapStrictAdditiveXD function for clarity and consistency in balance checks.
- Added a comprehensive test for ExactOut strict additivity, validating multiple split scenarios and fee reinvestment impacts.
- Updated rounding invariants tests to utilize configurable amounts, ensuring robustness in high-precision scenarios.
- Enhanced logging for better traceability of test results and outcomes.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my detailed analysis:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity). The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Correct rounding: Floor for output (protects maker), ceiling for input

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. Consider whether this range should be expanded for better precision in edge cases.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Optimizations already in place: precomputed constants, unrolled loops
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • Potential lookup tables for frequently used calculations
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds, output limits
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol
  • Split invariance: Prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples
  • ✅ Asymmetric pools
  • ✅ Precision analysis showing sub-ppb differences

Test Quality Highlights:

  • Excellent precision analysis across different scenarios
  • Well-structured tests with clear documentation
  • Good use of console logging for debugging

📝 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure

The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides (deterministic final state regardless of trade splitting).

Verdict: ✅ Approve - This is high-quality code ready for production use.

… and enhance documentation

- Revised mathematical formulas in the XYCSwapStrictAdditive contract to reflect the two curves design for input tokens.
- Updated documentation to clarify the behavior of ExactIn and ExactOut under the new model.
- Enhanced test cases to validate the two curves behavior, ensuring consistency and accuracy in swap calculations.
- Improved logging in tests for better traceability of results and insights into fee impacts.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity). The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Two-curves design: Correctly implements the paper's approach where X→Y uses x^α * y = K and Y→X uses x * y^α = K

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test shows 54M gas for RoundingInvariants test (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δ=100, α=0.997)
  • ✅ Two-curves design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • Paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the two-curves design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure
  • Correct implementation of the two-curves design as specified in the paper

The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides (deterministic final state regardless of trade splitting).

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

…lit behavior

- Adjusted tolerance levels in strict additivity assertions to reflect improved precision in ExactIn calculations.
- Introduced a new test for ExactOut strict additivity, verifying mathematical correctness across two reserve models.
- Enhanced logging for clarity in test outputs, particularly regarding split behavior and differences from single swaps.
- Updated existing tests to ensure consistency with the new two curves design and its implications on swap behavior.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity). The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Two-curves design: Correctly implements the paper's approach where X→Y uses x^α * y = K and Y→X uses x * y^α = K

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test shows 54M gas for RoundingInvariants test (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δ=100, α=0.997)
  • ✅ Two-curves design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • Paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the two-curves design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure
  • Correct implementation of the two-curves design as specified in the paper

The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides (deterministic final state regardless of trade splitting).

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

… new LaTeX documentation

- Deleted the outdated fee reinvestment PDF document.
- Introduced a new LaTeX document detailing the two-curve design and its mathematical foundations.
- Updated comments in the XYCSwapStrictAdditive contract to reflect the new documentation structure and clarify the behavior of ExactIn and ExactOut.
- Enhanced test cases to ensure consistency with the updated documentation and verify the correctness of the two curves design.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity). The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Two-curves design: Correctly implements the paper's approach where X→Y uses x^α * y = K and Y→X uses x * y^α = K

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test shows 54M gas for RoundingInvariants test (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δ=100, α=0.997)
  • ✅ Two-curves design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • Paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the two-curves design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure
  • Correct implementation of the two-curves design as specified in the paper

The main trade-off is higher gas costs for the mathematical complexity, which is acceptable given the unique properties this AMM provides (deterministic final state regardless of trade splitting).

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

- Added Sergey Prilutskiy as a co-author to the LaTeX document detailing the strict-additive fees reinvested inside pricing for AMMs.
- Updated the corresponding PDF file to reflect the changes made in the LaTeX source.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity) for ExactIn operations. The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Two-curves design: Correctly implements the paper's approach where X→Y uses K = y * x^α and Y→X uses K = x * y^α

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test test_XYCSwapStrictAdditive_RoundingInvariants shows 54M gas (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output, ceiling for input)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δx=100, α=0.997)
  • ✅ Two-curves design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences for ExactIn
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • PDF paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the two-curves design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

Important note: The paper describes both a single-curve design (Curve A) and a two-curve design (Curve B). The implementation uses the two-curve design where:

  • ExactIn is strictly additive
  • ExactOut is NOT strictly additive (by design)
  • This creates a real bid-ask spread that accumulates in reserves

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property for ExactIn
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure
  • Correct implementation of the two-curves design as specified in the paper

The main trade-offs are:

  1. Higher gas costs for the mathematical complexity (acceptable given the unique properties)
  2. ExactOut is intentionally NOT strictly additive (creates economic value through bid-ask spread)

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

…in XYCSwapStrictAdditive

- Revised the LaTeX document to reflect changes from the two-curve model to a single deterministic mapping, emphasizing the conservative and dissipative designs.
- Updated the corresponding PDF file to align with the new documentation.
- Modified comments in the XYCSwapStrictAdditive contract to clarify the new dissipative design and its implications for ExactIn and ExactOut behavior.
- Enhanced documentation to highlight the non-conservative nature of the new design and its impact on trader value during round trips.
@claude
Copy link

claude bot commented Jan 27, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model, maintaining the crucial property of split invariance (strict additivity) for ExactIn operations. The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Dissipative design: Correctly implements the paper's approach where power α is always applied to the input token's reserve

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test test_XYCSwapStrictAdditive_RoundingInvariants_Library shows 54M gas (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output, ceiling for input)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δx=100, α=0.997)
  • ✅ Dissipative design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences for ExactIn
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • PDF paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the dissipative design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

Important note: The paper describes both a conservative design (single invariant) and a dissipative design (single deterministic mapping). The implementation uses the dissipative design where:

  • The power α is always applied to the input token's reserve
  • This creates a real bid-ask spread that accumulates in reserves
  • Round trips dissipate trader value into the pool (time-irreversible)

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property for ExactIn
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure
  • Correct implementation of the dissipative design as specified in the paper

The main trade-offs are:

  1. Higher gas costs for the mathematical complexity (acceptable given the unique properties)
  2. Non-conservative design means round trips dissipate value (creates economic incentive through bid-ask spread)

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

…meric examples for dissipative design

- Added detailed implementation formulas for ExactIn and ExactOut swap directions in the LaTeX document.
- Included numeric examples to illustrate the behavior of the dissipative design, highlighting the differences from strict additivity.
- Updated the corresponding PDF file to reflect these additions and ensure consistency with the new documentation.
@claude
Copy link

claude bot commented Jan 28, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model using the dissipative design, maintaining the crucial property of split invariance (strict additivity) for both ExactIn and ExactOut operations. The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Dissipative design: Correctly implements the paper's approach where power α is always applied to the input token's reserve

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test test_XYCSwapStrictAdditive_RoundingInvariants shows 54M gas (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output, ceiling for input)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations using same curve inverse formulas
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δx=100, α=0.997)
  • ✅ Dissipative design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • LaTeX/PDF paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the dissipative design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

Important note: The implementation uses the dissipative design where:

  • The power α is always applied to the input token's reserve
  • This creates a real bid-ask spread that accumulates in reserves
  • Round trips dissipate trader value into the pool (time-irreversible)
  • Both ExactIn and ExactOut maintain strict additivity using same curve with inverse formulas

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure (added at index 50 in opcodes)
  • Correct implementation of the dissipative design as specified in the paper

The main trade-offs are:

  1. Higher gas costs for the mathematical complexity (acceptable given the unique properties)
  2. Non-conservative design means round trips dissipate value (creates economic incentive through bid-ask spread)

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

@claude
Copy link

claude bot commented Jan 28, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model using the dissipative design, maintaining the crucial property of split invariance (strict additivity) for both ExactIn and ExactOut operations. The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Dissipative design: Correctly implements the paper's approach where power α is always applied to the input token's reserve

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test test_XYCSwapStrictAdditive_RoundingInvariants shows 54M gas (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output, ceiling for input)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations using same curve inverse formulas
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δx=100, α=0.997)
  • ✅ Dissipative design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK

📚 Documentation & Theory

  • LaTeX/PDF paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the dissipative design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

Important note: The implementation uses the dissipative design where:

  • The power α is always applied to the input token's reserve
  • This creates a real bid-ask spread that accumulates in reserves
  • Round trips dissipate trader value into the pool (time-irreversible)
  • Both ExactIn and ExactOut maintain strict additivity using same curve with inverse formulas

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure (added at index 50 in opcodes)
  • Correct implementation of the dissipative design as specified in the paper

The main trade-offs are:

  1. Higher gas costs for the mathematical complexity (acceptable given the unique properties)
  2. Non-conservative design means round trips dissipate value (creates economic incentive through bid-ask spread)

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

@claude
Copy link

claude bot commented Jan 29, 2026

Claude finished @ifelsedeveloper's task —— View job


📋 PR Review Task List

  • Check for repository-specific guidelines (CLAUDE.md)
  • Review mathematical implementation in StrictAdditiveMath.sol
  • Review swap instruction implementation in XYCSwapStrictAdditive.sol
  • Analyze test coverage and quality
  • Evaluate security considerations
  • Assess performance and gas usage
  • Review integration with existing opcodes
  • Provide comprehensive feedback

🔍 Code Review: XYCSwapStrictAdditive Implementation

I've completed a thorough review of this PR implementing the x^α * y = K AMM formula with strict additive fees. Here's my comprehensive feedback:

✅ Overall Assessment

This is a high-quality implementation of a novel AMM design. The code successfully implements the "Strict-Additive Fees Reinvested Inside Pricing" model using the dissipative design, maintaining the crucial property of split invariance (strict additivity) for both ExactIn and ExactOut operations. The implementation follows established patterns from the codebase and incorporates sophisticated optimizations.

📊 Code Quality and Best Practices

StrictAdditiveMath.sol

  • ✅ Excellent: Implements Balancer-style optimized logarithm/exponential functions
  • ✅ Great design: Precomputed constants for e^(2^n) avoid expensive loop operations
  • ✅ Precision handling: 18-decimal fixed-point arithmetic with special 36-decimal paths for values near 1
  • ✅ Error handling: Well-defined custom errors for invalid inputs
  • ✅ Gas optimizations: Unrolled Taylor series (6 terms for ln, 12 for exp)

XYCSwapStrictAdditive.sol

  • ✅ Clean architecture: Follows established swap instruction patterns
  • ✅ Excellent documentation: Comprehensive ASCII art diagram explaining formulas
  • ✅ Proper validation: Checks for zero balances and detects recompute attempts
  • ✅ Dissipative design: Correctly implements the paper's approach where power α is always applied to the input token's reserve

🐛 Potential Issues & Recommendations

  1. Precision at Boundary Values (src/libs/StrictAdditiveMath.sol:126-128)

    if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
        return _ln_36(a) / ONE_18;
    }

    Recommendation: Document the precision guarantees outside the [0.9, 1.1] range. The high-precision path only covers a limited range around 1.

  2. Large Value Multiplication (src/libs/StrictAdditiveMath.sol:300)

    return (((product * seriesSum) / ONE_20) * firstAN) / 100;

    Minor concern: While bounds checking prevents typical overflow, document the safety invariants for extreme edge cases.

  3. Fixed Taylor Series Iterations

    • No explicit convergence checks, relying on fixed iteration counts
    • Recommendation: Add comments explaining why 6 terms for ln and 12 for exp are sufficient for 18-decimal precision

⚡ Performance Analysis

  • Gas Usage: 227k-352k gas for swaps (vs ~218k for standard XYC)

    • ~30-60% overhead is reasonable given the mathematical complexity
    • Test test_XYCSwapStrictAdditive_RoundingInvariants shows 54M gas (extensive edge case testing)
  • Optimization Opportunities:

    • Consider caching results for common alpha values (997_000_000, 990_000_000)
    • The precomputed constants are already a great optimization
    • Document typical gas usage in comments to help users

🔒 Security Analysis

✅ Strong Security Profile:

  • No reentrancy risk: Pure functions with no external calls
  • Input validation: Comprehensive checks for zero balances, alpha bounds (0 < α ≤ 1e9)
  • Overflow protection: Explicit bounds in _exp function (±130e18)
  • Rounding direction: Correctly implemented to protect the protocol (floor for output, ceiling for input)
  • Split invariance: Mathematical property prevents manipulation through trade splitting

No critical vulnerabilities identified.

🧪 Test Coverage Excellence

Comprehensive test suite covering:

  • ✅ Basic functionality with various fee levels (0%, 0.3%, 1%, 5%, 10%)
  • Split invariance verification (key property) - tested with 2, 3, 5, 10, 20, 100-way splits
  • ✅ ExactIn and ExactOut calculations using same curve inverse formulas
  • ✅ Edge cases (1e12 to 500e18 amounts)
  • ✅ Rounding invariants preventing value extraction
  • ✅ Numerical validation matching paper examples (x=1000, y=1000, Δx=100, α=0.997)
  • ✅ Dissipative design verification (proper round-trip behavior)
  • ✅ Gas comparison benchmarks
  • Security tests (StrictAdditiveSecurityTest.t.sol) with edge cases:
    • 1 wei balances
    • Extreme imbalances (1e30:1)
    • Near-100% swaps
    • Minimum alpha values

Test Quality Highlights:

  • Excellent precision analysis showing sub-ppb differences
  • Well-structured tests with clear documentation
  • Comprehensive gas benchmarking against standard XYK
  • Security-focused edge case testing

📚 Documentation & Theory

  • LaTeX/PDF paper provided: Clear mathematical derivation of the model
  • Inline documentation: Excellent ASCII art explaining the dissipative design
  • Mathematical correctness: Implementation matches the paper's formulas exactly

The paper clearly explains:

  • Why standard Uniswap fees break strict additivity
  • The cocycle condition R(x,a)R(x+a,b) = R(x,a+b)
  • The general solution yΨ(x) = K with Ψ(x) = x^α

Important note: The implementation uses the dissipative design where:

  • The power α is always applied to the input token's reserve
  • This creates a real bid-ask spread that accumulates in reserves
  • Round trips dissipate trader value into the pool (time-irreversible)
  • Both ExactIn and ExactOut maintain strict additivity using same curve with inverse formulas

💡 Minor Suggestions

  1. Add Alpha Constants for common values:

    uint32 constant ALPHA_NO_FEE = 1_000_000_000;   // 0% fee
    uint32 constant ALPHA_0_3_PCT = 997_000_000;    // 0.3% fee
    uint32 constant ALPHA_1_PCT = 990_000_000;      // 1% fee
  2. Document Precision Guarantees: Add comments about maximum relative error for the ln/exp approximations

  3. Gas Usage Documentation: Add typical gas costs in function comments

  4. Consider Edge Case: Test behavior when calculations approach precision limits or when alpha is very close to 0

✅ Summary

This is a production-ready implementation of a sophisticated AMM design. The code demonstrates:

  • Strong mathematical foundations with proper optimizations
  • Excellent test coverage proving the key split invariance property
  • Proper security considerations and input validation
  • Clean integration with existing infrastructure (added at index 50 in opcodes)
  • Correct implementation of the dissipative design as specified in the paper

The main trade-offs are:

  1. Higher gas costs for the mathematical complexity (acceptable given the unique properties)
  2. Non-conservative design means round trips dissipate value (creates economic incentive through bid-ask spread)

Verdict: ✅ Approve - This is high-quality code ready for production use. The implementation correctly solves the problem of fees breaking strict additivity in standard AMMs while maintaining full input credit and reinvesting fees inside pricing.

Boogerwooger and others added 3 commits February 13, 2026 14:19
…impossibility theorem

- Added new sections discussing the importance of strict additivity and its implications for trader output.
- Introduced an impossibility theorem demonstrating the trade-offs between statelessness, LP-protection, and fee mechanisms.
- Enhanced the PDF to reflect these updates and ensure consistency with the revised LaTeX source.
… of github.com:1inch/swap-vm into feature/Strict-Additive-Fees-Reinvested-Inside-Pricing
…thors and acknowledgements

- Revised author section to include additional contributors with their contact information.
- Added an acknowledgements paragraph recognizing contributors for discussions and feedback.
- Updated the corresponding PDF to reflect these changes.
…e fees

- Added 1inch Labs and OpenZeppelin as affiliations for authors.
- Revised author contact information for clarity.
- Updated the corresponding PDF to reflect these changes.
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