Created
February 26, 2023 11:04
-
-
Save DanielZlotin/567a22b8d29746f0574f852fc0074e0d to your computer and use it in GitHub Desktop.
AMM Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset | |
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { | |
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); | |
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); | |
uint amountInWithFee = amountIn.mul(997); | |
uint numerator = amountInWithFee.mul(reserveOut); | |
uint denominator = reserveIn.mul(1000).add(amountInWithFee); | |
amountOut = numerator / denominator; | |
} | |
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset | |
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { | |
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); | |
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); | |
uint numerator = reserveIn.mul(amountOut).mul(1000); | |
uint denominator = reserveOut.sub(amountOut).mul(997); | |
amountIn = (numerator / denominator).add(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment