Skip to content
Lattice

ConstantProductLib

Git Source

Title: ConstantProductLib

Authors: David Dada <daveproxy80@gmail.com> (https://github.com/dadadave80), Modified from Uniswap V2 (https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Pair.sol)

Library implementing a Uniswap V2-style constant-product AMM (x*y=k) as a stateless Diamond facet.

All state lives in a single ERC-7201 namespaced slot. LP shares are tracked internally (not as a separate ERC-20 token) to avoid an extra facet dependency. 0.3% swap fee (30 bps).

Constants

FEE_BPS

Swap fee in basis points (0.3%).

uint16 internal constant FEE_BPS = 30;

MINIMUM_LIQUIDITY

Minimum liquidity permanently locked on first deposit (Uniswap V2 convention).

uint256 internal constant MINIMUM_LIQUIDITY = 1000;

Functions

constantProductStorage

Returns the ConstantProduct storage struct.

function constantProductStorage() internal pure returns (ConstantProductStorage storage $);

Returns

NameTypeDescription
$ConstantProductStorage

__ConstantProduct_init

Initializes the ConstantProduct pool with two ERC-20 token addresses.

Must be called inside a pre/postInitializer block. Sorts tokens so token0 < token1.

function __ConstantProduct_init(address tokenA, address tokenB) internal;

Parameters

NameTypeDescription
tokenAaddressOne of the two pool tokens.
tokenBaddressThe other pool token.

registerInterface

Registers support for IConstantProduct via ERC-165.

function registerInterface() internal;

token0

Returns token0 address.

function token0() internal view returns (address);

Returns

NameTypeDescription
<none>address

token1

Returns token1 address.

function token1() internal view returns (address);

Returns

NameTypeDescription
<none>address

getReserves

Returns the current reserves and last-update timestamp.

function getReserves() internal view returns (uint256 reserve0, uint256 reserve1, uint32 blockTimestampLast);

Returns

NameTypeDescription
reserve0uint256
reserve1uint256
blockTimestampLastuint32

totalLpSupply

Returns the total LP share supply.

function totalLpSupply() internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256

lpBalanceOf

Returns the LP share balance of account.

function lpBalanceOf(address account) internal view returns (uint256);

Parameters

NameTypeDescription
accountaddress

Returns

NameTypeDescription
<none>uint256

feeBps

Returns the swap fee in basis points (always 30).

function feeBps() internal pure returns (uint16);

Returns

NameTypeDescription
<none>uint16

addLiquidity

Adds liquidity to the pool and mints LP shares to to.

function addLiquidity(
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 amount0Min,
        uint256 amount1Min,
        address to
    ) internal returns (uint256 amount0, uint256 amount1, uint256 liquidity);

Parameters

NameTypeDescription
amount0Desireduint256Desired deposit of token0.
amount1Desireduint256Desired deposit of token1.
amount0Minuint256Minimum acceptable token0 deposit (slippage guard).
amount1Minuint256Minimum acceptable token1 deposit (slippage guard).
toaddressRecipient of minted LP shares.

Returns

NameTypeDescription
amount0uint256Actual token0 deposited.
amount1uint256Actual token1 deposited.
liquidityuint256LP shares minted to to.

removeLiquidity

Burns LP shares from the caller and returns underlying tokens to to.

function removeLiquidity(uint256 liquidity, uint256 amount0Min, uint256 amount1Min, address to)
        internal
        returns (uint256 amount0, uint256 amount1);

Parameters

NameTypeDescription
liquidityuint256Amount of LP shares to burn.
amount0Minuint256Minimum acceptable token0 returned (slippage guard).
amount1Minuint256Minimum acceptable token1 returned (slippage guard).
toaddressRecipient of the returned tokens.

Returns

NameTypeDescription
amount0uint256Amount of token0 returned.
amount1uint256Amount of token1 returned.

swapExactTokensForTokens

Swaps an exact input amount for output tokens.

function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, bool zeroForOne, address to)
        internal
        returns (uint256 amountOut);

Parameters

NameTypeDescription
amountInuint256Exact input token amount to sell.
amountOutMinuint256Minimum acceptable output (slippage guard).
zeroForOneboolTrue = sell token0 for token1; False = sell token1 for token0.
toaddressRecipient of output tokens.

Returns

NameTypeDescription
amountOutuint256Output token amount sent to to.

_executeSwap

Internal helper that carries out the swap to avoid stack-too-deep in the public entry point. Fee-on-transfer safe: the input is pulled first and the ACTUAL received balance delta (effectiveAmountIn) drives the output, K-invariant, slippage and reserve math. For standard tokens the delta equals the requested amount, preserving existing behavior. The reentrancy guard in the caller protects the pull-before-update ordering.

function _executeSwap(
        ConstantProductStorage storage $,
        uint256 amountIn,
        uint256 amountOutMin,
        bool zeroForOne,
        address caller,
        address to
    ) private returns (uint256 amountOut);

Parameters

NameTypeDescription
$ConstantProductStorage
amountInuint256
amountOutMinuint256
zeroForOnebool
calleraddress
toaddress

Returns

NameTypeDescription
amountOutuint256

_checkK

Validates that the constant-product invariant holds after a swap.

function _checkK(uint256 amountIn, uint256 amountOut, uint256 reserveIn, uint256 reserveOut) private pure;

Parameters

NameTypeDescription
amountInuint256
amountOutuint256
reserveInuint256
reserveOutuint256

getAmountOut

Computes the output amount given an input amount and pool reserves, applying the 0.3% fee.

function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountOut);

Parameters

NameTypeDescription
amountInuint256The input amount.
reserveInuint256The reserve of the input token.
reserveOutuint256The reserve of the output token.

Returns

NameTypeDescription
amountOutuint256The output amount after fee.

getAmountIn

Computes the required input to receive a specific output amount, applying the 0.3% fee.

function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountIn);

Parameters

NameTypeDescription
amountOutuint256The desired output amount.
reserveInuint256The reserve of the input token.
reserveOutuint256The reserve of the output token.

Returns

NameTypeDescription
amountInuint256The required input amount (rounded up).

quote

Returns the equivalent amount of tokenB given amountA at the current pool ratio.

No fee is applied — this is used for liquidity proportion calculations.

function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB);

Parameters

NameTypeDescription
amountAuint256Amount of tokenA.
reserveAuint256Reserve of tokenA.
reserveBuint256Reserve of tokenB.

Returns

NameTypeDescription
amountBuint256Equivalent amount of tokenB.

_sqrt

Babylonian square-root used for first-liquidity LP share calculation.

function _sqrt(uint256 y) internal pure returns (uint256 z);

Parameters

NameTypeDescription
yuint256The value to take the square root of.

Returns

NameTypeDescription
zuint256The integer square root of y.

_mintLp

Mints LP shares to account, updating total supply.

function _mintLp(ConstantProductStorage storage $, address account, uint256 amount) private;

Parameters

NameTypeDescription
$ConstantProductStorage
accountaddress
amountuint256

_burnLp

Burns LP shares from account, updating total supply.

function _burnLp(ConstantProductStorage storage $, address account, uint256 amount) private;

Parameters

NameTypeDescription
$ConstantProductStorage
accountaddress
amountuint256

_safeTransferFromReceived

Pulls amount of token from from into the pool and returns the ACTUAL received amount (the pool balance delta).

Fee-on-transfer / deflationary tokens deliver less than amount; the measured delta is the effective input used for reserve, LP and K math. For standard tokens the delta equals amount, preserving existing behavior. Reverts ConstantProductTransferFailed on a false return.

function _safeTransferFromReceived(address token, address from, uint256 amount) private returns (uint256 received);

Parameters

NameTypeDescription
tokenaddressThe token to pull.
fromaddressThe address to pull from.
amountuint256The requested transfer amount.

Returns

NameTypeDescription
receiveduint256The actual amount credited to the pool (post-fee).

_safeTransfer

Calls transfer on token, reverts with ConstantProductTransferFailed on false return.

function _safeTransfer(address token, address to, uint256 amount) private;

Parameters

NameTypeDescription
tokenaddress
toaddress
amountuint256