Skip to content

Conversation

@2PykeETH
Copy link

@2PykeETH 2PykeETH commented Oct 3, 2025

Summary

This PR introduces the swap external function to the TestAMMContract, enabling users to swap between token pairs within a prediction market pool. The function is built on the constant product formula (x * y = k) to preserve AMM invariants and includes slippage protection via a minimum output amount check.


Changes

  • New Function: swap

    • Parameters:

      • _marketId — unique identifier of the prediction market pool.
      • _amountIn — amount of input tokens provided by the user.
      • _amountOutMinimum — minimum acceptable output amount (slippage protection).
      • _zeroForOne — swap direction flag (true = tokenA → tokenB, false = tokenB → tokenA).
    • Core Logic:

      • Determines input/output tokens and reserves based on _zeroForOne.
      • Validates pool is initialized and has sufficient reserves.
      • Uses constant product formula:
        amountOut = (reserveOut * amountIn) / (reserveIn + amountIn)
        
        Ensures the invariant (reserveIn + amountIn) * (reserveOut - amountOut) = reserveIn * reserveOut.
      • Transfers input tokens from the user to the pool.
      • Updates pool reserves (reserveA and reserveB).
      • Transfers output tokens back to the user.
      • Emits TokensSwapped event with details of the swap.
  • Event Emission:

    • Reuses the TokensSwapped event for transparency and analytics.
  • Formatting:

    • Applied forge fmt for style consistency.

Motivation

  • Core AMM Functionality: Provides the essential swap feature, enabling token exchanges within market-specific liquidity pools.
  • User Protection: Introduces _amountOutMinimum check to mitigate slippage attacks and guarantee minimum expected returns.
  • Protocol Growth: With addLiquidity, removeLiquidity, and now swap, the AMM contract supports the full lifecycle of pool interactions.

Next Steps

  • Add unit/integration tests for swap:
    • Successful swap with sufficient liquidity.
    • Failure when amountOut < _amountOutMinimum.
    • Failure when pool reserves are insufficient.
    • Edge cases (e.g., very small input amounts, large swaps relative to reserves).
  • Future optimization: Consider adding a swap fee mechanism to incentivize liquidity providers.

@Neros0 Neros0 self-requested a review October 3, 2025 14:30
@Neros0 Neros0 added documentation Improvements or additions to documentation enhancement New feature or request labels Oct 3, 2025
@Neros0 Neros0 merged commit 1ca2474 into Arenium-Social:main Oct 3, 2025
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants