ETH Price: $3,140.84 (-8.93%)

Contract

0xb4315e873dBcf96Ffd0acd8EA43f689D8c20fB30
Transaction Hash
Method
Block
From
To
Swap Exact Token...2359039212024-07-25 12:40:514 mins ago1721911251IN
Trader Joe: LBRouter v2.1
0 ETH0.000002820.013486
Swap Exact Token...2359036722024-07-25 12:39:485 mins ago1721911188IN
Trader Joe: LBRouter v2.1
0 ETH0.000002190.01
Swap Exact Token...2359035892024-07-25 12:39:275 mins ago1721911167IN
Trader Joe: LBRouter v2.1
0 ETH0.000002040.01
Remove Liquidity...2359031692024-07-25 12:37:417 mins ago1721911061IN
Trader Joe: LBRouter v2.1
0 ETH0.00001520.01253
Remove Liquidity...2359024752024-07-25 12:34:4710 mins ago1721910887IN
Trader Joe: LBRouter v2.1
0 ETH0.00001150.010667
Remove Liquidity...2358981652024-07-25 12:16:5028 mins ago1721909810IN
Trader Joe: LBRouter v2.1
0 ETH0.000009730.01
Add Liquidity NA...2358973662024-07-25 12:13:2931 mins ago1721909609IN
Trader Joe: LBRouter v2.1
0.01 ETH0.000022910.01
Remove Liquidity2358929162024-07-25 11:54:5650 mins ago1721908496IN
Trader Joe: LBRouter v2.1
0 ETH0.000010340.01
Add Liquidity NA...2358925932024-07-25 11:53:3451 mins ago1721908414IN
Trader Joe: LBRouter v2.1
0.0042 ETH0.000026580.01
Remove Liquidity...2358912752024-07-25 11:48:0557 mins ago1721908085IN
Trader Joe: LBRouter v2.1
0 ETH0.000011860.01
Add Liquidity NA...2358911022024-07-25 11:47:2158 mins ago1721908041IN
Trader Joe: LBRouter v2.1
0.09 ETH0.000023170.01
Add Liquidity NA...2358901602024-07-25 11:43:261 hr ago1721907806IN
Trader Joe: LBRouter v2.1
0 ETH0.000029120.01
Add Liquidity NA...2358901022024-07-25 11:43:121 hr ago1721907792IN
Trader Joe: LBRouter v2.1
0.00866666 ETH0.000029650.01
Add Liquidity NA...2358900462024-07-25 11:42:581 hr ago1721907778IN
Trader Joe: LBRouter v2.1
0.01733333 ETH0.000029370.01
Remove Liquidity...2358897602024-07-25 11:41:461 hr ago1721907706IN
Trader Joe: LBRouter v2.1
0 ETH0.000012920.01
Remove Liquidity...2358896922024-07-25 11:41:291 hr ago1721907689IN
Trader Joe: LBRouter v2.1
0 ETH0.000003910.01
Remove Liquidity...2358896462024-07-25 11:41:171 hr ago1721907677IN
Trader Joe: LBRouter v2.1
0 ETH0.000001370.01
Remove Liquidity...2358896102024-07-25 11:41:081 hr ago1721907668IN
Trader Joe: LBRouter v2.1
0 ETH0.000004030.01
Remove Liquidity...2358894962024-07-25 11:40:401 hr ago1721907640IN
Trader Joe: LBRouter v2.1
0 ETH0.000025230.01
Add Liquidity NA...2358891212024-07-25 11:39:071 hr ago1721907547IN
Trader Joe: LBRouter v2.1
0 ETH0.000029190.01
Add Liquidity NA...2358891192024-07-25 11:39:071 hr ago1721907547IN
Trader Joe: LBRouter v2.1
0.04 ETH0.000023010.01
Add Liquidity NA...2358890782024-07-25 11:38:561 hr ago1721907536IN
Trader Joe: LBRouter v2.1
0.00866666 ETH0.000029720.01
Add Liquidity NA...2358890352024-07-25 11:38:461 hr ago1721907526IN
Trader Joe: LBRouter v2.1
0.01733333 ETH0.000029440.01
Remove Liquidity...2358888042024-07-25 11:37:471 hr ago1721907467IN
Trader Joe: LBRouter v2.1
0 ETH0.000001410.01
Remove Liquidity...2358887372024-07-25 11:37:301 hr ago1721907450IN
Trader Joe: LBRouter v2.1
0 ETH0.000037690.01
View all transactions

Latest 25 internal transactions (View All)

Parent Transaction Hash Block From To
2359039212024-07-25 12:40:514 mins ago1721911251
Trader Joe: LBRouter v2.1
0.9532948 ETH
2359039212024-07-25 12:40:514 mins ago1721911251
Trader Joe: LBRouter v2.1
0.9532948 ETH
2359036722024-07-25 12:39:485 mins ago1721911188
Trader Joe: LBRouter v2.1
0.56016682 ETH
2359036722024-07-25 12:39:485 mins ago1721911188
Trader Joe: LBRouter v2.1
0.56016682 ETH
2359035892024-07-25 12:39:275 mins ago1721911167
Trader Joe: LBRouter v2.1
0.48202924 ETH
2359035892024-07-25 12:39:275 mins ago1721911167
Trader Joe: LBRouter v2.1
0.48202924 ETH
2359031692024-07-25 12:37:417 mins ago1721911061
Trader Joe: LBRouter v2.1
0.01858526 ETH
2359031692024-07-25 12:37:417 mins ago1721911061
Trader Joe: LBRouter v2.1
0.01858526 ETH
2359024752024-07-25 12:34:4710 mins ago1721910887
Trader Joe: LBRouter v2.1
0.04665547 ETH
2359024752024-07-25 12:34:4710 mins ago1721910887
Trader Joe: LBRouter v2.1
0.04665547 ETH
2358973662024-07-25 12:13:2931 mins ago1721909609
Trader Joe: LBRouter v2.1
0.01 ETH
2358925932024-07-25 11:53:3451 mins ago1721908414
Trader Joe: LBRouter v2.1
0.0042 ETH
2358911022024-07-25 11:47:2158 mins ago1721908041
Trader Joe: LBRouter v2.1
0.09 ETH
2358901022024-07-25 11:43:121 hr ago1721907792
Trader Joe: LBRouter v2.1
0.00866666 ETH
2358900462024-07-25 11:42:581 hr ago1721907778
Trader Joe: LBRouter v2.1
0.01733333 ETH
2358894962024-07-25 11:40:401 hr ago1721907640
Trader Joe: LBRouter v2.1
0.02607581 ETH
2358894962024-07-25 11:40:401 hr ago1721907640
Trader Joe: LBRouter v2.1
0.02607581 ETH
2358891192024-07-25 11:39:071 hr ago1721907547
Trader Joe: LBRouter v2.1
0.04 ETH
2358890782024-07-25 11:38:561 hr ago1721907536
Trader Joe: LBRouter v2.1
0.00866666 ETH
2358890352024-07-25 11:38:461 hr ago1721907526
Trader Joe: LBRouter v2.1
0.01733333 ETH
2358887372024-07-25 11:37:301 hr ago1721907450
Trader Joe: LBRouter v2.1
0.02003712 ETH
2358887372024-07-25 11:37:301 hr ago1721907450
Trader Joe: LBRouter v2.1
0.02003712 ETH
2358882592024-07-25 11:35:301 hr ago1721907330
Trader Joe: LBRouter v2.1
0.00666666 ETH
2358882032024-07-25 11:35:161 hr ago1721907316
Trader Joe: LBRouter v2.1
0.01333333 ETH
2358877492024-07-25 11:33:221 hr ago1721907202
Trader Joe: LBRouter v2.1
0.017 ETH
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LBRouter

Compiler Version
v0.8.10+commit.fc410830

Optimization Enabled:
Yes with 800 runs

Other Settings:
default evmVersion
File 1 of 31 : LBRouter.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {BinHelper} from "./libraries/BinHelper.sol";
import {Constants} from "./libraries/Constants.sol";
import {Encoded} from "./libraries/math/Encoded.sol";
import {FeeHelper} from "./libraries/FeeHelper.sol";
import {JoeLibrary} from "./libraries/JoeLibrary.sol";
import {LiquidityConfigurations} from "./libraries/math/LiquidityConfigurations.sol";
import {PackedUint128Math} from "./libraries/math/PackedUint128Math.sol";
import {TokenHelper} from "./libraries/TokenHelper.sol";
import {Uint256x256Math} from "./libraries/math/Uint256x256Math.sol";

import {IJoePair} from "./interfaces/IJoePair.sol";
import {ILBPair} from "./interfaces/ILBPair.sol";
import {ILBLegacyPair} from "./interfaces/ILBLegacyPair.sol";
import {ILBToken} from "./interfaces/ILBToken.sol";
import {ILBRouter} from "./interfaces/ILBRouter.sol";
import {ILBLegacyRouter} from "./interfaces/ILBLegacyRouter.sol";
import {IJoeFactory} from "./interfaces/IJoeFactory.sol";
import {ILBLegacyFactory} from "./interfaces/ILBLegacyFactory.sol";
import {ILBFactory} from "./interfaces/ILBFactory.sol";
import {IWNATIVE} from "./interfaces/IWNATIVE.sol";

/**
 * @title Liquidity Book Router
 * @author Trader Joe
 * @notice Main contract to interact with to swap and manage liquidity on Joe V2 exchange.
 */
contract LBRouter is ILBRouter {
    using TokenHelper for IERC20;
    using TokenHelper for IWNATIVE;
    using JoeLibrary for uint256;
    using PackedUint128Math for bytes32;

    ILBFactory private immutable _factory;
    IJoeFactory private immutable _factoryV1;
    ILBLegacyFactory private immutable _legacyFactory;
    ILBLegacyRouter private immutable _legacyRouter;
    IWNATIVE private immutable _wnative;

    modifier onlyFactoryOwner() {
        if (msg.sender != _factory.owner()) revert LBRouter__NotFactoryOwner();
        _;
    }

    modifier ensure(uint256 deadline) {
        if (block.timestamp > deadline) revert LBRouter__DeadlineExceeded(deadline, block.timestamp);
        _;
    }

    modifier verifyPathValidity(Path memory path) {
        if (
            path.pairBinSteps.length == 0 || path.versions.length != path.pairBinSteps.length
                || path.pairBinSteps.length + 1 != path.tokenPath.length
        ) revert LBRouter__LengthsMismatch();
        _;
    }

    /**
     * @notice Constructor
     * @param factory Address of Joe V2.1 factory
     * @param factoryV1 Address of Joe V1 factory
     * @param legacyFactory Address of Joe V2 factory
     * @param legacyRouter Address of Joe V2 router
     * @param wnative Address of WNATIVE
     */
    constructor(
        ILBFactory factory,
        IJoeFactory factoryV1,
        ILBLegacyFactory legacyFactory,
        ILBLegacyRouter legacyRouter,
        IWNATIVE wnative
    ) {
        _factory = factory;
        _factoryV1 = factoryV1;
        _legacyFactory = legacyFactory;
        _legacyRouter = legacyRouter;
        _wnative = wnative;
    }

    /**
     * @dev Receive function that only accept NATIVE from the WNATIVE contract
     */
    receive() external payable {
        if (msg.sender != address(_wnative)) revert LBRouter__SenderIsNotWNATIVE();
    }

    /**
     * View function to get the factory V2.1 address
     * @return lbFactory The address of the factory V2.1
     */
    function getFactory() external view override returns (ILBFactory lbFactory) {
        return _factory;
    }

    /**
     * View function to get the factory V2 address
     * @return legacyLBfactory The address of the factory V2
     */
    function getLegacyFactory() external view override returns (ILBLegacyFactory legacyLBfactory) {
        return _legacyFactory;
    }

    /**
     * View function to get the factory V1 address
     * @return factoryV1 The address of the factory V1
     */
    function getV1Factory() external view override returns (IJoeFactory factoryV1) {
        return _factoryV1;
    }

    /**
     * View function to get the router V2 address
     * @return legacyRouter The address of the router V2
     */
    function getLegacyRouter() external view override returns (ILBLegacyRouter legacyRouter) {
        return _legacyRouter;
    }

    /**
     * View function to get the WNATIVE address
     * @return wnative The address of WNATIVE
     */
    function getWNATIVE() external view override returns (IWNATIVE wnative) {
        return _wnative;
    }

    /**
     * @notice Returns the approximate id corresponding to the inputted price.
     * Warning, the returned id may be inaccurate close to the start price of a bin
     * @param pair The address of the LBPair
     * @param price The price of y per x (multiplied by 1e36)
     * @return The id corresponding to this price
     */
    function getIdFromPrice(ILBPair pair, uint256 price) external view override returns (uint24) {
        return pair.getIdFromPrice(price);
    }

    /**
     * @notice Returns the price corresponding to the inputted id
     * @param pair The address of the LBPair
     * @param id The id
     * @return The price corresponding to this id
     */
    function getPriceFromId(ILBPair pair, uint24 id) external view override returns (uint256) {
        return pair.getPriceFromId(id);
    }

    /**
     * @notice Simulate a swap in
     * @param pair The address of the LBPair
     * @param amountOut The amount of token to receive
     * @param swapForY Whether you swap X for Y (true), or Y for X (false)
     * @return amountIn The amount of token to send in order to receive amountOut token
     * @return amountOutLeft The amount of token Out that can't be returned due to a lack of liquidity
     * @return fee The amount of fees paid in token sent
     */
    function getSwapIn(ILBPair pair, uint128 amountOut, bool swapForY)
        public
        view
        override
        returns (uint128 amountIn, uint128 amountOutLeft, uint128 fee)
    {
        (amountIn, amountOutLeft, fee) = pair.getSwapIn(amountOut, swapForY);
    }

    /**
     * @notice Simulate a swap out
     * @param pair The address of the LBPair
     * @param amountIn The amount of token sent
     * @param swapForY Whether you swap X for Y (true), or Y for X (false)
     * @return amountInLeft The amount of token In that can't be swapped due to a lack of liquidity
     * @return amountOut The amount of token received if amountIn tokenX are sent
     * @return fee The amount of fees paid in token sent
     */
    function getSwapOut(ILBPair pair, uint128 amountIn, bool swapForY)
        external
        view
        override
        returns (uint128 amountInLeft, uint128 amountOut, uint128 fee)
    {
        (amountInLeft, amountOut, fee) = pair.getSwapOut(amountIn, swapForY);
    }

    /**
     * @notice Create a liquidity bin LBPair for tokenX and tokenY using the factory
     * @param tokenX The address of the first token
     * @param tokenY The address of the second token
     * @param activeId The active id of the pair
     * @param binStep The bin step in basis point, used to calculate log(1 + binStep)
     * @return pair The address of the newly created LBPair
     */
    function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
        external
        override
        returns (ILBPair pair)
    {
        pair = _factory.createLBPair(tokenX, tokenY, activeId, binStep);
    }

    /**
     * @notice Add liquidity while performing safety checks
     * @dev This function is compliant with fee on transfer tokens
     * @param liquidityParameters The liquidity parameters
     * @return amountXAdded The amount of token X added
     * @return amountYAdded The amount of token Y added
     * @return amountXLeft The amount of token X left (sent back to liquidityParameters.refundTo)
     * @return amountYLeft The amount of token Y left (sent back to liquidityParameters.refundTo)
     * @return depositIds The ids of the deposits
     * @return liquidityMinted The amount of liquidity minted
     */
    function addLiquidity(LiquidityParameters calldata liquidityParameters)
        external
        override
        returns (
            uint256 amountXAdded,
            uint256 amountYAdded,
            uint256 amountXLeft,
            uint256 amountYLeft,
            uint256[] memory depositIds,
            uint256[] memory liquidityMinted
        )
    {
        ILBPair lbPair = ILBPair(
            _getLBPairInformation(
                liquidityParameters.tokenX, liquidityParameters.tokenY, liquidityParameters.binStep, Version.V2_1
            )
        );
        if (liquidityParameters.tokenX != lbPair.getTokenX()) revert LBRouter__WrongTokenOrder();

        liquidityParameters.tokenX.safeTransferFrom(msg.sender, address(lbPair), liquidityParameters.amountX);
        liquidityParameters.tokenY.safeTransferFrom(msg.sender, address(lbPair), liquidityParameters.amountY);

        (amountXAdded, amountYAdded, amountXLeft, amountYLeft, depositIds, liquidityMinted) =
            _addLiquidity(liquidityParameters, lbPair);
    }

    /**
     * @notice Add liquidity with NATIVE while performing safety checks
     * @dev This function is compliant with fee on transfer tokens
     * @param liquidityParameters The liquidity parameters
     * @return amountXAdded The amount of token X added
     * @return amountYAdded The amount of token Y added
     * @return amountXLeft The amount of token X left (sent back to liquidityParameters.refundTo)
     * @return amountYLeft The amount of token Y left (sent back to liquidityParameters.refundTo)
     * @return depositIds The ids of the deposits
     * @return liquidityMinted The amount of liquidity minted
     */
    function addLiquidityNATIVE(LiquidityParameters calldata liquidityParameters)
        external
        payable
        override
        returns (
            uint256 amountXAdded,
            uint256 amountYAdded,
            uint256 amountXLeft,
            uint256 amountYLeft,
            uint256[] memory depositIds,
            uint256[] memory liquidityMinted
        )
    {
        ILBPair _LBPair = ILBPair(
            _getLBPairInformation(
                liquidityParameters.tokenX, liquidityParameters.tokenY, liquidityParameters.binStep, Version.V2_1
            )
        );
        if (liquidityParameters.tokenX != _LBPair.getTokenX()) revert LBRouter__WrongTokenOrder();

        if (liquidityParameters.tokenX == _wnative && liquidityParameters.amountX == msg.value) {
            _wnativeDepositAndTransfer(address(_LBPair), msg.value);
            liquidityParameters.tokenY.safeTransferFrom(msg.sender, address(_LBPair), liquidityParameters.amountY);
        } else if (liquidityParameters.tokenY == _wnative && liquidityParameters.amountY == msg.value) {
            liquidityParameters.tokenX.safeTransferFrom(msg.sender, address(_LBPair), liquidityParameters.amountX);
            _wnativeDepositAndTransfer(address(_LBPair), msg.value);
        } else {
            revert LBRouter__WrongNativeLiquidityParameters(
                address(liquidityParameters.tokenX),
                address(liquidityParameters.tokenY),
                liquidityParameters.amountX,
                liquidityParameters.amountY,
                msg.value
            );
        }

        (amountXAdded, amountYAdded, amountXLeft, amountYLeft, depositIds, liquidityMinted) =
            _addLiquidity(liquidityParameters, _LBPair);
    }

    /**
     * @notice Remove liquidity while performing safety checks
     * @dev This function is compliant with fee on transfer tokens
     * @param tokenX The address of token X
     * @param tokenY The address of token Y
     * @param binStep The bin step of the LBPair
     * @param amountXMin The min amount to receive of token X
     * @param amountYMin The min amount to receive of token Y
     * @param ids The list of ids to burn
     * @param amounts The list of amounts to burn of each id in `_ids`
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountX Amount of token X returned
     * @return amountY Amount of token Y returned
     */
    function removeLiquidity(
        IERC20 tokenX,
        IERC20 tokenY,
        uint16 binStep,
        uint256 amountXMin,
        uint256 amountYMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address to,
        uint256 deadline
    ) external override ensure(deadline) returns (uint256 amountX, uint256 amountY) {
        ILBPair _LBPair = ILBPair(_getLBPairInformation(tokenX, tokenY, binStep, Version.V2_1));
        bool isWrongOrder = tokenX != _LBPair.getTokenX();

        if (isWrongOrder) (amountXMin, amountYMin) = (amountYMin, amountXMin);

        (amountX, amountY) = _removeLiquidity(_LBPair, amountXMin, amountYMin, ids, amounts, to);

        if (isWrongOrder) (amountX, amountY) = (amountY, amountX);
    }

    /**
     * @notice Remove NATIVE liquidity while performing safety checks
     * @dev This function is **NOT** compliant with fee on transfer tokens.
     * This is wanted as it would make users pays the fee on transfer twice,
     * use the `removeLiquidity` function to remove liquidity with fee on transfer tokens.
     * @param token The address of token
     * @param binStep The bin step of the LBPair
     * @param amountTokenMin The min amount to receive of token
     * @param amountNATIVEMin The min amount to receive of NATIVE
     * @param ids The list of ids to burn
     * @param amounts The list of amounts to burn of each id in `_ids`
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountToken Amount of token returned
     * @return amountNATIVE Amount of NATIVE returned
     */
    function removeLiquidityNATIVE(
        IERC20 token,
        uint16 binStep,
        uint256 amountTokenMin,
        uint256 amountNATIVEMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address payable to,
        uint256 deadline
    ) external override ensure(deadline) returns (uint256 amountToken, uint256 amountNATIVE) {
        IWNATIVE wnative = _wnative;

        ILBPair lbPair = ILBPair(_getLBPairInformation(token, IERC20(wnative), binStep, Version.V2_1));

        {
            bool isNATIVETokenY = IERC20(wnative) == lbPair.getTokenY();

            if (!isNATIVETokenY) {
                (amountTokenMin, amountNATIVEMin) = (amountNATIVEMin, amountTokenMin);
            }

            (uint256 amountX, uint256 amountY) =
                _removeLiquidity(lbPair, amountTokenMin, amountNATIVEMin, ids, amounts, address(this));

            (amountToken, amountNATIVE) = isNATIVETokenY ? (amountX, amountY) : (amountY, amountX);
        }

        token.safeTransfer(to, amountToken);

        wnative.withdraw(amountNATIVE);
        _safeTransferNATIVE(to, amountNATIVE);
    }

    /**
     * @notice Swaps exact tokens for tokens while performing safety checks
     * @param amountIn The amount of token to send
     * @param amountOutMin The min amount of token to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountIn);

        amountOut = _swapExactTokensForTokens(amountIn, pairs, path.versions, path.tokenPath, to);

        if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
    }

    /**
     * @notice Swaps exact tokens for NATIVE while performing safety checks
     * @param amountIn The amount of token to send
     * @param amountOutMinNATIVE The min amount of NATIVE to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactTokensForNATIVE(
        uint256 amountIn,
        uint256 amountOutMinNATIVE,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
        if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
            revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
        }

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountIn);

        amountOut = _swapExactTokensForTokens(amountIn, pairs, path.versions, path.tokenPath, address(this));

        if (amountOutMinNATIVE > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMinNATIVE, amountOut);

        _wnative.withdraw(amountOut);
        _safeTransferNATIVE(to, amountOut);
    }

    /**
     * @notice Swaps exact NATIVE for tokens while performing safety checks
     * @param amountOutMin The min amount of token to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactNATIVEForTokens(uint256 amountOutMin, Path memory path, address to, uint256 deadline)
        external
        payable
        override
        ensure(deadline)
        verifyPathValidity(path)
        returns (uint256 amountOut)
    {
        if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        _wnativeDepositAndTransfer(pairs[0], msg.value);

        amountOut = _swapExactTokensForTokens(msg.value, pairs, path.versions, path.tokenPath, to);

        if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
    }

    /**
     * @notice Swaps tokens for exact tokens while performing safety checks
     * @param amountOut The amount of token to receive
     * @param amountInMax The max amount of token to send
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountsIn Input amounts of the swap
     */
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        Path memory path,
        address to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256[] memory amountsIn) {
        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        {
            amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountOut);

            if (amountsIn[0] > amountInMax) revert LBRouter__MaxAmountInExceeded(amountInMax, amountsIn[0]);

            path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountsIn[0]);

            uint256 _amountOutReal = _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, to);

            if (_amountOutReal < amountOut) revert LBRouter__InsufficientAmountOut(amountOut, _amountOutReal);
        }
    }

    /**
     * @notice Swaps tokens for exact NATIVE while performing safety checks
     * @param amountNATIVEOut The amount of NATIVE to receive
     * @param amountInMax The max amount of token to send
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountsIn path amounts for every step of the swap
     */
    function swapTokensForExactNATIVE(
        uint256 amountNATIVEOut,
        uint256 amountInMax,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256[] memory amountsIn) {
        if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
            revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
        }

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
        amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountNATIVEOut);

        if (amountsIn[0] > amountInMax) revert LBRouter__MaxAmountInExceeded(amountInMax, amountsIn[0]);

        path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountsIn[0]);

        uint256 _amountOutReal =
            _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, address(this));

        if (_amountOutReal < amountNATIVEOut) revert LBRouter__InsufficientAmountOut(amountNATIVEOut, _amountOutReal);

        _wnative.withdraw(_amountOutReal);
        _safeTransferNATIVE(to, _amountOutReal);
    }

    /**
     * @notice Swaps NATIVE for exact tokens while performing safety checks
     * @dev Will refund any NATIVE amount sent in excess to `msg.sender`
     * @param amountOut The amount of tokens to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountsIn path amounts for every step of the swap
     */
    function swapNATIVEForExactTokens(uint256 amountOut, Path memory path, address to, uint256 deadline)
        external
        payable
        override
        ensure(deadline)
        verifyPathValidity(path)
        returns (uint256[] memory amountsIn)
    {
        if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);
        amountsIn = _getAmountsIn(path.versions, pairs, path.tokenPath, amountOut);

        if (amountsIn[0] > msg.value) revert LBRouter__MaxAmountInExceeded(msg.value, amountsIn[0]);

        _wnativeDepositAndTransfer(pairs[0], amountsIn[0]);

        uint256 amountOutReal = _swapTokensForExactTokens(pairs, path.versions, path.tokenPath, amountsIn, to);

        if (amountOutReal < amountOut) revert LBRouter__InsufficientAmountOut(amountOut, amountOutReal);

        if (msg.value > amountsIn[0]) _safeTransferNATIVE(msg.sender, msg.value - amountsIn[0]);
    }

    /**
     * @notice Swaps exact tokens for tokens while performing safety checks supporting for fee on transfer tokens
     * @param amountIn The amount of token to send
     * @param amountOutMin The min amount of token to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        IERC20 targetToken = path.tokenPath[pairs.length];

        uint256 balanceBefore = targetToken.balanceOf(to);

        path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountIn);

        _swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, to);

        amountOut = targetToken.balanceOf(to) - balanceBefore;
        if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
    }

    /**
     * @notice Swaps exact tokens for NATIVE while performing safety checks supporting for fee on transfer tokens
     * @param amountIn The amount of token to send
     * @param amountOutMinNATIVE The min amount of NATIVE to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactTokensForNATIVESupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMinNATIVE,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
        if (path.tokenPath[path.pairBinSteps.length] != IERC20(_wnative)) {
            revert LBRouter__InvalidTokenPath(address(path.tokenPath[path.pairBinSteps.length]));
        }

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        uint256 balanceBefore = _wnative.balanceOf(address(this));

        path.tokenPath[0].safeTransferFrom(msg.sender, pairs[0], amountIn);

        _swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, address(this));

        amountOut = _wnative.balanceOf(address(this)) - balanceBefore;
        if (amountOutMinNATIVE > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMinNATIVE, amountOut);

        _wnative.withdraw(amountOut);
        _safeTransferNATIVE(to, amountOut);
    }

    /**
     * @notice Swaps exact NATIVE for tokens while performing safety checks supporting for fee on transfer tokens
     * @param amountOutMin The min amount of token to receive
     * @param path The path of the swap
     * @param to The address of the recipient
     * @param deadline The deadline of the tx
     * @return amountOut Output amount of the swap
     */
    function swapExactNATIVEForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external payable override ensure(deadline) verifyPathValidity(path) returns (uint256 amountOut) {
        if (path.tokenPath[0] != IERC20(_wnative)) revert LBRouter__InvalidTokenPath(address(path.tokenPath[0]));

        address[] memory pairs = _getPairs(path.pairBinSteps, path.versions, path.tokenPath);

        IERC20 targetToken = path.tokenPath[pairs.length];

        uint256 balanceBefore = targetToken.balanceOf(to);

        _wnativeDepositAndTransfer(pairs[0], msg.value);

        _swapSupportingFeeOnTransferTokens(pairs, path.versions, path.tokenPath, to);

        amountOut = targetToken.balanceOf(to) - balanceBefore;
        if (amountOutMin > amountOut) revert LBRouter__InsufficientAmountOut(amountOutMin, amountOut);
    }

    /**
     * @notice Unstuck tokens that are sent to this contract by mistake
     * @dev Only callable by the factory owner
     * @param token The address of the token
     * @param to The address of the user to send back the tokens
     * @param amount The amount to send
     */
    function sweep(IERC20 token, address to, uint256 amount) external override onlyFactoryOwner {
        if (address(token) == address(0)) {
            if (amount == type(uint256).max) amount = address(this).balance;
            _safeTransferNATIVE(to, amount);
        } else {
            if (amount == type(uint256).max) amount = token.balanceOf(address(this));
            token.safeTransfer(to, amount);
        }
    }

    /**
     * @notice Unstuck LBTokens that are sent to this contract by mistake
     * @dev Only callable by the factory owner
     * @param lbToken The address of the LBToken
     * @param to The address of the user to send back the tokens
     * @param ids The list of token ids
     * @param amounts The list of amounts to send
     */
    function sweepLBToken(ILBToken lbToken, address to, uint256[] calldata ids, uint256[] calldata amounts)
        external
        override
        onlyFactoryOwner
    {
        lbToken.batchTransferFrom(address(this), to, ids, amounts);
    }

    /**
     * @notice Helper function to add liquidity
     * @param liq The liquidity parameter
     * @param pair LBPair where liquidity is deposited
     * @return amountXAdded Amount of token X added
     * @return amountYAdded Amount of token Y added
     * @return amountXLeft Amount of token X left
     * @return amountYLeft Amount of token Y left
     * @return depositIds The list of deposit ids
     * @return liquidityMinted The list of liquidity minted
     */
    function _addLiquidity(LiquidityParameters calldata liq, ILBPair pair)
        private
        ensure(liq.deadline)
        returns (
            uint256 amountXAdded,
            uint256 amountYAdded,
            uint256 amountXLeft,
            uint256 amountYLeft,
            uint256[] memory depositIds,
            uint256[] memory liquidityMinted
        )
    {
        unchecked {
            if (liq.deltaIds.length != liq.distributionX.length || liq.deltaIds.length != liq.distributionY.length) {
                revert LBRouter__LengthsMismatch();
            }

            if (liq.activeIdDesired > type(uint24).max || liq.idSlippage > type(uint24).max) {
                revert LBRouter__IdDesiredOverflows(liq.activeIdDesired, liq.idSlippage);
            }

            bytes32[] memory liquidityConfigs = new bytes32[](liq.deltaIds.length);
            depositIds = new uint256[](liq.deltaIds.length);
            {
                uint256 _activeId = pair.getActiveId();
                if (
                    liq.activeIdDesired + liq.idSlippage < _activeId || _activeId + liq.idSlippage < liq.activeIdDesired
                ) {
                    revert LBRouter__IdSlippageCaught(liq.activeIdDesired, liq.idSlippage, _activeId);
                }

                for (uint256 i; i < liquidityConfigs.length; ++i) {
                    int256 _id = int256(_activeId) + liq.deltaIds[i];

                    if (_id < 0 || uint256(_id) > type(uint24).max) revert LBRouter__IdOverflows(_id);
                    depositIds[i] = uint256(_id);
                    liquidityConfigs[i] = LiquidityConfigurations.encodeParams(
                        uint64(liq.distributionX[i]), uint64(liq.distributionY[i]), uint24(uint256(_id))
                    );
                }
            }

            bytes32 amountsReceived;
            bytes32 amountsLeft;
            (amountsReceived, amountsLeft, liquidityMinted) = pair.mint(liq.to, liquidityConfigs, liq.refundTo);

            amountXAdded = amountsReceived.decodeX();
            amountYAdded = amountsReceived.decodeY();

            if (amountXAdded < liq.amountXMin || amountYAdded < liq.amountYMin) {
                revert LBRouter__AmountSlippageCaught(liq.amountXMin, amountXAdded, liq.amountYMin, amountYAdded);
            }

            amountXLeft = amountsLeft.decodeX();
            amountYLeft = amountsLeft.decodeY();
        }
    }

    /**
     * @notice Helper function to return the amounts in
     * @param versions The list of versions (V1, V2 or V2_1)
     * @param pairs The list of pairs
     * @param tokenPath The swap path
     * @param amountOut The amount out
     * @return amountsIn The list of amounts in
     */
    function _getAmountsIn(
        Version[] memory versions,
        address[] memory pairs,
        IERC20[] memory tokenPath,
        uint256 amountOut
    ) private view returns (uint256[] memory amountsIn) {
        amountsIn = new uint256[](tokenPath.length);
        // Avoid doing -1, as `pairs.length == pairBinSteps.length-1`
        amountsIn[pairs.length] = amountOut;

        for (uint256 i = pairs.length; i != 0; i--) {
            IERC20 token = tokenPath[i - 1];
            Version version = versions[i - 1];
            address pair = pairs[i - 1];

            if (version == Version.V1) {
                (uint256 reserveIn, uint256 reserveOut,) = IJoePair(pair).getReserves();
                if (token > tokenPath[i]) {
                    (reserveIn, reserveOut) = (reserveOut, reserveIn);
                }

                uint256 amountOut_ = amountsIn[i];
                amountsIn[i - 1] = uint128(amountOut_.getAmountIn(reserveIn, reserveOut));
            } else if (version == Version.V2) {
                (amountsIn[i - 1],) = _legacyRouter.getSwapIn(
                    ILBLegacyPair(pair), uint128(amountsIn[i]), ILBLegacyPair(pair).tokenX() == token
                );
            } else {
                (amountsIn[i - 1],,) =
                    getSwapIn(ILBPair(pair), uint128(amountsIn[i]), ILBPair(pair).getTokenX() == token);
            }
        }
    }

    /**
     * @notice Helper function to remove liquidity
     * @param pair The address of the LBPair
     * @param amountXMin The min amount to receive of token X
     * @param amountYMin The min amount to receive of token Y
     * @param ids The list of ids to burn
     * @param amounts The list of amounts to burn of each id in `_ids`
     * @param to The address of the recipient
     * @return amountX The amount of token X sent by the pair
     * @return amountY The amount of token Y sent by the pair
     */
    function _removeLiquidity(
        ILBPair pair,
        uint256 amountXMin,
        uint256 amountYMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address to
    ) private returns (uint256 amountX, uint256 amountY) {
        (bytes32[] memory amountsBurned) = pair.burn(msg.sender, to, ids, amounts);

        for (uint256 i; i < amountsBurned.length; ++i) {
            amountX += amountsBurned[i].decodeX();
            amountY += amountsBurned[i].decodeY();
        }

        if (amountX < amountXMin || amountY < amountYMin) {
            revert LBRouter__AmountSlippageCaught(amountXMin, amountX, amountYMin, amountY);
        }
    }

    /**
     * @notice Helper function to swap exact tokens for tokens
     * @param amountIn The amount of token sent
     * @param pairs The list of pairs
     * @param versions The list of versions (V1, V2 or V2_1)
     * @param tokenPath The swap path using the binSteps following `pairBinSteps`
     * @param to The address of the recipient
     * @return amountOut The amount of token sent to `to`
     */
    function _swapExactTokensForTokens(
        uint256 amountIn,
        address[] memory pairs,
        Version[] memory versions,
        IERC20[] memory tokenPath,
        address to
    ) private returns (uint256 amountOut) {
        IERC20 token;
        Version version;
        address recipient;
        address pair;

        IERC20 tokenNext = tokenPath[0];
        amountOut = amountIn;

        unchecked {
            for (uint256 i; i < pairs.length; ++i) {
                pair = pairs[i];
                version = versions[i];

                token = tokenNext;
                tokenNext = tokenPath[i + 1];

                recipient = i + 1 == pairs.length ? to : pairs[i + 1];

                if (version == Version.V1) {
                    (uint256 reserve0, uint256 reserve1,) = IJoePair(pair).getReserves();

                    if (token < tokenNext) {
                        amountOut = amountOut.getAmountOut(reserve0, reserve1);
                        IJoePair(pair).swap(0, amountOut, recipient, "");
                    } else {
                        amountOut = amountOut.getAmountOut(reserve1, reserve0);
                        IJoePair(pair).swap(amountOut, 0, recipient, "");
                    }
                } else if (version == Version.V2) {
                    bool swapForY = tokenNext == ILBLegacyPair(pair).tokenY();

                    (uint256 amountXOut, uint256 amountYOut) = ILBLegacyPair(pair).swap(swapForY, recipient);

                    if (swapForY) amountOut = amountYOut;
                    else amountOut = amountXOut;
                } else {
                    bool swapForY = tokenNext == ILBPair(pair).getTokenY();

                    (uint256 amountXOut, uint256 amountYOut) = ILBPair(pair).swap(swapForY, recipient).decode();

                    if (swapForY) amountOut = amountYOut;
                    else amountOut = amountXOut;
                }
            }
        }
    }

    /**
     * @notice Helper function to swap tokens for exact tokens
     * @param pairs The array of pairs
     * @param versions The list of versions (V1, V2 or V2_1)
     * @param tokenPath The swap path using the binSteps following `pairBinSteps`
     * @param amountsIn The list of amounts in
     * @param to The address of the recipient
     * @return amountOut The amount of token sent to `to`
     */
    function _swapTokensForExactTokens(
        address[] memory pairs,
        Version[] memory versions,
        IERC20[] memory tokenPath,
        uint256[] memory amountsIn,
        address to
    ) private returns (uint256 amountOut) {
        IERC20 token;
        address recipient;
        address pair;
        Version version;

        IERC20 tokenNext = tokenPath[0];

        unchecked {
            for (uint256 i; i < pairs.length; ++i) {
                pair = pairs[i];
                version = versions[i];

                token = tokenNext;
                tokenNext = tokenPath[i + 1];

                recipient = i + 1 == pairs.length ? to : pairs[i + 1];

                if (version == Version.V1) {
                    amountOut = amountsIn[i + 1];
                    if (token < tokenNext) {
                        IJoePair(pair).swap(0, amountOut, recipient, "");
                    } else {
                        IJoePair(pair).swap(amountOut, 0, recipient, "");
                    }
                } else if (version == Version.V2) {
                    bool swapForY = tokenNext == ILBLegacyPair(pair).tokenY();

                    (uint256 amountXOut, uint256 amountYOut) = ILBLegacyPair(pair).swap(swapForY, recipient);

                    if (swapForY) amountOut = amountYOut;
                    else amountOut = amountXOut;
                } else {
                    bool swapForY = tokenNext == ILBPair(pair).getTokenY();

                    (uint256 amountXOut, uint256 amountYOut) = ILBPair(pair).swap(swapForY, recipient).decode();

                    if (swapForY) amountOut = amountYOut;
                    else amountOut = amountXOut;
                }
            }
        }
    }

    /**
     * @notice Helper function to swap exact tokens supporting for fee on transfer tokens
     * @param pairs The list of pairs
     * @param versions The list of versions (V1, V2 or V2_1)
     * @param tokenPath The swap path using the binSteps following `pairBinSteps`
     * @param to The address of the recipient
     */
    function _swapSupportingFeeOnTransferTokens(
        address[] memory pairs,
        Version[] memory versions,
        IERC20[] memory tokenPath,
        address to
    ) private {
        IERC20 token;
        Version version;
        address recipient;
        address pair;

        IERC20 tokenNext = tokenPath[0];

        unchecked {
            for (uint256 i; i < pairs.length; ++i) {
                pair = pairs[i];
                version = versions[i];

                token = tokenNext;
                tokenNext = tokenPath[i + 1];

                recipient = i + 1 == pairs.length ? to : pairs[i + 1];

                if (version == Version.V1) {
                    (uint256 _reserve0, uint256 _reserve1,) = IJoePair(pair).getReserves();
                    if (token < tokenNext) {
                        uint256 amountIn = token.balanceOf(pair) - _reserve0;
                        uint256 amountOut = amountIn.getAmountOut(_reserve0, _reserve1);

                        IJoePair(pair).swap(0, amountOut, recipient, "");
                    } else {
                        uint256 amountIn = token.balanceOf(pair) - _reserve1;
                        uint256 amountOut = amountIn.getAmountOut(_reserve1, _reserve0);

                        IJoePair(pair).swap(amountOut, 0, recipient, "");
                    }
                } else if (version == Version.V2) {
                    ILBLegacyPair(pair).swap(tokenNext == ILBLegacyPair(pair).tokenY(), recipient);
                } else {
                    ILBPair(pair).swap(tokenNext == ILBPair(pair).getTokenY(), recipient);
                }
            }
        }
    }

    /**
     * @notice Helper function to return the address of the LBPair
     * @dev Revert if the pair is not created yet
     * @param tokenX The address of the tokenX
     * @param tokenY The address of the tokenY
     * @param binStep The bin step of the LBPair
     * @param version The version of the LBPair
     * @return lbPair The address of the LBPair
     */
    function _getLBPairInformation(IERC20 tokenX, IERC20 tokenY, uint256 binStep, Version version)
        private
        view
        returns (address lbPair)
    {
        if (version == Version.V2) {
            lbPair = address(_legacyFactory.getLBPairInformation(tokenX, tokenY, binStep).LBPair);
        } else {
            lbPair = address(_factory.getLBPairInformation(tokenX, tokenY, binStep).LBPair);
        }

        if (lbPair == address(0)) {
            revert LBRouter__PairNotCreated(address(tokenX), address(tokenY), binStep);
        }
    }

    /**
     * @notice Helper function to return the address of the pair (v1 or v2, according to `binStep`)
     * @dev Revert if the pair is not created yet
     * @param tokenX The address of the tokenX
     * @param tokenY The address of the tokenY
     * @param binStep The bin step of the LBPair
     * @param version The version of the LBPair
     * @return pair The address of the pair of binStep `binStep`
     */
    function _getPair(IERC20 tokenX, IERC20 tokenY, uint256 binStep, Version version)
        private
        view
        returns (address pair)
    {
        if (version == Version.V1) {
            pair = _factoryV1.getPair(address(tokenX), address(tokenY));
            if (pair == address(0)) revert LBRouter__PairNotCreated(address(tokenX), address(tokenY), binStep);
        } else {
            pair = address(_getLBPairInformation(tokenX, tokenY, binStep, version));
        }
    }

    /**
     * @notice Helper function to return a list of pairs
     * @param pairBinSteps The list of bin steps
     * @param versions The list of versions (V1, V2 or V2_1)
     * @param tokenPath The swap path using the binSteps following `pairBinSteps`
     * @return pairs The list of pairs
     */
    function _getPairs(uint256[] memory pairBinSteps, Version[] memory versions, IERC20[] memory tokenPath)
        private
        view
        returns (address[] memory pairs)
    {
        pairs = new address[](pairBinSteps.length);

        IERC20 token;
        IERC20 tokenNext = tokenPath[0];
        unchecked {
            for (uint256 i; i < pairs.length; ++i) {
                token = tokenNext;
                tokenNext = tokenPath[i + 1];

                pairs[i] = _getPair(token, tokenNext, pairBinSteps[i], versions[i]);
            }
        }
    }

    /**
     * @notice Helper function to transfer NATIVE
     * @param to The address of the recipient
     * @param amount The NATIVE amount to send
     */
    function _safeTransferNATIVE(address to, uint256 amount) private {
        (bool success,) = to.call{value: amount}("");
        if (!success) revert LBRouter__FailedToSendNATIVE(to, amount);
    }

    /**
     * @notice Helper function to deposit and transfer _wnative
     * @param to The address of the recipient
     * @param amount The NATIVE amount to wrap
     */
    function _wnativeDepositAndTransfer(address to, uint256 amount) private {
        _wnative.deposit{value: amount}();
        _wnative.safeTransfer(to, amount);
    }
}

File 2 of 31 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

File 3 of 31 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 4 of 31 : IJoeFactory.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/// @title Joe V1 Factory Interface
/// @notice Interface to interact with Joe V1 Factory
interface IJoeFactory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint256);

    function feeTo() external view returns (address);

    function feeToSetter() external view returns (address);

    function migrator() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);

    function allPairs(uint256) external view returns (address pair);

    function allPairsLength() external view returns (uint256);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;

    function setFeeToSetter(address) external;

    function setMigrator(address) external;
}

File 5 of 31 : IJoePair.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/// @title Joe V1 Pair Interface
/// @notice Interface to interact with Joe V1 Pairs
interface IJoePair {
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Transfer(address indexed from, address indexed to, uint256 value);

    function name() external pure returns (string memory);

    function symbol() external pure returns (string memory);

    function decimals() external pure returns (uint8);

    function totalSupply() external view returns (uint256);

    function balanceOf(address owner) external view returns (uint256);

    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 value) external returns (bool);

    function transfer(address to, uint256 value) external returns (bool);

    function transferFrom(address from, address to, uint256 value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function PERMIT_TYPEHASH() external pure returns (bytes32);

    function nonces(address owner) external view returns (uint256);

    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    event Mint(address indexed sender, uint256 amount0, uint256 amount1);
    event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint256 amount0In,
        uint256 amount1In,
        uint256 amount0Out,
        uint256 amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint256);

    function factory() external view returns (address);

    function token0() external view returns (address);

    function token1() external view returns (address);

    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);

    function price0CumulativeLast() external view returns (uint256);

    function price1CumulativeLast() external view returns (uint256);

    function kLast() external view returns (uint256);

    function mint(address to) external returns (uint256 liquidity);

    function burn(address to) external returns (uint256 amount0, uint256 amount1);

    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;

    function skim(address to) external;

    function sync() external;

    function initialize(address, address) external;
}

File 6 of 31 : ILBFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {ILBPair} from "./ILBPair.sol";
import {IPendingOwnable} from "./IPendingOwnable.sol";

/**
 * @title Liquidity Book Factory Interface
 * @author Trader Joe
 * @notice Required interface of LBFactory contract
 */
interface ILBFactory is IPendingOwnable {
    error LBFactory__IdenticalAddresses(IERC20 token);
    error LBFactory__QuoteAssetNotWhitelisted(IERC20 quoteAsset);
    error LBFactory__QuoteAssetAlreadyWhitelisted(IERC20 quoteAsset);
    error LBFactory__AddressZero();
    error LBFactory__LBPairAlreadyExists(IERC20 tokenX, IERC20 tokenY, uint256 _binStep);
    error LBFactory__LBPairDoesNotExist(IERC20 tokenX, IERC20 tokenY, uint256 binStep);
    error LBFactory__LBPairNotCreated(IERC20 tokenX, IERC20 tokenY, uint256 binStep);
    error LBFactory__FlashLoanFeeAboveMax(uint256 fees, uint256 maxFees);
    error LBFactory__BinStepTooLow(uint256 binStep);
    error LBFactory__PresetIsLockedForUsers(address user, uint256 binStep);
    error LBFactory__LBPairIgnoredIsAlreadyInTheSameState();
    error LBFactory__BinStepHasNoPreset(uint256 binStep);
    error LBFactory__PresetOpenStateIsAlreadyInTheSameState();
    error LBFactory__SameFeeRecipient(address feeRecipient);
    error LBFactory__SameFlashLoanFee(uint256 flashLoanFee);
    error LBFactory__LBPairSafetyCheckFailed(address LBPairImplementation);
    error LBFactory__SameImplementation(address LBPairImplementation);
    error LBFactory__ImplementationNotSet();

    /**
     * @dev Structure to store the LBPair information, such as:
     * binStep: The bin step of the LBPair
     * LBPair: The address of the LBPair
     * createdByOwner: Whether the pair was created by the owner of the factory
     * ignoredForRouting: Whether the pair is ignored for routing or not. An ignored pair will not be explored during routes finding
     */
    struct LBPairInformation {
        uint16 binStep;
        ILBPair LBPair;
        bool createdByOwner;
        bool ignoredForRouting;
    }

    event LBPairCreated(
        IERC20 indexed tokenX, IERC20 indexed tokenY, uint256 indexed binStep, ILBPair LBPair, uint256 pid
    );

    event FeeRecipientSet(address oldRecipient, address newRecipient);

    event FlashLoanFeeSet(uint256 oldFlashLoanFee, uint256 newFlashLoanFee);

    event LBPairImplementationSet(address oldLBPairImplementation, address LBPairImplementation);

    event LBPairIgnoredStateChanged(ILBPair indexed LBPair, bool ignored);

    event PresetSet(
        uint256 indexed binStep,
        uint256 baseFactor,
        uint256 filterPeriod,
        uint256 decayPeriod,
        uint256 reductionFactor,
        uint256 variableFeeControl,
        uint256 protocolShare,
        uint256 maxVolatilityAccumulator
    );

    event PresetOpenStateChanged(uint256 indexed binStep, bool indexed isOpen);

    event PresetRemoved(uint256 indexed binStep);

    event QuoteAssetAdded(IERC20 indexed quoteAsset);

    event QuoteAssetRemoved(IERC20 indexed quoteAsset);

    function getMinBinStep() external pure returns (uint256);

    function getFeeRecipient() external view returns (address);

    function getMaxFlashLoanFee() external pure returns (uint256);

    function getFlashLoanFee() external view returns (uint256);

    function getLBPairImplementation() external view returns (address);

    function getNumberOfLBPairs() external view returns (uint256);

    function getLBPairAtIndex(uint256 id) external returns (ILBPair);

    function getNumberOfQuoteAssets() external view returns (uint256);

    function getQuoteAssetAtIndex(uint256 index) external view returns (IERC20);

    function isQuoteAsset(IERC20 token) external view returns (bool);

    function getLBPairInformation(IERC20 tokenX, IERC20 tokenY, uint256 binStep)
        external
        view
        returns (LBPairInformation memory);

    function getPreset(uint256 binStep)
        external
        view
        returns (
            uint256 baseFactor,
            uint256 filterPeriod,
            uint256 decayPeriod,
            uint256 reductionFactor,
            uint256 variableFeeControl,
            uint256 protocolShare,
            uint256 maxAccumulator,
            bool isOpen
        );

    function getAllBinSteps() external view returns (uint256[] memory presetsBinStep);

    function getOpenBinSteps() external view returns (uint256[] memory openBinStep);

    function getAllLBPairs(IERC20 tokenX, IERC20 tokenY)
        external
        view
        returns (LBPairInformation[] memory LBPairsBinStep);

    function setLBPairImplementation(address lbPairImplementation) external;

    function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
        external
        returns (ILBPair pair);

    function setLBPairIgnored(IERC20 tokenX, IERC20 tokenY, uint16 binStep, bool ignored) external;

    function setPreset(
        uint16 binStep,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator,
        bool isOpen
    ) external;

    function setPresetOpenState(uint16 binStep, bool isOpen) external;

    function removePreset(uint16 binStep) external;

    function setFeesParametersOnPair(
        IERC20 tokenX,
        IERC20 tokenY,
        uint16 binStep,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator
    ) external;

    function setFeeRecipient(address feeRecipient) external;

    function setFlashLoanFee(uint256 flashLoanFee) external;

    function addQuoteAsset(IERC20 quoteAsset) external;

    function removeQuoteAsset(IERC20 quoteAsset) external;

    function forceDecay(ILBPair lbPair) external;
}

File 7 of 31 : ILBFlashLoanCallback.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

/// @title Liquidity Book Flashloan Callback Interface
/// @author Trader Joe
/// @notice Required interface to interact with LB flash loans
interface ILBFlashLoanCallback {
    function LBFlashLoanCallback(
        address sender,
        IERC20 tokenX,
        IERC20 tokenY,
        bytes32 amounts,
        bytes32 totalFees,
        bytes calldata data
    ) external returns (bytes32);
}

File 8 of 31 : ILBLegacyFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {ILBLegacyPair} from "./ILBLegacyPair.sol";
import {IPendingOwnable} from "./IPendingOwnable.sol";

/// @title Liquidity Book Factory Interface
/// @author Trader Joe
/// @notice Required interface of LBFactory contract
interface ILBLegacyFactory is IPendingOwnable {
    /// @dev Structure to store the LBPair information, such as:
    /// - binStep: The bin step of the LBPair
    /// - LBPair: The address of the LBPair
    /// - createdByOwner: Whether the pair was created by the owner of the factory
    /// - ignoredForRouting: Whether the pair is ignored for routing or not. An ignored pair will not be explored during routes finding
    struct LBPairInformation {
        uint16 binStep;
        ILBLegacyPair LBPair;
        bool createdByOwner;
        bool ignoredForRouting;
    }

    event LBPairCreated(
        IERC20 indexed tokenX, IERC20 indexed tokenY, uint256 indexed binStep, ILBLegacyPair LBPair, uint256 pid
    );

    event FeeRecipientSet(address oldRecipient, address newRecipient);

    event FlashLoanFeeSet(uint256 oldFlashLoanFee, uint256 newFlashLoanFee);

    event FeeParametersSet(
        address indexed sender,
        ILBLegacyPair indexed LBPair,
        uint256 binStep,
        uint256 baseFactor,
        uint256 filterPeriod,
        uint256 decayPeriod,
        uint256 reductionFactor,
        uint256 variableFeeControl,
        uint256 protocolShare,
        uint256 maxVolatilityAccumulator
    );

    event FactoryLockedStatusUpdated(bool unlocked);

    event LBPairImplementationSet(address oldLBPairImplementation, address LBPairImplementation);

    event LBPairIgnoredStateChanged(ILBLegacyPair indexed LBPair, bool ignored);

    event PresetSet(
        uint256 indexed binStep,
        uint256 baseFactor,
        uint256 filterPeriod,
        uint256 decayPeriod,
        uint256 reductionFactor,
        uint256 variableFeeControl,
        uint256 protocolShare,
        uint256 maxVolatilityAccumulator,
        uint256 sampleLifetime
    );

    event PresetRemoved(uint256 indexed binStep);

    event QuoteAssetAdded(IERC20 indexed quoteAsset);

    event QuoteAssetRemoved(IERC20 indexed quoteAsset);

    function MAX_FEE() external pure returns (uint256);

    function MIN_BIN_STEP() external pure returns (uint256);

    function MAX_BIN_STEP() external pure returns (uint256);

    function MAX_PROTOCOL_SHARE() external pure returns (uint256);

    function LBPairImplementation() external view returns (address);

    function getNumberOfQuoteAssets() external view returns (uint256);

    function getQuoteAsset(uint256 index) external view returns (IERC20);

    function isQuoteAsset(IERC20 token) external view returns (bool);

    function feeRecipient() external view returns (address);

    function flashLoanFee() external view returns (uint256);

    function creationUnlocked() external view returns (bool);

    function allLBPairs(uint256 id) external returns (ILBLegacyPair);

    function getNumberOfLBPairs() external view returns (uint256);

    function getLBPairInformation(IERC20 tokenX, IERC20 tokenY, uint256 binStep)
        external
        view
        returns (LBPairInformation memory);

    function getPreset(uint16 binStep)
        external
        view
        returns (
            uint256 baseFactor,
            uint256 filterPeriod,
            uint256 decayPeriod,
            uint256 reductionFactor,
            uint256 variableFeeControl,
            uint256 protocolShare,
            uint256 maxAccumulator,
            uint256 sampleLifetime
        );

    function getAllBinSteps() external view returns (uint256[] memory presetsBinStep);

    function getAllLBPairs(IERC20 tokenX, IERC20 tokenY)
        external
        view
        returns (LBPairInformation[] memory LBPairsBinStep);

    function setLBPairImplementation(address LBPairImplementation) external;

    function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
        external
        returns (ILBLegacyPair pair);

    function setLBPairIgnored(IERC20 tokenX, IERC20 tokenY, uint256 binStep, bool ignored) external;

    function setPreset(
        uint16 binStep,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator,
        uint16 sampleLifetime
    ) external;

    function removePreset(uint16 binStep) external;

    function setFeesParametersOnPair(
        IERC20 tokenX,
        IERC20 tokenY,
        uint16 binStep,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator
    ) external;

    function setFeeRecipient(address feeRecipient) external;

    function setFlashLoanFee(uint256 flashLoanFee) external;

    function setFactoryLockedState(bool locked) external;

    function addQuoteAsset(IERC20 quoteAsset) external;

    function removeQuoteAsset(IERC20 quoteAsset) external;

    function forceDecay(ILBLegacyPair LBPair) external;
}

File 9 of 31 : ILBLegacyPair.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {ILBLegacyToken} from "./ILBLegacyToken.sol";

/// @title Liquidity Book Pair V2 Interface
/// @author Trader Joe
/// @notice Required interface of LBPair contract
interface ILBLegacyPair is ILBLegacyToken {
    /// @dev Structure to store the protocol fees:
    /// - binStep: The bin step
    /// - baseFactor: The base factor
    /// - filterPeriod: The filter period, where the fees stays constant
    /// - decayPeriod: The decay period, where the fees are halved
    /// - reductionFactor: The reduction factor, used to calculate the reduction of the accumulator
    /// - variableFeeControl: The variable fee control, used to control the variable fee, can be 0 to disable them
    /// - protocolShare: The share of fees sent to protocol
    /// - maxVolatilityAccumulated: The max value of volatility accumulated
    /// - volatilityAccumulated: The value of volatility accumulated
    /// - volatilityReference: The value of volatility reference
    /// - indexRef: The index reference
    /// - time: The last time the accumulator was called
    struct FeeParameters {
        // 144 lowest bits in slot
        uint16 binStep;
        uint16 baseFactor;
        uint16 filterPeriod;
        uint16 decayPeriod;
        uint16 reductionFactor;
        uint24 variableFeeControl;
        uint16 protocolShare;
        uint24 maxVolatilityAccumulated;
        // 112 highest bits in slot
        uint24 volatilityAccumulated;
        uint24 volatilityReference;
        uint24 indexRef;
        uint40 time;
    }

    /// @dev Structure used during swaps to distributes the fees:
    /// - total: The total amount of fees
    /// - protocol: The amount of fees reserved for protocol
    struct FeesDistribution {
        uint128 total;
        uint128 protocol;
    }

    /// @dev Structure to store the reserves of bins:
    /// - reserveX: The current reserve of tokenX of the bin
    /// - reserveY: The current reserve of tokenY of the bin
    struct Bin {
        uint112 reserveX;
        uint112 reserveY;
        uint256 accTokenXPerShare;
        uint256 accTokenYPerShare;
    }

    /// @dev Structure to store the information of the pair such as:
    /// slot0:
    /// - activeId: The current id used for swaps, this is also linked with the price
    /// - reserveX: The sum of amounts of tokenX across all bins
    /// slot1:
    /// - reserveY: The sum of amounts of tokenY across all bins
    /// - oracleSampleLifetime: The lifetime of an oracle sample
    /// - oracleSize: The current size of the oracle, can be increase by users
    /// - oracleActiveSize: The current active size of the oracle, composed only from non empty data sample
    /// - oracleLastTimestamp: The current last timestamp at which a sample was added to the circular buffer
    /// - oracleId: The current id of the oracle
    /// slot2:
    /// - feesX: The current amount of fees to distribute in tokenX (total, protocol)
    /// slot3:
    /// - feesY: The current amount of fees to distribute in tokenY (total, protocol)
    struct PairInformation {
        uint24 activeId;
        uint136 reserveX;
        uint136 reserveY;
        uint16 oracleSampleLifetime;
        uint16 oracleSize;
        uint16 oracleActiveSize;
        uint40 oracleLastTimestamp;
        uint16 oracleId;
        FeesDistribution feesX;
        FeesDistribution feesY;
    }

    /// @dev Structure to store the debts of users
    /// - debtX: The tokenX's debt
    /// - debtY: The tokenY's debt
    struct Debts {
        uint256 debtX;
        uint256 debtY;
    }

    /// @dev Structure to store fees:
    /// - tokenX: The amount of fees of token X
    /// - tokenY: The amount of fees of token Y
    struct Fees {
        uint128 tokenX;
        uint128 tokenY;
    }

    /// @dev Structure to minting informations:
    /// - amountXIn: The amount of token X sent
    /// - amountYIn: The amount of token Y sent
    /// - amountXAddedToPair: The amount of token X that have been actually added to the pair
    /// - amountYAddedToPair: The amount of token Y that have been actually added to the pair
    /// - activeFeeX: Fees X currently generated
    /// - activeFeeY: Fees Y currently generated
    /// - totalDistributionX: Total distribution of token X. Should be 1e18 (100%) or 0 (0%)
    /// - totalDistributionY: Total distribution of token Y. Should be 1e18 (100%) or 0 (0%)
    /// - id: Id of the current working bin when looping on the distribution array
    /// - amountX: The amount of token X deposited in the current bin
    /// - amountY: The amount of token Y deposited in the current bin
    /// - distributionX: Distribution of token X for the current working bin
    /// - distributionY: Distribution of token Y for the current working bin
    struct MintInfo {
        uint256 amountXIn;
        uint256 amountYIn;
        uint256 amountXAddedToPair;
        uint256 amountYAddedToPair;
        uint256 activeFeeX;
        uint256 activeFeeY;
        uint256 totalDistributionX;
        uint256 totalDistributionY;
        uint256 id;
        uint256 amountX;
        uint256 amountY;
        uint256 distributionX;
        uint256 distributionY;
    }

    event Swap(
        address indexed sender,
        address indexed recipient,
        uint256 indexed id,
        bool swapForY,
        uint256 amountIn,
        uint256 amountOut,
        uint256 volatilityAccumulated,
        uint256 fees
    );

    event FlashLoan(address indexed sender, address indexed receiver, IERC20 token, uint256 amount, uint256 fee);

    event CompositionFee(
        address indexed sender, address indexed recipient, uint256 indexed id, uint256 feesX, uint256 feesY
    );

    event DepositedToBin(
        address indexed sender, address indexed recipient, uint256 indexed id, uint256 amountX, uint256 amountY
    );

    event WithdrawnFromBin(
        address indexed sender, address indexed recipient, uint256 indexed id, uint256 amountX, uint256 amountY
    );

    event FeesCollected(address indexed sender, address indexed recipient, uint256 amountX, uint256 amountY);

    event ProtocolFeesCollected(address indexed sender, address indexed recipient, uint256 amountX, uint256 amountY);

    event OracleSizeIncreased(uint256 previousSize, uint256 newSize);

    function tokenX() external view returns (IERC20);

    function tokenY() external view returns (IERC20);

    function factory() external view returns (address);

    function getReservesAndId() external view returns (uint256 reserveX, uint256 reserveY, uint256 activeId);

    function getGlobalFees()
        external
        view
        returns (uint128 feesXTotal, uint128 feesYTotal, uint128 feesXProtocol, uint128 feesYProtocol);

    function getOracleParameters()
        external
        view
        returns (
            uint256 oracleSampleLifetime,
            uint256 oracleSize,
            uint256 oracleActiveSize,
            uint256 oracleLastTimestamp,
            uint256 oracleId,
            uint256 min,
            uint256 max
        );

    function getOracleSampleFrom(uint256 timeDelta)
        external
        view
        returns (uint256 cumulativeId, uint256 cumulativeAccumulator, uint256 cumulativeBinCrossed);

    function feeParameters() external view returns (FeeParameters memory);

    function findFirstNonEmptyBinId(uint24 id_, bool sentTokenY) external view returns (uint24 id);

    function getBin(uint24 id) external view returns (uint256 reserveX, uint256 reserveY);

    function pendingFees(address account, uint256[] memory ids)
        external
        view
        returns (uint256 amountX, uint256 amountY);

    function swap(bool sentTokenY, address to) external returns (uint256 amountXOut, uint256 amountYOut);

    function flashLoan(address receiver, IERC20 token, uint256 amount, bytes calldata data) external;

    function mint(
        uint256[] calldata ids,
        uint256[] calldata distributionX,
        uint256[] calldata distributionY,
        address to
    ) external returns (uint256 amountXAddedToPair, uint256 amountYAddedToPair, uint256[] memory liquidityMinted);

    function burn(uint256[] calldata ids, uint256[] calldata amounts, address to)
        external
        returns (uint256 amountX, uint256 amountY);

    function increaseOracleLength(uint16 newSize) external;

    function collectFees(address account, uint256[] calldata ids) external returns (uint256 amountX, uint256 amountY);

    function collectProtocolFees() external returns (uint128 amountX, uint128 amountY);

    function setFeesParameters(bytes32 packedFeeParameters) external;

    function forceDecay() external;

    function initialize(
        IERC20 tokenX,
        IERC20 tokenY,
        uint24 activeId,
        uint16 sampleLifetime,
        bytes32 packedFeeParameters
    ) external;
}

File 10 of 31 : ILBLegacyRouter.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {ILBFactory} from "./ILBFactory.sol";
import {IJoeFactory} from "./IJoeFactory.sol";
import {ILBLegacyPair} from "./ILBLegacyPair.sol";
import {ILBToken} from "./ILBToken.sol";
import {IWNATIVE} from "./IWNATIVE.sol";

/// @title Liquidity Book Router Interface
/// @author Trader Joe
/// @notice Required interface of LBRouter contract
interface ILBLegacyRouter {
    struct LiquidityParameters {
        IERC20 tokenX;
        IERC20 tokenY;
        uint256 binStep;
        uint256 amountX;
        uint256 amountY;
        uint256 amountXMin;
        uint256 amountYMin;
        uint256 activeIdDesired;
        uint256 idSlippage;
        int256[] deltaIds;
        uint256[] distributionX;
        uint256[] distributionY;
        address to;
        uint256 deadline;
    }

    function factory() external view returns (address);

    function wavax() external view returns (address);

    function oldFactory() external view returns (address);

    function getIdFromPrice(ILBLegacyPair LBPair, uint256 price) external view returns (uint24);

    function getPriceFromId(ILBLegacyPair LBPair, uint24 id) external view returns (uint256);

    function getSwapIn(ILBLegacyPair lbPair, uint256 amountOut, bool swapForY)
        external
        view
        returns (uint256 amountIn, uint256 feesIn);

    function getSwapOut(ILBLegacyPair lbPair, uint256 amountIn, bool swapForY)
        external
        view
        returns (uint256 amountOut, uint256 feesIn);

    function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
        external
        returns (ILBLegacyPair pair);

    function addLiquidity(LiquidityParameters calldata liquidityParameters)
        external
        returns (uint256[] memory depositIds, uint256[] memory liquidityMinted);

    function addLiquidityAVAX(LiquidityParameters calldata liquidityParameters)
        external
        payable
        returns (uint256[] memory depositIds, uint256[] memory liquidityMinted);

    function removeLiquidity(
        IERC20 tokenX,
        IERC20 tokenY,
        uint16 binStep,
        uint256 amountXMin,
        uint256 amountYMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address to,
        uint256 deadline
    ) external returns (uint256 amountX, uint256 amountY);

    function removeLiquidityAVAX(
        IERC20 token,
        uint16 binStep,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountAVAX);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactTokensForAVAX(
        uint256 amountIn,
        uint256 amountOutMinAVAX,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactAVAXForTokens(
        uint256 amountOutMin,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountOut);

    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amountsIn);

    function swapTokensForExactAVAX(
        uint256 amountOut,
        uint256 amountInMax,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address payable to,
        uint256 deadline
    ) external returns (uint256[] memory amountsIn);

    function swapAVAXForExactTokens(
        uint256 amountOut,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external payable returns (uint256[] memory amountsIn);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactTokensForAVAXSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMinAVAX,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactAVAXForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        uint256[] memory pairBinSteps,
        IERC20[] memory tokenPath,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountOut);

    function sweep(IERC20 token, address to, uint256 amount) external;

    function sweepLBToken(ILBToken _lbToken, address _to, uint256[] calldata _ids, uint256[] calldata _amounts)
        external;
}

File 11 of 31 : ILBLegacyToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import "openzeppelin/utils/introspection/IERC165.sol";

/// @title Liquidity Book V2 Token Interface
/// @author Trader Joe
/// @notice Required interface of LBToken contract
interface ILBLegacyToken is IERC165 {
    event TransferSingle(address indexed sender, address indexed from, address indexed to, uint256 id, uint256 amount);

    event TransferBatch(
        address indexed sender, address indexed from, address indexed to, uint256[] ids, uint256[] amounts
    );

    event ApprovalForAll(address indexed account, address indexed sender, bool approved);

    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function balanceOf(address account, uint256 id) external view returns (uint256);

    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory batchBalances);

    function totalSupply(uint256 id) external view returns (uint256);

    function isApprovedForAll(address owner, address spender) external view returns (bool);

    function setApprovalForAll(address sender, bool approved) external;

    function safeTransferFrom(address from, address to, uint256 id, uint256 amount) external;

    function safeBatchTransferFrom(address from, address to, uint256[] calldata id, uint256[] calldata amount)
        external;
}

File 12 of 31 : ILBPair.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {ILBFactory} from "./ILBFactory.sol";
import {ILBFlashLoanCallback} from "./ILBFlashLoanCallback.sol";
import {ILBToken} from "./ILBToken.sol";

interface ILBPair is ILBToken {
    error LBPair__ZeroBorrowAmount();
    error LBPair__AddressZero();
    error LBPair__AlreadyInitialized();
    error LBPair__EmptyMarketConfigs();
    error LBPair__FlashLoanCallbackFailed();
    error LBPair__FlashLoanInsufficientAmount();
    error LBPair__InsufficientAmountIn();
    error LBPair__InsufficientAmountOut();
    error LBPair__InvalidInput();
    error LBPair__InvalidStaticFeeParameters();
    error LBPair__OnlyFactory();
    error LBPair__OnlyProtocolFeeRecipient();
    error LBPair__OutOfLiquidity();
    error LBPair__TokenNotSupported();
    error LBPair__ZeroAmount(uint24 id);
    error LBPair__ZeroAmountsOut(uint24 id);
    error LBPair__ZeroShares(uint24 id);
    error LBPair__MaxTotalFeeExceeded();

    struct MintArrays {
        uint256[] ids;
        bytes32[] amounts;
        uint256[] liquidityMinted;
    }

    event DepositedToBins(address indexed sender, address indexed to, uint256[] ids, bytes32[] amounts);

    event WithdrawnFromBins(address indexed sender, address indexed to, uint256[] ids, bytes32[] amounts);

    event CompositionFees(address indexed sender, uint24 id, bytes32 totalFees, bytes32 protocolFees);

    event CollectedProtocolFees(address indexed feeRecipient, bytes32 protocolFees);

    event Swap(
        address indexed sender,
        address indexed to,
        uint24 id,
        bytes32 amountsIn,
        bytes32 amountsOut,
        uint24 volatilityAccumulator,
        bytes32 totalFees,
        bytes32 protocolFees
    );

    event StaticFeeParametersSet(
        address indexed sender,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator
    );

    event FlashLoan(
        address indexed sender,
        ILBFlashLoanCallback indexed receiver,
        uint24 activeId,
        bytes32 amounts,
        bytes32 totalFees,
        bytes32 protocolFees
    );

    event OracleLengthIncreased(address indexed sender, uint16 oracleLength);

    event ForcedDecay(address indexed sender, uint24 idReference, uint24 volatilityReference);

    function initialize(
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator,
        uint24 activeId
    ) external;

    function getFactory() external view returns (ILBFactory factory);

    function getTokenX() external view returns (IERC20 tokenX);

    function getTokenY() external view returns (IERC20 tokenY);

    function getBinStep() external view returns (uint16 binStep);

    function getReserves() external view returns (uint128 reserveX, uint128 reserveY);

    function getActiveId() external view returns (uint24 activeId);

    function getBin(uint24 id) external view returns (uint128 binReserveX, uint128 binReserveY);

    function getNextNonEmptyBin(bool swapForY, uint24 id) external view returns (uint24 nextId);

    function getProtocolFees() external view returns (uint128 protocolFeeX, uint128 protocolFeeY);

    function getStaticFeeParameters()
        external
        view
        returns (
            uint16 baseFactor,
            uint16 filterPeriod,
            uint16 decayPeriod,
            uint16 reductionFactor,
            uint24 variableFeeControl,
            uint16 protocolShare,
            uint24 maxVolatilityAccumulator
        );

    function getVariableFeeParameters()
        external
        view
        returns (uint24 volatilityAccumulator, uint24 volatilityReference, uint24 idReference, uint40 timeOfLastUpdate);

    function getOracleParameters()
        external
        view
        returns (uint8 sampleLifetime, uint16 size, uint16 activeSize, uint40 lastUpdated, uint40 firstTimestamp);

    function getOracleSampleAt(uint40 lookupTimestamp)
        external
        view
        returns (uint64 cumulativeId, uint64 cumulativeVolatility, uint64 cumulativeBinCrossed);

    function getPriceFromId(uint24 id) external view returns (uint256 price);

    function getIdFromPrice(uint256 price) external view returns (uint24 id);

    function getSwapIn(uint128 amountOut, bool swapForY)
        external
        view
        returns (uint128 amountIn, uint128 amountOutLeft, uint128 fee);

    function getSwapOut(uint128 amountIn, bool swapForY)
        external
        view
        returns (uint128 amountInLeft, uint128 amountOut, uint128 fee);

    function swap(bool swapForY, address to) external returns (bytes32 amountsOut);

    function flashLoan(ILBFlashLoanCallback receiver, bytes32 amounts, bytes calldata data) external;

    function mint(address to, bytes32[] calldata liquidityConfigs, address refundTo)
        external
        returns (bytes32 amountsReceived, bytes32 amountsLeft, uint256[] memory liquidityMinted);

    function burn(address from, address to, uint256[] calldata ids, uint256[] calldata amountsToBurn)
        external
        returns (bytes32[] memory amounts);

    function collectProtocolFees() external returns (bytes32 collectedProtocolFees);

    function increaseOracleLength(uint16 newLength) external;

    function setStaticFeeParameters(
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator
    ) external;

    function forceDecay() external;
}

File 13 of 31 : ILBRouter.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {IJoeFactory} from "./IJoeFactory.sol";
import {ILBFactory} from "./ILBFactory.sol";
import {ILBLegacyFactory} from "./ILBLegacyFactory.sol";
import {ILBLegacyRouter} from "./ILBLegacyRouter.sol";
import {ILBPair} from "./ILBPair.sol";
import {ILBToken} from "./ILBToken.sol";
import {IWNATIVE} from "./IWNATIVE.sol";

/**
 * @title Liquidity Book Router Interface
 * @author Trader Joe
 * @notice Required interface of LBRouter contract
 */
interface ILBRouter {
    error LBRouter__SenderIsNotWNATIVE();
    error LBRouter__PairNotCreated(address tokenX, address tokenY, uint256 binStep);
    error LBRouter__WrongAmounts(uint256 amount, uint256 reserve);
    error LBRouter__SwapOverflows(uint256 id);
    error LBRouter__BrokenSwapSafetyCheck();
    error LBRouter__NotFactoryOwner();
    error LBRouter__TooMuchTokensIn(uint256 excess);
    error LBRouter__BinReserveOverflows(uint256 id);
    error LBRouter__IdOverflows(int256 id);
    error LBRouter__LengthsMismatch();
    error LBRouter__WrongTokenOrder();
    error LBRouter__IdSlippageCaught(uint256 activeIdDesired, uint256 idSlippage, uint256 activeId);
    error LBRouter__AmountSlippageCaught(uint256 amountXMin, uint256 amountX, uint256 amountYMin, uint256 amountY);
    error LBRouter__IdDesiredOverflows(uint256 idDesired, uint256 idSlippage);
    error LBRouter__FailedToSendNATIVE(address recipient, uint256 amount);
    error LBRouter__DeadlineExceeded(uint256 deadline, uint256 currentTimestamp);
    error LBRouter__AmountSlippageBPTooBig(uint256 amountSlippage);
    error LBRouter__InsufficientAmountOut(uint256 amountOutMin, uint256 amountOut);
    error LBRouter__MaxAmountInExceeded(uint256 amountInMax, uint256 amountIn);
    error LBRouter__InvalidTokenPath(address wrongToken);
    error LBRouter__InvalidVersion(uint256 version);
    error LBRouter__WrongNativeLiquidityParameters(
        address tokenX, address tokenY, uint256 amountX, uint256 amountY, uint256 msgValue
    );

    /**
     * @dev This enum represents the version of the pair requested
     * - V1: Joe V1 pair
     * - V2: LB pair V2. Also called legacyPair
     * - V2_1: LB pair V2.1 (current version)
     */
    enum Version {
        V1,
        V2,
        V2_1
    }

    /**
     * @dev The liquidity parameters, such as:
     * - tokenX: The address of token X
     * - tokenY: The address of token Y
     * - binStep: The bin step of the pair
     * - amountX: The amount to send of token X
     * - amountY: The amount to send of token Y
     * - amountXMin: The min amount of token X added to liquidity
     * - amountYMin: The min amount of token Y added to liquidity
     * - activeIdDesired: The active id that user wants to add liquidity from
     * - idSlippage: The number of id that are allowed to slip
     * - deltaIds: The list of delta ids to add liquidity (`deltaId = activeId - desiredId`)
     * - distributionX: The distribution of tokenX with sum(distributionX) = 100e18 (100%) or 0 (0%)
     * - distributionY: The distribution of tokenY with sum(distributionY) = 100e18 (100%) or 0 (0%)
     * - to: The address of the recipient
     * - refundTo: The address of the recipient of the refunded tokens if too much tokens are sent
     * - deadline: The deadline of the transaction
     */
    struct LiquidityParameters {
        IERC20 tokenX;
        IERC20 tokenY;
        uint256 binStep;
        uint256 amountX;
        uint256 amountY;
        uint256 amountXMin;
        uint256 amountYMin;
        uint256 activeIdDesired;
        uint256 idSlippage;
        int256[] deltaIds;
        uint256[] distributionX;
        uint256[] distributionY;
        address to;
        address refundTo;
        uint256 deadline;
    }

    /**
     * @dev The path parameters, such as:
     * - pairBinSteps: The list of bin steps of the pairs to go through
     * - versions: The list of versions of the pairs to go through
     * - tokenPath: The list of tokens in the path to go through
     */
    struct Path {
        uint256[] pairBinSteps;
        Version[] versions;
        IERC20[] tokenPath;
    }

    function getFactory() external view returns (ILBFactory);

    function getLegacyFactory() external view returns (ILBLegacyFactory);

    function getV1Factory() external view returns (IJoeFactory);

    function getLegacyRouter() external view returns (ILBLegacyRouter);

    function getWNATIVE() external view returns (IWNATIVE);

    function getIdFromPrice(ILBPair LBPair, uint256 price) external view returns (uint24);

    function getPriceFromId(ILBPair LBPair, uint24 id) external view returns (uint256);

    function getSwapIn(ILBPair LBPair, uint128 amountOut, bool swapForY)
        external
        view
        returns (uint128 amountIn, uint128 amountOutLeft, uint128 fee);

    function getSwapOut(ILBPair LBPair, uint128 amountIn, bool swapForY)
        external
        view
        returns (uint128 amountInLeft, uint128 amountOut, uint128 fee);

    function createLBPair(IERC20 tokenX, IERC20 tokenY, uint24 activeId, uint16 binStep)
        external
        returns (ILBPair pair);

    function addLiquidity(LiquidityParameters calldata liquidityParameters)
        external
        returns (
            uint256 amountXAdded,
            uint256 amountYAdded,
            uint256 amountXLeft,
            uint256 amountYLeft,
            uint256[] memory depositIds,
            uint256[] memory liquidityMinted
        );

    function addLiquidityNATIVE(LiquidityParameters calldata liquidityParameters)
        external
        payable
        returns (
            uint256 amountXAdded,
            uint256 amountYAdded,
            uint256 amountXLeft,
            uint256 amountYLeft,
            uint256[] memory depositIds,
            uint256[] memory liquidityMinted
        );

    function removeLiquidity(
        IERC20 tokenX,
        IERC20 tokenY,
        uint16 binStep,
        uint256 amountXMin,
        uint256 amountYMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address to,
        uint256 deadline
    ) external returns (uint256 amountX, uint256 amountY);

    function removeLiquidityNATIVE(
        IERC20 token,
        uint16 binStep,
        uint256 amountTokenMin,
        uint256 amountNATIVEMin,
        uint256[] memory ids,
        uint256[] memory amounts,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountNATIVE);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactTokensForNATIVE(
        uint256 amountIn,
        uint256 amountOutMinNATIVE,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactNATIVEForTokens(uint256 amountOutMin, Path memory path, address to, uint256 deadline)
        external
        payable
        returns (uint256 amountOut);

    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        Path memory path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amountsIn);

    function swapTokensForExactNATIVE(
        uint256 amountOut,
        uint256 amountInMax,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external returns (uint256[] memory amountsIn);

    function swapNATIVEForExactTokens(uint256 amountOut, Path memory path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amountsIn);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactTokensForNATIVESupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMinNATIVE,
        Path memory path,
        address payable to,
        uint256 deadline
    ) external returns (uint256 amountOut);

    function swapExactNATIVEForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        Path memory path,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountOut);

    function sweep(IERC20 token, address to, uint256 amount) external;

    function sweepLBToken(ILBToken _lbToken, address _to, uint256[] calldata _ids, uint256[] calldata _amounts)
        external;
}

File 14 of 31 : ILBToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Token Interface
 * @author Trader Joe
 * @notice Interface to interact with the LBToken.
 */
interface ILBToken {
    error LBToken__AddressThisOrZero();
    error LBToken__InvalidLength();
    error LBToken__SelfApproval(address owner);
    error LBToken__SpenderNotApproved(address from, address spender);
    error LBToken__TransferExceedsBalance(address from, uint256 id, uint256 amount);
    error LBToken__BurnExceedsBalance(address from, uint256 id, uint256 amount);

    event TransferBatch(
        address indexed sender, address indexed from, address indexed to, uint256[] ids, uint256[] amounts
    );

    event ApprovalForAll(address indexed account, address indexed sender, bool approved);

    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function totalSupply(uint256 id) external view returns (uint256);

    function balanceOf(address account, uint256 id) external view returns (uint256);

    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    function isApprovedForAll(address owner, address spender) external view returns (bool);

    function approveForAll(address spender, bool approved) external;

    function batchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts) external;
}

File 15 of 31 : IPendingOwnable.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Pending Ownable Interface
 * @author Trader Joe
 * @notice Required interface of Pending Ownable contract used for LBFactory
 */
interface IPendingOwnable {
    error PendingOwnable__AddressZero();
    error PendingOwnable__NoPendingOwner();
    error PendingOwnable__NotOwner();
    error PendingOwnable__NotPendingOwner();
    error PendingOwnable__PendingOwnerAlreadySet();

    event PendingOwnerSet(address indexed pendingOwner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    function owner() external view returns (address);

    function pendingOwner() external view returns (address);

    function setPendingOwner(address pendingOwner) external;

    function revokePendingOwner() external;

    function becomeOwner() external;

    function renounceOwnership() external;
}

File 16 of 31 : IWNATIVE.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

/**
 * @title WNATIVE Interface
 * @notice Required interface of Wrapped NATIVE contract
 */
interface IWNATIVE is IERC20 {
    function deposit() external payable;

    function withdraw(uint256) external;
}

File 17 of 31 : AddressHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Address Helper Library
 * @author Trader Joe
 * @notice This library contains functions to check if an address is a contract and
 * catch low level calls errors
 */
library AddressHelper {
    error AddressHelper__NonContract();
    error AddressHelper__CallFailed();

    /**
     * @notice Private view function to perform a low level call on `target`
     * @dev Revert if the call doesn't succeed
     * @param target The address of the account
     * @param data The data to execute on `target`
     * @return returnData The data returned by the call
     */
    function callAndCatch(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returnData) = target.call(data);

        if (success) {
            if (returnData.length == 0 && !isContract(target)) revert AddressHelper__NonContract();
        } else {
            if (returnData.length == 0) {
                revert AddressHelper__CallFailed();
            } else {
                // Look for revert reason and bubble it up if present
                assembly {
                    revert(add(32, returnData), mload(returnData))
                }
            }
        }

        return returnData;
    }

    /**
     * @notice Private view function to return if an address is a contract
     * @dev It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * @param account The address of the account
     * @return Whether the account is a contract (true) or not (false)
     */
    function isContract(address account) internal view returns (bool) {
        return account.code.length > 0;
    }
}

File 18 of 31 : BinHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {PackedUint128Math} from "./math/PackedUint128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
import {PairParameterHelper} from "./PairParameterHelper.sol";
import {FeeHelper} from "./FeeHelper.sol";
import {PriceHelper} from "./PriceHelper.sol";
import {TokenHelper} from "./TokenHelper.sol";

/**
 * @title Liquidity Book Bin Helper Library
 * @author Trader Joe
 * @notice This library contains functions to help interaction with bins.
 */
library BinHelper {
    using PackedUint128Math for bytes32;
    using PackedUint128Math for uint128;
    using Uint256x256Math for uint256;
    using PriceHelper for uint24;
    using SafeCast for uint256;
    using PairParameterHelper for bytes32;
    using FeeHelper for uint128;
    using TokenHelper for IERC20;

    error BinHelper__CompositionFactorFlawed(uint24 id);
    error BinHelper__LiquidityOverflow();

    /**
     * @dev Returns the amount of tokens that will be received when burning the given amount of liquidity
     * @param binReserves The reserves of the bin
     * @param amountToBurn The amount of liquidity to burn
     * @param totalSupply The total supply of the liquidity book
     * @return amountsOut The encoded amount of tokens that will be received
     */
    function getAmountOutOfBin(bytes32 binReserves, uint256 amountToBurn, uint256 totalSupply)
        internal
        pure
        returns (bytes32 amountsOut)
    {
        (uint128 binReserveX, uint128 binReserveY) = binReserves.decode();

        uint128 amountXOutFromBin;
        uint128 amountYOutFromBin;

        if (binReserveX > 0) {
            amountXOutFromBin = (amountToBurn.mulDivRoundDown(binReserveX, totalSupply)).safe128();
        }

        if (binReserveY > 0) {
            amountYOutFromBin = (amountToBurn.mulDivRoundDown(binReserveY, totalSupply)).safe128();
        }

        amountsOut = amountXOutFromBin.encode(amountYOutFromBin);
    }

    /**
     * @dev Returns the share and the effective amounts in when adding liquidity
     * @param binReserves The reserves of the bin
     * @param amountsIn The amounts of tokens to add
     * @param price The price of the bin
     * @param totalSupply The total supply of the liquidity book
     * @return shares The share of the liquidity book that the user will receive
     * @return effectiveAmountsIn The encoded effective amounts of tokens that the user will add.
     * This is the amount of tokens that the user will actually add to the liquidity book,
     * and will always be less than or equal to the amountsIn.
     */
    function getSharesAndEffectiveAmountsIn(bytes32 binReserves, bytes32 amountsIn, uint256 price, uint256 totalSupply)
        internal
        pure
        returns (uint256 shares, bytes32 effectiveAmountsIn)
    {
        (uint256 x, uint256 y) = amountsIn.decode();

        uint256 userLiquidity = getLiquidity(x, y, price);
        if (totalSupply == 0 || userLiquidity == 0) return (userLiquidity, amountsIn);

        uint256 binLiquidity = getLiquidity(binReserves, price);
        if (binLiquidity == 0) return (userLiquidity, amountsIn);

        shares = userLiquidity.mulDivRoundDown(totalSupply, binLiquidity);
        uint256 effectiveLiquidity = shares.mulDivRoundUp(binLiquidity, totalSupply);

        if (userLiquidity > effectiveLiquidity) {
            uint256 deltaLiquidity = userLiquidity - effectiveLiquidity;

            // The other way might be more efficient, but as y is the quote asset, it is more valuable
            if (deltaLiquidity >= Constants.SCALE) {
                uint256 deltaY = deltaLiquidity >> Constants.SCALE_OFFSET;
                deltaY = deltaY > y ? y : deltaY;

                y -= deltaY;
                deltaLiquidity -= deltaY << Constants.SCALE_OFFSET;
            }

            if (deltaLiquidity >= price) {
                uint256 deltaX = deltaLiquidity / price;
                deltaX = deltaX > x ? x : deltaX;

                x -= deltaX;
            }

            amountsIn = uint128(x).encode(uint128(y));
        }

        return (shares, amountsIn);
    }

    /**
     * @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
     * @param amounts The amounts of tokens
     * @param price The price of the bin
     * @return liquidity The amount of liquidity
     */
    function getLiquidity(bytes32 amounts, uint256 price) internal pure returns (uint256 liquidity) {
        (uint256 x, uint256 y) = amounts.decode();
        return getLiquidity(x, y, price);
    }

    /**
     * @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
     * @param x The amount of the token X
     * @param y The amount of the token Y
     * @param price The price of the bin
     * @return liquidity The amount of liquidity
     */
    function getLiquidity(uint256 x, uint256 y, uint256 price) internal pure returns (uint256 liquidity) {
        if (x > 0) {
            unchecked {
                liquidity = price * x;
                if (liquidity / x != price) revert BinHelper__LiquidityOverflow();
            }
        }
        if (y > 0) {
            unchecked {
                y <<= Constants.SCALE_OFFSET;
                liquidity += y;

                if (liquidity < y) revert BinHelper__LiquidityOverflow();
            }
        }

        return liquidity;
    }

    /**
     * @dev Verify that the amounts are correct and that the composition factor is not flawed
     * @param amounts The amounts of tokens
     * @param activeId The id of the active bin
     * @param id The id of the bin
     */
    function verifyAmounts(bytes32 amounts, uint24 activeId, uint24 id) internal pure {
        if (id < activeId && (amounts << 128) > 0 || id > activeId && uint256(amounts) > type(uint128).max) {
            revert BinHelper__CompositionFactorFlawed(id);
        }
    }

    /**
     * @dev Returns the composition fees when adding liquidity to the active bin with a different
     * composition factor than the bin's one, as it does an implicit swap
     * @param binReserves The reserves of the bin
     * @param parameters The parameters of the liquidity book
     * @param binStep The step of the bin
     * @param amountsIn The amounts of tokens to add
     * @param totalSupply The total supply of the liquidity book
     * @param shares The share of the liquidity book that the user will receive
     * @return fees The encoded fees that will be charged
     */
    function getCompositionFees(
        bytes32 binReserves,
        bytes32 parameters,
        uint16 binStep,
        bytes32 amountsIn,
        uint256 totalSupply,
        uint256 shares
    ) internal pure returns (bytes32 fees) {
        if (shares == 0) return 0;

        (uint128 amountX, uint128 amountY) = amountsIn.decode();
        (uint128 receivedAmountX, uint128 receivedAmountY) =
            getAmountOutOfBin(binReserves.add(amountsIn), shares, totalSupply + shares).decode();

        if (receivedAmountX > amountX) {
            uint128 feeY = (amountY - receivedAmountY).getCompositionFee(parameters.getTotalFee(binStep));

            fees = feeY.encodeSecond();
        } else if (receivedAmountY > amountY) {
            uint128 feeX = (amountX - receivedAmountX).getCompositionFee(parameters.getTotalFee(binStep));

            fees = feeX.encodeFirst();
        }
    }

    /**
     * @dev Returns whether the bin is empty (true) or not (false)
     * @param binReserves The reserves of the bin
     * @param isX Whether the reserve to check is the X reserve (true) or the Y reserve (false)
     * @return Whether the bin is empty (true) or not (false)
     */
    function isEmpty(bytes32 binReserves, bool isX) internal pure returns (bool) {
        return isX ? binReserves.decodeX() == 0 : binReserves.decodeY() == 0;
    }

    /**
     * @dev Returns the amounts of tokens that will be added and removed from the bin during a swap
     * along with the fees that will be charged
     * @param binReserves The reserves of the bin
     * @param parameters The parameters of the liquidity book
     * @param binStep The step of the bin
     * @param swapForY Whether the swap is for Y (true) or for X (false)
     * @param activeId The id of the active bin
     * @param amountsInLeft The amounts of tokens left to swap
     * @return amountsInWithFees The encoded amounts of tokens that will be added to the bin, including fees
     * @return amountsOutOfBin The encoded amounts of tokens that will be removed from the bin
     * @return totalFees The encoded fees that will be charged
     */
    function getAmounts(
        bytes32 binReserves,
        bytes32 parameters,
        uint16 binStep,
        bool swapForY, // swap `swapForY` and `activeId` to avoid stack too deep
        uint24 activeId,
        bytes32 amountsInLeft
    ) internal pure returns (bytes32 amountsInWithFees, bytes32 amountsOutOfBin, bytes32 totalFees) {
        uint256 price = activeId.getPriceFromId(binStep);

        uint128 binReserveOut = binReserves.decode(!swapForY);

        uint128 maxAmountIn = swapForY
            ? uint256(binReserveOut).shiftDivRoundUp(Constants.SCALE_OFFSET, price).safe128()
            : uint256(binReserveOut).mulShiftRoundUp(price, Constants.SCALE_OFFSET).safe128();

        uint128 totalFee = parameters.getTotalFee(binStep);
        uint128 maxFee = maxAmountIn.getFeeAmount(totalFee);

        maxAmountIn += maxFee;

        uint128 amountIn128 = amountsInLeft.decode(swapForY);
        uint128 fee128;
        uint128 amountOut128;

        if (amountIn128 >= maxAmountIn) {
            fee128 = maxFee;

            amountIn128 = maxAmountIn;
            amountOut128 = binReserveOut;
        } else {
            fee128 = amountIn128.getFeeAmountFrom(totalFee);

            uint256 amountIn = amountIn128 - fee128;

            amountOut128 = swapForY
                ? uint256(amountIn).mulShiftRoundDown(price, Constants.SCALE_OFFSET).safe128()
                : uint256(amountIn).shiftDivRoundDown(Constants.SCALE_OFFSET, price).safe128();

            if (amountOut128 > binReserveOut) amountOut128 = binReserveOut;
        }

        (amountsInWithFees, amountsOutOfBin, totalFees) = swapForY
            ? (amountIn128.encodeFirst(), amountOut128.encodeSecond(), fee128.encodeFirst())
            : (amountIn128.encodeSecond(), amountOut128.encodeFirst(), fee128.encodeSecond());
    }

    /**
     * @dev Returns the encoded amounts that were transferred to the contract
     * @param reserves The reserves
     * @param tokenX The token X
     * @param tokenY The token Y
     * @return amounts The amounts, encoded as follows:
     * [0 - 128[: amountX
     * [128 - 256[: amountY
     */
    function received(bytes32 reserves, IERC20 tokenX, IERC20 tokenY) internal view returns (bytes32 amounts) {
        amounts = _balanceOf(tokenX).encode(_balanceOf(tokenY)).sub(reserves);
    }

    /**
     * @dev Returns the encoded amounts that were transferred to the contract, only for token X
     * @param reserves The reserves
     * @param tokenX The token X
     * @return amounts The amounts, encoded as follows:
     * [0 - 128[: amountX
     * [128 - 256[: empty
     */
    function receivedX(bytes32 reserves, IERC20 tokenX) internal view returns (bytes32) {
        uint128 reserveX = reserves.decodeX();
        return (_balanceOf(tokenX) - reserveX).encodeFirst();
    }

    /**
     * @dev Returns the encoded amounts that were transferred to the contract, only for token Y
     * @param reserves The reserves
     * @param tokenY The token Y
     * @return amounts The amounts, encoded as follows:
     * [0 - 128[: empty
     * [128 - 256[: amountY
     */
    function receivedY(bytes32 reserves, IERC20 tokenY) internal view returns (bytes32) {
        uint128 reserveY = reserves.decodeY();
        return (_balanceOf(tokenY) - reserveY).encodeSecond();
    }

    /**
     * @dev Transfers the encoded amounts to the recipient
     * @param amounts The amounts, encoded as follows:
     * [0 - 128[: amountX
     * [128 - 256[: amountY
     * @param tokenX The token X
     * @param tokenY The token Y
     * @param recipient The recipient
     */
    function transfer(bytes32 amounts, IERC20 tokenX, IERC20 tokenY, address recipient) internal {
        (uint128 amountX, uint128 amountY) = amounts.decode();

        if (amountX > 0) tokenX.safeTransfer(recipient, amountX);
        if (amountY > 0) tokenY.safeTransfer(recipient, amountY);
    }

    /**
     * @dev Transfers the encoded amounts to the recipient, only for token X
     * @param amounts The amounts, encoded as follows:
     * [0 - 128[: amountX
     * [128 - 256[: empty
     * @param tokenX The token X
     * @param recipient The recipient
     */
    function transferX(bytes32 amounts, IERC20 tokenX, address recipient) internal {
        uint128 amountX = amounts.decodeX();

        if (amountX > 0) tokenX.safeTransfer(recipient, amountX);
    }

    /**
     * @dev Transfers the encoded amounts to the recipient, only for token Y
     * @param amounts The amounts, encoded as follows:
     * [0 - 128[: empty
     * [128 - 256[: amountY
     * @param tokenY The token Y
     * @param recipient The recipient
     */
    function transferY(bytes32 amounts, IERC20 tokenY, address recipient) internal {
        uint128 amountY = amounts.decodeY();

        if (amountY > 0) tokenY.safeTransfer(recipient, amountY);
    }

    function _balanceOf(IERC20 token) private view returns (uint128) {
        return token.balanceOf(address(this)).safe128();
    }
}

File 19 of 31 : Constants.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Constants Library
 * @author Trader Joe
 * @notice Set of constants for Liquidity Book contracts
 */
library Constants {
    uint8 internal constant SCALE_OFFSET = 128;
    uint256 internal constant SCALE = 1 << SCALE_OFFSET;

    uint256 internal constant PRECISION = 1e18;
    uint256 internal constant SQUARED_PRECISION = PRECISION * PRECISION;

    uint256 internal constant MAX_FEE = 0.1e18; // 10%
    uint256 internal constant MAX_PROTOCOL_SHARE = 2_500; // 25% of the fee

    uint256 internal constant BASIS_POINT_MAX = 10_000;

    /// @dev The expected return after a successful flash loan
    bytes32 internal constant CALLBACK_SUCCESS = keccak256("LBPair.onFlashLoan");
}

File 20 of 31 : FeeHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {Constants} from "./Constants.sol";

/**
 * @title Liquidity Book Fee Helper Library
 * @author Trader Joe
 * @notice This library contains functions to calculate fees
 */
library FeeHelper {
    error FeeHelper__FeeTooLarge();
    error FeeHelper__ProtocolShareTooLarge();

    /**
     * @dev Modifier to check that the fee is not too large
     * @param fee The fee
     */
    modifier verifyFee(uint128 fee) {
        if (fee > Constants.MAX_FEE) revert FeeHelper__FeeTooLarge();
        _;
    }

    /**
     * @dev Modifier to check that the protocol share is not too large
     * @param protocolShare The protocol share
     */
    modifier verifyProtocolShare(uint128 protocolShare) {
        if (protocolShare > Constants.MAX_PROTOCOL_SHARE) revert FeeHelper__ProtocolShareTooLarge();
        _;
    }

    /**
     * @dev Calculates the fee amount from the amount with fees, rounding up
     * @param amountWithFees The amount with fees
     * @param totalFee The total fee
     * @return feeAmount The fee amount
     */
    function getFeeAmountFrom(uint128 amountWithFees, uint128 totalFee)
        internal
        pure
        verifyFee(totalFee)
        returns (uint128)
    {
        unchecked {
            // Can't overflow, max(result) = (type(uint128).max * 0.1e18 + 1e18 - 1) / 1e18 < 2^128
            return uint128((uint256(amountWithFees) * totalFee + Constants.PRECISION - 1) / Constants.PRECISION);
        }
    }

    /**
     * @dev Calculates the fee amount that will be charged, rounding up
     * @param amount The amount
     * @param totalFee The total fee
     * @return feeAmount The fee amount
     */
    function getFeeAmount(uint128 amount, uint128 totalFee) internal pure verifyFee(totalFee) returns (uint128) {
        unchecked {
            uint256 denominator = Constants.PRECISION - totalFee;
            // Can't overflow, max(result) = (type(uint128).max * 0.1e18 + (1e18 - 1)) / 0.9e18 < 2^128
            return uint128((uint256(amount) * totalFee + denominator - 1) / denominator);
        }
    }

    /**
     * @dev Calculates the composition fee amount from the amount with fees, rounding down
     * @param amountWithFees The amount with fees
     * @param totalFee The total fee
     * @return The amount with fees
     */
    function getCompositionFee(uint128 amountWithFees, uint128 totalFee)
        internal
        pure
        verifyFee(totalFee)
        returns (uint128)
    {
        unchecked {
            uint256 denominator = Constants.SQUARED_PRECISION;
            // Can't overflow, max(result) = type(uint128).max * 0.1e18 * 1.1e18 / 1e36 <= 2^128 * 0.11e36 / 1e36 < 2^128
            return uint128(uint256(amountWithFees) * totalFee * (uint256(totalFee) + Constants.PRECISION) / denominator);
        }
    }

    /**
     * @dev Calculates the protocol fee amount from the fee amount and the protocol share, rounding down
     * @param feeAmount The fee amount
     * @param protocolShare The protocol share
     * @return protocolFeeAmount The protocol fee amount
     */
    function getProtocolFeeAmount(uint128 feeAmount, uint128 protocolShare)
        internal
        pure
        verifyProtocolShare(protocolShare)
        returns (uint128)
    {
        unchecked {
            return uint128(uint256(feeAmount) * protocolShare / Constants.BASIS_POINT_MAX);
        }
    }
}

File 21 of 31 : JoeLibrary.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Joe Library Helper Library
 * @author Trader Joe
 * @notice Helper contract used for Joe V1 related calculations
 */
library JoeLibrary {
    error JoeLibrary__AddressZero();
    error JoeLibrary__IdenticalAddresses();
    error JoeLibrary__InsufficientAmount();
    error JoeLibrary__InsufficientLiquidity();

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        if (tokenA == tokenB) revert JoeLibrary__IdenticalAddresses();
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        if (token0 == address(0)) revert JoeLibrary__AddressZero();
    }

    // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
    function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) {
        if (amountA == 0) revert JoeLibrary__InsufficientAmount();
        if (reserveA == 0 || reserveB == 0) revert JoeLibrary__InsufficientLiquidity();
        amountB = (amountA * reserveB) / reserveA;
    }

    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountOut)
    {
        if (amountIn == 0) revert JoeLibrary__InsufficientAmount();
        if (reserveIn == 0 || reserveOut == 0) revert JoeLibrary__InsufficientLiquidity();
        uint256 amountInWithFee = amountIn * 997;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = reserveIn * 1000 + 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(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountIn)
    {
        if (amountOut == 0) revert JoeLibrary__InsufficientAmount();
        if (reserveIn == 0 || reserveOut == 0) revert JoeLibrary__InsufficientLiquidity();
        uint256 numerator = reserveIn * amountOut * 1000;
        uint256 denominator = (reserveOut - amountOut) * 997;
        amountIn = numerator / denominator + 1;
    }
}

File 22 of 31 : PairParameterHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {Constants} from "./Constants.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Encoded} from "./math/Encoded.sol";

/**
 * @title Liquidity Book Pair Parameter Helper Library
 * @author Trader Joe
 * @dev This library contains functions to get and set parameters of a pair
 * The parameters are stored in a single bytes32 variable in the following format:
 * [0 - 16[: base factor (16 bits)
 * [16 - 28[: filter period (12 bits)
 * [28 - 40[: decay period (12 bits)
 * [40 - 54[: reduction factor (14 bits)
 * [54 - 78[: variable fee control (24 bits)
 * [78 - 92[: protocol share (14 bits)
 * [92 - 112[: max volatility accumulator (20 bits)
 * [112 - 132[: volatility accumulator (20 bits)
 * [132 - 152[: volatility reference (20 bits)
 * [152 - 176[: index reference (24 bits)
 * [176 - 216[: time of last update (40 bits)
 * [216 - 232[: oracle index (16 bits)
 * [232 - 256[: active index (24 bits)
 */
library PairParameterHelper {
    using SafeCast for uint256;
    using Encoded for bytes32;

    error PairParametersHelper__InvalidParameter();

    uint256 internal constant OFFSET_BASE_FACTOR = 0;
    uint256 internal constant OFFSET_FILTER_PERIOD = 16;
    uint256 internal constant OFFSET_DECAY_PERIOD = 28;
    uint256 internal constant OFFSET_REDUCTION_FACTOR = 40;
    uint256 internal constant OFFSET_VAR_FEE_CONTROL = 54;
    uint256 internal constant OFFSET_PROTOCOL_SHARE = 78;
    uint256 internal constant OFFSET_MAX_VOL_ACC = 92;
    uint256 internal constant OFFSET_VOL_ACC = 112;
    uint256 internal constant OFFSET_VOL_REF = 132;
    uint256 internal constant OFFSET_ID_REF = 152;
    uint256 internal constant OFFSET_TIME_LAST_UPDATE = 176;
    uint256 internal constant OFFSET_ORACLE_ID = 216;
    uint256 internal constant OFFSET_ACTIVE_ID = 232;

    uint256 internal constant MASK_STATIC_PARAMETER = 0xffffffffffffffffffffffffffff;

    /**
     * @dev Get the base factor from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 16[: base factor (16 bits)
     * [16 - 256[: other parameters
     * @return baseFactor The base factor
     */
    function getBaseFactor(bytes32 params) internal pure returns (uint16 baseFactor) {
        baseFactor = params.decodeUint16(OFFSET_BASE_FACTOR);
    }

    /**
     * @dev Get the filter period from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 16[: other parameters
     * [16 - 28[: filter period (12 bits)
     * [28 - 256[: other parameters
     * @return filterPeriod The filter period
     */
    function getFilterPeriod(bytes32 params) internal pure returns (uint16 filterPeriod) {
        filterPeriod = params.decodeUint12(OFFSET_FILTER_PERIOD);
    }

    /**
     * @dev Get the decay period from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 28[: other parameters
     * [28 - 40[: decay period (12 bits)
     * [40 - 256[: other parameters
     * @return decayPeriod The decay period
     */
    function getDecayPeriod(bytes32 params) internal pure returns (uint16 decayPeriod) {
        decayPeriod = params.decodeUint12(OFFSET_DECAY_PERIOD);
    }

    /**
     * @dev Get the reduction factor from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 40[: other parameters
     * [40 - 54[: reduction factor (14 bits)
     * [54 - 256[: other parameters
     * @return reductionFactor The reduction factor
     */
    function getReductionFactor(bytes32 params) internal pure returns (uint16 reductionFactor) {
        reductionFactor = params.decodeUint14(OFFSET_REDUCTION_FACTOR);
    }

    /**
     * @dev Get the variable fee control from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 54[: other parameters
     * [54 - 78[: variable fee control (24 bits)
     * [78 - 256[: other parameters
     * @return variableFeeControl The variable fee control
     */
    function getVariableFeeControl(bytes32 params) internal pure returns (uint24 variableFeeControl) {
        variableFeeControl = params.decodeUint24(OFFSET_VAR_FEE_CONTROL);
    }

    /**
     * @dev Get the protocol share from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 78[: other parameters
     * [78 - 92[: protocol share (14 bits)
     * [92 - 256[: other parameters
     * @return protocolShare The protocol share
     */
    function getProtocolShare(bytes32 params) internal pure returns (uint16 protocolShare) {
        protocolShare = params.decodeUint14(OFFSET_PROTOCOL_SHARE);
    }

    /**
     * @dev Get the max volatility accumulator from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 92[: other parameters
     * [92 - 112[: max volatility accumulator (20 bits)
     * [112 - 256[: other parameters
     * @return maxVolatilityAccumulator The max volatility accumulator
     */
    function getMaxVolatilityAccumulator(bytes32 params) internal pure returns (uint24 maxVolatilityAccumulator) {
        maxVolatilityAccumulator = params.decodeUint20(OFFSET_MAX_VOL_ACC);
    }

    /**
     * @dev Get the volatility accumulator from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 112[: other parameters
     * [112 - 132[: volatility accumulator (20 bits)
     * [132 - 256[: other parameters
     * @return volatilityAccumulator The volatility accumulator
     */
    function getVolatilityAccumulator(bytes32 params) internal pure returns (uint24 volatilityAccumulator) {
        volatilityAccumulator = params.decodeUint20(OFFSET_VOL_ACC);
    }

    /**
     * @dev Get the volatility reference from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 132[: other parameters
     * [132 - 152[: volatility reference (20 bits)
     * [152 - 256[: other parameters
     * @return volatilityReference The volatility reference
     */
    function getVolatilityReference(bytes32 params) internal pure returns (uint24 volatilityReference) {
        volatilityReference = params.decodeUint20(OFFSET_VOL_REF);
    }

    /**
     * @dev Get the index reference from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 152[: other parameters
     * [152 - 176[: index reference (24 bits)
     * [176 - 256[: other parameters
     * @return idReference The index reference
     */
    function getIdReference(bytes32 params) internal pure returns (uint24 idReference) {
        idReference = params.decodeUint24(OFFSET_ID_REF);
    }

    /**
     * @dev Get the time of last update from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 176[: other parameters
     * [176 - 216[: time of last update (40 bits)
     * [216 - 256[: other parameters
     * @return timeOflastUpdate The time of last update
     */
    function getTimeOfLastUpdate(bytes32 params) internal pure returns (uint40 timeOflastUpdate) {
        timeOflastUpdate = params.decodeUint40(OFFSET_TIME_LAST_UPDATE);
    }

    /**
     * @dev Get the oracle id from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 216[: other parameters
     * [216 - 232[: oracle id (16 bits)
     * [232 - 256[: other parameters
     * @return oracleId The oracle id
     */
    function getOracleId(bytes32 params) internal pure returns (uint16 oracleId) {
        oracleId = params.decodeUint16(OFFSET_ORACLE_ID);
    }

    /**
     * @dev Get the active index from the encoded pair parameters
     * @param params The encoded pair parameters, as follows:
     * [0 - 232[: other parameters
     * [232 - 256[: active index (24 bits)
     * @return activeId The active index
     */
    function getActiveId(bytes32 params) internal pure returns (uint24 activeId) {
        activeId = params.decodeUint24(OFFSET_ACTIVE_ID);
    }

    /**
     * @dev Get the delta between the current active index and the cached active index
     * @param params The encoded pair parameters, as follows:
     * [0 - 232[: other parameters
     * [232 - 256[: active index (24 bits)
     * @param activeId The current active index
     * @return The delta
     */
    function getDeltaId(bytes32 params, uint24 activeId) internal pure returns (uint24) {
        uint24 id = getActiveId(params);
        unchecked {
            return activeId > id ? activeId - id : id - activeId;
        }
    }

    /**
     * @dev Calculates the base fee, with 18 decimals
     * @param params The encoded pair parameters
     * @param binStep The bin step (in basis points)
     * @return baseFee The base fee
     */
    function getBaseFee(bytes32 params, uint16 binStep) internal pure returns (uint256) {
        unchecked {
            // Base factor is in basis points, binStep is in basis points, so we multiply by 1e10
            return uint256(getBaseFactor(params)) * binStep * 1e10;
        }
    }

    /**
     * @dev Calculates the variable fee
     * @param params The encoded pair parameters
     * @param binStep The bin step (in basis points)
     * @return variableFee The variable fee
     */
    function getVariableFee(bytes32 params, uint16 binStep) internal pure returns (uint256 variableFee) {
        uint256 variableFeeControl = getVariableFeeControl(params);

        if (variableFeeControl != 0) {
            unchecked {
                // The volatility accumulator is in basis points, binStep is in basis points,
                // and the variable fee control is in basis points, so the result is in 100e18th
                uint256 prod = uint256(getVolatilityAccumulator(params)) * binStep;
                variableFee = (prod * prod * variableFeeControl + 99) / 100;
            }
        }
    }

    /**
     * @dev Calculates the total fee, which is the sum of the base fee and the variable fee
     * @param params The encoded pair parameters
     * @param binStep The bin step (in basis points)
     * @return totalFee The total fee
     */
    function getTotalFee(bytes32 params, uint16 binStep) internal pure returns (uint128) {
        unchecked {
            return (getBaseFee(params, binStep) + getVariableFee(params, binStep)).safe128();
        }
    }

    /**
     * @dev Set the oracle id in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param oracleId The oracle id
     * @return The updated encoded pair parameters
     */
    function setOracleId(bytes32 params, uint16 oracleId) internal pure returns (bytes32) {
        return params.set(oracleId, Encoded.MASK_UINT16, OFFSET_ORACLE_ID);
    }

    /**
     * @dev Set the volatility reference in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param volRef The volatility reference
     * @return The updated encoded pair parameters
     */
    function setVolatilityReference(bytes32 params, uint24 volRef) internal pure returns (bytes32) {
        if (volRef > Encoded.MASK_UINT20) revert PairParametersHelper__InvalidParameter();

        return params.set(volRef, Encoded.MASK_UINT20, OFFSET_VOL_REF);
    }

    /**
     * @dev Set the volatility accumulator in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param volAcc The volatility accumulator
     * @return The updated encoded pair parameters
     */
    function setVolatilityAccumulator(bytes32 params, uint24 volAcc) internal pure returns (bytes32) {
        if (volAcc > Encoded.MASK_UINT20) revert PairParametersHelper__InvalidParameter();

        return params.set(volAcc, Encoded.MASK_UINT20, OFFSET_VOL_ACC);
    }

    /**
     * @dev Set the active id in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param activeId The active id
     * @return newParams The updated encoded pair parameters
     */
    function setActiveId(bytes32 params, uint24 activeId) internal pure returns (bytes32 newParams) {
        return params.set(activeId, Encoded.MASK_UINT24, OFFSET_ACTIVE_ID);
    }

    /**
     * @dev Sets the static fee parameters in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param baseFactor The base factor
     * @param filterPeriod The filter period
     * @param decayPeriod The decay period
     * @param reductionFactor The reduction factor
     * @param variableFeeControl The variable fee control
     * @param protocolShare The protocol share
     * @param maxVolatilityAccumulator The max volatility accumulator
     * @return newParams The updated encoded pair parameters
     */
    function setStaticFeeParameters(
        bytes32 params,
        uint16 baseFactor,
        uint16 filterPeriod,
        uint16 decayPeriod,
        uint16 reductionFactor,
        uint24 variableFeeControl,
        uint16 protocolShare,
        uint24 maxVolatilityAccumulator
    ) internal pure returns (bytes32 newParams) {
        if (
            filterPeriod > decayPeriod || decayPeriod > Encoded.MASK_UINT12
                || reductionFactor > Constants.BASIS_POINT_MAX || protocolShare > Constants.MAX_PROTOCOL_SHARE
                || maxVolatilityAccumulator > Encoded.MASK_UINT20
        ) revert PairParametersHelper__InvalidParameter();

        newParams = newParams.set(baseFactor, Encoded.MASK_UINT16, OFFSET_BASE_FACTOR);
        newParams = newParams.set(filterPeriod, Encoded.MASK_UINT12, OFFSET_FILTER_PERIOD);
        newParams = newParams.set(decayPeriod, Encoded.MASK_UINT12, OFFSET_DECAY_PERIOD);
        newParams = newParams.set(reductionFactor, Encoded.MASK_UINT14, OFFSET_REDUCTION_FACTOR);
        newParams = newParams.set(variableFeeControl, Encoded.MASK_UINT24, OFFSET_VAR_FEE_CONTROL);
        newParams = newParams.set(protocolShare, Encoded.MASK_UINT14, OFFSET_PROTOCOL_SHARE);
        newParams = newParams.set(maxVolatilityAccumulator, Encoded.MASK_UINT20, OFFSET_MAX_VOL_ACC);

        return params.set(uint256(newParams), MASK_STATIC_PARAMETER, 0);
    }

    /**
     * @dev Updates the index reference in the encoded pair parameters
     * @param params The encoded pair parameters
     * @return newParams The updated encoded pair parameters
     */
    function updateIdReference(bytes32 params) internal pure returns (bytes32 newParams) {
        uint24 activeId = getActiveId(params);
        return params.set(activeId, Encoded.MASK_UINT24, OFFSET_ID_REF);
    }

    /**
     * @dev Updates the time of last update in the encoded pair parameters
     * @param params The encoded pair parameters
     * @return newParams The updated encoded pair parameters
     */
    function updateTimeOfLastUpdate(bytes32 params) internal view returns (bytes32 newParams) {
        uint40 currentTime = block.timestamp.safe40();
        return params.set(currentTime, Encoded.MASK_UINT40, OFFSET_TIME_LAST_UPDATE);
    }

    /**
     * @dev Updates the volatility reference in the encoded pair parameters
     * @param params The encoded pair parameters
     * @return The updated encoded pair parameters
     */
    function updateVolatilityReference(bytes32 params) internal pure returns (bytes32) {
        uint256 volAcc = getVolatilityAccumulator(params);
        uint256 reductionFactor = getReductionFactor(params);

        uint24 volRef;
        unchecked {
            volRef = uint24(volAcc * reductionFactor / Constants.BASIS_POINT_MAX);
        }

        return setVolatilityReference(params, volRef);
    }

    /**
     * @dev Updates the volatility accumulator in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param activeId The active id
     * @return The updated encoded pair parameters
     */
    function updateVolatilityAccumulator(bytes32 params, uint24 activeId) internal pure returns (bytes32) {
        uint256 idReference = getIdReference(params);

        uint256 deltaId;
        uint256 volAcc;

        unchecked {
            deltaId = activeId > idReference ? activeId - idReference : idReference - activeId;
            volAcc = (uint256(getVolatilityReference(params)) + deltaId * Constants.BASIS_POINT_MAX);
        }

        uint256 maxVolAcc = getMaxVolatilityAccumulator(params);

        volAcc = volAcc > maxVolAcc ? maxVolAcc : volAcc;

        return setVolatilityAccumulator(params, uint24(volAcc));
    }

    /**
     * @dev Updates the volatility reference and the volatility accumulator in the encoded pair parameters
     * @param params The encoded pair parameters
     * @return The updated encoded pair parameters
     */
    function updateReferences(bytes32 params) internal view returns (bytes32) {
        uint256 dt = block.timestamp - getTimeOfLastUpdate(params);

        if (dt >= getFilterPeriod(params)) {
            params = updateIdReference(params);
            params = dt < getDecayPeriod(params) ? updateVolatilityReference(params) : setVolatilityReference(params, 0);
        }

        return updateTimeOfLastUpdate(params);
    }

    /**
     * @dev Updates the volatility reference and the volatility accumulator in the encoded pair parameters
     * @param params The encoded pair parameters
     * @param activeId The active id
     * @return The updated encoded pair parameters
     */
    function updateVolatilityParameters(bytes32 params, uint24 activeId) internal view returns (bytes32) {
        params = updateReferences(params);
        return updateVolatilityAccumulator(params, activeId);
    }
}

File 23 of 31 : PriceHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {Uint128x128Math} from "./math/Uint128x128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";

/**
 * @title Liquidity Book Price Helper Library
 * @author Trader Joe
 * @notice This library contains functions to calculate prices
 */
library PriceHelper {
    using Uint128x128Math for uint256;
    using Uint256x256Math for uint256;
    using SafeCast for uint256;

    int256 private constant REAL_ID_SHIFT = 1 << 23;

    /**
     * @dev Calculates the price from the id and the bin step
     * @param id The id
     * @param binStep The bin step
     * @return price The price as a 128.128-binary fixed-point number
     */
    function getPriceFromId(uint24 id, uint16 binStep) internal pure returns (uint256 price) {
        uint256 base = getBase(binStep);
        int256 exponent = getExponent(id);

        price = base.pow(exponent);
    }

    /**
     * @dev Calculates the id from the price and the bin step
     * @param price The price as a 128.128-binary fixed-point number
     * @param binStep The bin step
     * @return id The id
     */
    function getIdFromPrice(uint256 price, uint16 binStep) internal pure returns (uint24 id) {
        uint256 base = getBase(binStep);
        int256 realId = price.log2() / base.log2();

        unchecked {
            id = uint256(REAL_ID_SHIFT + realId).safe24();
        }
    }

    /**
     * @dev Calculates the base from the bin step, which is `1 + binStep / BASIS_POINT_MAX`
     * @param binStep The bin step
     * @return base The base
     */
    function getBase(uint16 binStep) internal pure returns (uint256) {
        unchecked {
            return Constants.SCALE + (uint256(binStep) << Constants.SCALE_OFFSET) / Constants.BASIS_POINT_MAX;
        }
    }

    /**
     * @dev Calculates the exponent from the id, which is `id - REAL_ID_SHIFT`
     * @param id The id
     * @return exponent The exponent
     */
    function getExponent(uint24 id) internal pure returns (int256) {
        unchecked {
            return int256(uint256(id)) - REAL_ID_SHIFT;
        }
    }

    /**
     * @dev Converts a price with 18 decimals to a 128.128-binary fixed-point number
     * @param price The price with 18 decimals
     * @return price128x128 The 128.128-binary fixed-point number
     */
    function convertDecimalPriceTo128x128(uint256 price) internal pure returns (uint256) {
        return price.shiftDivRoundDown(Constants.SCALE_OFFSET, Constants.PRECISION);
    }

    /**
     * @dev Converts a 128.128-binary fixed-point number to a price with 18 decimals
     * @param price128x128 The 128.128-binary fixed-point number
     * @return price The price with 18 decimals
     */
    function convert128x128PriceToDecimal(uint256 price128x128) internal pure returns (uint256) {
        return price128x128.mulShiftRoundDown(Constants.PRECISION, Constants.SCALE_OFFSET);
    }
}

File 24 of 31 : TokenHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";

import {AddressHelper} from "./AddressHelper.sol";

/**
 * @title Liquidity Book Token Helper Library
 * @author Trader Joe
 * @notice Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using TokenHelper for IERC20;` statement to your contract,
 * which allows you to call the safe operation as `token.safeTransfer(...)`
 */
library TokenHelper {
    using AddressHelper for address;

    error TokenHelper__TransferFailed();

    /**
     * @notice Transfers token and reverts if the transfer fails
     * @param token The address of the token
     * @param owner The owner of the tokens
     * @param recipient The address of the recipient
     * @param amount The amount to send
     */
    function safeTransferFrom(IERC20 token, address owner, address recipient, uint256 amount) internal {
        bytes memory data = abi.encodeWithSelector(token.transferFrom.selector, owner, recipient, amount);

        bytes memory returnData = address(token).callAndCatch(data);

        if (returnData.length > 0 && !abi.decode(returnData, (bool))) revert TokenHelper__TransferFailed();
    }

    /**
     * @notice Transfers token and reverts if the transfer fails
     * @param token The address of the token
     * @param recipient The address of the recipient
     * @param amount The amount to send
     */
    function safeTransfer(IERC20 token, address recipient, uint256 amount) internal {
        bytes memory data = abi.encodeWithSelector(token.transfer.selector, recipient, amount);

        bytes memory returnData = address(token).callAndCatch(data);

        if (returnData.length > 0 && !abi.decode(returnData, (bool))) revert TokenHelper__TransferFailed();
    }
}

File 25 of 31 : BitMath.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Bit Math Library
 * @author Trader Joe
 * @notice Helper contract used for bit calculations
 */
library BitMath {
    /**
     * @dev Returns the index of the closest bit on the right of x that is non null
     * @param x The value as a uint256
     * @param bit The index of the bit to start searching at
     * @return id The index of the closest non null bit on the right of x.
     * If there is no closest bit, it returns max(uint256)
     */
    function closestBitRight(uint256 x, uint8 bit) internal pure returns (uint256 id) {
        unchecked {
            uint256 shift = 255 - bit;
            x <<= shift;

            // can't overflow as it's non-zero and we shifted it by `_shift`
            return (x == 0) ? type(uint256).max : mostSignificantBit(x) - shift;
        }
    }

    /**
     * @dev Returns the index of the closest bit on the left of x that is non null
     * @param x The value as a uint256
     * @param bit The index of the bit to start searching at
     * @return id The index of the closest non null bit on the left of x.
     * If there is no closest bit, it returns max(uint256)
     */
    function closestBitLeft(uint256 x, uint8 bit) internal pure returns (uint256 id) {
        unchecked {
            x >>= bit;

            return (x == 0) ? type(uint256).max : leastSignificantBit(x) + bit;
        }
    }

    /**
     * @dev Returns the index of the most significant bit of x
     * This function returns 0 if x is 0
     * @param x The value as a uint256
     * @return msb The index of the most significant bit of x
     */
    function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
        assembly {
            if gt(x, 0xffffffffffffffffffffffffffffffff) {
                x := shr(128, x)
                msb := 128
            }
            if gt(x, 0xffffffffffffffff) {
                x := shr(64, x)
                msb := add(msb, 64)
            }
            if gt(x, 0xffffffff) {
                x := shr(32, x)
                msb := add(msb, 32)
            }
            if gt(x, 0xffff) {
                x := shr(16, x)
                msb := add(msb, 16)
            }
            if gt(x, 0xff) {
                x := shr(8, x)
                msb := add(msb, 8)
            }
            if gt(x, 0xf) {
                x := shr(4, x)
                msb := add(msb, 4)
            }
            if gt(x, 0x3) {
                x := shr(2, x)
                msb := add(msb, 2)
            }
            if gt(x, 0x1) { msb := add(msb, 1) }
        }
    }

    /**
     * @dev Returns the index of the least significant bit of x
     * This function returns 255 if x is 0
     * @param x The value as a uint256
     * @return lsb The index of the least significant bit of x
     */
    function leastSignificantBit(uint256 x) internal pure returns (uint8 lsb) {
        assembly {
            let sx := shl(128, x)
            if iszero(iszero(sx)) {
                lsb := 128
                x := sx
            }
            sx := shl(64, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 64)
            }
            sx := shl(32, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 32)
            }
            sx := shl(16, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 16)
            }
            sx := shl(8, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 8)
            }
            sx := shl(4, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 4)
            }
            sx := shl(2, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 2)
            }
            if iszero(iszero(shl(1, x))) { lsb := add(lsb, 1) }

            lsb := sub(255, lsb)
        }
    }
}

File 26 of 31 : Encoded.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Encoded Library
 * @author Trader Joe
 * @notice Helper contract used for decoding bytes32 sample
 */
library Encoded {
    uint256 internal constant MASK_UINT1 = 0x1;
    uint256 internal constant MASK_UINT8 = 0xff;
    uint256 internal constant MASK_UINT12 = 0xfff;
    uint256 internal constant MASK_UINT14 = 0x3fff;
    uint256 internal constant MASK_UINT16 = 0xffff;
    uint256 internal constant MASK_UINT20 = 0xfffff;
    uint256 internal constant MASK_UINT24 = 0xffffff;
    uint256 internal constant MASK_UINT40 = 0xffffffffff;
    uint256 internal constant MASK_UINT64 = 0xffffffffffffffff;
    uint256 internal constant MASK_UINT128 = 0xffffffffffffffffffffffffffffffff;

    /**
     * @notice Internal function to set a value in an encoded bytes32 using a mask and offset
     * @dev This function can overflow
     * @param encoded The previous encoded value
     * @param value The value to encode
     * @param mask The mask
     * @param offset The offset
     * @return newEncoded The new encoded value
     */
    function set(bytes32 encoded, uint256 value, uint256 mask, uint256 offset)
        internal
        pure
        returns (bytes32 newEncoded)
    {
        assembly {
            newEncoded := and(encoded, not(shl(offset, mask)))
            newEncoded := or(newEncoded, shl(offset, and(value, mask)))
        }
    }

    /**
     * @notice Internal function to set a bool in an encoded bytes32 using an offset
     * @dev This function can overflow
     * @param encoded The previous encoded value
     * @param boolean The bool to encode
     * @param offset The offset
     * @return newEncoded The new encoded value
     */
    function setBool(bytes32 encoded, bool boolean, uint256 offset) internal pure returns (bytes32 newEncoded) {
        return set(encoded, boolean ? 1 : 0, MASK_UINT1, offset);
    }

    /**
     * @notice Internal function to decode a bytes32 sample using a mask and offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param mask The mask
     * @param offset The offset
     * @return value The decoded value
     */
    function decode(bytes32 encoded, uint256 mask, uint256 offset) internal pure returns (uint256 value) {
        assembly {
            value := and(shr(offset, encoded), mask)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a bool using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return boolean The decoded value as a bool
     */
    function decodeBool(bytes32 encoded, uint256 offset) internal pure returns (bool boolean) {
        assembly {
            boolean := and(shr(offset, encoded), MASK_UINT1)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint8 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint8(bytes32 encoded, uint256 offset) internal pure returns (uint8 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT8)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint12 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value as a uint16, since uint12 is not supported
     */
    function decodeUint12(bytes32 encoded, uint256 offset) internal pure returns (uint16 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT12)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint14 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value as a uint16, since uint14 is not supported
     */
    function decodeUint14(bytes32 encoded, uint256 offset) internal pure returns (uint16 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT14)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint16 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint16(bytes32 encoded, uint256 offset) internal pure returns (uint16 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT16)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint20 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value as a uint24, since uint20 is not supported
     */
    function decodeUint20(bytes32 encoded, uint256 offset) internal pure returns (uint24 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT20)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint24 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint24(bytes32 encoded, uint256 offset) internal pure returns (uint24 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT24)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint40 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint40(bytes32 encoded, uint256 offset) internal pure returns (uint40 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT40)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint64 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint64(bytes32 encoded, uint256 offset) internal pure returns (uint64 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT64)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint128 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint128(bytes32 encoded, uint256 offset) internal pure returns (uint128 value) {
        assembly {
            value := and(shr(offset, encoded), MASK_UINT128)
        }
    }
}

File 27 of 31 : LiquidityConfigurations.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {PackedUint128Math} from "./PackedUint128Math.sol";
import {Encoded} from "./Encoded.sol";

/**
 * @title Liquidity Book Liquidity Configurations Library
 * @author Trader Joe
 * @notice This library contains functions to encode and decode the config of a pool and interact with the encoded bytes32.
 */
library LiquidityConfigurations {
    using PackedUint128Math for bytes32;
    using PackedUint128Math for uint128;
    using Encoded for bytes32;

    error LiquidityConfigurations__InvalidConfig();

    uint256 private constant OFFSET_ID = 0;
    uint256 private constant OFFSET_DISTRIBUTION_Y = 24;
    uint256 private constant OFFSET_DISTRIBUTION_X = 88;

    uint256 private constant PRECISION = 1e18;

    /**
     * @dev Encode the distributionX, distributionY and id into a single bytes32
     * @param distributionX The distribution of the first token
     * @param distributionY The distribution of the second token
     * @param id The id of the pool
     * @return config The encoded config as follows:
     * [0 - 24[: id
     * [24 - 88[: distributionY
     * [88 - 152[: distributionX
     * [152 - 256[: empty
     */
    function encodeParams(uint64 distributionX, uint64 distributionY, uint24 id)
        internal
        pure
        returns (bytes32 config)
    {
        config = config.set(distributionX, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_X);
        config = config.set(distributionY, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_Y);
        config = config.set(id, Encoded.MASK_UINT24, OFFSET_ID);
    }

    /**
     * @dev Decode the distributionX, distributionY and id from a single bytes32
     * @param config The encoded config as follows:
     * [0 - 24[: id
     * [24 - 88[: distributionY
     * [88 - 152[: distributionX
     * [152 - 256[: empty
     * @return distributionX The distribution of the first token
     * @return distributionY The distribution of the second token
     * @return id The id of the bin to add the liquidity to
     */
    function decodeParams(bytes32 config)
        internal
        pure
        returns (uint64 distributionX, uint64 distributionY, uint24 id)
    {
        distributionX = config.decodeUint64(OFFSET_DISTRIBUTION_X);
        distributionY = config.decodeUint64(OFFSET_DISTRIBUTION_Y);
        id = config.decodeUint24(OFFSET_ID);

        if (uint256(config) > type(uint152).max || distributionX > PRECISION || distributionY > PRECISION) {
            revert LiquidityConfigurations__InvalidConfig();
        }
    }

    /**
     * @dev Get the amounts and id from a config and amountsIn
     * @param config The encoded config as follows:
     * [0 - 24[: id
     * [24 - 88[: distributionY
     * [88 - 152[: distributionX
     * [152 - 256[: empty
     * @param amountsIn The amounts to distribute as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @return amounts The distributed amounts as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @return id The id of the bin to add the liquidity to
     */
    function getAmountsAndId(bytes32 config, bytes32 amountsIn) internal pure returns (bytes32, uint24) {
        (uint64 distributionX, uint64 distributionY, uint24 id) = decodeParams(config);

        (uint128 x1, uint128 x2) = amountsIn.decode();

        assembly {
            x1 := div(mul(x1, distributionX), PRECISION)
            x2 := div(mul(x2, distributionY), PRECISION)
        }

        return (x1.encode(x2), id);
    }
}

File 28 of 31 : PackedUint128Math.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {Constants} from "../Constants.sol";

/**
 * @title Liquidity Book Packed Uint128 Math Library
 * @author Trader Joe
 * @notice This library contains functions to encode and decode two uint128 into a single bytes32
 * and interact with the encoded bytes32.
 */
library PackedUint128Math {
    error PackedUint128Math__AddOverflow();
    error PackedUint128Math__SubUnderflow();
    error PackedUint128Math__MultiplierTooLarge();

    uint256 private constant OFFSET = 128;
    uint256 private constant MASK_128 = 0xffffffffffffffffffffffffffffffff;
    uint256 private constant MASK_128_PLUS_ONE = MASK_128 + 1;

    /**
     * @dev Encodes two uint128 into a single bytes32
     * @param x1 The first uint128
     * @param x2 The second uint128
     * @return z The encoded bytes32 as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     */
    function encode(uint128 x1, uint128 x2) internal pure returns (bytes32 z) {
        assembly {
            z := or(and(x1, MASK_128), shl(OFFSET, x2))
        }
    }

    /**
     * @dev Encodes a uint128 into a single bytes32 as the first uint128
     * @param x1 The uint128
     * @return z The encoded bytes32 as follows:
     * [0 - 128[: x1
     * [128 - 256[: empty
     */
    function encodeFirst(uint128 x1) internal pure returns (bytes32 z) {
        assembly {
            z := and(x1, MASK_128)
        }
    }

    /**
     * @dev Encodes a uint128 into a single bytes32 as the second uint128
     * @param x2 The uint128
     * @return z The encoded bytes32 as follows:
     * [0 - 128[: empty
     * [128 - 256[: x2
     */
    function encodeSecond(uint128 x2) internal pure returns (bytes32 z) {
        assembly {
            z := shl(OFFSET, x2)
        }
    }

    /**
     * @dev Encodes a uint128 into a single bytes32 as the first or second uint128
     * @param x The uint128
     * @param first Whether to encode as the first or second uint128
     * @return z The encoded bytes32 as follows:
     * if first:
     * [0 - 128[: x
     * [128 - 256[: empty
     * else:
     * [0 - 128[: empty
     * [128 - 256[: x
     */
    function encode(uint128 x, bool first) internal pure returns (bytes32 z) {
        return first ? encodeFirst(x) : encodeSecond(x);
    }

    /**
     * @dev Decodes a bytes32 into two uint128
     * @param z The encoded bytes32 as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @return x1 The first uint128
     * @return x2 The second uint128
     */
    function decode(bytes32 z) internal pure returns (uint128 x1, uint128 x2) {
        assembly {
            x1 := and(z, MASK_128)
            x2 := shr(OFFSET, z)
        }
    }

    /**
     * @dev Decodes a bytes32 into a uint128 as the first uint128
     * @param z The encoded bytes32 as follows:
     * [0 - 128[: x
     * [128 - 256[: any
     * @return x The first uint128
     */
    function decodeX(bytes32 z) internal pure returns (uint128 x) {
        assembly {
            x := and(z, MASK_128)
        }
    }

    /**
     * @dev Decodes a bytes32 into a uint128 as the second uint128
     * @param z The encoded bytes32 as follows:
     * [0 - 128[: any
     * [128 - 256[: y
     * @return y The second uint128
     */
    function decodeY(bytes32 z) internal pure returns (uint128 y) {
        assembly {
            y := shr(OFFSET, z)
        }
    }

    /**
     * @dev Decodes a bytes32 into a uint128 as the first or second uint128
     * @param z The encoded bytes32 as follows:
     * if first:
     * [0 - 128[: x1
     * [128 - 256[: empty
     * else:
     * [0 - 128[: empty
     * [128 - 256[: x2
     * @param first Whether to decode as the first or second uint128
     * @return x The decoded uint128
     */
    function decode(bytes32 z, bool first) internal pure returns (uint128 x) {
        return first ? decodeX(z) : decodeY(z);
    }

    /**
     * @dev Adds two encoded bytes32, reverting on overflow on any of the uint128
     * @param x The first bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y The second bytes32 encoded as follows:
     * [0 - 128[: y1
     * [128 - 256[: y2
     * @return z The sum of x and y encoded as follows:
     * [0 - 128[: x1 + y1
     * [128 - 256[: x2 + y2
     */
    function add(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        assembly {
            z := add(x, y)
        }

        if (z < x || uint128(uint256(z)) < uint128(uint256(x))) {
            revert PackedUint128Math__AddOverflow();
        }
    }

    /**
     * @dev Adds an encoded bytes32 and two uint128, reverting on overflow on any of the uint128
     * @param x The bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y1 The first uint128
     * @param y2 The second uint128
     * @return z The sum of x and y encoded as follows:
     * [0 - 128[: x1 + y1
     * [128 - 256[: x2 + y2
     */
    function add(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
        return add(x, encode(y1, y2));
    }

    /**
     * @dev Subtracts two encoded bytes32, reverting on underflow on any of the uint128
     * @param x The first bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y The second bytes32 encoded as follows:
     * [0 - 128[: y1
     * [128 - 256[: y2
     * @return z The difference of x and y encoded as follows:
     * [0 - 128[: x1 - y1
     * [128 - 256[: x2 - y2
     */
    function sub(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        assembly {
            z := sub(x, y)
        }

        if (z > x || uint128(uint256(z)) > uint128(uint256(x))) {
            revert PackedUint128Math__SubUnderflow();
        }
    }

    /**
     * @dev Subtracts an encoded bytes32 and two uint128, reverting on underflow on any of the uint128
     * @param x The bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y1 The first uint128
     * @param y2 The second uint128
     * @return z The difference of x and y encoded as follows:
     * [0 - 128[: x1 - y1
     * [128 - 256[: x2 - y2
     */
    function sub(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
        return sub(x, encode(y1, y2));
    }

    /**
     * @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
     * @param x The first bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y The second bytes32 encoded as follows:
     * [0 - 128[: y1
     * [128 - 256[: y2
     * @return x1 < y1 || x2 < y2
     */
    function lt(bytes32 x, bytes32 y) internal pure returns (bool) {
        (uint128 x1, uint128 x2) = decode(x);
        (uint128 y1, uint128 y2) = decode(y);

        return x1 < y1 || x2 < y2;
    }

    /**
     * @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
     * @param x The first bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param y The second bytes32 encoded as follows:
     * [0 - 128[: y1
     * [128 - 256[: y2
     * @return x1 < y1 || x2 < y2
     */
    function gt(bytes32 x, bytes32 y) internal pure returns (bool) {
        (uint128 x1, uint128 x2) = decode(x);
        (uint128 y1, uint128 y2) = decode(y);

        return x1 > y1 || x2 > y2;
    }

    /**
     * @dev Multiplies an encoded bytes32 by a uint128 then divides the result by 10_000, rounding down
     * The result can't overflow as the multiplier needs to be smaller or equal to 10_000
     * @param x The bytes32 encoded as follows:
     * [0 - 128[: x1
     * [128 - 256[: x2
     * @param multiplier The uint128 to multiply by (must be smaller or equal to 10_000)
     * @return z The product of x and multiplier encoded as follows:
     * [0 - 128[: floor((x1 * multiplier) / 10_000)
     * [128 - 256[: floor((x2 * multiplier) / 10_000)
     */
    function scalarMulDivBasisPointRoundDown(bytes32 x, uint128 multiplier) internal pure returns (bytes32 z) {
        if (multiplier == 0) return 0;

        uint256 BASIS_POINT_MAX = Constants.BASIS_POINT_MAX;
        if (multiplier > BASIS_POINT_MAX) revert PackedUint128Math__MultiplierTooLarge();

        (uint128 x1, uint128 x2) = decode(x);

        assembly {
            x1 := div(mul(x1, multiplier), BASIS_POINT_MAX)
            x2 := div(mul(x2, multiplier), BASIS_POINT_MAX)
        }

        return encode(x1, x2);
    }
}

File 29 of 31 : SafeCast.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Safe Cast Library
 * @author Trader Joe
 * @notice This library contains functions to safely cast uint256 to different uint types.
 */
library SafeCast {
    error SafeCast__Exceeds248Bits();
    error SafeCast__Exceeds240Bits();
    error SafeCast__Exceeds232Bits();
    error SafeCast__Exceeds224Bits();
    error SafeCast__Exceeds216Bits();
    error SafeCast__Exceeds208Bits();
    error SafeCast__Exceeds200Bits();
    error SafeCast__Exceeds192Bits();
    error SafeCast__Exceeds184Bits();
    error SafeCast__Exceeds176Bits();
    error SafeCast__Exceeds168Bits();
    error SafeCast__Exceeds160Bits();
    error SafeCast__Exceeds152Bits();
    error SafeCast__Exceeds144Bits();
    error SafeCast__Exceeds136Bits();
    error SafeCast__Exceeds128Bits();
    error SafeCast__Exceeds120Bits();
    error SafeCast__Exceeds112Bits();
    error SafeCast__Exceeds104Bits();
    error SafeCast__Exceeds96Bits();
    error SafeCast__Exceeds88Bits();
    error SafeCast__Exceeds80Bits();
    error SafeCast__Exceeds72Bits();
    error SafeCast__Exceeds64Bits();
    error SafeCast__Exceeds56Bits();
    error SafeCast__Exceeds48Bits();
    error SafeCast__Exceeds40Bits();
    error SafeCast__Exceeds32Bits();
    error SafeCast__Exceeds24Bits();
    error SafeCast__Exceeds16Bits();
    error SafeCast__Exceeds8Bits();

    /**
     * @dev Returns x on uint248 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint248
     */
    function safe248(uint256 x) internal pure returns (uint248 y) {
        if ((y = uint248(x)) != x) revert SafeCast__Exceeds248Bits();
    }

    /**
     * @dev Returns x on uint240 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint240
     */
    function safe240(uint256 x) internal pure returns (uint240 y) {
        if ((y = uint240(x)) != x) revert SafeCast__Exceeds240Bits();
    }

    /**
     * @dev Returns x on uint232 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint232
     */
    function safe232(uint256 x) internal pure returns (uint232 y) {
        if ((y = uint232(x)) != x) revert SafeCast__Exceeds232Bits();
    }

    /**
     * @dev Returns x on uint224 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint224
     */
    function safe224(uint256 x) internal pure returns (uint224 y) {
        if ((y = uint224(x)) != x) revert SafeCast__Exceeds224Bits();
    }

    /**
     * @dev Returns x on uint216 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint216
     */
    function safe216(uint256 x) internal pure returns (uint216 y) {
        if ((y = uint216(x)) != x) revert SafeCast__Exceeds216Bits();
    }

    /**
     * @dev Returns x on uint208 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint208
     */
    function safe208(uint256 x) internal pure returns (uint208 y) {
        if ((y = uint208(x)) != x) revert SafeCast__Exceeds208Bits();
    }

    /**
     * @dev Returns x on uint200 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint200
     */
    function safe200(uint256 x) internal pure returns (uint200 y) {
        if ((y = uint200(x)) != x) revert SafeCast__Exceeds200Bits();
    }

    /**
     * @dev Returns x on uint192 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint192
     */
    function safe192(uint256 x) internal pure returns (uint192 y) {
        if ((y = uint192(x)) != x) revert SafeCast__Exceeds192Bits();
    }

    /**
     * @dev Returns x on uint184 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint184
     */
    function safe184(uint256 x) internal pure returns (uint184 y) {
        if ((y = uint184(x)) != x) revert SafeCast__Exceeds184Bits();
    }

    /**
     * @dev Returns x on uint176 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint176
     */
    function safe176(uint256 x) internal pure returns (uint176 y) {
        if ((y = uint176(x)) != x) revert SafeCast__Exceeds176Bits();
    }

    /**
     * @dev Returns x on uint168 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint168
     */
    function safe168(uint256 x) internal pure returns (uint168 y) {
        if ((y = uint168(x)) != x) revert SafeCast__Exceeds168Bits();
    }

    /**
     * @dev Returns x on uint160 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint160
     */
    function safe160(uint256 x) internal pure returns (uint160 y) {
        if ((y = uint160(x)) != x) revert SafeCast__Exceeds160Bits();
    }

    /**
     * @dev Returns x on uint152 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint152
     */
    function safe152(uint256 x) internal pure returns (uint152 y) {
        if ((y = uint152(x)) != x) revert SafeCast__Exceeds152Bits();
    }

    /**
     * @dev Returns x on uint144 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint144
     */
    function safe144(uint256 x) internal pure returns (uint144 y) {
        if ((y = uint144(x)) != x) revert SafeCast__Exceeds144Bits();
    }

    /**
     * @dev Returns x on uint136 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint136
     */
    function safe136(uint256 x) internal pure returns (uint136 y) {
        if ((y = uint136(x)) != x) revert SafeCast__Exceeds136Bits();
    }

    /**
     * @dev Returns x on uint128 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint128
     */
    function safe128(uint256 x) internal pure returns (uint128 y) {
        if ((y = uint128(x)) != x) revert SafeCast__Exceeds128Bits();
    }

    /**
     * @dev Returns x on uint120 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint120
     */
    function safe120(uint256 x) internal pure returns (uint120 y) {
        if ((y = uint120(x)) != x) revert SafeCast__Exceeds120Bits();
    }

    /**
     * @dev Returns x on uint112 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint112
     */
    function safe112(uint256 x) internal pure returns (uint112 y) {
        if ((y = uint112(x)) != x) revert SafeCast__Exceeds112Bits();
    }

    /**
     * @dev Returns x on uint104 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint104
     */
    function safe104(uint256 x) internal pure returns (uint104 y) {
        if ((y = uint104(x)) != x) revert SafeCast__Exceeds104Bits();
    }

    /**
     * @dev Returns x on uint96 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint96
     */
    function safe96(uint256 x) internal pure returns (uint96 y) {
        if ((y = uint96(x)) != x) revert SafeCast__Exceeds96Bits();
    }

    /**
     * @dev Returns x on uint88 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint88
     */
    function safe88(uint256 x) internal pure returns (uint88 y) {
        if ((y = uint88(x)) != x) revert SafeCast__Exceeds88Bits();
    }

    /**
     * @dev Returns x on uint80 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint80
     */
    function safe80(uint256 x) internal pure returns (uint80 y) {
        if ((y = uint80(x)) != x) revert SafeCast__Exceeds80Bits();
    }

    /**
     * @dev Returns x on uint72 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint72
     */
    function safe72(uint256 x) internal pure returns (uint72 y) {
        if ((y = uint72(x)) != x) revert SafeCast__Exceeds72Bits();
    }

    /**
     * @dev Returns x on uint64 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint64
     */
    function safe64(uint256 x) internal pure returns (uint64 y) {
        if ((y = uint64(x)) != x) revert SafeCast__Exceeds64Bits();
    }

    /**
     * @dev Returns x on uint56 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint56
     */
    function safe56(uint256 x) internal pure returns (uint56 y) {
        if ((y = uint56(x)) != x) revert SafeCast__Exceeds56Bits();
    }

    /**
     * @dev Returns x on uint48 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint48
     */
    function safe48(uint256 x) internal pure returns (uint48 y) {
        if ((y = uint48(x)) != x) revert SafeCast__Exceeds48Bits();
    }

    /**
     * @dev Returns x on uint40 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint40
     */
    function safe40(uint256 x) internal pure returns (uint40 y) {
        if ((y = uint40(x)) != x) revert SafeCast__Exceeds40Bits();
    }

    /**
     * @dev Returns x on uint32 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint32
     */
    function safe32(uint256 x) internal pure returns (uint32 y) {
        if ((y = uint32(x)) != x) revert SafeCast__Exceeds32Bits();
    }

    /**
     * @dev Returns x on uint24 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint24
     */
    function safe24(uint256 x) internal pure returns (uint24 y) {
        if ((y = uint24(x)) != x) revert SafeCast__Exceeds24Bits();
    }

    /**
     * @dev Returns x on uint16 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint16
     */
    function safe16(uint256 x) internal pure returns (uint16 y) {
        if ((y = uint16(x)) != x) revert SafeCast__Exceeds16Bits();
    }

    /**
     * @dev Returns x on uint8 and check that it does not overflow
     * @param x The value as an uint256
     * @return y The value as an uint8
     */
    function safe8(uint256 x) internal pure returns (uint8 y) {
        if ((y = uint8(x)) != x) revert SafeCast__Exceeds8Bits();
    }
}

File 30 of 31 : Uint128x128Math.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

import {Constants} from "../Constants.sol";
import {BitMath} from "./BitMath.sol";

/**
 * @title Liquidity Book Uint128x128 Math Library
 * @author Trader Joe
 * @notice Helper contract used for power and log calculations
 */
library Uint128x128Math {
    using BitMath for uint256;

    error Uint128x128Math__LogUnderflow();
    error Uint128x128Math__PowUnderflow(uint256 x, int256 y);

    uint256 constant LOG_SCALE_OFFSET = 127;
    uint256 constant LOG_SCALE = 1 << LOG_SCALE_OFFSET;
    uint256 constant LOG_SCALE_SQUARED = LOG_SCALE * LOG_SCALE;

    /**
     * @notice Calculates the binary logarithm of x.
     * @dev Based on the iterative approximation algorithm.
     * https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
     * Requirements:
     * - x must be greater than zero.
     * Caveats:
     * - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation
     * Also because x is converted to an unsigned 129.127-binary fixed-point number during the operation to optimize the multiplication
     * @param x The unsigned 128.128-binary fixed-point number for which to calculate the binary logarithm.
     * @return result The binary logarithm as a signed 128.128-binary fixed-point number.
     */
    function log2(uint256 x) internal pure returns (int256 result) {
        // Convert x to a unsigned 129.127-binary fixed-point number to optimize the multiplication.
        // If we use an offset of 128 bits, y would need 129 bits and y**2 would would overflow and we would have to
        // use mulDiv, by reducing x to 129.127-binary fixed-point number we assert that y will use 128 bits, and we
        // can use the regular multiplication

        if (x == 1) return -128;
        if (x == 0) revert Uint128x128Math__LogUnderflow();

        x >>= 1;

        unchecked {
            // This works because log2(x) = -log2(1/x).
            int256 sign;
            if (x >= LOG_SCALE) {
                sign = 1;
            } else {
                sign = -1;
                // Do the fixed-point inversion inline to save gas
                x = LOG_SCALE_SQUARED / x;
            }

            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
            uint256 n = (x >> LOG_SCALE_OFFSET).mostSignificantBit();

            // The integer part of the logarithm as a signed 129.127-binary fixed-point number. The operation can't overflow
            // because n is maximum 255, LOG_SCALE_OFFSET is 127 bits and sign is either 1 or -1.
            result = int256(n) << LOG_SCALE_OFFSET;

            // This is y = x * 2^(-n).
            uint256 y = x >> n;

            // If y = 1, the fractional part is zero.
            if (y != LOG_SCALE) {
                // Calculate the fractional part via the iterative approximation.
                // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
                for (int256 delta = int256(1 << (LOG_SCALE_OFFSET - 1)); delta > 0; delta >>= 1) {
                    y = (y * y) >> LOG_SCALE_OFFSET;

                    // Is y^2 > 2 and so in the range [2,4)?
                    if (y >= 1 << (LOG_SCALE_OFFSET + 1)) {
                        // Add the 2^(-m) factor to the logarithm.
                        result += delta;

                        // Corresponds to z/2 on Wikipedia.
                        y >>= 1;
                    }
                }
            }
            // Convert x back to unsigned 128.128-binary fixed-point number
            result = (result * sign) << 1;
        }
    }

    /**
     * @notice Returns the value of x^y. It calculates `1 / x^abs(y)` if x is bigger than 2^128.
     * At the end of the operations, we invert the result if needed.
     * @param x The unsigned 128.128-binary fixed-point number for which to calculate the power
     * @param y A relative number without any decimals, needs to be between ]2^21; 2^21[
     */
    function pow(uint256 x, int256 y) internal pure returns (uint256 result) {
        bool invert;
        uint256 absY;

        if (y == 0) return Constants.SCALE;

        assembly {
            absY := y
            if slt(absY, 0) {
                absY := sub(0, absY)
                invert := iszero(invert)
            }
        }

        if (absY < 0x100000) {
            result = Constants.SCALE;
            assembly {
                let squared := x
                if gt(x, 0xffffffffffffffffffffffffffffffff) {
                    squared := div(not(0), squared)
                    invert := iszero(invert)
                }

                if and(absY, 0x1) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x2) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x4) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x8) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x10) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x20) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x40) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x80) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x100) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x200) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x400) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x800) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x1000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x2000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x4000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x8000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x10000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x20000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x40000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x80000) { result := shr(128, mul(result, squared)) }
            }
        }

        // revert if y is too big or if x^y underflowed
        if (result == 0) revert Uint128x128Math__PowUnderflow(x, y);

        return invert ? type(uint256).max / result : result;
    }
}

File 31 of 31 : Uint256x256Math.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.10;

/**
 * @title Liquidity Book Uint256x256 Math Library
 * @author Trader Joe
 * @notice Helper contract used for full precision calculations
 */
library Uint256x256Math {
    error Uint256x256Math__MulShiftOverflow();
    error Uint256x256Math__MulDivOverflow();

    /**
     * @notice Calculates floor(x*y/denominator) with full precision
     * The result will be rounded down
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The denominator cannot be zero
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @param denominator The divisor as an uint256
     * @return result The result as an uint256
     */
    function mulDivRoundDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        (uint256 prod0, uint256 prod1) = _getMulProds(x, y);

        return _getEndOfDivRoundDown(x, y, denominator, prod0, prod1);
    }

    /**
     * @notice Calculates ceil(x*y/denominator) with full precision
     * The result will be rounded up
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The denominator cannot be zero
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @param denominator The divisor as an uint256
     * @return result The result as an uint256
     */
    function mulDivRoundUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        result = mulDivRoundDown(x, y, denominator);
        if (mulmod(x, y, denominator) != 0) result += 1;
    }

    /**
     * @notice Calculates floor(x * y / 2**offset) with full precision
     * The result will be rounded down
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The offset needs to be strictly lower than 256
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @param offset The offset as an uint256, can't be greater than 256
     * @return result The result as an uint256
     */
    function mulShiftRoundDown(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
        (uint256 prod0, uint256 prod1) = _getMulProds(x, y);

        if (prod0 != 0) result = prod0 >> offset;
        if (prod1 != 0) {
            // Make sure the result is less than 2^256.
            if (prod1 >= 1 << offset) revert Uint256x256Math__MulShiftOverflow();

            unchecked {
                result += prod1 << (256 - offset);
            }
        }
    }

    /**
     * @notice Calculates floor(x * y / 2**offset) with full precision
     * The result will be rounded down
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The offset needs to be strictly lower than 256
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @param offset The offset as an uint256, can't be greater than 256
     * @return result The result as an uint256
     */
    function mulShiftRoundUp(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
        result = mulShiftRoundDown(x, y, offset);
        if (mulmod(x, y, 1 << offset) != 0) result += 1;
    }

    /**
     * @notice Calculates floor(x << offset / y) with full precision
     * The result will be rounded down
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The offset needs to be strictly lower than 256
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param offset The number of bit to shift x as an uint256
     * @param denominator The divisor as an uint256
     * @return result The result as an uint256
     */
    function shiftDivRoundDown(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
        uint256 prod0;
        uint256 prod1;

        prod0 = x << offset; // Least significant 256 bits of the product
        unchecked {
            prod1 = x >> (256 - offset); // Most significant 256 bits of the product
        }

        return _getEndOfDivRoundDown(x, 1 << offset, denominator, prod0, prod1);
    }

    /**
     * @notice Calculates ceil(x << offset / y) with full precision
     * The result will be rounded up
     * @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
     * Requirements:
     * - The offset needs to be strictly lower than 256
     * - The result must fit within uint256
     * Caveats:
     * - This function does not work with fixed-point numbers
     * @param x The multiplicand as an uint256
     * @param offset The number of bit to shift x as an uint256
     * @param denominator The divisor as an uint256
     * @return result The result as an uint256
     */
    function shiftDivRoundUp(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
        result = shiftDivRoundDown(x, offset, denominator);
        if (mulmod(x, 1 << offset, denominator) != 0) result += 1;
    }

    /**
     * @notice Helper function to return the result of `x * y` as 2 uint256
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @return prod0 The least significant 256 bits of the product
     * @return prod1 The most significant 256 bits of the product
     */
    function _getMulProds(uint256 x, uint256 y) private pure returns (uint256 prod0, uint256 prod1) {
        // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
        // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = prod1 * 2^256 + prod0.
        assembly {
            let mm := mulmod(x, y, not(0))
            prod0 := mul(x, y)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }
    }

    /**
     * @notice Helper function to return the result of `x * y / denominator` with full precision
     * @param x The multiplicand as an uint256
     * @param y The multiplier as an uint256
     * @param denominator The divisor as an uint256
     * @param prod0 The least significant 256 bits of the product
     * @param prod1 The most significant 256 bits of the product
     * @return result The result as an uint256
     */
    function _getEndOfDivRoundDown(uint256 x, uint256 y, uint256 denominator, uint256 prod0, uint256 prod1)
        private
        pure
        returns (uint256 result)
    {
        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            unchecked {
                result = prod0 / denominator;
            }
        } else {
            // Make sure the result is less than 2^256. Also prevents denominator == 0
            if (prod1 >= denominator) revert Uint256x256Math__MulDivOverflow();

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1
            // See https://cs.stackexchange.com/q/138556/92363
            unchecked {
                // Does not overflow because the denominator cannot be zero at this stage in the function
                uint256 lpotdod = denominator & (~denominator + 1);
                assembly {
                    // Divide denominator by lpotdod.
                    denominator := div(denominator, lpotdod)

                    // Divide [prod1 prod0] by lpotdod.
                    prod0 := div(prod0, lpotdod)

                    // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one
                    lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
                }

                // Shift in bits from prod1 into prod0
                prod0 |= prod1 * lpotdod;

                // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                // four bits. That is, denominator * inv = 1 mod 2^4
                uint256 inverse = (3 * denominator) ^ 2;

                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                // in modular arithmetic, doubling the correct bits in each step
                inverse *= 2 - denominator * inverse; // inverse mod 2^8
                inverse *= 2 - denominator * inverse; // inverse mod 2^16
                inverse *= 2 - denominator * inverse; // inverse mod 2^32
                inverse *= 2 - denominator * inverse; // inverse mod 2^64
                inverse *= 2 - denominator * inverse; // inverse mod 2^128
                inverse *= 2 - denominator * inverse; // inverse mod 2^256

                // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                // is no longer required.
                result = prod0 * inverse;
            }
        }
    }
}

Settings
{
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract ILBFactory","name":"factory","type":"address"},{"internalType":"contract IJoeFactory","name":"factoryV1","type":"address"},{"internalType":"contract ILBLegacyFactory","name":"legacyFactory","type":"address"},{"internalType":"contract ILBLegacyRouter","name":"legacyRouter","type":"address"},{"internalType":"contract IWNATIVE","name":"wnative","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AddressHelper__CallFailed","type":"error"},{"inputs":[],"name":"AddressHelper__NonContract","type":"error"},{"inputs":[],"name":"JoeLibrary__InsufficientAmount","type":"error"},{"inputs":[],"name":"JoeLibrary__InsufficientLiquidity","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountSlippage","type":"uint256"}],"name":"LBRouter__AmountSlippageBPTooBig","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountXMin","type":"uint256"},{"internalType":"uint256","name":"amountX","type":"uint256"},{"internalType":"uint256","name":"amountYMin","type":"uint256"},{"internalType":"uint256","name":"amountY","type":"uint256"}],"name":"LBRouter__AmountSlippageCaught","type":"error"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"LBRouter__BinReserveOverflows","type":"error"},{"inputs":[],"name":"LBRouter__BrokenSwapSafetyCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"currentTimestamp","type":"uint256"}],"name":"LBRouter__DeadlineExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LBRouter__FailedToSendNATIVE","type":"error"},{"inputs":[{"internalType":"uint256","name":"idDesired","type":"uint256"},{"internalType":"uint256","name":"idSlippage","type":"uint256"}],"name":"LBRouter__IdDesiredOverflows","type":"error"},{"inputs":[{"internalType":"int256","name":"id","type":"int256"}],"name":"LBRouter__IdOverflows","type":"error"},{"inputs":[{"internalType":"uint256","name":"activeIdDesired","type":"uint256"},{"internalType":"uint256","name":"idSlippage","type":"uint256"},{"internalType":"uint256","name":"activeId","type":"uint256"}],"name":"LBRouter__IdSlippageCaught","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"LBRouter__InsufficientAmountOut","type":"error"},{"inputs":[{"internalType":"address","name":"wrongToken","type":"address"}],"name":"LBRouter__InvalidTokenPath","type":"error"},{"inputs":[{"internalType":"uint256","name":"version","type":"uint256"}],"name":"LBRouter__InvalidVersion","type":"error"},{"inputs":[],"name":"LBRouter__LengthsMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"LBRouter__MaxAmountInExceeded","type":"error"},{"inputs":[],"name":"LBRouter__NotFactoryOwner","type":"error"},{"inputs":[{"internalType":"address","name":"tokenX","type":"address"},{"internalType":"address","name":"tokenY","type":"address"},{"internalType":"uint256","name":"binStep","type":"uint256"}],"name":"LBRouter__PairNotCreated","type":"error"},{"inputs":[],"name":"LBRouter__SenderIsNotWNATIVE","type":"error"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"LBRouter__SwapOverflows","type":"error"},{"inputs":[{"internalType":"uint256","name":"excess","type":"uint256"}],"name":"LBRouter__TooMuchTokensIn","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"reserve","type":"uint256"}],"name":"LBRouter__WrongAmounts","type":"error"},{"inputs":[{"internalType":"address","name":"tokenX","type":"address"},{"internalType":"address","name":"tokenY","type":"address"},{"internalType":"uint256","name":"amountX","type":"uint256"},{"internalType":"uint256","name":"amountY","type":"uint256"},{"internalType":"uint256","name":"msgValue","type":"uint256"}],"name":"LBRouter__WrongNativeLiquidityParameters","type":"error"},{"inputs":[],"name":"LBRouter__WrongTokenOrder","type":"error"},{"inputs":[],"name":"TokenHelper__TransferFailed","type":"error"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenX","type":"address"},{"internalType":"contract IERC20","name":"tokenY","type":"address"},{"internalType":"uint256","name":"binStep","type":"uint256"},{"internalType":"uint256","name":"amountX","type":"uint256"},{"internalType":"uint256","name":"amountY","type":"uint256"},{"internalType":"uint256","name":"amountXMin","type":"uint256"},{"internalType":"uint256","name":"amountYMin","type":"uint256"},{"internalType":"uint256","name":"activeIdDesired","type":"uint256"},{"internalType":"uint256","name":"idSlippage","type":"uint256"},{"internalType":"int256[]","name":"deltaIds","type":"int256[]"},{"internalType":"uint256[]","name":"distributionX","type":"uint256[]"},{"internalType":"uint256[]","name":"distributionY","type":"uint256[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"refundTo","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct ILBRouter.LiquidityParameters","name":"liquidityParameters","type":"tuple"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"amountXAdded","type":"uint256"},{"internalType":"uint256","name":"amountYAdded","type":"uint256"},{"internalType":"uint256","name":"amountXLeft","type":"uint256"},{"internalType":"uint256","name":"amountYLeft","type":"uint256"},{"internalType":"uint256[]","name":"depositIds","type":"uint256[]"},{"internalType":"uint256[]","name":"liquidityMinted","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20","name":"tokenX","type":"address"},{"internalType":"contract IERC20","name":"tokenY","type":"address"},{"internalType":"uint256","name":"binStep","type":"uint256"},{"internalType":"uint256","name":"amountX","type":"uint256"},{"internalType":"uint256","name":"amountY","type":"uint256"},{"internalType":"uint256","name":"amountXMin","type":"uint256"},{"internalType":"uint256","name":"amountYMin","type":"uint256"},{"internalType":"uint256","name":"activeIdDesired","type":"uint256"},{"internalType":"uint256","name":"idSlippage","type":"uint256"},{"internalType":"int256[]","name":"deltaIds","type":"int256[]"},{"internalType":"uint256[]","name":"distributionX","type":"uint256[]"},{"internalType":"uint256[]","name":"distributionY","type":"uint256[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"refundTo","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct ILBRouter.LiquidityParameters","name":"liquidityParameters","type":"tuple"}],"name":"addLiquidityNATIVE","outputs":[{"internalType":"uint256","name":"amountXAdded","type":"uint256"},{"internalType":"uint256","name":"amountYAdded","type":"uint256"},{"internalType":"uint256","name":"amountXLeft","type":"uint256"},{"internalType":"uint256","name":"amountYLeft","type":"uint256"},{"internalType":"uint256[]","name":"depositIds","type":"uint256[]"},{"internalType":"uint256[]","name":"liquidityMinted","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenX","type":"address"},{"internalType":"contract IERC20","name":"tokenY","type":"address"},{"internalType":"uint24","name":"activeId","type":"uint24"},{"internalType":"uint16","name":"binStep","type":"uint16"}],"name":"createLBPair","outputs":[{"internalType":"contract ILBPair","name":"pair","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getFactory","outputs":[{"internalType":"contract ILBFactory","name":"lbFactory","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ILBPair","name":"pair","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"}],"name":"getIdFromPrice","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLegacyFactory","outputs":[{"internalType":"contract ILBLegacyFactory","name":"legacyLBfactory","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLegacyRouter","outputs":[{"internalType":"contract ILBLegacyRouter","name":"legacyRouter","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ILBPair","name":"pair","type":"address"},{"internalType":"uint24","name":"id","type":"uint24"}],"name":"getPriceFromId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ILBPair","name":"pair","type":"address"},{"internalType":"uint128","name":"amountOut","type":"uint128"},{"internalType":"bool","name":"swapForY","type":"bool"}],"name":"getSwapIn","outputs":[{"internalType":"uint128","name":"amountIn","type":"uint128"},{"internalType":"uint128","name":"amountOutLeft","type":"uint128"},{"internalType":"uint128","name":"fee","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ILBPair","name":"pair","type":"address"},{"internalType":"uint128","name":"amountIn","type":"uint128"},{"internalType":"bool","name":"swapForY","type":"bool"}],"name":"getSwapOut","outputs":[{"internalType":"uint128","name":"amountInLeft","type":"uint128"},{"internalType":"uint128","name":"amountOut","type":"uint128"},{"internalType":"uint128","name":"fee","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getV1Factory","outputs":[{"internalType":"contract IJoeFactory","name":"factoryV1","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getWNATIVE","outputs":[{"internalType":"contract IWNATIVE","name":"wnative","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"tokenX","type":"address"},{"internalType":"contract IERC20","name":"tokenY","type":"address"},{"internalType":"uint16","name":"binStep","type":"uint16"},{"internalType":"uint256","name":"amountXMin","type":"uint256"},{"internalType":"uint256","name":"amountYMin","type":"uint256"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"removeLiquidity","outputs":[{"internalType":"uint256","name":"amountX","type":"uint256"},{"internalType":"uint256","name":"amountY","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint16","name":"binStep","type":"uint16"},{"internalType":"uint256","name":"amountTokenMin","type":"uint256"},{"internalType":"uint256","name":"amountNATIVEMin","type":"uint256"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"removeLiquidityNATIVE","outputs":[{"internalType":"uint256","name":"amountToken","type":"uint256"},{"internalType":"uint256","name":"amountNATIVE","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactNATIVEForTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactNATIVEForTokensSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinNATIVE","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForNATIVE","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinNATIVE","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForNATIVESupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokensSupportingFeeOnTransferTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapNATIVEForExactTokens","outputs":[{"internalType":"uint256[]","name":"amountsIn","type":"uint256[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountNATIVEOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address payable","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactNATIVE","outputs":[{"internalType":"uint256[]","name":"amountsIn","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"components":[{"internalType":"uint256[]","name":"pairBinSteps","type":"uint256[]"},{"internalType":"enum ILBRouter.Version[]","name":"versions","type":"uint8[]"},{"internalType":"contract IERC20[]","name":"tokenPath","type":"address[]"}],"internalType":"struct ILBRouter.Path","name":"path","type":"tuple"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapTokensForExactTokens","outputs":[{"internalType":"uint256[]","name":"amountsIn","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sweep","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ILBToken","name":"lbToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"sweepLBToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101206040523480156200001257600080fd5b50604051620054b6380380620054b6833981016040819052620000359162000078565b6001600160a01b0394851660805292841660a05290831660c052821660e0521661010052620000f8565b6001600160a01b03811681146200007557600080fd5b50565b600080600080600060a086880312156200009157600080fd5b85516200009e816200005f565b6020870151909550620000b1816200005f565b6040870151909450620000c4816200005f565b6060870151909350620000d7816200005f565b6080870151909250620000ea816200005f565b809150509295509295909350565b60805160a05160c05160e051610100516152d1620001e5600039600081816101aa015281816103090152818161065e0152818161073c0152818161082c015281816108ec015281816109e901528181610d6901528181610eec015281816113d501528181611621015281816116b0015281816119f501528181611af001528181611d0f01528181611ff601528181612fdd015261305b0152600081816104d90152612d8a01526000818161033c0152613a5001526000818161050c01526141e80152600081816103a40152818161118a0152818161132d015281816121f00152613af401526152d16000f3fe60806040526004361061019a5760003560e01c806392fe8e70116100e1578063ba8465231161008a578063d0e380f211610064578063d0e380f214610550578063e038e6dc14610570578063e9361c0814610583578063f96fe925146105a357600080fd5b8063ba846523146104ca578063bb558a9f146104fd578063c22159b61461053057600080fd5b8063a0d376cf116100bb578063a0d376cf14610477578063a3c7271a14610497578063b066ea7c146104b757600080fd5b806392fe8e70146103ed578063964f987c1461040d5780639ab6156b1461045757600080fd5b8063659ac74b1161014357806381c2fdfb1161011d57806381c2fdfb1461036057806388cc58e4146103955780638efc2b2c146103c857600080fd5b8063659ac74b146102c25780636c9c0078146102fa57806371d1974a1461032d57600080fd5b80633dc8f8ec116101745780633dc8f8ec146102625780634b8018701461028257806362c06767146102a257600080fd5b80631a24f9a9146101ef5780632075ad22146102225780632a443fae1461024257600080fd5b366101ea57336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146101e857604051636c8cb79360e01b815260040160405180910390fd5b005b600080fd5b3480156101fb57600080fd5b5061020f61020a36600461477f565b6105d7565b6040519081526020015b60405180910390f35b6102356102303660046147ea565b610967565b6040516102199190614886565b34801561024e57600080fd5b5061020f61025d36600461477f565b610bc7565b34801561026e57600080fd5b5061023561027d36600461477f565b610ce7565b34801561028e57600080fd5b5061020f61029d36600461477f565b610f5a565b3480156102ae57600080fd5b506101e86102bd366004614899565b611188565b3480156102ce57600080fd5b506102e26102dd366004614906565b6112ee565b6040516001600160a01b039091168152602001610219565b34801561030657600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006102e2565b34801561033957600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006102e2565b34801561036c57600080fd5b5061038061037b366004614962565b6113a5565b60408051928352602083019190915201610219565b3480156103a157600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006102e2565b6103db6103d6366004614a1d565b611541565b60405161021996959493929190614a59565b3480156103f957600080fd5b5061023561040836600461477f565b6117a1565b34801561041957600080fd5b5061042d610428366004614ac6565b6118e3565b604080516001600160801b0394851681529284166020840152921691810191909152606001610219565b34801561046357600080fd5b5061020f61047236600461477f565b611973565b34801561048357600080fd5b5061042d610492366004614ac6565b611b5e565b3480156104a357600080fd5b506103db6104b2366004614a1d565b611ba2565b61020f6104c53660046147ea565b611c8d565b3480156104d657600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006102e2565b34801561050957600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006102e2565b34801561053c57600080fd5b5061038061054b366004614b11565b611e07565b34801561055c57600080fd5b5061020f61056b366004614bd9565b611efd565b61020f61057e3660046147ea565b611f74565b34801561058f57600080fd5b506101e861059e366004614c5e565b6121ee565b3480156105af57600080fd5b506105c36105be366004614cf3565b612311565b60405162ffffff9091168152602001610219565b600081804211156106095760405163dae7ca7d60e01b8152600481018290524260248201526044015b60405180910390fd5b84515185901580610621575080515160208201515114155b8061063e575060408101515181515161063b906001614d35565b14155b1561065c5760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168660400151876000015151815181106106a1576106a1614d4d565b60200260200101516001600160a01b031614610700576040860151865151815181106106cf576106cf614d4d565b602002602001015160405163cfec0e0160e01b815260040161060091906001600160a01b0391909116815260200190565b600061071987600001518860200151896040015161237d565b6040516370a0823160e01b81523060048201529091506000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa158015610783573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a79190614d63565b905061080133836000815181106107c0576107c0614d4d565b60200260200101518c8b604001516000815181106107e0576107e0614d4d565b60200260200101516001600160a01b031661248d909392919063ffffffff16565b6108158289602001518a604001513061254c565b6040516370a0823160e01b815230600482015281907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa15801561087b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061089f9190614d63565b6108a99190614d7c565b9450848911156108d6576040516313fab00360e21b8152600481018a905260248101869052604401610600565b604051632e1a7d4d60e01b8152600481018690527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b15801561093857600080fd5b505af115801561094c573d6000803e3d6000fd5b5050505061095a8786612ab4565b5050505095945050505050565b606081804211156109945760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806109ac575080515160208201515114155b806109c957506040810151518151516109c6906001614d35565b14155b156109e75760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168660400151600081518110610a2857610a28614d4d565b60200260200101516001600160a01b031614610a555785604001516000815181106106cf576106cf614d4d565b6000610a6e87600001518860200151896040015161237d565b9050610a8487602001518289604001518b612b3a565b93503484600081518110610a9a57610a9a614d4d565b60200260200101511115610ae8573484600081518110610abc57610abc614d4d565b602002602001015160405163194ee21960e31b8152600401610600929190918252602082015260400190565b610b2681600081518110610afe57610afe614d4d565b602002602001015185600081518110610b1957610b19614d4d565b6020026020010151612fdb565b6000610b3d8289602001518a60400151888b61308a565b905088811015610b6a576040516313fab00360e21b8152600481018a905260248101829052604401610600565b84600081518110610b7d57610b7d614d4d565b6020026020010151341115610bbb57610bbb3386600081518110610ba357610ba3614d4d565b602002602001015134610bb69190614d7c565b612ab4565b50505050949350505050565b60008180421115610bf45760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610c0c575080515160208201515114155b80610c295750604081015151815151610c26906001614d35565b14155b15610c475760405163b91b4d4d60e01b815260040160405180910390fd5b6000610c6087600001518860200151896040015161237d565b9050610c993382600081518110610c7957610c79614d4d565b60200260200101518b8a604001516000815181106107e0576107e0614d4d565b610cae898289602001518a604001518a6134c5565b935083881115610cdb576040516313fab00360e21b81526004810189905260248101859052604401610600565b50505095945050505050565b60608180421115610d145760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610d2c575080515160208201515114155b80610d495750604081015151815151610d46906001614d35565b14155b15610d675760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316866040015187600001515181518110610dac57610dac614d4d565b60200260200101516001600160a01b031614610dda576040860151865151815181106106cf576106cf614d4d565b6000610df387600001518860200151896040015161237d565b9050610e0987602001518289604001518c612b3a565b93508784600081518110610e1f57610e1f614d4d565b60200260200101511115610e41578784600081518110610abc57610abc614d4d565b610e923382600081518110610e5857610e58614d4d565b602002602001015186600081518110610e7357610e73614d4d565b60200260200101518a604001516000815181106107e0576107e0614d4d565b6000610ea98289602001518a60400151883061308a565b905089811015610ed6576040516313fab00360e21b8152600481018b905260248101829052604401610600565b604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b158015610f3857600080fd5b505af1158015610f4c573d6000803e3d6000fd5b5050505061095a8782612ab4565b60008180421115610f875760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610f9f575080515160208201515114155b80610fbc5750604081015151815151610fb9906001614d35565b14155b15610fda5760405163b91b4d4d60e01b815260040160405180910390fd5b6000610ff387600001518860200151896040015161237d565b90506000876040015182518151811061100e5761100e614d4d565b60209081029190910101516040516370a0823160e01b81526001600160a01b0389811660048301529192506000918316906370a0823190602401602060405180830381865afa158015611065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110899190614d63565b90506110c233846000815181106110a2576110a2614d4d565b60200260200101518d8c604001516000815181106107e0576107e0614d4d565b6110d6838a602001518b604001518b61254c565b6040516370a0823160e01b81526001600160a01b0389811660048301528291908416906370a0823190602401602060405180830381865afa15801561111f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111439190614d63565b61114d9190614d7c565b9550858a111561117a576040516313fab00360e21b8152600481018b905260248101879052604401610600565b505050505095945050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061120a9190614d93565b6001600160a01b0316336001600160a01b03161461123b57604051635d9515b960e11b815260040160405180910390fd5b6001600160a01b038316611265576000198114156112565750475b6112608282612ab4565b505050565b6000198114156112da576040516370a0823160e01b81523060048201526001600160a01b038416906370a0823190602401602060405180830381865afa1580156112b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112d79190614d63565b90505b6112606001600160a01b0384168383613950565b60405163659ac74b60e01b81526001600160a01b038581166004830152848116602483015262ffffff8416604483015261ffff831660648301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063659ac74b906084016020604051808303816000875af1158015611378573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061139c9190614d93565b95945050505050565b60008082804211156113d35760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b7f000000000000000000000000000000000000000000000000000000000000000060006114078d8361ffff8f166002613a06565b90506000816001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611449573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146d9190614d93565b6001600160a01b0316836001600160a01b03161490508061148c57999a995b60008061149d848f8f8f8f30613baf565b91509150826114ad5780826114b0565b81815b90985096506114cd925050506001600160a01b038e168887613950565b604051632e1a7d4d60e01b8152600481018590526001600160a01b03831690632e1a7d4d90602401600060405180830381600087803b15801561150f57600080fd5b505af1158015611523573d6000803e3d6000fd5b505050506115318785612ab4565b5050509850989650505050505050565b60008080806060808261157661155a60208a018a614db0565b61156a60408b0160208c01614db0565b8a604001356002613a06565b9050806001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115da9190614d93565b6001600160a01b03166115f060208a018a614db0565b6001600160a01b0316146116175760405163b33f8ab960e01b815260040160405180910390fd5b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001661164e60208a018a614db0565b6001600160a01b03161480156116675750348860600135145b156116a6576116768134612fdb565b6116a1338260808b013561169060408d0160208e01614db0565b6001600160a01b031692919061248d565b611782565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166116e060408a0160208b01614db0565b6001600160a01b03161480156116f95750348860800135145b1561171f57611715338260608b013561169060208d018d614db0565b6116a18134612fdb565b61172c6020890189614db0565b61173c60408a0160208b01614db0565b60405163d0a4f13b60e01b81526001600160a01b03928316600482015291166024820152606089013560448201526080890135606482015234608482015260a401610600565b61178c8882613d11565b949d939c50919a509850965090945092505050565b606081804211156117ce5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806117e6575080515160208201515114155b806118035750604081015151815151611800906001614d35565b14155b156118215760405163b91b4d4d60e01b815260040160405180910390fd5b600061183a87600001518860200151896040015161237d565b905061185087602001518289604001518c612b3a565b9350878460008151811061186657611866614d4d565b60200260200101511115611888578784600081518110610abc57610abc614d4d565b61189f3382600081518110610e5857610e58614d4d565b60006118b68289602001518a60400151888b61308a565b90508981101561095a576040516313fab00360e21b8152600481018b905260248101829052604401610600565b604051630abcd78360e41b81526001600160801b03831660048201528115156024820152600090819081906001600160a01b0387169063abcd7830906044015b606060405180830381865afa158015611940573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119649190614dcd565b91989097509095509350505050565b600081804211156119a05760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806119b8575080515160208201515114155b806119d557506040810151518151516119d2906001614d35565b14155b156119f35760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316866040015187600001515181518110611a3857611a38614d4d565b60200260200101516001600160a01b031614611a66576040860151865151815181106106cf576106cf614d4d565b6000611a7f87600001518860200151896040015161237d565b9050611a983382600081518110610c7957610c79614d4d565b611aad898289602001518a60400151306134c5565b935083881115611ada576040516313fab00360e21b81526004810189905260248101859052604401610600565b604051632e1a7d4d60e01b8152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b158015611b3c57600080fd5b505af1158015611b50573d6000803e3d6000fd5b50505050610cdb8685612ab4565b604051631cee6cdf60e31b81526001600160801b03831660048201528115156024820152600090819081906001600160a01b0387169063e77366f890604401611923565b600080808060608082611bbb61155a60208a018a614db0565b9050806001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bfb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1f9190614d93565b6001600160a01b0316611c3560208a018a614db0565b6001600160a01b031614611c5c5760405163b33f8ab960e01b815260040160405180910390fd5b611c73338260608b013561169060208d018d614db0565b611782338260808b013561169060408d0160208e01614db0565b60008180421115611cba5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580611cd2575080515160208201515114155b80611cef5750604081015151815151611cec906001614d35565b14155b15611d0d5760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168660400151600081518110611d4e57611d4e614d4d565b60200260200101516001600160a01b031614611d7b5785604001516000815181106106cf576106cf614d4d565b6000611d9487600001518860200151896040015161237d565b9050611dba81600081518110611dac57611dac614d4d565b602002602001015134612fdb565b611dcf348289602001518a604001518a6134c5565b935083881115611dfc576040516313fab00360e21b81526004810189905260248101859052604401610600565b505050949350505050565b6000808280421115611e355760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b6000611e488d8d8d61ffff166002613a06565b90506000816001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e8a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eae9190614d93565b6001600160a01b03168e6001600160a01b0316141590508015611ecf579899985b611edd828c8c8c8c8c613baf565b90955093508015611eec579293925b505050995099975050505050505050565b604051634c7cffbd60e01b815262ffffff821660048201526000906001600160a01b03841690634c7cffbd90602401602060405180830381865afa158015611f49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f6d9190614d63565b9392505050565b60008180421115611fa15760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580611fb9575080515160208201515114155b80611fd65750604081015151815151611fd3906001614d35565b14155b15611ff45760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316866040015160008151811061203557612035614d4d565b60200260200101516001600160a01b0316146120625785604001516000815181106106cf576106cf614d4d565b600061207b87600001518860200151896040015161237d565b90506000876040015182518151811061209657612096614d4d565b60209081029190910101516040516370a0823160e01b81526001600160a01b0389811660048301529192506000918316906370a0823190602401602060405180830381865afa1580156120ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121119190614d63565b905061212983600081518110611dac57611dac614d4d565b61213d838a602001518b604001518b61254c565b6040516370a0823160e01b81526001600160a01b0389811660048301528291908416906370a0823190602401602060405180830381865afa158015612186573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121aa9190614d63565b6121b49190614d7c565b9550858a11156121e1576040516313fab00360e21b8152600481018b905260248101879052604401610600565b5050505050949350505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561224c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122709190614d93565b6001600160a01b0316336001600160a01b0316146122a157604051635d9515b960e11b815260040160405180910390fd5b6040516305feb5ff60e21b81526001600160a01b038716906317fad7fc906122d790309089908990899089908990600401614e5e565b600060405180830381600087803b1580156122f157600080fd5b505af1158015612305573d6000803e3d6000fd5b50505050505050505050565b60405163f5e2932960e01b8152600481018290526000906001600160a01b0384169063f5e2932990602401602060405180830381865afa158015612359573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f6d9190614e9e565b6060835167ffffffffffffffff811115612399576123996144da565b6040519080825280602002602001820160405280156123c2578160200160208202803683370190505b509050600080836000815181106123db576123db614d4d565b6020026020010151905060005b83518110156124835781925084816001018151811061240957612409614d4d565b60200260200101519150612451838389848151811061242a5761242a614d4d565b602002602001015189858151811061244457612444614d4d565b60200260200101516141a6565b84828151811061246357612463614d4d565b6001600160a01b03909216602092830291909101909101526001016123e8565b5050509392505050565b604080516001600160a01b038581166024830152848116604483015260648083018590528351808403909101815260849092019092526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166323b872dd60e01b17905290600090612502908716836142a7565b9050600081511180156125265750808060200190518101906125249190614ebb565b155b156125445760405163197138bd60e11b815260040160405180910390fd5b505050505050565b60008060008060008660008151811061256757612567614d4d565b6020026020010151905060005b89518110156123055789818151811061258f5761258f614d4d565b602002602001015192508881815181106125ab576125ab614d4d565b602002602001015194508195508781600101815181106125cd576125cd614d4d565b6020026020010151915089518160010114612604578981600101815181106125f7576125f7614d4d565b6020026020010151612606565b865b9350600085600281111561261c5761261c614ed8565b14156128c357600080846001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa158015612663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126879190614f05565b506001600160701b031691506001600160701b03169150836001600160a01b0316886001600160a01b031610156127bc576040516370a0823160e01b81526001600160a01b03868116600483015260009184918b16906370a0823190602401602060405180830381865afa158015612703573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127279190614d63565b039050600061273782858561436d565b60405163022c0d9f60e01b8152600060048201819052602482018390526001600160a01b038b811660448401526080606484015260848301919091529192509088169063022c0d9f9060a401600060405180830381600087803b15801561279d57600080fd5b505af11580156127b1573d6000803e3d6000fd5b5050505050506128bc565b6040516370a0823160e01b81526001600160a01b03868116600483015260009183918b16906370a0823190602401602060405180830381865afa158015612807573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061282b9190614d63565b039050600061283b82848661436d565b60405163022c0d9f60e01b8152600481018290526000602482018190526001600160a01b038b811660448401526080606484015260848301919091529192509088169063022c0d9f9060a401600060405180830381600087803b1580156128a157600080fd5b505af11580156128b5573d6000803e3d6000fd5b5050505050505b5050612aac565b60018560028111156128d7576128d7614ed8565b14156129c357826001600160a01b03166353c059a0846001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa15801561292a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061294e9190614d93565b60405160e083901b6001600160e01b03191681526001600160a01b03918216868316146004820152908716602482015260440160408051808303816000875af115801561299f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128bc9190614f4a565b826001600160a01b03166353c059a0846001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a10573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a349190614d93565b60405160e083901b6001600160e01b03191681526001600160a01b0391821686831614600482015290871660248201526044016020604051808303816000875af1158015612a86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612aaa9190614d63565b505b600101612574565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114612b01576040519150601f19603f3d011682016040523d82523d6000602084013e612b06565b606091505b50509050806112605760405163047b96f760e41b81526001600160a01b038416600482015260248101839052604401610600565b6060825167ffffffffffffffff811115612b5657612b566144da565b604051908082528060200260200182016040528015612b7f578160200160208202803683370190505b5090508181855181518110612b9657612b96614d4d565b602090810291909101015283515b8015612fd257600084612bb8600184614d7c565b81518110612bc857612bc8614d4d565b60200260200101519050600087600184612be29190614d7c565b81518110612bf257612bf2614d4d565b60200260200101519050600087600185612c0c9190614d7c565b81518110612c1c57612c1c614d4d565b6020026020010151905060006002811115612c3957612c39614ed8565b826002811115612c4b57612c4b614ed8565b1415612d6e57600080826001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa158015612c92573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cb69190614f05565b506001600160701b031691506001600160701b03169150888681518110612cdf57612cdf614d4d565b60200260200101516001600160a01b0316856001600160a01b03161115612d0257905b6000878781518110612d1657612d16614d4d565b60200260200101519050612d358383836144049092919063ffffffff16565b6001600160801b031688612d4a60018a614d7c565b81518110612d5a57612d5a614d4d565b602002602001018181525050505050612fbc565b6001826002811115612d8257612d82614ed8565b1415612eef577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635bdd4b7c82878781518110612dca57612dca614d4d565b6020026020010151866001600160a01b0316856001600160a01b03166316dc165b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612e1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e3e9190614d93565b6040516001600160e01b031960e087901b1681526001600160a01b0394851660048201526001600160801b0390931660248401529092169190911460448201526064016040805180830381865afa158015612e9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ec19190614f4a565b5085612ece600187614d7c565b81518110612ede57612ede614d4d565b602002602001018181525050612fbc565b612f8881868681518110612f0557612f05614d4d565b6020026020010151856001600160a01b0316846001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f799190614d93565b6001600160a01b0316146118e3565b50506001600160801b031685612f9f600187614d7c565b81518110612faf57612faf614d4d565b6020026020010181815250505b5050508080612fca90614f6e565b915050612ba4565b50949350505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561303657600080fd5b505af115801561304a573d6000803e3d6000fd5b506130869350506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016915084905083613950565b5050565b600080600080600080886000815181106130a6576130a6614d4d565b6020026020010151905060005b8b518110156134b6578b81815181106130ce576130ce614d4d565b602002602001015193508a81815181106130ea576130ea614d4d565b6020026020010151925081955089816001018151811061310c5761310c614d4d565b602002602001015191508b518160010114613143578b816001018151811061313657613136614d4d565b6020026020010151613145565b875b9450600083600281111561315b5761315b614ed8565b14156132675788816001018151811061317657613176614d4d565b60200260200101519650816001600160a01b0316866001600160a01b0316101561321a5760405163022c0d9f60e01b8152600060048201819052602482018990526001600160a01b03878116604484015260806064840152608483019190915285169063022c0d9f9060a4015b600060405180830381600087803b1580156131fd57600080fd5b505af1158015613211573d6000803e3d6000fd5b505050506134ae565b60405163022c0d9f60e01b8152600481018890526000602482018190526001600160a01b03878116604484015260806064840152608483019190915285169063022c0d9f9060a4016131e3565b600183600281111561327b5761327b614ed8565b1415613384576000846001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156132c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132e59190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052888316602483015292506000918291908816906353c059a09060440160408051808303816000875af1158015613342573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133669190614f4a565b9150915082156133785780995061337c565b8199505b5050506134ae565b6000846001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133e89190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052888316602483015292506000918291613482918916906353c059a0906044015b6020604051808303816000875af115801561344a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061346e9190614d63565b6001600160801b0381169160809190911c90565b6001600160801b031691506001600160801b0316915082156134a6578099506134aa565b8199505b5050505b6001016130b3565b50505050505095945050505050565b600080600080600080876000815181106134e1576134e1614d4d565b602002602001015190508a955060005b8a518110156134b6578a818151811061350c5761350c614d4d565b6020026020010151925089818151811061352857613528614d4d565b6020026020010151945081955088816001018151811061354a5761354a614d4d565b602002602001015191508a518160010114613581578a816001018151811061357457613574614d4d565b6020026020010151613583565b875b9350600085600281111561359957613599614ed8565b141561375457600080846001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa1580156135e0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136049190614f05565b506001600160701b031691506001600160701b03169150836001600160a01b0316886001600160a01b031610156136c35761364089838361436d565b60405163022c0d9f60e01b8152600060048201819052602482018390526001600160a01b038981166044840152608060648401526084830191909152919a509086169063022c0d9f9060a401600060405180830381600087803b1580156136a657600080fd5b505af11580156136ba573d6000803e3d6000fd5b5050505061374d565b6136ce89828461436d565b60405163022c0d9f60e01b8152600481018290526000602482018190526001600160a01b038981166044840152608060648401526084830191909152919a509086169063022c0d9f9060a401600060405180830381600087803b15801561373457600080fd5b505af1158015613748573d6000803e3d6000fd5b505050505b5050613948565b600185600281111561376857613768614ed8565b1415613871576000836001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137d29190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052878316602483015292506000918291908716906353c059a09060440160408051808303816000875af115801561382f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138539190614f4a565b91509150821561386557809950613869565b8199505b505050613948565b6000836001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138d59190614d93565b60405163029e02cd60e51b81526001600160a01b03918216858316146004820181905287831660248301529250600091829161391c918816906353c059a09060440161342b565b6001600160801b031691506001600160801b03169150821561394057809950613944565b8199505b5050505b6001016134f1565b604080516001600160a01b03848116602483015260448083018590528351808403909101815260649092019092526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663a9059cbb60e01b179052906000906139bd908616836142a7565b9050600081511180156139e15750808060200190518101906139df9190614ebb565b155b156139ff5760405163197138bd60e11b815260040160405180910390fd5b5050505050565b60006001826002811115613a1c57613a1c614ed8565b1415613ac65760405163704037bd60e01b81526001600160a01b0386811660048301528581166024830152604482018590527f0000000000000000000000000000000000000000000000000000000000000000169063704037bd90606401608060405180830381865afa158015613a97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613abb9190614f85565b602001519050613b66565b60405163704037bd60e01b81526001600160a01b0386811660048301528581166024830152604482018590527f0000000000000000000000000000000000000000000000000000000000000000169063704037bd90606401608060405180830381865afa158015613b3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b5f9190614f85565b6020015190505b6001600160a01b038116613ba757604051636b2471d160e11b81526001600160a01b0380871660048301528516602482015260448101849052606401610600565b949350505050565b6000806000886001600160a01b031663c9939f5e338689896040518563ffffffff1660e01b8152600401613be69493929190614fec565b6000604051808303816000875af1158015613c05573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613c2d919081019061502a565b905060005b8151811015613cc157613c64828281518110613c5057613c50614d4d565b60200260200101516001600160801b031690565b613c77906001600160801b031685614d35565b9350613c9c828281518110613c8e57613c8e614d4d565b602002602001015160801c90565b613caf906001600160801b031684614d35565b9250613cba816150b0565b9050613c32565b5087831080613ccf57508682105b15613d05576040516318ccfb7760e11b815260048101899052602481018490526044810188905260648101839052608401610600565b50965096945050505050565b600080600080606080876101c0013580421115613d4a5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b613d586101408a018a6150cb565b9050613d686101208b018b6150cb565b9050141580613d955750613d806101608a018a6150cb565b9050613d906101208b018b6150cb565b905014155b15613db35760405163b91b4d4d60e01b815260040160405180910390fd5b62ffffff60e08a01351180613dcf575062ffffff6101008a0135115b15613dfe5760405163197a55c760e11b815260e08a013560048201526101008a01356024820152604401610600565b6000613e0e6101208b018b6150cb565b905067ffffffffffffffff811115613e2857613e286144da565b604051908082528060200260200182016040528015613e51578160200160208202803683370190505b509050613e626101208b018b6150cb565b905067ffffffffffffffff811115613e7c57613e7c6144da565b604051908082528060200260200182016040528015613ea5578160200160208202803683370190505b5093506000896001600160a01b031663dbe65edc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f0c9190614e9e565b62ffffff169050808b61010001358c60e00135011080613f3657508a60e001358b61010001358201105b15613f6c57604051637d50edab60e11b815260e08c013560048201526101008c0135602482015260448101829052606401610600565b60005b825181101561406f576000613f886101208e018e6150cb565b83818110613f9857613f98614d4d565b90506020020135830190506000811280613fb4575062ffffff81115b15613fd5576040516370a82e6160e11b815260048101829052602401610600565b80878381518110613fe857613fe8614d4d565b60209081029190910101526140496140046101408f018f6150cb565b8481811061401457614014614d4d565b905060200201358e80610160019061402c91906150cb565b8581811061403c5761403c614d4d565b90506020020135836144a0565b84838151811061405b5761405b614d4d565b602090810291909101015250600101613f6f565b50506000808a6001600160a01b031663383d15c58d6101800160208101906140979190614db0565b858f6101a00160208101906140ac9190614db0565b6040518463ffffffff1660e01b81526004016140ca93929190615115565b6000604051808303816000875af11580156140e9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526141119190810190615179565b6001600160801b0383169c50608083901c9b509650909250905060a08c01358a108061414057508b60c0013589105b1561417c576040516318ccfb7760e11b815260a08d01356004820152602481018b905260c08d01356044820152606481018a9052608401610600565b6001600160801b0381169750608081901c6001600160801b03169650505050509295509295509295565b6000808260028111156141bb576141bb614ed8565b141561429b5760405163e6a4390560e01b81526001600160a01b03868116600483015285811660248301527f0000000000000000000000000000000000000000000000000000000000000000169063e6a4390590604401602060405180830381865afa15801561422f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906142539190614d93565b90506001600160a01b03811661429657604051636b2471d160e11b81526001600160a01b0380871660048301528516602482015260448101849052606401610600565b613ba7565b61139c85858585613a06565b6060600080846001600160a01b0316846040516142c4919061521f565b6000604051808303816000865af19150503d8060008114614301576040519150601f19603f3d011682016040523d82523d6000602084013e614306565b606091505b5091509150811561434657805115801561432857506001600160a01b0385163b155b1561429657604051633b99915360e21b815260040160405180910390fd5b8051614365576040516373483fab60e11b815260040160405180910390fd5b805181602001fd5b60008361438d5760405163b229ed3360e01b815260040160405180910390fd5b821580614398575081155b156143b6576040516398c59a2960e01b815260040160405180910390fd5b60006143c4856103e561525a565b905060006143d2848361525a565b90506000826143e3876103e861525a565b6143ed9190614d35565b90506143f98183615279565b979650505050505050565b6000836144245760405163b229ed3360e01b815260040160405180910390fd5b82158061442f575081155b1561444d576040516398c59a2960e01b815260040160405180910390fd5b6000614459858561525a565b614465906103e861525a565b905060006144738685614d7c565b61447f906103e561525a565b905061448b8183615279565b614496906001614d35565b9695505050505050565b601882901b6affffffffffffffff00000016605884901b72ffffffffffffffff0000000000000000000000161762ffffff82168117613ba7565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff81118282101715614513576145136144da565b60405290565b6040516080810167ffffffffffffffff81118282101715614513576145136144da565b604051601f8201601f1916810167ffffffffffffffff81118282101715614565576145656144da565b604052919050565b600067ffffffffffffffff821115614587576145876144da565b5060051b60200190565b600082601f8301126145a257600080fd5b813560206145b76145b28361456d565b61453c565b82815260059290921b840181019181810190868411156145d657600080fd5b8286015b848110156145f157803583529183019183016145da565b509695505050505050565b6001600160a01b038116811461461157600080fd5b50565b803561461f816145fc565b919050565b600082601f83011261463557600080fd5b813560206146456145b28361456d565b82815260059290921b8401810191818101908684111561466457600080fd5b8286015b848110156145f157803561467b816145fc565b8352918301918301614668565b60006060828403121561469a57600080fd5b6146a26144f0565b9050813567ffffffffffffffff808211156146bc57600080fd5b6146c885838601614591565b83526020915081840135818111156146df57600080fd5b8401601f810186136146f057600080fd5b80356146fe6145b28261456d565b81815260059190911b8201840190848101908883111561471d57600080fd5b928501925b828410156147495783356003811061473a5760008081fd5b82529285019290850190614722565b808688015250505050604084013591508082111561476657600080fd5b5061477384828501614624565b60408301525092915050565b600080600080600060a0868803121561479757600080fd5b8535945060208601359350604086013567ffffffffffffffff8111156147bc57600080fd5b6147c888828901614688565b93505060608601356147d9816145fc565b949793965091946080013592915050565b6000806000806080858703121561480057600080fd5b84359350602085013567ffffffffffffffff81111561481e57600080fd5b61482a87828801614688565b935050604085013561483b816145fc565b9396929550929360600135925050565b600081518084526020808501945080840160005b8381101561487b5781518752958201959082019060010161485f565b509495945050505050565b602081526000611f6d602083018461484b565b6000806000606084860312156148ae57600080fd5b83356148b9816145fc565b925060208401356148c9816145fc565b929592945050506040919091013590565b62ffffff8116811461461157600080fd5b61ffff8116811461461157600080fd5b803561461f816148eb565b6000806000806080858703121561491c57600080fd5b8435614927816145fc565b93506020850135614937816145fc565b92506040850135614947816148da565b91506060850135614957816148eb565b939692955090935050565b600080600080600080600080610100898b03121561497f57600080fd5b883561498a816145fc565b9750602089013561499a816148eb565b96506040890135955060608901359450608089013567ffffffffffffffff808211156149c557600080fd5b6149d18c838d01614591565b955060a08b01359150808211156149e757600080fd5b506149f48b828c01614591565b93505060c0890135614a05816145fc565b8092505060e089013590509295985092959890939650565b600060208284031215614a2f57600080fd5b813567ffffffffffffffff811115614a4657600080fd5b82016101e08185031215611f6d57600080fd5b86815285602082015284604082015283606082015260c060808201526000614a8460c083018561484b565b82810360a0840152614a96818561484b565b9998505050505050505050565b6001600160801b038116811461461157600080fd5b801515811461461157600080fd5b600080600060608486031215614adb57600080fd5b8335614ae6816145fc565b92506020840135614af681614aa3565b91506040840135614b0681614ab8565b809150509250925092565b60008060008060008060008060006101208a8c031215614b3057600080fd5b8935614b3b816145fc565b985060208a0135614b4b816145fc565b9750614b5960408b016148fb565b965060608a0135955060808a0135945060a08a013567ffffffffffffffff80821115614b8457600080fd5b614b908d838e01614591565b955060c08c0135915080821115614ba657600080fd5b50614bb38c828d01614591565b935050614bc260e08b01614614565b91506101008a013590509295985092959850929598565b60008060408385031215614bec57600080fd5b8235614bf7816145fc565b91506020830135614c07816148da565b809150509250929050565b60008083601f840112614c2457600080fd5b50813567ffffffffffffffff811115614c3c57600080fd5b6020830191508360208260051b8501011115614c5757600080fd5b9250929050565b60008060008060008060808789031215614c7757600080fd5b8635614c82816145fc565b95506020870135614c92816145fc565b9450604087013567ffffffffffffffff80821115614caf57600080fd5b614cbb8a838b01614c12565b90965094506060890135915080821115614cd457600080fd5b50614ce189828a01614c12565b979a9699509497509295939492505050565b60008060408385031215614d0657600080fd5b8235614d11816145fc565b946020939093013593505050565b634e487b7160e01b600052601160045260246000fd5b60008219821115614d4857614d48614d1f565b500190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215614d7557600080fd5b5051919050565b600082821015614d8e57614d8e614d1f565b500390565b600060208284031215614da557600080fd5b8151611f6d816145fc565b600060208284031215614dc257600080fd5b8135611f6d816145fc565b600080600060608486031215614de257600080fd5b8351614ded81614aa3565b6020850151909350614dfe81614aa3565b6040850151909250614b0681614aa3565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115614e4157600080fd5b8260051b8083602087013760009401602001938452509192915050565b60006001600160a01b03808916835280881660208401525060806040830152614e8b608083018688614e0f565b8281036060840152614a96818587614e0f565b600060208284031215614eb057600080fd5b8151611f6d816148da565b600060208284031215614ecd57600080fd5b8151611f6d81614ab8565b634e487b7160e01b600052602160045260246000fd5b80516001600160701b038116811461461f57600080fd5b600080600060608486031215614f1a57600080fd5b614f2384614eee565b9250614f3160208501614eee565b9150604084015163ffffffff81168114614b0657600080fd5b60008060408385031215614f5d57600080fd5b505080516020909101519092909150565b600081614f7d57614f7d614d1f565b506000190190565b600060808284031215614f9757600080fd5b614f9f614519565b8251614faa816148eb565b81526020830151614fba816145fc565b60208201526040830151614fcd81614ab8565b60408201526060830151614fe081614ab8565b60608201529392505050565b60006001600160a01b03808716835280861660208401525060806040830152615018608083018561484b565b82810360608401526143f9818561484b565b6000602080838503121561503d57600080fd5b825167ffffffffffffffff81111561505457600080fd5b8301601f8101851361506557600080fd5b80516150736145b28261456d565b81815260059190911b8201830190838101908783111561509257600080fd5b928401925b828410156143f957835182529284019290840190615097565b60006000198214156150c4576150c4614d1f565b5060010190565b6000808335601e198436030181126150e257600080fd5b83018035915067ffffffffffffffff8211156150fd57600080fd5b6020019150600581901b3603821315614c5757600080fd5b6000606082016001600160a01b0380871684526020606081860152828751808552608087019150828901945060005b8181101561516057855183529483019491830191600101615144565b5050809450505080851660408501525050949350505050565b60008060006060848603121561518e57600080fd5b835192506020808501519250604085015167ffffffffffffffff8111156151b457600080fd5b8501601f810187136151c557600080fd5b80516151d36145b28261456d565b81815260059190911b820183019083810190898311156151f257600080fd5b928401925b82841015615210578351825292840192908401906151f7565b80955050505050509250925092565b6000825160005b818110156152405760208186018101518583015201615226565b8181111561524f576000828501525b509190910192915050565b600081600019048311821515161561527457615274614d1f565b500290565b60008261529657634e487b7160e01b600052601260045260246000fd5b50049056fea2646970667358221220b39aa5e8e65e5f7732083a1f46863bf4c9fe3dc8a0635e6b8d2ee3e6c3d73b0b64736f6c634300080a00330000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e000000000000000000000000ae4ec9901c3076d0ddbe76a520f9e90a6227acb70000000000000000000000001886d09c9ade0c5db822d85d21678db67b6c29820000000000000000000000007bfd7192e76d950832c77bb412aae841049d8d9b00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1

Deployed Bytecode

0x60806040526004361061019a5760003560e01c806392fe8e70116100e1578063ba8465231161008a578063d0e380f211610064578063d0e380f214610550578063e038e6dc14610570578063e9361c0814610583578063f96fe925146105a357600080fd5b8063ba846523146104ca578063bb558a9f146104fd578063c22159b61461053057600080fd5b8063a0d376cf116100bb578063a0d376cf14610477578063a3c7271a14610497578063b066ea7c146104b757600080fd5b806392fe8e70146103ed578063964f987c1461040d5780639ab6156b1461045757600080fd5b8063659ac74b1161014357806381c2fdfb1161011d57806381c2fdfb1461036057806388cc58e4146103955780638efc2b2c146103c857600080fd5b8063659ac74b146102c25780636c9c0078146102fa57806371d1974a1461032d57600080fd5b80633dc8f8ec116101745780633dc8f8ec146102625780634b8018701461028257806362c06767146102a257600080fd5b80631a24f9a9146101ef5780632075ad22146102225780632a443fae1461024257600080fd5b366101ea57336001600160a01b037f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab116146101e857604051636c8cb79360e01b815260040160405180910390fd5b005b600080fd5b3480156101fb57600080fd5b5061020f61020a36600461477f565b6105d7565b6040519081526020015b60405180910390f35b6102356102303660046147ea565b610967565b6040516102199190614886565b34801561024e57600080fd5b5061020f61025d36600461477f565b610bc7565b34801561026e57600080fd5b5061023561027d36600461477f565b610ce7565b34801561028e57600080fd5b5061020f61029d36600461477f565b610f5a565b3480156102ae57600080fd5b506101e86102bd366004614899565b611188565b3480156102ce57600080fd5b506102e26102dd366004614906565b6112ee565b6040516001600160a01b039091168152602001610219565b34801561030657600080fd5b507f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16102e2565b34801561033957600080fd5b507f0000000000000000000000001886d09c9ade0c5db822d85d21678db67b6c29826102e2565b34801561036c57600080fd5b5061038061037b366004614962565b6113a5565b60408051928352602083019190915201610219565b3480156103a157600080fd5b507f0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e6102e2565b6103db6103d6366004614a1d565b611541565b60405161021996959493929190614a59565b3480156103f957600080fd5b5061023561040836600461477f565b6117a1565b34801561041957600080fd5b5061042d610428366004614ac6565b6118e3565b604080516001600160801b0394851681529284166020840152921691810191909152606001610219565b34801561046357600080fd5b5061020f61047236600461477f565b611973565b34801561048357600080fd5b5061042d610492366004614ac6565b611b5e565b3480156104a357600080fd5b506103db6104b2366004614a1d565b611ba2565b61020f6104c53660046147ea565b611c8d565b3480156104d657600080fd5b507f0000000000000000000000007bfd7192e76d950832c77bb412aae841049d8d9b6102e2565b34801561050957600080fd5b507f000000000000000000000000ae4ec9901c3076d0ddbe76a520f9e90a6227acb76102e2565b34801561053c57600080fd5b5061038061054b366004614b11565b611e07565b34801561055c57600080fd5b5061020f61056b366004614bd9565b611efd565b61020f61057e3660046147ea565b611f74565b34801561058f57600080fd5b506101e861059e366004614c5e565b6121ee565b3480156105af57600080fd5b506105c36105be366004614cf3565b612311565b60405162ffffff9091168152602001610219565b600081804211156106095760405163dae7ca7d60e01b8152600481018290524260248201526044015b60405180910390fd5b84515185901580610621575080515160208201515114155b8061063e575060408101515181515161063b906001614d35565b14155b1561065c5760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b03168660400151876000015151815181106106a1576106a1614d4d565b60200260200101516001600160a01b031614610700576040860151865151815181106106cf576106cf614d4d565b602002602001015160405163cfec0e0160e01b815260040161060091906001600160a01b0391909116815260200190565b600061071987600001518860200151896040015161237d565b6040516370a0823160e01b81523060048201529091506000906001600160a01b037f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab116906370a0823190602401602060405180830381865afa158015610783573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a79190614d63565b905061080133836000815181106107c0576107c0614d4d565b60200260200101518c8b604001516000815181106107e0576107e0614d4d565b60200260200101516001600160a01b031661248d909392919063ffffffff16565b6108158289602001518a604001513061254c565b6040516370a0823160e01b815230600482015281907f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b0316906370a0823190602401602060405180830381865afa15801561087b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061089f9190614d63565b6108a99190614d7c565b9450848911156108d6576040516313fab00360e21b8152600481018a905260248101869052604401610600565b604051632e1a7d4d60e01b8152600481018690527f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031690632e1a7d4d90602401600060405180830381600087803b15801561093857600080fd5b505af115801561094c573d6000803e3d6000fd5b5050505061095a8786612ab4565b5050505095945050505050565b606081804211156109945760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806109ac575080515160208201515114155b806109c957506040810151518151516109c6906001614d35565b14155b156109e75760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b03168660400151600081518110610a2857610a28614d4d565b60200260200101516001600160a01b031614610a555785604001516000815181106106cf576106cf614d4d565b6000610a6e87600001518860200151896040015161237d565b9050610a8487602001518289604001518b612b3a565b93503484600081518110610a9a57610a9a614d4d565b60200260200101511115610ae8573484600081518110610abc57610abc614d4d565b602002602001015160405163194ee21960e31b8152600401610600929190918252602082015260400190565b610b2681600081518110610afe57610afe614d4d565b602002602001015185600081518110610b1957610b19614d4d565b6020026020010151612fdb565b6000610b3d8289602001518a60400151888b61308a565b905088811015610b6a576040516313fab00360e21b8152600481018a905260248101829052604401610600565b84600081518110610b7d57610b7d614d4d565b6020026020010151341115610bbb57610bbb3386600081518110610ba357610ba3614d4d565b602002602001015134610bb69190614d7c565b612ab4565b50505050949350505050565b60008180421115610bf45760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610c0c575080515160208201515114155b80610c295750604081015151815151610c26906001614d35565b14155b15610c475760405163b91b4d4d60e01b815260040160405180910390fd5b6000610c6087600001518860200151896040015161237d565b9050610c993382600081518110610c7957610c79614d4d565b60200260200101518b8a604001516000815181106107e0576107e0614d4d565b610cae898289602001518a604001518a6134c5565b935083881115610cdb576040516313fab00360e21b81526004810189905260248101859052604401610600565b50505095945050505050565b60608180421115610d145760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610d2c575080515160208201515114155b80610d495750604081015151815151610d46906001614d35565b14155b15610d675760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b0316866040015187600001515181518110610dac57610dac614d4d565b60200260200101516001600160a01b031614610dda576040860151865151815181106106cf576106cf614d4d565b6000610df387600001518860200151896040015161237d565b9050610e0987602001518289604001518c612b3a565b93508784600081518110610e1f57610e1f614d4d565b60200260200101511115610e41578784600081518110610abc57610abc614d4d565b610e923382600081518110610e5857610e58614d4d565b602002602001015186600081518110610e7357610e73614d4d565b60200260200101518a604001516000815181106107e0576107e0614d4d565b6000610ea98289602001518a60400151883061308a565b905089811015610ed6576040516313fab00360e21b8152600481018b905260248101829052604401610600565b604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031690632e1a7d4d90602401600060405180830381600087803b158015610f3857600080fd5b505af1158015610f4c573d6000803e3d6000fd5b5050505061095a8782612ab4565b60008180421115610f875760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580610f9f575080515160208201515114155b80610fbc5750604081015151815151610fb9906001614d35565b14155b15610fda5760405163b91b4d4d60e01b815260040160405180910390fd5b6000610ff387600001518860200151896040015161237d565b90506000876040015182518151811061100e5761100e614d4d565b60209081029190910101516040516370a0823160e01b81526001600160a01b0389811660048301529192506000918316906370a0823190602401602060405180830381865afa158015611065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110899190614d63565b90506110c233846000815181106110a2576110a2614d4d565b60200260200101518d8c604001516000815181106107e0576107e0614d4d565b6110d6838a602001518b604001518b61254c565b6040516370a0823160e01b81526001600160a01b0389811660048301528291908416906370a0823190602401602060405180830381865afa15801561111f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111439190614d63565b61114d9190614d7c565b9550858a111561117a576040516313fab00360e21b8152600481018b905260248101879052604401610600565b505050505095945050505050565b7f0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061120a9190614d93565b6001600160a01b0316336001600160a01b03161461123b57604051635d9515b960e11b815260040160405180910390fd5b6001600160a01b038316611265576000198114156112565750475b6112608282612ab4565b505050565b6000198114156112da576040516370a0823160e01b81523060048201526001600160a01b038416906370a0823190602401602060405180830381865afa1580156112b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112d79190614d63565b90505b6112606001600160a01b0384168383613950565b60405163659ac74b60e01b81526001600160a01b038581166004830152848116602483015262ffffff8416604483015261ffff831660648301526000917f0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e9091169063659ac74b906084016020604051808303816000875af1158015611378573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061139c9190614d93565b95945050505050565b60008082804211156113d35760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab160006114078d8361ffff8f166002613a06565b90506000816001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611449573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146d9190614d93565b6001600160a01b0316836001600160a01b03161490508061148c57999a995b60008061149d848f8f8f8f30613baf565b91509150826114ad5780826114b0565b81815b90985096506114cd925050506001600160a01b038e168887613950565b604051632e1a7d4d60e01b8152600481018590526001600160a01b03831690632e1a7d4d90602401600060405180830381600087803b15801561150f57600080fd5b505af1158015611523573d6000803e3d6000fd5b505050506115318785612ab4565b5050509850989650505050505050565b60008080806060808261157661155a60208a018a614db0565b61156a60408b0160208c01614db0565b8a604001356002613a06565b9050806001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115da9190614d93565b6001600160a01b03166115f060208a018a614db0565b6001600160a01b0316146116175760405163b33f8ab960e01b815260040160405180910390fd5b6001600160a01b037f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab11661164e60208a018a614db0565b6001600160a01b03161480156116675750348860600135145b156116a6576116768134612fdb565b6116a1338260808b013561169060408d0160208e01614db0565b6001600160a01b031692919061248d565b611782565b6001600160a01b037f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1166116e060408a0160208b01614db0565b6001600160a01b03161480156116f95750348860800135145b1561171f57611715338260608b013561169060208d018d614db0565b6116a18134612fdb565b61172c6020890189614db0565b61173c60408a0160208b01614db0565b60405163d0a4f13b60e01b81526001600160a01b03928316600482015291166024820152606089013560448201526080890135606482015234608482015260a401610600565b61178c8882613d11565b949d939c50919a509850965090945092505050565b606081804211156117ce5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806117e6575080515160208201515114155b806118035750604081015151815151611800906001614d35565b14155b156118215760405163b91b4d4d60e01b815260040160405180910390fd5b600061183a87600001518860200151896040015161237d565b905061185087602001518289604001518c612b3a565b9350878460008151811061186657611866614d4d565b60200260200101511115611888578784600081518110610abc57610abc614d4d565b61189f3382600081518110610e5857610e58614d4d565b60006118b68289602001518a60400151888b61308a565b90508981101561095a576040516313fab00360e21b8152600481018b905260248101829052604401610600565b604051630abcd78360e41b81526001600160801b03831660048201528115156024820152600090819081906001600160a01b0387169063abcd7830906044015b606060405180830381865afa158015611940573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119649190614dcd565b91989097509095509350505050565b600081804211156119a05760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b845151859015806119b8575080515160208201515114155b806119d557506040810151518151516119d2906001614d35565b14155b156119f35760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b0316866040015187600001515181518110611a3857611a38614d4d565b60200260200101516001600160a01b031614611a66576040860151865151815181106106cf576106cf614d4d565b6000611a7f87600001518860200151896040015161237d565b9050611a983382600081518110610c7957610c79614d4d565b611aad898289602001518a60400151306134c5565b935083881115611ada576040516313fab00360e21b81526004810189905260248101859052604401610600565b604051632e1a7d4d60e01b8152600481018590527f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031690632e1a7d4d90602401600060405180830381600087803b158015611b3c57600080fd5b505af1158015611b50573d6000803e3d6000fd5b50505050610cdb8685612ab4565b604051631cee6cdf60e31b81526001600160801b03831660048201528115156024820152600090819081906001600160a01b0387169063e77366f890604401611923565b600080808060608082611bbb61155a60208a018a614db0565b9050806001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bfb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1f9190614d93565b6001600160a01b0316611c3560208a018a614db0565b6001600160a01b031614611c5c5760405163b33f8ab960e01b815260040160405180910390fd5b611c73338260608b013561169060208d018d614db0565b611782338260808b013561169060408d0160208e01614db0565b60008180421115611cba5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580611cd2575080515160208201515114155b80611cef5750604081015151815151611cec906001614d35565b14155b15611d0d5760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b03168660400151600081518110611d4e57611d4e614d4d565b60200260200101516001600160a01b031614611d7b5785604001516000815181106106cf576106cf614d4d565b6000611d9487600001518860200151896040015161237d565b9050611dba81600081518110611dac57611dac614d4d565b602002602001015134612fdb565b611dcf348289602001518a604001518a6134c5565b935083881115611dfc576040516313fab00360e21b81526004810189905260248101859052604401610600565b505050949350505050565b6000808280421115611e355760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b6000611e488d8d8d61ffff166002613a06565b90506000816001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e8a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eae9190614d93565b6001600160a01b03168e6001600160a01b0316141590508015611ecf579899985b611edd828c8c8c8c8c613baf565b90955093508015611eec579293925b505050995099975050505050505050565b604051634c7cffbd60e01b815262ffffff821660048201526000906001600160a01b03841690634c7cffbd90602401602060405180830381865afa158015611f49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f6d9190614d63565b9392505050565b60008180421115611fa15760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b84515185901580611fb9575080515160208201515114155b80611fd65750604081015151815151611fd3906001614d35565b14155b15611ff45760405163b91b4d4d60e01b815260040160405180910390fd5b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b0316866040015160008151811061203557612035614d4d565b60200260200101516001600160a01b0316146120625785604001516000815181106106cf576106cf614d4d565b600061207b87600001518860200151896040015161237d565b90506000876040015182518151811061209657612096614d4d565b60209081029190910101516040516370a0823160e01b81526001600160a01b0389811660048301529192506000918316906370a0823190602401602060405180830381865afa1580156120ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121119190614d63565b905061212983600081518110611dac57611dac614d4d565b61213d838a602001518b604001518b61254c565b6040516370a0823160e01b81526001600160a01b0389811660048301528291908416906370a0823190602401602060405180830381865afa158015612186573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121aa9190614d63565b6121b49190614d7c565b9550858a11156121e1576040516313fab00360e21b8152600481018b905260248101879052604401610600565b5050505050949350505050565b7f0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e6001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561224c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122709190614d93565b6001600160a01b0316336001600160a01b0316146122a157604051635d9515b960e11b815260040160405180910390fd5b6040516305feb5ff60e21b81526001600160a01b038716906317fad7fc906122d790309089908990899089908990600401614e5e565b600060405180830381600087803b1580156122f157600080fd5b505af1158015612305573d6000803e3d6000fd5b50505050505050505050565b60405163f5e2932960e01b8152600481018290526000906001600160a01b0384169063f5e2932990602401602060405180830381865afa158015612359573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f6d9190614e9e565b6060835167ffffffffffffffff811115612399576123996144da565b6040519080825280602002602001820160405280156123c2578160200160208202803683370190505b509050600080836000815181106123db576123db614d4d565b6020026020010151905060005b83518110156124835781925084816001018151811061240957612409614d4d565b60200260200101519150612451838389848151811061242a5761242a614d4d565b602002602001015189858151811061244457612444614d4d565b60200260200101516141a6565b84828151811061246357612463614d4d565b6001600160a01b03909216602092830291909101909101526001016123e8565b5050509392505050565b604080516001600160a01b038581166024830152848116604483015260648083018590528351808403909101815260849092019092526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166323b872dd60e01b17905290600090612502908716836142a7565b9050600081511180156125265750808060200190518101906125249190614ebb565b155b156125445760405163197138bd60e11b815260040160405180910390fd5b505050505050565b60008060008060008660008151811061256757612567614d4d565b6020026020010151905060005b89518110156123055789818151811061258f5761258f614d4d565b602002602001015192508881815181106125ab576125ab614d4d565b602002602001015194508195508781600101815181106125cd576125cd614d4d565b6020026020010151915089518160010114612604578981600101815181106125f7576125f7614d4d565b6020026020010151612606565b865b9350600085600281111561261c5761261c614ed8565b14156128c357600080846001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa158015612663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126879190614f05565b506001600160701b031691506001600160701b03169150836001600160a01b0316886001600160a01b031610156127bc576040516370a0823160e01b81526001600160a01b03868116600483015260009184918b16906370a0823190602401602060405180830381865afa158015612703573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127279190614d63565b039050600061273782858561436d565b60405163022c0d9f60e01b8152600060048201819052602482018390526001600160a01b038b811660448401526080606484015260848301919091529192509088169063022c0d9f9060a401600060405180830381600087803b15801561279d57600080fd5b505af11580156127b1573d6000803e3d6000fd5b5050505050506128bc565b6040516370a0823160e01b81526001600160a01b03868116600483015260009183918b16906370a0823190602401602060405180830381865afa158015612807573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061282b9190614d63565b039050600061283b82848661436d565b60405163022c0d9f60e01b8152600481018290526000602482018190526001600160a01b038b811660448401526080606484015260848301919091529192509088169063022c0d9f9060a401600060405180830381600087803b1580156128a157600080fd5b505af11580156128b5573d6000803e3d6000fd5b5050505050505b5050612aac565b60018560028111156128d7576128d7614ed8565b14156129c357826001600160a01b03166353c059a0846001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa15801561292a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061294e9190614d93565b60405160e083901b6001600160e01b03191681526001600160a01b03918216868316146004820152908716602482015260440160408051808303816000875af115801561299f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128bc9190614f4a565b826001600160a01b03166353c059a0846001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a10573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a349190614d93565b60405160e083901b6001600160e01b03191681526001600160a01b0391821686831614600482015290871660248201526044016020604051808303816000875af1158015612a86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612aaa9190614d63565b505b600101612574565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114612b01576040519150601f19603f3d011682016040523d82523d6000602084013e612b06565b606091505b50509050806112605760405163047b96f760e41b81526001600160a01b038416600482015260248101839052604401610600565b6060825167ffffffffffffffff811115612b5657612b566144da565b604051908082528060200260200182016040528015612b7f578160200160208202803683370190505b5090508181855181518110612b9657612b96614d4d565b602090810291909101015283515b8015612fd257600084612bb8600184614d7c565b81518110612bc857612bc8614d4d565b60200260200101519050600087600184612be29190614d7c565b81518110612bf257612bf2614d4d565b60200260200101519050600087600185612c0c9190614d7c565b81518110612c1c57612c1c614d4d565b6020026020010151905060006002811115612c3957612c39614ed8565b826002811115612c4b57612c4b614ed8565b1415612d6e57600080826001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa158015612c92573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cb69190614f05565b506001600160701b031691506001600160701b03169150888681518110612cdf57612cdf614d4d565b60200260200101516001600160a01b0316856001600160a01b03161115612d0257905b6000878781518110612d1657612d16614d4d565b60200260200101519050612d358383836144049092919063ffffffff16565b6001600160801b031688612d4a60018a614d7c565b81518110612d5a57612d5a614d4d565b602002602001018181525050505050612fbc565b6001826002811115612d8257612d82614ed8565b1415612eef577f0000000000000000000000007bfd7192e76d950832c77bb412aae841049d8d9b6001600160a01b0316635bdd4b7c82878781518110612dca57612dca614d4d565b6020026020010151866001600160a01b0316856001600160a01b03166316dc165b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612e1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e3e9190614d93565b6040516001600160e01b031960e087901b1681526001600160a01b0394851660048201526001600160801b0390931660248401529092169190911460448201526064016040805180830381865afa158015612e9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ec19190614f4a565b5085612ece600187614d7c565b81518110612ede57612ede614d4d565b602002602001018181525050612fbc565b612f8881868681518110612f0557612f05614d4d565b6020026020010151856001600160a01b0316846001600160a01b03166305e8746d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f799190614d93565b6001600160a01b0316146118e3565b50506001600160801b031685612f9f600187614d7c565b81518110612faf57612faf614d4d565b6020026020010181815250505b5050508080612fca90614f6e565b915050612ba4565b50949350505050565b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561303657600080fd5b505af115801561304a573d6000803e3d6000fd5b506130869350506001600160a01b037f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab116915084905083613950565b5050565b600080600080600080886000815181106130a6576130a6614d4d565b6020026020010151905060005b8b518110156134b6578b81815181106130ce576130ce614d4d565b602002602001015193508a81815181106130ea576130ea614d4d565b6020026020010151925081955089816001018151811061310c5761310c614d4d565b602002602001015191508b518160010114613143578b816001018151811061313657613136614d4d565b6020026020010151613145565b875b9450600083600281111561315b5761315b614ed8565b14156132675788816001018151811061317657613176614d4d565b60200260200101519650816001600160a01b0316866001600160a01b0316101561321a5760405163022c0d9f60e01b8152600060048201819052602482018990526001600160a01b03878116604484015260806064840152608483019190915285169063022c0d9f9060a4015b600060405180830381600087803b1580156131fd57600080fd5b505af1158015613211573d6000803e3d6000fd5b505050506134ae565b60405163022c0d9f60e01b8152600481018890526000602482018190526001600160a01b03878116604484015260806064840152608483019190915285169063022c0d9f9060a4016131e3565b600183600281111561327b5761327b614ed8565b1415613384576000846001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156132c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132e59190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052888316602483015292506000918291908816906353c059a09060440160408051808303816000875af1158015613342573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133669190614f4a565b9150915082156133785780995061337c565b8199505b5050506134ae565b6000846001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133e89190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052888316602483015292506000918291613482918916906353c059a0906044015b6020604051808303816000875af115801561344a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061346e9190614d63565b6001600160801b0381169160809190911c90565b6001600160801b031691506001600160801b0316915082156134a6578099506134aa565b8199505b5050505b6001016130b3565b50505050505095945050505050565b600080600080600080876000815181106134e1576134e1614d4d565b602002602001015190508a955060005b8a518110156134b6578a818151811061350c5761350c614d4d565b6020026020010151925089818151811061352857613528614d4d565b6020026020010151945081955088816001018151811061354a5761354a614d4d565b602002602001015191508a518160010114613581578a816001018151811061357457613574614d4d565b6020026020010151613583565b875b9350600085600281111561359957613599614ed8565b141561375457600080846001600160a01b0316630902f1ac6040518163ffffffff1660e01b8152600401606060405180830381865afa1580156135e0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136049190614f05565b506001600160701b031691506001600160701b03169150836001600160a01b0316886001600160a01b031610156136c35761364089838361436d565b60405163022c0d9f60e01b8152600060048201819052602482018390526001600160a01b038981166044840152608060648401526084830191909152919a509086169063022c0d9f9060a401600060405180830381600087803b1580156136a657600080fd5b505af11580156136ba573d6000803e3d6000fd5b5050505061374d565b6136ce89828461436d565b60405163022c0d9f60e01b8152600481018290526000602482018190526001600160a01b038981166044840152608060648401526084830191909152919a509086169063022c0d9f9060a401600060405180830381600087803b15801561373457600080fd5b505af1158015613748573d6000803e3d6000fd5b505050505b5050613948565b600185600281111561376857613768614ed8565b1415613871576000836001600160a01b031663b7d19fc46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137d29190614d93565b60405163029e02cd60e51b81526001600160a01b039182168583161460048201819052878316602483015292506000918291908716906353c059a09060440160408051808303816000875af115801561382f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138539190614f4a565b91509150821561386557809950613869565b8199505b505050613948565b6000836001600160a01b031663da10610c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138d59190614d93565b60405163029e02cd60e51b81526001600160a01b03918216858316146004820181905287831660248301529250600091829161391c918816906353c059a09060440161342b565b6001600160801b031691506001600160801b03169150821561394057809950613944565b8199505b5050505b6001016134f1565b604080516001600160a01b03848116602483015260448083018590528351808403909101815260649092019092526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663a9059cbb60e01b179052906000906139bd908616836142a7565b9050600081511180156139e15750808060200190518101906139df9190614ebb565b155b156139ff5760405163197138bd60e11b815260040160405180910390fd5b5050505050565b60006001826002811115613a1c57613a1c614ed8565b1415613ac65760405163704037bd60e01b81526001600160a01b0386811660048301528581166024830152604482018590527f0000000000000000000000001886d09c9ade0c5db822d85d21678db67b6c2982169063704037bd90606401608060405180830381865afa158015613a97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613abb9190614f85565b602001519050613b66565b60405163704037bd60e01b81526001600160a01b0386811660048301528581166024830152604482018590527f0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e169063704037bd90606401608060405180830381865afa158015613b3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b5f9190614f85565b6020015190505b6001600160a01b038116613ba757604051636b2471d160e11b81526001600160a01b0380871660048301528516602482015260448101849052606401610600565b949350505050565b6000806000886001600160a01b031663c9939f5e338689896040518563ffffffff1660e01b8152600401613be69493929190614fec565b6000604051808303816000875af1158015613c05573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613c2d919081019061502a565b905060005b8151811015613cc157613c64828281518110613c5057613c50614d4d565b60200260200101516001600160801b031690565b613c77906001600160801b031685614d35565b9350613c9c828281518110613c8e57613c8e614d4d565b602002602001015160801c90565b613caf906001600160801b031684614d35565b9250613cba816150b0565b9050613c32565b5087831080613ccf57508682105b15613d05576040516318ccfb7760e11b815260048101899052602481018490526044810188905260648101839052608401610600565b50965096945050505050565b600080600080606080876101c0013580421115613d4a5760405163dae7ca7d60e01b815260048101829052426024820152604401610600565b613d586101408a018a6150cb565b9050613d686101208b018b6150cb565b9050141580613d955750613d806101608a018a6150cb565b9050613d906101208b018b6150cb565b905014155b15613db35760405163b91b4d4d60e01b815260040160405180910390fd5b62ffffff60e08a01351180613dcf575062ffffff6101008a0135115b15613dfe5760405163197a55c760e11b815260e08a013560048201526101008a01356024820152604401610600565b6000613e0e6101208b018b6150cb565b905067ffffffffffffffff811115613e2857613e286144da565b604051908082528060200260200182016040528015613e51578160200160208202803683370190505b509050613e626101208b018b6150cb565b905067ffffffffffffffff811115613e7c57613e7c6144da565b604051908082528060200260200182016040528015613ea5578160200160208202803683370190505b5093506000896001600160a01b031663dbe65edc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ee8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f0c9190614e9e565b62ffffff169050808b61010001358c60e00135011080613f3657508a60e001358b61010001358201105b15613f6c57604051637d50edab60e11b815260e08c013560048201526101008c0135602482015260448101829052606401610600565b60005b825181101561406f576000613f886101208e018e6150cb565b83818110613f9857613f98614d4d565b90506020020135830190506000811280613fb4575062ffffff81115b15613fd5576040516370a82e6160e11b815260048101829052602401610600565b80878381518110613fe857613fe8614d4d565b60209081029190910101526140496140046101408f018f6150cb565b8481811061401457614014614d4d565b905060200201358e80610160019061402c91906150cb565b8581811061403c5761403c614d4d565b90506020020135836144a0565b84838151811061405b5761405b614d4d565b602090810291909101015250600101613f6f565b50506000808a6001600160a01b031663383d15c58d6101800160208101906140979190614db0565b858f6101a00160208101906140ac9190614db0565b6040518463ffffffff1660e01b81526004016140ca93929190615115565b6000604051808303816000875af11580156140e9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526141119190810190615179565b6001600160801b0383169c50608083901c9b509650909250905060a08c01358a108061414057508b60c0013589105b1561417c576040516318ccfb7760e11b815260a08d01356004820152602481018b905260c08d01356044820152606481018a9052608401610600565b6001600160801b0381169750608081901c6001600160801b03169650505050509295509295509295565b6000808260028111156141bb576141bb614ed8565b141561429b5760405163e6a4390560e01b81526001600160a01b03868116600483015285811660248301527f000000000000000000000000ae4ec9901c3076d0ddbe76a520f9e90a6227acb7169063e6a4390590604401602060405180830381865afa15801561422f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906142539190614d93565b90506001600160a01b03811661429657604051636b2471d160e11b81526001600160a01b0380871660048301528516602482015260448101849052606401610600565b613ba7565b61139c85858585613a06565b6060600080846001600160a01b0316846040516142c4919061521f565b6000604051808303816000865af19150503d8060008114614301576040519150601f19603f3d011682016040523d82523d6000602084013e614306565b606091505b5091509150811561434657805115801561432857506001600160a01b0385163b155b1561429657604051633b99915360e21b815260040160405180910390fd5b8051614365576040516373483fab60e11b815260040160405180910390fd5b805181602001fd5b60008361438d5760405163b229ed3360e01b815260040160405180910390fd5b821580614398575081155b156143b6576040516398c59a2960e01b815260040160405180910390fd5b60006143c4856103e561525a565b905060006143d2848361525a565b90506000826143e3876103e861525a565b6143ed9190614d35565b90506143f98183615279565b979650505050505050565b6000836144245760405163b229ed3360e01b815260040160405180910390fd5b82158061442f575081155b1561444d576040516398c59a2960e01b815260040160405180910390fd5b6000614459858561525a565b614465906103e861525a565b905060006144738685614d7c565b61447f906103e561525a565b905061448b8183615279565b614496906001614d35565b9695505050505050565b601882901b6affffffffffffffff00000016605884901b72ffffffffffffffff0000000000000000000000161762ffffff82168117613ba7565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff81118282101715614513576145136144da565b60405290565b6040516080810167ffffffffffffffff81118282101715614513576145136144da565b604051601f8201601f1916810167ffffffffffffffff81118282101715614565576145656144da565b604052919050565b600067ffffffffffffffff821115614587576145876144da565b5060051b60200190565b600082601f8301126145a257600080fd5b813560206145b76145b28361456d565b61453c565b82815260059290921b840181019181810190868411156145d657600080fd5b8286015b848110156145f157803583529183019183016145da565b509695505050505050565b6001600160a01b038116811461461157600080fd5b50565b803561461f816145fc565b919050565b600082601f83011261463557600080fd5b813560206146456145b28361456d565b82815260059290921b8401810191818101908684111561466457600080fd5b8286015b848110156145f157803561467b816145fc565b8352918301918301614668565b60006060828403121561469a57600080fd5b6146a26144f0565b9050813567ffffffffffffffff808211156146bc57600080fd5b6146c885838601614591565b83526020915081840135818111156146df57600080fd5b8401601f810186136146f057600080fd5b80356146fe6145b28261456d565b81815260059190911b8201840190848101908883111561471d57600080fd5b928501925b828410156147495783356003811061473a5760008081fd5b82529285019290850190614722565b808688015250505050604084013591508082111561476657600080fd5b5061477384828501614624565b60408301525092915050565b600080600080600060a0868803121561479757600080fd5b8535945060208601359350604086013567ffffffffffffffff8111156147bc57600080fd5b6147c888828901614688565b93505060608601356147d9816145fc565b949793965091946080013592915050565b6000806000806080858703121561480057600080fd5b84359350602085013567ffffffffffffffff81111561481e57600080fd5b61482a87828801614688565b935050604085013561483b816145fc565b9396929550929360600135925050565b600081518084526020808501945080840160005b8381101561487b5781518752958201959082019060010161485f565b509495945050505050565b602081526000611f6d602083018461484b565b6000806000606084860312156148ae57600080fd5b83356148b9816145fc565b925060208401356148c9816145fc565b929592945050506040919091013590565b62ffffff8116811461461157600080fd5b61ffff8116811461461157600080fd5b803561461f816148eb565b6000806000806080858703121561491c57600080fd5b8435614927816145fc565b93506020850135614937816145fc565b92506040850135614947816148da565b91506060850135614957816148eb565b939692955090935050565b600080600080600080600080610100898b03121561497f57600080fd5b883561498a816145fc565b9750602089013561499a816148eb565b96506040890135955060608901359450608089013567ffffffffffffffff808211156149c557600080fd5b6149d18c838d01614591565b955060a08b01359150808211156149e757600080fd5b506149f48b828c01614591565b93505060c0890135614a05816145fc565b8092505060e089013590509295985092959890939650565b600060208284031215614a2f57600080fd5b813567ffffffffffffffff811115614a4657600080fd5b82016101e08185031215611f6d57600080fd5b86815285602082015284604082015283606082015260c060808201526000614a8460c083018561484b565b82810360a0840152614a96818561484b565b9998505050505050505050565b6001600160801b038116811461461157600080fd5b801515811461461157600080fd5b600080600060608486031215614adb57600080fd5b8335614ae6816145fc565b92506020840135614af681614aa3565b91506040840135614b0681614ab8565b809150509250925092565b60008060008060008060008060006101208a8c031215614b3057600080fd5b8935614b3b816145fc565b985060208a0135614b4b816145fc565b9750614b5960408b016148fb565b965060608a0135955060808a0135945060a08a013567ffffffffffffffff80821115614b8457600080fd5b614b908d838e01614591565b955060c08c0135915080821115614ba657600080fd5b50614bb38c828d01614591565b935050614bc260e08b01614614565b91506101008a013590509295985092959850929598565b60008060408385031215614bec57600080fd5b8235614bf7816145fc565b91506020830135614c07816148da565b809150509250929050565b60008083601f840112614c2457600080fd5b50813567ffffffffffffffff811115614c3c57600080fd5b6020830191508360208260051b8501011115614c5757600080fd5b9250929050565b60008060008060008060808789031215614c7757600080fd5b8635614c82816145fc565b95506020870135614c92816145fc565b9450604087013567ffffffffffffffff80821115614caf57600080fd5b614cbb8a838b01614c12565b90965094506060890135915080821115614cd457600080fd5b50614ce189828a01614c12565b979a9699509497509295939492505050565b60008060408385031215614d0657600080fd5b8235614d11816145fc565b946020939093013593505050565b634e487b7160e01b600052601160045260246000fd5b60008219821115614d4857614d48614d1f565b500190565b634e487b7160e01b600052603260045260246000fd5b600060208284031215614d7557600080fd5b5051919050565b600082821015614d8e57614d8e614d1f565b500390565b600060208284031215614da557600080fd5b8151611f6d816145fc565b600060208284031215614dc257600080fd5b8135611f6d816145fc565b600080600060608486031215614de257600080fd5b8351614ded81614aa3565b6020850151909350614dfe81614aa3565b6040850151909250614b0681614aa3565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115614e4157600080fd5b8260051b8083602087013760009401602001938452509192915050565b60006001600160a01b03808916835280881660208401525060806040830152614e8b608083018688614e0f565b8281036060840152614a96818587614e0f565b600060208284031215614eb057600080fd5b8151611f6d816148da565b600060208284031215614ecd57600080fd5b8151611f6d81614ab8565b634e487b7160e01b600052602160045260246000fd5b80516001600160701b038116811461461f57600080fd5b600080600060608486031215614f1a57600080fd5b614f2384614eee565b9250614f3160208501614eee565b9150604084015163ffffffff81168114614b0657600080fd5b60008060408385031215614f5d57600080fd5b505080516020909101519092909150565b600081614f7d57614f7d614d1f565b506000190190565b600060808284031215614f9757600080fd5b614f9f614519565b8251614faa816148eb565b81526020830151614fba816145fc565b60208201526040830151614fcd81614ab8565b60408201526060830151614fe081614ab8565b60608201529392505050565b60006001600160a01b03808716835280861660208401525060806040830152615018608083018561484b565b82810360608401526143f9818561484b565b6000602080838503121561503d57600080fd5b825167ffffffffffffffff81111561505457600080fd5b8301601f8101851361506557600080fd5b80516150736145b28261456d565b81815260059190911b8201830190838101908783111561509257600080fd5b928401925b828410156143f957835182529284019290840190615097565b60006000198214156150c4576150c4614d1f565b5060010190565b6000808335601e198436030181126150e257600080fd5b83018035915067ffffffffffffffff8211156150fd57600080fd5b6020019150600581901b3603821315614c5757600080fd5b6000606082016001600160a01b0380871684526020606081860152828751808552608087019150828901945060005b8181101561516057855183529483019491830191600101615144565b5050809450505080851660408501525050949350505050565b60008060006060848603121561518e57600080fd5b835192506020808501519250604085015167ffffffffffffffff8111156151b457600080fd5b8501601f810187136151c557600080fd5b80516151d36145b28261456d565b81815260059190911b820183019083810190898311156151f257600080fd5b928401925b82841015615210578351825292840192908401906151f7565b80955050505050509250925092565b6000825160005b818110156152405760208186018101518583015201615226565b8181111561524f576000828501525b509190910192915050565b600081600019048311821515161561527457615274614d1f565b500290565b60008261529657634e487b7160e01b600052601260045260246000fd5b50049056fea2646970667358221220b39aa5e8e65e5f7732083a1f46863bf4c9fe3dc8a0635e6b8d2ee3e6c3d73b0b64736f6c634300080a0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e000000000000000000000000ae4ec9901c3076d0ddbe76a520f9e90a6227acb70000000000000000000000001886d09c9ade0c5db822d85d21678db67b6c29820000000000000000000000007bfd7192e76d950832c77bb412aae841049d8d9b00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1

-----Decoded View---------------
Arg [0] : factory (address): 0x8e42f2F4101563bF679975178e880FD87d3eFd4e
Arg [1] : factoryV1 (address): 0xaE4EC9901c3076D0DdBe76A520F9E90a6227aCB7
Arg [2] : legacyFactory (address): 0x1886D09C9Ade0c5DB822D85D21678Db67B6c2982
Arg [3] : legacyRouter (address): 0x7BFd7192E76D950832c77BB412aaE841049D8D9B
Arg [4] : wnative (address): 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 0000000000000000000000008e42f2f4101563bf679975178e880fd87d3efd4e
Arg [1] : 000000000000000000000000ae4ec9901c3076d0ddbe76a520f9e90a6227acb7
Arg [2] : 0000000000000000000000001886d09c9ade0c5db822d85d21678db67b6c2982
Arg [3] : 0000000000000000000000007bfd7192e76d950832c77bb412aae841049d8d9b
Arg [4] : 00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Chain Token Portfolio % Price Amount Value
ETH73.40%$3,141.069.8575$30,962.95
ARB11.25%$0.35734213,282.2511$4,746.31
ARB<0.01%$0.6966880.2351$0.1638
BASE9.04%$3,142.281.214$3,814.76
AVAX4.98%$0.004691447,366.7665$2,098.78
AVAX0.02%$0.99974210$10
AVAX0.01%$27.360.2$5.47
AVAX<0.01%$0.9997421$0.9997
AVAX<0.01%$0.0768591.4456$0.1111
OP0.60%$3,148.240.0805$253.44
ZKSYNC0.49%$3,141.060.0654$205.56
SCROLL0.11%$3,141.060.0151$47.42
MATIC0.04%$0.49854335.1686$17.53
FTM0.03%$0.43599531.1267$13.57
LINEA<0.01%$3,144.540.00132686$4.17
BSC<0.01%$27.40.1$2.74
CRONOS<0.01%$0.08946$0.536403
MANTLE<0.01%$0.8146990.3728$0.303726
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.