feat: Add getAmountOut External View Function to Test_AMMContract #123
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This PR adds a new external view function
getAmountOutto theTest_AMMContract, enabling users and external contracts to query expected swap amounts before executing trades. This function implements the constant product AMM formula (x * y = k) for price calculations.Changes
1. New Function -
getAmountOutAdded a gas-efficient view function that calculates the expected output amount for a given input without executing the swap.
Function Signature:
Parameters:
marketId- The unique identifier for the liquidity poolamountIn- The amount of input tokenszeroForOne- Direction flag (true = tokenA → tokenB, false = tokenB → tokenA)Returns:
amountOut- The calculated output amount based on current pool reserves2. Implementation Details
Validation Checks:
amountIn > 0to prevent zero-amount queriespool.poolInitializedCalculation Logic:
amountOut = (reserveOut * amountIn) / (reserveIn + amountIn)zeroForOne)Swap Direction Handling:
zeroForOne = true: Swaps tokenA for tokenB (uses reserveA as input, reserveB as output)zeroForOne = false: Swaps tokenB for tokenA (uses reserveB as input, reserveA as output)3. Code Formatting
Applied
forge fmtto maintain consistent code styling.Use Cases
This function enables several important workflows:
Price Discovery:
Arbitrage Detection:
Slippage Calculation:
minAmountOutparameters for actual swap transactionsMulti-hop Route Planning:
getAmountOutcalls to calculate optimal routing pathsFiles Changed
src/onchain/TestAMMContract.sol- AddedgetAmountOutfunction with 21 new linesTechnical Notes
Gas Efficiency:
viewonly - no gas cost when called externallyImportant Considerations:
Formula Breakdown:
Testing Recommendations
Suggested test cases:
Security Impact
Risk Level: Very Low
Security considerations:
Breaking Changes
None. This is a purely additive change that doesn't modify existing functionality.
Integration Example
Next Steps
Consider adding: