Sepolia Testnet

Contract

0xe44C842FFaBB9658e817999738a5f6159341e5f3

Overview

ETH Balance

0 ETH

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Create And Initi...61924662024-06-26 18:24:1222 days ago1719426252IN
0xe44C842F...59341e5f3
0.101 ETH0.0623499312.19356691
0x60e0806061923372024-06-26 17:58:1222 days ago1719424692IN
 Create: PoolInitializer
0 ETH0.021652569.23825281

Latest 4 internal transactions

Advanced mode:
Parent Transaction Hash Block From To
61924662024-06-26 18:24:1222 days ago1719426252
0xe44C842F...59341e5f3
0.000954 ETH
61924662024-06-26 18:24:1222 days ago1719426252
0xe44C842F...59341e5f3
0.10004599 ETH
61924662024-06-26 18:24:1222 days ago1719426252
0xe44C842F...59341e5f3
0 ETH
61924662024-06-26 18:24:1222 days ago1719426252
0xe44C842F...59341e5f3
0 ETH
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PoolInitializer

Compiler Version
v0.8.15+commit.e14f2714

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion, GNU AGPLv3 license
File 1 of 38 : PoolInitializer.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;

import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";

import {PeripheryValidation} from "@uniswap/v3-periphery/contracts/base/PeripheryValidation.sol";
import {Multicall} from "@uniswap/v3-periphery/contracts/base/Multicall.sol";

import {IMarginalV1SwapCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1SwapCallback.sol";
import {IMarginalV1Factory} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Factory.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {SwapMath} from "@marginal/v1-core/contracts/libraries/SwapMath.sol";

import {LiquidityManagement} from "./base/LiquidityManagement.sol";
import {PeripheryImmutableState} from "./base/PeripheryImmutableState.sol";

import {CallbackValidation} from "./libraries/CallbackValidation.sol";
import {LiquidityAmounts} from "./libraries/LiquidityAmounts.sol";
import {Path} from "./libraries/Path.sol";
import {PoolAddress} from "./libraries/PoolAddress.sol";
import {PoolConstants} from "./libraries/PoolConstants.sol";

import {IPoolInitializer} from "./interfaces/IPoolInitializer.sol";

/// @title Initializer for Marginal v1 pools
/// @notice Provides methods for preparing, creating and initializing a Marginal v1 pool and its associated Uniswap v3 oracle
contract PoolInitializer is
    IPoolInitializer,
    IMarginalV1SwapCallback,
    PeripheryImmutableState,
    LiquidityManagement,
    PeripheryValidation,
    Multicall
{
    using Path for bytes;

    event PoolInitialize(
        address indexed sender,
        address pool,
        uint256 shares,
        int256 amount0,
        int256 amount1
    );

    error InvalidOracle();
    error PoolNotInitialized();
    error AmountInGreaterThanMax(uint256 amountIn);
    error AmountOutLessThanMin(uint256 amountOut);
    error LiquidityBurnedLessThanMin();
    error Amount0BurnedGreaterThanMax(int256 amount0Burned);
    error Amount1BurnedGreaterThanMax(int256 amount1Burned);

    constructor(
        address _factory,
        address _WETH9
    ) PeripheryImmutableState(_factory, _WETH9) {}

    struct SwapCallbackData {
        bytes path;
        address payer;
    }

    /// @inheritdoc IMarginalV1SwapCallback
    function marginalV1SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata _data
    ) external override {
        require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
        SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
        (
            address tokenIn,
            address tokenOut,
            uint24 maintenance,
            address oracle
        ) = data.path.decodeFirstPool();
        CallbackValidation.verifyCallback(
            factory,
            tokenIn,
            tokenOut,
            maintenance,
            oracle
        );

        (bool isExactInput, uint256 amountToPay) = amount0Delta > 0
            ? (tokenIn < tokenOut, uint256(amount0Delta))
            : (tokenOut < tokenIn, uint256(amount1Delta));
        require(isExactInput);
        pay(tokenIn, data.payer, msg.sender, amountToPay);
    }

    /// @inheritdoc IPoolInitializer
    function createAndInitializePoolIfNecessary(
        CreateAndInitializeParams calldata params
    )
        public
        payable
        override
        checkDeadline(params.deadline)
        returns (address pool, uint256 shares, int256 amount0, int256 amount1)
    {
        require(params.token0 < params.token1);
        address oracle = IUniswapV3Factory(uniswapV3Factory).getPool(
            params.token0,
            params.token1,
            params.uniswapV3Fee
        );
        if (oracle == address(0)) revert InvalidOracle();

        pool = IMarginalV1Factory(factory).getPool(
            params.token0,
            params.token1,
            params.maintenance,
            oracle
        );
        if (pool == address(0)) {
            pool = IMarginalV1Factory(factory).createPool(
                params.token0,
                params.token1,
                params.maintenance,
                params.uniswapV3Fee
            );
        }

        // if not initialized, mint min liquidity with dust then swap to given price before adding full amount of liquidity
        (, , , , , , , bool initialized) = IMarginalV1Pool(pool).state();
        if (!initialized) {
            if (params.liquidityBurned <= PoolConstants.MINIMUM_LIQUIDITY)
                revert LiquidityBurnedLessThanMin();
            (, uint256 amount0BurnedOnMint, uint256 amount1BurnedOnMint) = mint(
                MintParams({
                    token0: params.token0,
                    token1: params.token1,
                    maintenance: params.maintenance,
                    oracle: oracle,
                    recipient: pool,
                    liquidityDelta: params.liquidityBurned, // burn extra to pool in case need buffer on rounding for swap (amountDelta > 0)
                    amount0Min: 0,
                    amount1Min: 0
                })
            );

            (
                int256 amount0BurnedOnSwap,
                int256 amount1BurnedOnSwap
            ) = initializePoolSqrtPriceX96(
                    InitializePoolSqrtPriceX96Params({
                        token0: params.token0,
                        token1: params.token1,
                        maintenance: params.maintenance,
                        oracle: oracle,
                        recipient: msg.sender,
                        sqrtPriceX96: params.sqrtPriceX96,
                        amountInMaximum: type(uint256).max, // impose max on amounts burned (including swap) below
                        amountOutMinimum: 0, // impose min on amounts in liquidity added in mint call below
                        sqrtPriceLimitX96: params.sqrtPriceLimitX96,
                        deadline: params.deadline
                    })
                );

            // check haven't burned more than want
            int256 amount0Burned = int256(amount0BurnedOnMint) +
                amount0BurnedOnSwap;
            if (amount0Burned > params.amount0BurnedMax)
                revert Amount0BurnedGreaterThanMax(amount0Burned);
            int256 amount1Burned = int256(amount1BurnedOnMint) +
                amount1BurnedOnSwap;
            if (amount1Burned > params.amount1BurnedMax)
                revert Amount1BurnedGreaterThanMax(amount1Burned);

            uint128 liquidityDelta = LiquidityAmounts.getLiquidityForAmounts(
                params.sqrtPriceX96,
                params.amount0Desired,
                params.amount1Desired
            );

            uint256 _amount0;
            uint256 _amount1;
            (shares, _amount0, _amount1) = mint(
                MintParams({
                    token0: params.token0,
                    token1: params.token1,
                    maintenance: params.maintenance,
                    oracle: oracle,
                    recipient: params.recipient,
                    liquidityDelta: liquidityDelta,
                    amount0Min: params.amount0Min,
                    amount1Min: params.amount1Min
                })
            );

            amount0 = int256(_amount0) + amount0Burned;
            amount1 = int256(_amount1) + amount1Burned;

            // any remaining ETH in the contract from payable return to sender
            refundETH();

            emit PoolInitialize(msg.sender, pool, shares, amount0, amount1);
        }
    }

    /// @inheritdoc IPoolInitializer
    function initializePoolSqrtPriceX96(
        InitializePoolSqrtPriceX96Params memory params
    )
        public
        payable
        override
        checkDeadline(params.deadline)
        returns (int256 amount0, int256 amount1)
    {
        require(params.token0 < params.token1);
        address pool = PoolAddress.getAddress(
            factory,
            PoolAddress.getPoolKey(
                params.token0,
                params.token1,
                params.maintenance,
                params.oracle
            )
        );

        (
            uint160 sqrtPriceX96Existing,
            ,
            uint128 liquidityExisting,
            ,
            ,
            ,
            ,
            bool initialized
        ) = IMarginalV1Pool(pool).state();
        if (!initialized) revert PoolNotInitialized();

        // calculate amount in needed (including fees) to get pool price to sqrtPriceX96 desired
        // @dev ignores fee add to liquidity effect on price for simplicity
        (int256 amount0Delta, int256 amount1Delta) = SwapMath.swapAmounts(
            liquidityExisting,
            sqrtPriceX96Existing,
            params.sqrtPriceX96
        );
        bool zeroForOne = params.sqrtPriceX96 < sqrtPriceX96Existing;
        int256 amountSpecified = zeroForOne ? amount0Delta : amount1Delta;
        require(amountSpecified > 0);
        amountSpecified += int256(
            SwapMath.swapFees(uint256(amountSpecified), PoolConstants.fee, true)
        );

        uint256 amountInMaximum = params.amountInMaximum == 0
            ? type(uint256).max
            : params.amountInMaximum;
        if (uint256(amountSpecified) > amountInMaximum)
            revert AmountInGreaterThanMax(uint256(amountSpecified));

        SwapCallbackData memory data = SwapCallbackData({
            path: abi.encodePacked(
                zeroForOne ? params.token0 : params.token1, // tokenIn
                params.maintenance,
                params.oracle,
                zeroForOne ? params.token1 : params.token0 // tokenOut
            ),
            payer: msg.sender
        });

        (amount0, amount1) = IMarginalV1Pool(pool).swap(
            params.recipient,
            zeroForOne,
            amountSpecified,
            params.sqrtPriceLimitX96 == 0
                ? (
                    zeroForOne
                        ? TickMath.MIN_SQRT_RATIO + 1
                        : TickMath.MAX_SQRT_RATIO - 1
                )
                : params.sqrtPriceLimitX96,
            abi.encode(data)
        );
        uint256 amountOut = uint256(-(zeroForOne ? amount1 : amount0));
        if (amountOut < params.amountOutMinimum)
            revert AmountOutLessThanMin(amountOut);
    }

    /// @inheritdoc IPoolInitializer
    function initializeOracleIfNecessary(
        InitializeOracleParams calldata params
    ) external override {
        require(params.token0 < params.token1);
        address oracle = IUniswapV3Factory(uniswapV3Factory).getPool(
            params.token0,
            params.token1,
            params.uniswapV3Fee
        );
        if (oracle == address(0)) revert InvalidOracle();

        (
            ,
            ,
            ,
            ,
            uint16 observationCardinalityNextExisting,
            ,

        ) = IUniswapV3Pool(oracle).slot0();
        uint16 observationCardinalityMinimum = IMarginalV1Factory(factory)
            .observationCardinalityMinimum();
        require(
            observationCardinalityNextExisting <
                params.observationCardinalityNext &&
                observationCardinalityMinimum <=
                params.observationCardinalityNext
        );

        if (
            observationCardinalityNextExisting < observationCardinalityMinimum
        ) {
            IUniswapV3Pool(oracle).increaseObservationCardinalityNext(
                params.observationCardinalityNext
            );
        }
    }
}

File 2 of 38 : SwapMath.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

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

/// @title Math library for swaps
/// @notice Determines amounts involved in swaps
library SwapMath {
    /// @notice Computes amounts in and out on swap without fees
    /// @dev amount > 0 is amountIn, amount < 0 is amountOut
    /// @param liquidity Pool liquidity before the swap
    /// @param sqrtPriceX96 Pool price at the start of the swap
    /// @param sqrtPriceX96Next Pool price at the end of the swap
    /// @return amount0Delta The delta in token0 balance for the pool
    /// @return amount1Delta The delta in token1 balance for the pool
    function swapAmounts(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint160 sqrtPriceX96Next
    ) internal pure returns (int256 amount0Delta, int256 amount1Delta) {
        // del x = L * del (1 / sqrt(P)); del y = L * del sqrt(P)
        bool zeroForOne = sqrtPriceX96Next < sqrtPriceX96;
        amount0Delta =
            int256(
                (uint256(liquidity) << FixedPoint96.RESOLUTION) /
                    sqrtPriceX96Next
            ) -
            int256(
                (uint256(liquidity) << FixedPoint96.RESOLUTION) / sqrtPriceX96
            );
        amount1Delta = zeroForOne
            ? -int256(
                Math.mulDiv(
                    liquidity,
                    sqrtPriceX96 - sqrtPriceX96Next,
                    FixedPoint96.Q96
                )
            )
            : int256(
                Math.mulDiv(
                    liquidity,
                    sqrtPriceX96Next - sqrtPriceX96,
                    FixedPoint96.Q96
                )
            );
    }

    /// @notice Computes swap fee on amount in
    /// @dev Can revert when amount > type(uint232).max, but irrelevant for SwapMath.sol::swapAmounts output and pool fee rate constant
    /// @param amount Amount in to calculate swap fees off of
    /// @param fee Fee rate applied on amount in to pool
    /// @param lessFee Whether `amount` excludes swap fee amount
    /// @return Total swap fees taken from amount in to pool
    function swapFees(
        uint256 amount,
        uint24 fee,
        bool lessFee
    ) internal pure returns (uint256) {
        return (!lessFee ? (amount * fee) / 1e6 : (amount * fee) / (1e6 - fee));
    }
}

File 3 of 38 : FixedPoint96.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

File 4 of 38 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 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.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

            // 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;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

File 5 of 38 : IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

File 6 of 38 : IMarginalV1Factory.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

/// @title The interface for the Marginal v1 factory
/// @notice The Marginal v1 factory creates pools and enables leverage tiers
interface IMarginalV1Factory {
    /// @notice Returns the Marginal v1 pool deployer to use when creating pools
    /// @return The address of the Marginal v1 pool deployer
    function marginalV1Deployer() external view returns (address);

    /// @notice Returns the Uniswap v3 factory to reference for pool oracles
    /// @return The address of the Uniswap v3 factory
    function uniswapV3Factory() external view returns (address);

    /// @notice Returns the minimum observation cardinality the Uniswap v3 oracle must have
    /// @dev Used as a check that averaging over `secondsAgo` in the Marginal v1 pool is likely to succeed
    /// @return The minimum observation cardinality the Uniswap v3 oracle must have
    function observationCardinalityMinimum() external view returns (uint16);

    /// @notice Returns the current owner of the Marginal v1 factory contract
    /// @dev Changed via permissioned `setOwner` function on the factory
    /// @return The address of the current owner of the Marginal v1 factory
    function owner() external view returns (address);

    /// @notice Returns the pool address for the given unique Marginal v1 pool key
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The address of either token0/token1
    /// @param tokenB The address of the other token token1/token0
    /// @param maintenance The minimum maintenance requirement for the pool
    /// @param oracle The address of the Uniswap v3 oracle used by the pool
    /// @return The address of the Marginal v1 pool
    function getPool(
        address tokenA,
        address tokenB,
        uint24 maintenance,
        address oracle
    ) external view returns (address);

    /// @notice Returns whether given address is a Marginal v1 pool deployed by the factory
    /// @return Whether address is a pool
    function isPool(address pool) external view returns (bool);

    /// @notice Returns the maximum leverage associated with the pool maintenance if pool exists
    /// @param maintenance The minimum maintenance margin requirement for the pool
    /// @return The maximum leverage for the pool maintenance if pool exists
    function getLeverage(uint24 maintenance) external view returns (uint256);

    /// @notice Creates a new Marginal v1 pool for the given unique pool key
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The address of either token0/token1
    /// @param tokenB The address of the other token token1/token0
    /// @param maintenance The minimum maintenance requirement for the pool
    /// @param uniswapV3Fee The fee tier of the Uniswap v3 oracle used by the Marginal v1 pool
    /// @return pool The address of the created Marginal v1 pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 maintenance,
        uint24 uniswapV3Fee
    ) external returns (address pool);

    /// @notice Sets the owner of the Marginal v1 factory contract
    /// @dev Can only be called by the current factory owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a new leverage tier for Marginal v1 pool deployments
    /// @dev Can only be called by the current factory owner
    /// @dev Set leverage tier obeys: l = 1 + 1/M; M = maintenance
    /// @param maintenance The minimum maintenance requirement associated with the leverage tier
    function enableLeverage(uint24 maintenance) external;
}

File 7 of 38 : Path.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import "@uniswap/v3-periphery/contracts/libraries/BytesLib.sol";

/// @title Functions for manipulating path data for multihop swaps
/// @dev Fork of Uniswap V3 periphery Path.sol
library Path {
    using BytesLib for bytes;

    /// @dev The length of the bytes encoded address
    uint256 private constant ADDR_SIZE = 20;
    /// @dev The length of the bytes encoded maintenance
    uint256 private constant MAINTENANCE_SIZE = 3;

    /// @dev The offset of a single token address, pool maintenance, and oracle
    uint256 private constant NEXT_OFFSET =
        ADDR_SIZE + MAINTENANCE_SIZE + ADDR_SIZE;
    /// @dev The offset of an encoded pool key
    uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
    /// @dev The minimum length of an encoding that contains 2 or more pools
    uint256 private constant MULTIPLE_POOLS_MIN_LENGTH =
        POP_OFFSET + NEXT_OFFSET;

    /// @notice Returns true iff the path contains two or more pools
    /// @param path The encoded swap path
    /// @return True if path contains two or more pools, otherwise false
    function hasMultiplePools(bytes memory path) internal pure returns (bool) {
        return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
    }

    /// @notice Returns the number of pools in the path
    /// @param path The encoded swap path
    /// @return The number of pools in the path
    function numPools(bytes memory path) internal pure returns (uint256) {
        // Ignore the first token address. From then on every maintenance and token offset indicates a pool.
        return ((path.length - ADDR_SIZE) / NEXT_OFFSET);
    }

    /// @notice Decodes the first pool in path
    /// @param path The bytes encoded swap path
    /// @return tokenA The first token of the given pool
    /// @return tokenB The second token of the given pool
    /// @return maintenance The maintenance level of the pool
    /// @return oracle The oracle referenced by the given pool
    function decodeFirstPool(
        bytes memory path
    )
        internal
        pure
        returns (
            address tokenA,
            address tokenB,
            uint24 maintenance,
            address oracle
        )
    {
        tokenA = path.toAddress(0);
        maintenance = path.toUint24(ADDR_SIZE);
        oracle = path.toAddress(ADDR_SIZE + MAINTENANCE_SIZE);
        tokenB = path.toAddress(NEXT_OFFSET);
    }

    /// @notice Gets the segment corresponding to the first pool in the path
    /// @param path The bytes encoded swap path
    /// @return The segment containing all data necessary to target the first pool in the path
    function getFirstPool(
        bytes memory path
    ) internal pure returns (bytes memory) {
        return path.slice(0, POP_OFFSET);
    }

    /// @notice Skips a token + maintenance + oracle element from the buffer and returns the remainder
    /// @param path The swap path
    /// @return The remaining token + maintenance + oracle elements in the path
    function skipToken(bytes memory path) internal pure returns (bytes memory) {
        return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
    }
}

File 8 of 38 : BytesLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.8.0 <0.9.0;

library BytesLib {
    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, 'slice_overflow');
        require(_bytes.length >= _start + _length, 'slice_outOfBounds');

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    mstore(mc, mload(cc))
                }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
        require(_start + 3 >= _start, 'toUint24_overflow');
        require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
        uint24 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x3), _start))
        }

        return tempUint;
    }
}

File 9 of 38 : IPoolInitializer.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;

/// @title Interface for the Marginal v1 pool initializer
/// @notice Provides methods for preparing, creating and initializing a Marginal v1 pool
interface IPoolInitializer {
    struct CreateAndInitializeParams {
        address token0;
        address token1;
        uint24 maintenance;
        uint24 uniswapV3Fee;
        address recipient;
        uint160 sqrtPriceX96;
        uint160 sqrtPriceLimitX96;
        uint128 liquidityBurned;
        int256 amount0BurnedMax;
        int256 amount1BurnedMax;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @param params The parameters necessary to create and initialize a pool, encoded as `CreateAndInitializeParams` in calldata
    /// @return pool Returns the pool address based on the pair of tokens, Uniswap v3 fee, and maintenance, will return the newly created pool address if necessary
    /// @return shares The amount of shares minted to `params.recipient` after initializing pool with liquidity
    /// @return amount0 The amount of the input token0 to create and initialize pool
    /// @return amount1 The amount of the input token1 to create and initialize pool
    function createAndInitializePoolIfNecessary(
        CreateAndInitializeParams calldata params
    )
        external
        payable
        returns (address pool, uint256 shares, int256 amount0, int256 amount1);

    struct InitializePoolSqrtPriceX96Params {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint160 sqrtPriceX96;
        uint256 amountInMaximum;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
        uint256 deadline;
    }

    /// @notice Swaps through pool to set the pool price
    /// @dev Intended for pools with dust amounts of liquidity as otherwise amount in will be substantial
    /// Ignores effect on pool price of adding fee to liquidity for simplicity. Results in difference of < 1 bps in practice vs desired price
    /// @param params The parameters necessary to initialize pool with `params.sqrtPriceX96`
    /// @return amount0 The amount of the input token0 to set the price
    /// @return amount1 The amount of the input token1 to set the price
    function initializePoolSqrtPriceX96(
        InitializePoolSqrtPriceX96Params memory params
    ) external payable returns (int256 amount0, int256 amount1);

    struct InitializeOracleParams {
        address token0;
        address token1;
        uint24 uniswapV3Fee;
        uint16 observationCardinalityNext;
    }

    /// @notice Increases observationCardinalityNext on oracle Uniswap v3 pool, if necessary, to prepare for Marginal v1 pool creation.
    /// @dev There will be a time lag between increasing observationCardinalityNext on the oracle pool and when observationCardinality on slot0 changes.
    /// @param params The parameters necessary to initialize oracle for pool, encoded as `InitializeOracleParams` in calldata
    function initializeOracleIfNecessary(
        InitializeOracleParams calldata params
    ) external;
}

File 10 of 38 : IMarginalV1Pool.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

/// @title The interface for a Marginal v1 pool
/// @notice A Marginal v1 pool facilitates leverage trading, swapping, and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev Inherits from IERC20 as liquidity providers are minted fungible pool tokens
interface IMarginalV1Pool is IERC20 {
    /// @notice The Marginal v1 factory that created the pool
    /// @return The address of the Marginal v1 factory
    function factory() external view returns (address);

    /// @notice The Uniswap v3 oracle referenced by the pool for funding and position safety
    /// @return The address of the Uniswap v3 oracle referenced by the pool
    function oracle() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The address of the token0 contract
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The address of the token1 contract
    function token1() external view returns (address);

    /// @notice The minimum maintenance requirement for leverage positions on the pool
    /// @return The minimum maintenance requirement
    function maintenance() external view returns (uint24);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The premium multiplier on liquidation rewards in hundredths of a bip, i.e. 1e-6
    /// @dev Liquidation rewards set aside in native (gas) token.
    /// Premium acts as an incentive above the expected gas cost to call IMarginalV1Pool#liquidate.
    /// @return The premium multiplier
    function rewardPremium() external view returns (uint24);

    /// @notice The maximum rate of change in tick cumulative between the Marginal v1 pool and the Uniswap v3 oracle
    /// @dev Puts a ceiling on funding paid per second
    /// @return The maximum tick cumulative rate per second
    function tickCumulativeRateMax() external view returns (uint24);

    /// @notice The amount of time in seconds to average the Uniswap v3 oracle TWAP over to assess position safety
    /// @return The averaging time for the Uniswap v3 oracle TWAP in seconds
    function secondsAgo() external view returns (uint32);

    /// @notice The period in seconds to benchmark funding payments with respect to
    /// @dev Acts as an averaging period on tick cumulative changes between the Marginal v1 pool and the Uniswap v3 oracle
    /// @return The funding period in seconds
    function fundingPeriod() external view returns (uint32);

    /// @notice The pool state represented in (L, sqrt(P)) space
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// totalPositions The total number of leverage positions that have ever been taken out on the pool
    /// liquidity The currently available liquidity offered by the pool for swaps and leverage positions
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// blockTimestamp The last `block.timestamp` at which state was synced
    /// tickCumulative The tick cumulative running sum of the pool, used in funding calculations
    /// feeProtocol The protocol fee for both tokens of the pool
    /// initialized Whether the pool has been initialized
    function state()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            uint96 totalPositions,
            uint128 liquidity,
            int24 tick,
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint8 feeProtocol,
            bool initialized
        );

    /// @notice The liquidity used to capitalize outstanding leverage positions
    /// @return The liquidity locked for outstanding leverage positions
    function liquidityLocked() external view returns (uint128);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    /// @return protocolFees0 The amount of token0 owed to the protocol
    /// @return protocolFees1 The amount of token1 owed to the protocol
    function protocolFees()
        external
        view
        returns (uint128 protocolFees0, uint128 protocolFees1);

    /// @notice Returns information about a leverage position by the position's key
    /// @dev Either debt0 (zeroForOne = true) or debt1 (zeroForOne = false) will be updated each funding sync
    /// @param key The position's key is a hash of the packed encoding of the owner and the position ID
    /// @return size The position size in the token the owner is long
    /// debt0 The position debt in token0 owed to the pool at settlement. If long token1 (zeroForOne = true), this is the debt to be repaid at settlement by owner. Otherwise, simply used for internal accounting
    /// debt1 The position debt in token1 owed to the pool at settlement. If long token0 (zeroForOne = false), this is the debt to be repaid at settlement by owner. Otherwise, simply used for internal accounting
    /// insurance0 The insurance in token0 set aside to backstop the position in case of late liquidations
    /// insurance1 The insurance in token1 set aside to backstop the position in case of late liquidations
    /// zeroForOne Whether the position is long token1 and short token0 (true) or long token0 and short token1 (false)
    /// liquidated Whether the position has been liquidated
    /// tick The pool tick prior to opening the position
    /// blockTimestamp The `block.timestamp` at which the position was last synced for funding
    /// tickCumulativeDelta The difference in the Uniswap v3 oracle tick cumulative and the Marginal v1 pool tick cumulative at the last funding sync
    /// margin The position margin in the token the owner is long
    /// liquidityLocked The liquidity locked by the pool to collateralize the position
    /// rewards The liquidation rewards in the native (gas) token received by liquidator if position becomes unsafe
    function positions(
        bytes32 key
    )
        external
        view
        returns (
            uint128 size,
            uint128 debt0,
            uint128 debt1,
            uint128 insurance0,
            uint128 insurance1,
            bool zeroForOne,
            bool liquidated,
            int24 tick,
            uint32 blockTimestamp,
            int56 tickCumulativeDelta,
            uint128 margin,
            uint128 liquidityLocked,
            uint256 rewards
        );

    /// @notice Opens a leverage position on the pool
    /// @dev The caller of this method receives a callback in the form of IMarginalV1OpenCallback#marginalV1OpenCallback.
    /// The caller must forward liquidation rewards in the native (gas) token to be escrowed by the pool contract
    /// Rewards determined by current `block.basefee` * estimated gas cost to call IMarginalV1Pool#liquidate * rewardPremium
    /// @param recipient The address of the owner of the opened position
    /// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @param liquidityDelta The amount of liquidity for the pool to lock to capitalize the position
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after opening the position otherwise the call reverts. If one for zero, the price cannot be greater than this value after opening
    /// @param margin The amount of margin used to back the position in the token the position is long
    /// @param data Any data to be passed through to the callback
    /// @return id The ID of the opened position
    /// @return size The size of the opened position in the token the position is long. Excludes margin amount provided by caller
    /// @return debt The debt of the opened position in the token the position is short
    /// @return amount0 The amount of token0 caller must send to pool to open the position
    /// @return amount1 The amount of token1 caller must send to pool to open the position
    function open(
        address recipient,
        bool zeroForOne,
        uint128 liquidityDelta,
        uint160 sqrtPriceLimitX96,
        uint128 margin,
        bytes calldata data
    )
        external
        payable
        returns (
            uint256 id,
            uint256 size,
            uint256 debt,
            uint256 amount0,
            uint256 amount1
        );

    /// @notice Adjusts the margin used to back a position on the pool
    /// @dev The caller of this method receives a callback in the form of IMarginalV1AdjustCallback#marginalV1AdjustCallback
    /// Old position margin is flashed out to recipient prior to the callback
    /// @param recipient The address to receive the old position margin
    /// @param id The ID of the position to adjust
    /// @param marginDelta The delta of the margin backing the position on the pool. Adding margin to the position when positive, removing margin when negative
    /// @param data Any data to be passed through to the callback
    /// @return margin0 The amount of token0 to be used as the new margin backing the position
    /// @return margin1 The amount of token1 to be used as the new margin backing the position
    function adjust(
        address recipient,
        uint96 id,
        int128 marginDelta,
        bytes calldata data
    ) external returns (uint256 margin0, uint256 margin1);

    /// @notice Settles a position on the pool
    /// @dev The caller of this method receives a callback in the form of IMarginalV1SettleCallback#marginalV1SettleCallback.
    /// If a contract, `recipient` must implement a `receive()` function to receive the escrowed liquidation rewards in the native (gas) token from the pool.
    /// Position size, margin, and liquidation rewards are flashed out before the callback to allow the caller to swap to repay the debt to the pool
    /// @param recipient The address to receive the size, margin, and liquidation rewards of the settled position
    /// @param id The ID of the position to settle
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool. Position debt into the pool (> 0) if long token1 (zeroForOne = true), or position size and margin out of the pool (< 0) if long token0 (zeroForOne = false)
    /// @return amount1 The delta of the balance of token1 of the pool. Position size and margin out of the pool (< 0) if long token1 (zeroForOne = true), or position debt into the pool (> 0) if long token0 (zeroForOne = false)
    /// @return rewards The amount of escrowed native (gas) token sent to `recipient`
    function settle(
        address recipient,
        uint96 id,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1, uint256 rewards);

    /// @notice Liquidates a position on the pool
    /// @dev Reverts if position is safe from liquidation. Position is considered safe if
    /// (`position.margin` + `position.size`) / oracleTwap >= (1 + `maintenance`) * `position.debt0` when position.zeroForOne = true
    /// (`position.margin` + `position.size`) * oracleTwap >= (1 + `maintenance`) * `position.debt1` when position.zeroForOne = false
    /// Safety checks are performed after syncing the position debts for funding payments
    /// If a contract, `recipient` must implement a `receive()` function to receive the escrowed liquidation rewards in the native (gas) token from the pool.
    /// @param recipient The address to receive liquidation rewards escrowed with the position
    /// @param owner The address of the owner of the position to liquidate
    /// @param id The ID of the position to liquidate
    /// @return rewards The amount of escrowed native (gas) token sent to `recipient`
    function liquidate(
        address recipient,
        address owner,
        uint96 id
    ) external returns (uint256 rewards);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IMarginalV1SwapCallback#marginalV1SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap otherwise the call reverts. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Adds liquidity to the pool
    /// @dev The caller of this method receives a callback in the form of IMarginalV1MintCallback#marginalV1MintCallback.
    /// The pool is initialized through the first call to mint
    /// @param recipient The address to mint LP tokens to after adding liquidity to the pool
    /// @param liquidityDelta The liquidity added to the pool
    /// @param data Any data to be passed through to the callback
    /// @return shares The amount of LP token shares minted to recipient
    /// @return amount0 The amount of token0 added to the pool reserves
    /// @return amount1 The amount of token1 added to the pool reserves
    function mint(
        address recipient,
        uint128 liquidityDelta,
        bytes calldata data
    ) external returns (uint256 shares, uint256 amount0, uint256 amount1);

    /// @notice Removes liquidity from the pool
    /// @dev Reverts if not enough liquidity available to exit due to outstanding leverage positions
    /// @param recipient The address to send token amounts to after removing liquidity from the pool
    /// @param shares The amount of LP token shares to burn
    /// @return liquidityDelta The liquidity removed from the pool
    /// @return amount0 The amount of token0 removed from pool reserves
    /// @return amount1 The amount of token1 removed from pool reserves
    function burn(
        address recipient,
        uint256 shares
    )
        external
        returns (uint128 liquidityDelta, uint256 amount0, uint256 amount1);

    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol new protocol fee denominator for the pool
    function setFeeProtocol(uint8 feeProtocol) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient
    ) external returns (uint128 amount0, uint128 amount1);
}

File 11 of 38 : 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 12 of 38 : PoolConstants.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

/// @title PoolConstants
/// @notice A library for pool internal constants relevant for periphery contracts
library PoolConstants {
    uint24 internal constant fee = 1000; // 10 bps across all pools
    uint24 internal constant rewardPremium = 2000000; // 2x base fee as liquidation rewards
    uint24 internal constant tickCumulativeRateMax = 920; // bound on funding rate of ~10% per funding period

    uint32 internal constant secondsAgo = 43200; // 12 hr TWAP for oracle price
    uint32 internal constant fundingPeriod = 604800; // 7 day funding period

    // @dev varies for different chains
    uint256 internal constant blockBaseFeeMin = 40e9; // min base fee for liquidation rewards
    uint256 internal constant gasLiquidate = 150000; // gas required to call liquidate

    uint128 internal constant MINIMUM_LIQUIDITY = 10000; // liquidity locked on initial mint always available for swaps
    uint128 internal constant MINIMUM_SIZE = 10000; // minimum position size, debt, insurance amounts to prevent dust sizes
}

File 13 of 38 : Multicall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;
pragma abicoder v2;

import '../interfaces/IMulticall.sol';

/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(data[i]);

            if (!success) {
                // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                if (result.length < 68) revert();
                assembly {
                    result := add(result, 0x04)
                }
                revert(abi.decode(result, (string)));
            }

            results[i] = result;
        }
    }
}

File 14 of 38 : IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

File 15 of 38 : PeripheryValidation.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import './BlockTimestamp.sol';

abstract contract PeripheryValidation is BlockTimestamp {
    modifier checkDeadline(uint256 deadline) {
        require(_blockTimestamp() <= deadline, 'Transaction too old');
        _;
    }
}

File 16 of 38 : BlockTimestamp.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

/// @title Function for getting block timestamp
/// @dev Base contract that is overridden for tests
abstract contract BlockTimestamp {
    /// @dev Method that exists purely to be overridden for tests
    /// @return The current block timestamp
    function _blockTimestamp() internal view virtual returns (uint256) {
        return block.timestamp;
    }
}

File 17 of 38 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio = absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

File 18 of 38 : CallbackValidation.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";

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

/// @notice Provides validation for callbacks from Marginal V1 Pools
/// @dev Fork of Uniswap V3 periphery CallbackValidation.sol
library CallbackValidation {
    error PoolNotSender();
    error OracleNotSender();

    /// @notice Returns the address of a valid Marginal V1 Pool
    /// @param factory The contract address of the Marginal V1 factory
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param maintenance The maintenance requirements of the pool
    /// @param oracle The contract address of the oracle referenced by the pool
    /// @return pool The V1 pool contract address
    function verifyCallback(
        address factory,
        address tokenA,
        address tokenB,
        uint24 maintenance,
        address oracle
    ) internal view returns (IMarginalV1Pool pool) {
        return
            verifyCallback(
                factory,
                PoolAddress.getPoolKey(tokenA, tokenB, maintenance, oracle)
            );
    }

    /// @notice Returns the address of a valid Marginal V1 Pool
    /// @param factory The contract address of the Marginal V1 factory
    /// @param poolKey The identifying key of the V1 pool
    /// @return pool The V1 pool contract address
    function verifyCallback(
        address factory,
        PoolAddress.PoolKey memory poolKey
    ) internal view returns (IMarginalV1Pool pool) {
        pool = IMarginalV1Pool(PoolAddress.getAddress(factory, poolKey));
        if (msg.sender != address(pool)) revert PoolNotSender();
    }

    /// @notice Returns the address of a valid Uniswap V3 Pool
    /// @param factory The contract address of the Marginal V1 factory
    /// @param poolKey The identifying key of the V1 pool
    /// @return uniswapV3Pool The Uniswap V3 pool oracle address associated with the V1 pool
    function verifyUniswapV3Callback(
        address factory,
        PoolAddress.PoolKey memory poolKey
    ) internal view returns (IUniswapV3Pool uniswapV3Pool) {
        PoolAddress.getAddress(factory, poolKey); // checks marginal pool active
        uniswapV3Pool = IUniswapV3Pool(poolKey.oracle);
        if (msg.sender != poolKey.oracle) revert OracleNotSender();
    }
}

File 19 of 38 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{

}

File 20 of 38 : IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 21 of 38 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 22 of 38 : IUniswapV3PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
}

File 23 of 38 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

File 24 of 38 : IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

File 25 of 38 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 26 of 38 : IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

File 27 of 38 : PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IMarginalV1Factory} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Factory.sol";

/// @dev Fork of Uniswap V3 periphery PoolAddress.sol
library PoolAddress {
    error PoolInactive();

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param maintenance The maintenance level of the pool
    /// @param oracle The contract address of the oracle referenced by the pool
    /// @return PoolKey The pool details with ordered token0 and token1 assignments
    function getPoolKey(
        address tokenA,
        address tokenB,
        uint24 maintenance,
        address oracle
    ) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return
            PoolKey({
                token0: tokenA,
                token1: tokenB,
                maintenance: maintenance,
                oracle: oracle
            });
    }

    /// @notice Gets the pool address from factory given pool key
    /// @dev Reverts if pool not created yet
    /// @param factory The factory contract address
    /// @param key The pool key
    /// @return pool The contract address of the pool
    function getAddress(
        address factory,
        PoolKey memory key
    ) internal view returns (address pool) {
        pool = IMarginalV1Factory(factory).getPool(
            key.token0,
            key.token1,
            key.maintenance,
            key.oracle
        );
        if (pool == address(0)) revert PoolInactive();
    }

    /// @notice Checks factory for whether `pool` is a valid pool
    /// @param factory The factory contract address
    /// @param pool The contract address to check whether is a pool
    function isPool(
        address factory,
        address pool
    ) internal view returns (bool) {
        return IMarginalV1Factory(factory).isPool(pool);
    }
}

File 28 of 38 : LiquidityManagement.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;

import {IMarginalV1MintCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1MintCallback.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";

import {PeripheryImmutableState} from "./PeripheryImmutableState.sol";
import {PeripheryPayments} from "./PeripheryPayments.sol";
import {CallbackValidation} from "../libraries/CallbackValidation.sol";
import {PoolAddress} from "../libraries/PoolAddress.sol";

abstract contract LiquidityManagement is
    IMarginalV1MintCallback,
    PeripheryImmutableState,
    PeripheryPayments
{
    struct LiquidityCallbackData {
        PoolAddress.PoolKey poolKey;
        address payer;
    }

    error Amount0LessThanMin(uint256 amount0);
    error Amount1LessThanMin(uint256 amount1);

    /// @dev Returns the pool for the given token pair and maintenance. The pool contract may or may not exist.
    function getPool(
        PoolAddress.PoolKey memory poolKey
    ) internal view returns (IMarginalV1Pool) {
        return IMarginalV1Pool(PoolAddress.getAddress(factory, poolKey));
    }

    struct MintParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint128 liquidityDelta;
        uint256 amount0Min;
        uint256 amount1Min;
    }

    /// @notice Mints liquidity on pool
    /// @dev Beware of re-entrancy issues given implicit ETH transfer at end of function
    /// @param params The parameters necessary to mint liquidity on the pool
    /// @return shares The amount of LP token shares minted to recipient
    /// @return amount0 The amount of token0 added to the pool reserves
    /// @return amount1 The amount of token1 added to the pool reserves
    function mint(
        MintParams memory params
    )
        internal
        virtual
        returns (uint256 shares, uint256 amount0, uint256 amount1)
    {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        (shares, amount0, amount1) = pool.mint(
            params.recipient,
            params.liquidityDelta,
            abi.encode(
                LiquidityCallbackData({poolKey: poolKey, payer: msg.sender})
            )
        );

        if (amount0 < params.amount0Min) revert Amount0LessThanMin(amount0);
        if (amount1 < params.amount1Min) revert Amount1LessThanMin(amount1);
    }

    /// @inheritdoc IMarginalV1MintCallback
    function marginalV1MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external virtual {
        LiquidityCallbackData memory decoded = abi.decode(
            data,
            (LiquidityCallbackData)
        );
        CallbackValidation.verifyCallback(factory, decoded.poolKey);

        if (amount0Owed > 0)
            pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
        if (amount1Owed > 0)
            pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
    }

    struct BurnParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint256 shares;
        uint256 amount0Min;
        uint256 amount1Min;
    }

    /// @notice Burns liquidity on pool
    /// @param params The parameters necessary to burn liquidity on the pool
    /// @return liquidityDelta The liquidity removed from the pool
    /// @return amount0 The amount of token0 removed from pool reserves
    /// @return amount1 The amount of token1 removed from pool reserves
    function burn(
        BurnParams memory params
    )
        internal
        virtual
        returns (uint128 liquidityDelta, uint256 amount0, uint256 amount1)
    {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        if (params.shares > 0)
            pay(address(pool), msg.sender, address(this), params.shares);

        (liquidityDelta, amount0, amount1) = pool.burn(
            params.recipient,
            params.shares
        );

        if (amount0 < params.amount0Min) revert Amount0LessThanMin(amount0);
        if (amount1 < params.amount1Min) revert Amount1LessThanMin(amount1);
    }
}

File 29 of 38 : PeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

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

import {IWETH9} from "@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol";
import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";

import {PoolAddress} from "../libraries/PoolAddress.sol";
import {IPeripheryPayments} from "../interfaces/IPeripheryPayments.sol";
import {PeripheryImmutableState} from "./PeripheryImmutableState.sol";

abstract contract PeripheryPayments is
    IPeripheryPayments,
    PeripheryImmutableState
{
    receive() external payable {
        // WETH9 if unwrap, pool when receiving escrowed liquidation rewards
        require(
            msg.sender == WETH9 || PoolAddress.isPool(factory, msg.sender),
            "Not WETH9 or pool"
        );
    }

    /// @inheritdoc IPeripheryPayments
    function unwrapWETH9(
        uint256 amountMinimum,
        address recipient
    ) public payable override {
        uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
        require(balanceWETH9 >= amountMinimum, "Insufficient WETH9");

        if (balanceWETH9 > 0) {
            IWETH9(WETH9).withdraw(balanceWETH9);
            TransferHelper.safeTransferETH(recipient, balanceWETH9);
        }
    }

    /// @inheritdoc IPeripheryPayments
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) public payable override {
        uint256 balanceToken = IERC20(token).balanceOf(address(this));
        require(balanceToken >= amountMinimum, "Insufficient token");

        if (balanceToken > 0) {
            TransferHelper.safeTransfer(token, recipient, balanceToken);
        }
    }

    /// @inheritdoc IPeripheryPayments
    function refundETH() public payable override {
        if (address(this).balance > 0)
            TransferHelper.safeTransferETH(msg.sender, address(this).balance);
    }

    /// @inheritdoc IPeripheryPayments
    function sweepETH(uint256 amountMinimum, address recipient) public payable {
        uint256 balanceETH = address(this).balance;
        require(balanceETH >= amountMinimum, "Insufficient ETH");

        if (balanceETH > 0)
            TransferHelper.safeTransferETH(recipient, balanceETH);
    }

    /// @notice Wraps balance of native (gas) token in contract to WETH9
    function wrapETH() internal {
        if (address(this).balance > 0)
            IWETH9(WETH9).deposit{value: address(this).balance}();
    }

    /// @notice Pay ERC20 token to recipient
    /// @param token The token to pay
    /// @param payer The entity that must pay
    /// @param recipient The entity that will receive payment
    /// @param value The amount to pay
    function pay(
        address token,
        address payer,
        address recipient,
        uint256 value
    ) internal {
        if (token == WETH9 && address(this).balance >= value) {
            // pay with WETH9
            IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
            IWETH9(WETH9).transfer(recipient, value);
        } else if (payer == address(this)) {
            // pay with tokens already in the contract (for the exact input multihop case)
            TransferHelper.safeTransfer(token, recipient, value);
        } else {
            // pull payment
            TransferHelper.safeTransferFrom(token, payer, recipient, value);
        }
    }

    /// @notice Balance of ERC20 token held by this contract
    /// @param token The token to check
    /// @return value The balance amount
    function balance(address token) internal view returns (uint256 value) {
        return IERC20(token).balanceOf(address(this));
    }
}

File 30 of 38 : IPeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(
        uint256 amountMinimum,
        address recipient
    ) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;

    /// @notice Transfers the full amount of ETH held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the ETH from users
    /// @param amountMinimum The minimum amount of ETH required for a transfer
    /// @param recipient The destination address of the ETH
    function sweepETH(
        uint256 amountMinimum,
        address recipient
    ) external payable;
}

File 31 of 38 : IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

File 32 of 38 : PeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;

import {IMarginalV1Factory} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Factory.sol";

import "../interfaces/IPeripheryImmutableState.sol";

/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract PeripheryImmutableState is IPeripheryImmutableState {
    address public immutable factory;
    address public immutable uniswapV3Factory;
    address public immutable WETH9;

    constructor(address _factory, address _WETH9) {
        factory = _factory;
        uniswapV3Factory = IMarginalV1Factory(_factory).uniswapV3Factory();
        WETH9 = _WETH9;
    }
}

File 33 of 38 : IPeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Marginal V1 factory
    function factory() external view returns (address);

    /// @return Returns the address of the Uniswap V3 factory
    function uniswapV3Factory() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}

File 34 of 38 : TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)
        );
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}

File 35 of 38 : IMarginalV1MintCallback.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

/// @title The interface for the Marginal v1 mint callback
/// @notice Callbacks called by Marginal v1 pools when adding liquidity
/// @dev Any contract that calls IMarginalV1Pool#mint must implement this interface
interface IMarginalV1MintCallback {
    /// @notice Called to `msg.sender` after adding liquidity via IMarginalV1Pool#mint
    /// @dev In the implementation you must pay the pool tokens owed to add liquidity to the pool and mint LP tokens.
    /// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
    /// @param amount0Owed The amount of token0 that must be payed to pool to successfully mint LP tokens
    /// @param amount1Owed The amount of token1 that must be payed to pool to successfully mint LP tokens
    /// @param data Any data passed through by the caller via the IMarginalV1Pool#mint call
    function marginalV1MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;
}

File 36 of 38 : IMarginalV1SwapCallback.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

/// @title The interface for the Marginal v1 swap callback
/// @notice Callbacks called by Marginal v1 pools when executing a swap
/// @dev Any contract that calls IMarginalV1Pool#swap must implement this interface
interface IMarginalV1SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IMarginalV1Pool#swap
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
    /// Amount that must be payed to pool is > 0 as IMarginalV1Pool#swap reverts otherwise.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IMarginalV1Pool#swap call
    function marginalV1SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 37 of 38 : LiquidityAmounts.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import {FixedPoint96} from "@marginal/v1-core/contracts/libraries/FixedPoint96.sol";

/// @title Liquidity amounts library
/// @notice Calculates liquidity from desired reserve amounts
library LiquidityAmounts {
    using SafeCast for uint256;

    /// @notice Gets the pool liquidity contribution for a given amount of token0
    /// @param sqrtPriceX96 The sqrt price of the pool
    /// @param amount0 The amount of token0
    /// @return The liquidity contribution
    function getLiquidityForAmount0(
        uint160 sqrtPriceX96,
        uint256 amount0
    ) internal pure returns (uint128) {
        return
            (Math.mulDiv(amount0, sqrtPriceX96, FixedPoint96.Q96)).toUint128();
    }

    /// @notice Gets the pool liquidity contribution for a given amount of token1
    /// @param sqrtPriceX96 The sqrt price of the pool
    /// @param amount1 The amount of token1
    /// @return The liquidity contribution
    function getLiquidityForAmount1(
        uint160 sqrtPriceX96,
        uint256 amount1
    ) internal pure returns (uint128) {
        return
            ((amount1 << FixedPoint96.RESOLUTION) / sqrtPriceX96).toUint128();
    }

    /// @notice Gets the pool liquidity contribution for given amounts of token0 and token1
    /// @dev Takes the minimum of contributions from either token0 or token1
    /// @param sqrtPriceX96 The sqrt price of the pool
    /// @param amount0 The amount of token0
    /// @param amount1 The amount of token1
    /// @return liquidity The liquidity contribution
    function getLiquidityForAmounts(
        uint160 sqrtPriceX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, amount0);
        uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceX96, amount1);

        liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
    }
}

File 38 of 38 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "remappings": [
    "@marginal/v1-core/contracts=.cache/marginal-v1-core/v1.0.1",
    "@openzeppelin/contracts=.cache/openzeppelin/v4.8.3",
    "@uniswap/v3-core/contracts=.cache/uniswap-v3-core/v0.8",
    "@uniswap/v3-periphery/contracts=.cache/uniswap-v3-periphery/v0.8"
  ],
  "viaIR": true
}

Contract ABI

[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"int256","name":"amount0Burned","type":"int256"}],"name":"Amount0BurnedGreaterThanMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount0","type":"uint256"}],"name":"Amount0LessThanMin","type":"error"},{"inputs":[{"internalType":"int256","name":"amount1Burned","type":"int256"}],"name":"Amount1BurnedGreaterThanMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Amount1LessThanMin","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"AmountInGreaterThanMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"AmountOutLessThanMin","type":"error"},{"inputs":[],"name":"InvalidOracle","type":"error"},{"inputs":[],"name":"LiquidityBurnedLessThanMin","type":"error"},{"inputs":[],"name":"PoolInactive","type":"error"},{"inputs":[],"name":"PoolNotInitialized","type":"error"},{"inputs":[],"name":"PoolNotSender","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"int256","name":"amount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"amount1","type":"int256"}],"name":"PoolInitialize","type":"event"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"uint24","name":"uniswapV3Fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint128","name":"liquidityBurned","type":"uint128"},{"internalType":"int256","name":"amount0BurnedMax","type":"int256"},{"internalType":"int256","name":"amount1BurnedMax","type":"int256"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IPoolInitializer.CreateAndInitializeParams","name":"params","type":"tuple"}],"name":"createAndInitializePoolIfNecessary","outputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"uniswapV3Fee","type":"uint24"},{"internalType":"uint16","name":"observationCardinalityNext","type":"uint16"}],"internalType":"struct IPoolInitializer.InitializeOracleParams","name":"params","type":"tuple"}],"name":"initializeOracleIfNecessary","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IPoolInitializer.InitializePoolSqrtPriceX96Params","name":"params","type":"tuple"}],"name":"initializePoolSqrtPriceX96","outputs":[{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1MintCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"marginalV1SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"uniswapV3Factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60e08060405234620001565760408162002af980380380916200002382856200015b565b8339810103126200015657600460206200004a81620000428562000195565b940162000195565b6080849052604051632daa48c160e11b815290939092839182906001600160a01b03165afa9081156200014a5760009162000106575b5060a05260c05260405161294e9081620001ab82396080518181816103060152818161080801528181610eae01528181611047015281816113b9015281816118d301528181611fa801526121c8015260a0518181816106e5015281816107cb0152610fce015260c0518181816103b7015281816104c00152818161213c01526124240152f35b906020823d821162000141575b8162000122602093836200015b565b810103126200013e5750620001379062000195565b3862000080565b80fd5b3d915062000113565b6040513d6000823e3d90fd5b600080fd5b601f909101601f19168101906001600160401b038211908210176200017f57604052565b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b0382168203620001565756fe60806040526004361015610023575b361561001957600080fd5b610021612132565b005b60003560e01c806312210e8a146101275780631e121fe81461011e5780632aa35ecb1461011557806349404b7c1461010c5780634aa4a4fc146101035780634e8d0f9e146100fa5780635b549182146100f157806361e4b8e7146100e857806374d328d2146100df5780639244b399146100d6578063ac9650d8146100cd578063c45a0155146100c45763df2ab5bb0361000e576100bf6113e8565b61000e565b506100bf6113a2565b506100bf61129f565b506100bf610f43565b506100bf610dad565b506100bf610714565b506100bf6106ce565b506100bf610627565b506100bf6104a9565b506100bf610381565b506100bf61023f565b506100bf6101a7565b506100bf610140565b600091031261013b57565b600080fd5b50600036600319011261013b57610021612409565b6001600160a01b0381160361013b57565b6004359061017382610155565b565b6024359061017382610155565b6064359061017382610155565b6084359061017382610155565b359061017382610155565b50604036600319011261013b576024356101c081610155565b4760043581106101da57806101d157005b6100219161228c565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b9181601f8401121561013b578235916001600160401b03831161013b576020838186019501011161013b57565b503461013b57606036600319011261013b576004356024356044356001600160401b03811161013b57610276903690600401610212565b81908101039260a0841261013b5760806040519461029386610506565b1261013b5761032a6102fc6080604051946102ad8661052e565b80356102b881610155565b865260208101356102c881610155565b602087015260408101356102db816105f2565b604087015260608101356102ee81610155565b60608701528588520161019c565b92602086019384527f0000000000000000000000000000000000000000000000000000000000000000612601565b508061035a575b508161033957005b9151602001519151610021926001600160a01b0390811691165b339161241a565b83515161037b91906001600160a01b031683516001600160a01b0316610353565b38610331565b50604036600319011261013b5760243561039a81610155565b6040516370a0823160e01b81523060048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691602082602481865afa91821561049c575b60009261046c575b5061040060043583101561224b565b8161040757005b823b1561013b57604051632e1a7d4d60e01b815260048101839052610021936000908290602490829084905af1801561045f575b610446575b5061228c565b8061045361045992610549565b80610130565b38610440565b61046761172e565b61043b565b61048e91925060203d8111610495575b6104868183610577565b81019061223c565b90386103f1565b503d61047c565b6104a461172e565b6103e9565b503461013b57600036600319011261013b576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b0382111761052157604052565b6105296104ef565b604052565b608081019081106001600160401b0382111761052157604052565b6001600160401b03811161052157604052565b60a081019081106001600160401b0382111761052157604052565b90601f801991011681019081106001600160401b0382111761052157604052565b6040519061014082018281106001600160401b0382111761052157604052565b6040519061010082018281106001600160401b0382111761052157604052565b6040519061017382610506565b604051906101738261052e565b62ffffff81160361013b57565b60443590610173826105f2565b60a4359061017382610155565b610104359061017382610155565b5061014036600319011261013b576106b8610640610598565b610648610166565b8152610652610175565b602082015261065f6105ff565b604082015261066c610182565b606082015261067961018f565b608082015261068661060c565b60a082015260c43560c082015260e43560e08201526106a3610619565b6101008201526101243561012082015261185d565b60408051928352602083019190915290f35b0390f35b503461013b57600036600319011261013b576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b506101e036600319011261013b576101c4356107328142111561169b565b600080918182916107416116dd565b61076c61075b61074f6116e9565b6001600160a01b031690565b6001600160a01b0392831610611694565b6107746116dd565b61077c6116e9565b610784611701565b60408051630b4c774160e11b81526001600160a01b0394851660048083019190915294909316602484015262ffffff909116604483015293602090818380606481010381887f0000000000000000000000000000000000000000000000000000000000000000165afa928315610da0575b8993610d81575b5084831615610d7157847f0000000000000000000000000000000000000000000000000000000000000000166108306116dd565b836108396116e9565b61084161170d565b8a51635d0aec4160e01b81526001600160a01b039485168a8201908152928516602084015262ffffff90911660408301529287166060820152829081906080010381855afa9a8b15610d64575b9a610d45575b50858a1615610c78575b50855163c19d93fb60e01b815289818681610100998a94165afa908115610c6b575b600091610c36575b50156108f7575b85516001600160a01b038a168152602081018b90526040810188905260608101899052608090f35b9296509297509293506127106001600160801b03610913611800565b161115610c2657610a8e610a886109c361092b6116dd565b6109b06109366116e9565b61098161094161170d565b61097661094c611800565b936109676109586105b8565b6001600160a01b039098168852565b6001600160a01b0316868c0152565b62ffffff16848c0152565b6001600160a01b03891660608401526001600160a01b038c1660808401525b6001600160801b031660a0830152565b600060c0820152600060e0820152611f13565b9a915093610a7d866109d36116dd565b93610a5d6109df6116e9565b610a388d6109eb61170d565b90610a2c6109f761180c565b94610a00611818565b98610a1b610a0c610598565b6001600160a01b03909e168e52565b6001600160a01b03909116908c0152565b89019062ffffff169052565b6001600160a01b038c1660608801523360808801526001600160a01b031660a0870152565b60001960c0860152600060e08601526001600160a01b0390911690840152565b61012082015261185d565b92611824565b96610104358813610c0b5790610aa391611824565b93610124358513610bec575091610b8b610b796106ca9593610b62610b85966109a0610adf610ad061180c565b61016435906101443590612630565b91610b52610aeb6116dd565b95610b42610af76116e9565b610b37610b0261170d565b91610b0b6116f5565b96610b26610b176105b8565b6001600160a01b03909d168d52565b6001600160a01b03909116908b0152565b62ffffff16888c0152565b6001600160a01b03166060870152565b6001600160a01b03166080850152565b6101843560c08201526101a43560e0820152611f13565b94919590988699611824565b93611824565b92610b94612409565b81516001600160a01b03871681526020810191909152604081018390526060810184905233907fc0082cd00fd0a3d71b293d290eb35a7b0f00990caafef28b28c4f21f6841394e90608090a2909192388080806108cf565b835163d4414d2d60e01b815290810185815281906020010390fd5b0390fd5b845163a79f68f160e01b815280870189815281906020010390fd5b50505051635b51ac7960e11b8152fd5b610c569150863d8811610c64575b610c4e8183610577565b810190611775565b9650505050505050386108c8565b503d610c44565b610c7361172e565b6108c0565b90985081610c846116dd565b91610c8d6116e9565b90610c9661170d565b93600088610cef610ca5611701565b8d516342265bc160e01b81526001600160a01b0395861693810193845294909616602083015262ffffff978816604083015296909416606085015290948593849291839160800190565b03925af1908115610d38575b600091610d0b575b50973861089e565b610d2b9150823d8411610d31575b610d238183610577565b810190611719565b38610d03565b503d610d19565b610d4061172e565b610cfb565b610d5d919a50833d8511610d3157610d238183610577565b9838610894565b610d6c61172e565b61088e565b8551639589a27d60e01b81528490fd5b610d99919350823d8411610d3157610d238183610577565b91386107fc565b610da861172e565b6107f5565b503461013b57606036600319011261013b576001600160401b0360243560043560443583811161013b57610de5903690600401610212565b9360009485841390818015610f3a575b15610f36578301946020938481880312610f2e57803590848211610f32570191604083880312610f2e578760405194610e2d86610506565b8435908111610f2a5784019780601f8a011215610f2a57883596610e50886115a6565b91610e5e6040519384610577565b88835281898c010111610f2657610e9581610eac97610e9f95828c610f039f9d82610ed29f01838a013787010152848a520161019c565b96019586526126e3565b90828499949793976127b9565b7f0000000000000000000000000000000000000000000000000000000000000000612601565b5015610f0857506103539190610ef6906001600160a01b0390811690851610611694565b516001600160a01b031690565b604051f35b93506103539190610ef6906001600160a01b03858116911610611694565b8280fd5b5080fd5b8780fd5b8880fd5b8680fd5b50868613610df5565b503461013b57608036600319011261013b57610f5d6116dd565b610f6b61075b61074f6116e9565b610f736116dd565b610f7b6116e9565b82610fc9610f8761170d565b60408051630b4c774160e11b81526001600160a01b03968716600482015294909516602485015262ffffff166044840152602092908390829081906064820190565b0381857f0000000000000000000000000000000000000000000000000000000000000000165afa9081156111d6575b6000916111b9575b50169283156111a8578251633850c7bd60e01b81528260e082600481895afa91821561119b575b600092611163575b50845163d6d5638560e01b81529192829060049082907f0000000000000000000000000000000000000000000000000000000000000000165afa928315611156575b600093611127575b505061108d611086611ebf565b61ffff1690565b9161ffff8092169283108061110c575b6110a690611694565b16116110ae57005b6110b6611ebf565b823b1561013b5781516332148f6760e01b815261ffff91909116600482015260009283908290602490829084905af180156110ff575b6110f257005b8061045361002192610549565b61110761172e565b6110ec565b506110a661111b611086611ebf565b8383161115905061109d565b611147929350803d1061114f575b61113f8183610577565b810190611eaa565b903880611079565b503d611135565b61115e61172e565b611071565b600492506111879060e03d8111611194575b61117f8183610577565b810190611e48565b505093505050509161102f565b503d611175565b6111a361172e565b611027565b8251639589a27d60e01b8152600490fd5b6111d09150833d8511610d3157610d238183610577565b38611000565b6111de61172e565b610ff8565b918091926000905b8282106112035750116111fc575050565b6000910152565b915080602091830151818601520182916111eb565b90602091611231815180928185528580860191016111e3565b601f01601f1916010190565b602080820190808352835180925260408301928160408460051b8301019501936000915b8483106112715750505050505090565b909192939495848061128f600193603f198682030187528a51611218565b9801930193019194939290611261565b50602036600319011261013b57600480356001600160401b039182821161013b573660238301121561013b578181013592831161013b57602490818301928236918660051b01011161013b576112f4846114b5565b9360005b81811061130d57604051806106ca888261123d565b60008061131b838589611549565b6040939161132d855180938193611598565b0390305af49061133b6115d0565b9182901561136a57505090611365916113548289611672565b5261135f8188611672565b50611516565b6112f8565b86838792604482511061013b5782610c07938561138d9401518301019101611600565b925162461bcd60e51b81529283928301611661565b503461013b57600036600319011261013b576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50606036600319011261013b5760043561140181610155565b60443561140d81610155565b6040516370a0823160e01b8152306004820152906020826024816001600160a01b0387165afa918215611482575b600092611462575b506114526024358310156122ff565b8161145957005b61002192612354565b61147b91925060203d8111610495576104868183610577565b9038611443565b61148a61172e565b61143b565b6020906001600160401b0381116114a8575b60051b0190565b6114b06104ef565b6114a1565b906114bf8261148f565b6114cc6040519182610577565b82815280926114dd601f199161148f565b019060005b8281106114ee57505050565b8060606020809385010152016114e2565b50634e487b7160e01b600052601160045260246000fd5b6001906000198114611526570190565b61152e6114ff565b0190565b50634e487b7160e01b600052603260045260246000fd5b919081101561158b575b60051b81013590601e198136030182121561013b5701908135916001600160401b03831161013b57602001823603811361013b579190565b611593611532565b611553565b908092918237016000815290565b6020906001600160401b0381116115c3575b601f01601f19160190565b6115cb6104ef565b6115b8565b3d156115fb573d906115e1826115a6565b916115ef6040519384610577565b82523d6000602084013e565b606090565b60208183031261013b578051906001600160401b03821161013b570181601f8201121561013b578051611632816115a6565b926116406040519485610577565b8184526020828401011161013b5761165e91602080850191016111e3565b90565b90602061165e928181520190611218565b6020918151811015611687575b60051b010190565b61168f611532565b61167f565b1561013b57565b156116a257565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b60043561165e81610155565b60243561165e81610155565b60843561165e81610155565b60643561165e816105f2565b60443561165e816105f2565b9081602091031261013b575161165e81610155565b506040513d6000823e3d90fd5b6001600160801b0381160361013b57565b51908160020b820361013b57565b519060ff8216820361013b57565b5190811515820361013b57565b91908261010091031261013b57815161178d81610155565b9160208101516bffffffffffffffffffffffff8116810361013b579160408201516117b78161173b565b916117c46060820161174c565b91608082015163ffffffff8116810361013b579160a08101518060060b810361013b579161165e60e06117f960c0850161175a565b9301611768565b60e43561165e8161173b565b60a43561165e81610155565b60c43561165e81610155565b6000811280156001600160ff1b03839003841316611850575b600160ff1b829003831216611526570190565b6118586114ff565b61183d565b906118cb9161187361012082015142111561169b565b80516020820180519092916001600160a01b0390811691811690611898828410611694565b6118f761074f61074f6118d1604096878901966118b8885162ffffff1690565b9060608b019d8e5160018060a01b031690565b926127b9565b7f0000000000000000000000000000000000000000000000000000000000000000612827565b9083519763c19d93fb60e01b895261010090818a600481875afa8015611c20575b600090819b8291611bf4575b5015611be3576119659a61198e91858061195360a08d01948461194d875160018060a01b031690565b91611d0f565b9451949f90946001600160a01b031690565b92169116109b8c15611bdc57505b61197f60008213611694565b61198881611dcd565b90611824565b9460c08801518015600014611bd757506000195b8611611bbf579186959493918b9384600014611ba65789516119e4906119d6906001600160a01b0316925b5162ffffff1690565b92516001600160a01b031690565b9a8515611b9557516001600160a01b03165b8851606092831b6bffffffffffffffffffffffff19908116602083015260e89490941b6001600160e81b03191660348201529b821b831660378d0152901b16604b8a0152603f8952601f1991611a4d605f8b610577565b611a556105d8565b998a523360208b015260808901516001600160a01b0316918901516001600160a01b031690811615600014611abd600094611ad993611ab193611b8f5750868614611b75576401000276a45b9c5b8a5193849160208301611c51565b03908101835282610577565b8751630251596160e31b81529a8b978896879560048701611c97565b03925af1948515611b68575b6000938496611b33575b5015611b285760e0611b0086611cd0565b9201518210611b0f5750509190565b51636b19f1cf60e11b8152600481019190915260249150fd5b60e0611b0084611cd0565b90955081611b579294503d8511611b61575b611b4f8183610577565b810190611c81565b9290929438611aef565b503d611b45565b611b7061172e565b611ae5565b73fffd8963efd1fc6a506488495d951d5263988d25611aa1565b9c611aa3565b5089516001600160a01b03166119f6565b8a516119e4906119d6906001600160a01b0316926119cd565b8651639c56bf3160e01b815260048101879052602490fd5b6119a2565b9050611973565b865163486aa30760e01b8152600490fd5b915050611c0f919a50823d8411610c6457610c4e8183610577565b9f9694955050505050909a38611924565b611c2861172e565b611918565b6001600160a01b039182169116818110611c45570390565b611c4d6114ff565b0390565b602081526040611c6c83518260208501526060840190611218565b6020909301516001600160a01b031691015290565b919082604091031261013b576020825192015190565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a06080820181905261165e92910190611218565b600160ff1b8114611ce2575b60000390565b611cea6114ff565b611cdc565b8115611cf9570490565b634e487b7160e01b600052601260045260246000fd5b6001600160a01b038084169493926001600160801b038316928282169060601b6fffffffffffffffffffffffffffffffff60601b16611d5882611d528a84611cef565b92611cef565b90600082128015600160ff1b8401831216611dc0575b6001600160ff1b038301821316611db3575b03961015611da65790611d9a61165e94611da19493611c2d565b1690611df7565b611cd0565b611d9a9061165e94611c2d565b611dbb6114ff565b611d80565b611dc86114ff565b611d6e565b620f3e58906103e8908060001904821181151516611dea57020490565b611df26114ff565b020490565b6000198282099082810292838084109303928084039314611e3357600160601b918383111561013b570990828211900360a01b910360601c1790565b50505060601c90565b61ffff81160361013b57565b908160e091031261013b578051611e5e81610155565b91611e6b6020830161174c565b916040810151611e7a81611e3c565b916060820151611e8981611e3c565b916080810151611e9881611e3c565b9161165e60c06117f960a0850161175a565b9081602091031261013b575161165e81611e3c565b60643561165e81611e3c565b9081606091031261013b578051916040602083015192015190565b6001600160801b0361165e949360609360018060a01b031683521660208201528160408201520190611218565b80516120859291906001600160a01b0316602082015190929060609061205b906001600160a01b031694611f9c604096611f8d611f558989015162ffffff1690565b88870151611f82906001600160a01b031693611f726109586105e5565b6001600160a01b03166020870152565b62ffffff16848a0152565b6001600160a01b031682850152565b611fcc61074f61074f837f0000000000000000000000000000000000000000000000000000000000000000612827565b60808601519091906000906001600160a01b0316612069611ff760a08a01516001600160801b031690565b936120006105d8565b8181523360209182019081528c5183516001600160a01b039081168285015292840151831660408083019190915284015162ffffff166060808301919091529093015182166080840152511660a082015295869060c0820190565b03601f198101875286610577565b88516392f026ad60e01b8152998a958694859360048501611ee6565b03925af18015612125575b600093849585926120ee575b50819386959660c082015181106120d5575060e0015182106120bc575050565b5163787bc1e760e11b8152600481019190915260249150fd5b8251637f7e554360e01b81526004810191909152602490fd5b9150935061211491945060603d811161211e575b61210c8183610577565b810190611ecb565b909491933861209c565b503d612102565b61212d61172e565b612090565b60018060a01b03807f00000000000000000000000000000000000000000000000000000000000000001633149081156121a7575b501561216e57565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f0000000000000000000000000000000000000000000000000000000000000000165afa90811561222f575b600091612201575b5038612166565b612222915060203d8111612228575b61221a8183610577565b810190612340565b386121fa565b503d612210565b61223761172e565b6121f2565b9081602091031261013b575190565b1561225257565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b60008092918192604051918360208401938085106001600160401b038611176122f2575b84604052525af16122bf6115d0565b50156122c757565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b6122fa6104ef565b6122b0565b1561230657565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b9081602091031261013b5761165e90611768565b60405163a9059cbb60e01b602082019081526001600160a01b039390931660248201526044808201949094529283526000928392908390612396606482610577565b51925af16123a26115d0565b816123da575b50156123b057565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b80518015925082156123ef575b5050386123a8565b6124029250602080918301019101612340565b38806123e7565b4761241057565b610173473361228c565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116949290828116861480612540575b1561251e57505050823b1561013b576124c592602092604051630d0e30db60e41b815260008160048187875af18015612511575b6124fe575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af180156124f1575b6124d75750565b6124ee9060203d81116122285761221a8183610577565b50565b6124f961172e565b6124d0565b8061045361250b92610549565b3861248c565b61251961172e565b612487565b9194509192919081163003612537575061017392612354565b6101739361254a565b5083471015612453565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b03809216602485015216604483015260648201526064815261258d8161055c565b51925af16125996115d0565b816125d2575b50156125a757565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b80518015925082156125e7575b50503861259f565b6125fa9250602080918301019101612340565b38806125df565b6001600160a01b039161261391612827565b169081330361261e57565b604051635cf3778960e01b8152600490fd5b61265d9161264f916001600160a01b0316906126549083908390611df7565b61267a565b9360601b611cef565b6001600160801b038181169083161015612675575090565b905090565b6001600160801b039081811161268e571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608490fd5b90601482511061275657602082015160601c91601781511061271a5760178101519061271761271182612793565b916127a6565b92565b60405162461bcd60e51b8152602060048201526014602482015273746f55696e7432345f6f75744f66426f756e647360601b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274746f416464726573735f6f75744f66426f756e647360581b6044820152606490fd5b602b815110612756576037015160601c90565b603f81511061275657604b015160601c90565b92909162ffffff90600060606040516127d18161052e565b828152602081018390526040810183905201526001600160a01b0393849080821687831611612821575b81604051976128098961052e565b16875216602086015216604084015216606082015290565b956127fb565b81519192916020906001600160a01b0316848201516001600160a01b0316906128b161286d606061285e60408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa92831561290b575b6000936128eb575b508216156128d957565b604051630f509b1160e01b8152600490fd5b61290491935060203d8111610d3157610d238183610577565b91386128cf565b61291361172e565b6128c756fea26469706673582212205e7d8658860dd4418aba1d15496ccefd09ada31b7f67c996dd0a97e1e1429c8c64736f6c634300080f0033000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14

Deployed Bytecode

0x60806040526004361015610023575b361561001957600080fd5b610021612132565b005b60003560e01c806312210e8a146101275780631e121fe81461011e5780632aa35ecb1461011557806349404b7c1461010c5780634aa4a4fc146101035780634e8d0f9e146100fa5780635b549182146100f157806361e4b8e7146100e857806374d328d2146100df5780639244b399146100d6578063ac9650d8146100cd578063c45a0155146100c45763df2ab5bb0361000e576100bf6113e8565b61000e565b506100bf6113a2565b506100bf61129f565b506100bf610f43565b506100bf610dad565b506100bf610714565b506100bf6106ce565b506100bf610627565b506100bf6104a9565b506100bf610381565b506100bf61023f565b506100bf6101a7565b506100bf610140565b600091031261013b57565b600080fd5b50600036600319011261013b57610021612409565b6001600160a01b0381160361013b57565b6004359061017382610155565b565b6024359061017382610155565b6064359061017382610155565b6084359061017382610155565b359061017382610155565b50604036600319011261013b576024356101c081610155565b4760043581106101da57806101d157005b6100219161228c565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b9181601f8401121561013b578235916001600160401b03831161013b576020838186019501011161013b57565b503461013b57606036600319011261013b576004356024356044356001600160401b03811161013b57610276903690600401610212565b81908101039260a0841261013b5760806040519461029386610506565b1261013b5761032a6102fc6080604051946102ad8661052e565b80356102b881610155565b865260208101356102c881610155565b602087015260408101356102db816105f2565b604087015260608101356102ee81610155565b60608701528588520161019c565b92602086019384527f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2612601565b508061035a575b508161033957005b9151602001519151610021926001600160a01b0390811691165b339161241a565b83515161037b91906001600160a01b031683516001600160a01b0316610353565b38610331565b50604036600319011261013b5760243561039a81610155565b6040516370a0823160e01b81523060048201526001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141691602082602481865afa91821561049c575b60009261046c575b5061040060043583101561224b565b8161040757005b823b1561013b57604051632e1a7d4d60e01b815260048101839052610021936000908290602490829084905af1801561045f575b610446575b5061228c565b8061045361045992610549565b80610130565b38610440565b61046761172e565b61043b565b61048e91925060203d8111610495575b6104868183610577565b81019061223c565b90386103f1565b503d61047c565b6104a461172e565b6103e9565b503461013b57600036600319011261013b576040517f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b146001600160a01b03168152602090f35b50634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b0382111761052157604052565b6105296104ef565b604052565b608081019081106001600160401b0382111761052157604052565b6001600160401b03811161052157604052565b60a081019081106001600160401b0382111761052157604052565b90601f801991011681019081106001600160401b0382111761052157604052565b6040519061014082018281106001600160401b0382111761052157604052565b6040519061010082018281106001600160401b0382111761052157604052565b6040519061017382610506565b604051906101738261052e565b62ffffff81160361013b57565b60443590610173826105f2565b60a4359061017382610155565b610104359061017382610155565b5061014036600319011261013b576106b8610640610598565b610648610166565b8152610652610175565b602082015261065f6105ff565b604082015261066c610182565b606082015261067961018f565b608082015261068661060c565b60a082015260c43560c082015260e43560e08201526106a3610619565b6101008201526101243561012082015261185d565b60408051928352602083019190915290f35b0390f35b503461013b57600036600319011261013b576040517f0000000000000000000000000227628f3f023bb0b980b67d528571c95c6dac1c6001600160a01b03168152602090f35b506101e036600319011261013b576101c4356107328142111561169b565b600080918182916107416116dd565b61076c61075b61074f6116e9565b6001600160a01b031690565b6001600160a01b0392831610611694565b6107746116dd565b61077c6116e9565b610784611701565b60408051630b4c774160e11b81526001600160a01b0394851660048083019190915294909316602484015262ffffff909116604483015293602090818380606481010381887f0000000000000000000000000227628f3f023bb0b980b67d528571c95c6dac1c165afa928315610da0575b8993610d81575b5084831615610d7157847f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2166108306116dd565b836108396116e9565b61084161170d565b8a51635d0aec4160e01b81526001600160a01b039485168a8201908152928516602084015262ffffff90911660408301529287166060820152829081906080010381855afa9a8b15610d64575b9a610d45575b50858a1615610c78575b50855163c19d93fb60e01b815289818681610100998a94165afa908115610c6b575b600091610c36575b50156108f7575b85516001600160a01b038a168152602081018b90526040810188905260608101899052608090f35b9296509297509293506127106001600160801b03610913611800565b161115610c2657610a8e610a886109c361092b6116dd565b6109b06109366116e9565b61098161094161170d565b61097661094c611800565b936109676109586105b8565b6001600160a01b039098168852565b6001600160a01b0316868c0152565b62ffffff16848c0152565b6001600160a01b03891660608401526001600160a01b038c1660808401525b6001600160801b031660a0830152565b600060c0820152600060e0820152611f13565b9a915093610a7d866109d36116dd565b93610a5d6109df6116e9565b610a388d6109eb61170d565b90610a2c6109f761180c565b94610a00611818565b98610a1b610a0c610598565b6001600160a01b03909e168e52565b6001600160a01b03909116908c0152565b89019062ffffff169052565b6001600160a01b038c1660608801523360808801526001600160a01b031660a0870152565b60001960c0860152600060e08601526001600160a01b0390911690840152565b61012082015261185d565b92611824565b96610104358813610c0b5790610aa391611824565b93610124358513610bec575091610b8b610b796106ca9593610b62610b85966109a0610adf610ad061180c565b61016435906101443590612630565b91610b52610aeb6116dd565b95610b42610af76116e9565b610b37610b0261170d565b91610b0b6116f5565b96610b26610b176105b8565b6001600160a01b03909d168d52565b6001600160a01b03909116908b0152565b62ffffff16888c0152565b6001600160a01b03166060870152565b6001600160a01b03166080850152565b6101843560c08201526101a43560e0820152611f13565b94919590988699611824565b93611824565b92610b94612409565b81516001600160a01b03871681526020810191909152604081018390526060810184905233907fc0082cd00fd0a3d71b293d290eb35a7b0f00990caafef28b28c4f21f6841394e90608090a2909192388080806108cf565b835163d4414d2d60e01b815290810185815281906020010390fd5b0390fd5b845163a79f68f160e01b815280870189815281906020010390fd5b50505051635b51ac7960e11b8152fd5b610c569150863d8811610c64575b610c4e8183610577565b810190611775565b9650505050505050386108c8565b503d610c44565b610c7361172e565b6108c0565b90985081610c846116dd565b91610c8d6116e9565b90610c9661170d565b93600088610cef610ca5611701565b8d516342265bc160e01b81526001600160a01b0395861693810193845294909616602083015262ffffff978816604083015296909416606085015290948593849291839160800190565b03925af1908115610d38575b600091610d0b575b50973861089e565b610d2b9150823d8411610d31575b610d238183610577565b810190611719565b38610d03565b503d610d19565b610d4061172e565b610cfb565b610d5d919a50833d8511610d3157610d238183610577565b9838610894565b610d6c61172e565b61088e565b8551639589a27d60e01b81528490fd5b610d99919350823d8411610d3157610d238183610577565b91386107fc565b610da861172e565b6107f5565b503461013b57606036600319011261013b576001600160401b0360243560043560443583811161013b57610de5903690600401610212565b9360009485841390818015610f3a575b15610f36578301946020938481880312610f2e57803590848211610f32570191604083880312610f2e578760405194610e2d86610506565b8435908111610f2a5784019780601f8a011215610f2a57883596610e50886115a6565b91610e5e6040519384610577565b88835281898c010111610f2657610e9581610eac97610e9f95828c610f039f9d82610ed29f01838a013787010152848a520161019c565b96019586526126e3565b90828499949793976127b9565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2612601565b5015610f0857506103539190610ef6906001600160a01b0390811690851610611694565b516001600160a01b031690565b604051f35b93506103539190610ef6906001600160a01b03858116911610611694565b8280fd5b5080fd5b8780fd5b8880fd5b8680fd5b50868613610df5565b503461013b57608036600319011261013b57610f5d6116dd565b610f6b61075b61074f6116e9565b610f736116dd565b610f7b6116e9565b82610fc9610f8761170d565b60408051630b4c774160e11b81526001600160a01b03968716600482015294909516602485015262ffffff166044840152602092908390829081906064820190565b0381857f0000000000000000000000000227628f3f023bb0b980b67d528571c95c6dac1c165afa9081156111d6575b6000916111b9575b50169283156111a8578251633850c7bd60e01b81528260e082600481895afa91821561119b575b600092611163575b50845163d6d5638560e01b81529192829060049082907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2165afa928315611156575b600093611127575b505061108d611086611ebf565b61ffff1690565b9161ffff8092169283108061110c575b6110a690611694565b16116110ae57005b6110b6611ebf565b823b1561013b5781516332148f6760e01b815261ffff91909116600482015260009283908290602490829084905af180156110ff575b6110f257005b8061045361002192610549565b61110761172e565b6110ec565b506110a661111b611086611ebf565b8383161115905061109d565b611147929350803d1061114f575b61113f8183610577565b810190611eaa565b903880611079565b503d611135565b61115e61172e565b611071565b600492506111879060e03d8111611194575b61117f8183610577565b810190611e48565b505093505050509161102f565b503d611175565b6111a361172e565b611027565b8251639589a27d60e01b8152600490fd5b6111d09150833d8511610d3157610d238183610577565b38611000565b6111de61172e565b610ff8565b918091926000905b8282106112035750116111fc575050565b6000910152565b915080602091830151818601520182916111eb565b90602091611231815180928185528580860191016111e3565b601f01601f1916010190565b602080820190808352835180925260408301928160408460051b8301019501936000915b8483106112715750505050505090565b909192939495848061128f600193603f198682030187528a51611218565b9801930193019194939290611261565b50602036600319011261013b57600480356001600160401b039182821161013b573660238301121561013b578181013592831161013b57602490818301928236918660051b01011161013b576112f4846114b5565b9360005b81811061130d57604051806106ca888261123d565b60008061131b838589611549565b6040939161132d855180938193611598565b0390305af49061133b6115d0565b9182901561136a57505090611365916113548289611672565b5261135f8188611672565b50611516565b6112f8565b86838792604482511061013b5782610c07938561138d9401518301019101611600565b925162461bcd60e51b81529283928301611661565b503461013b57600036600319011261013b576040517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26001600160a01b03168152602090f35b50606036600319011261013b5760043561140181610155565b60443561140d81610155565b6040516370a0823160e01b8152306004820152906020826024816001600160a01b0387165afa918215611482575b600092611462575b506114526024358310156122ff565b8161145957005b61002192612354565b61147b91925060203d8111610495576104868183610577565b9038611443565b61148a61172e565b61143b565b6020906001600160401b0381116114a8575b60051b0190565b6114b06104ef565b6114a1565b906114bf8261148f565b6114cc6040519182610577565b82815280926114dd601f199161148f565b019060005b8281106114ee57505050565b8060606020809385010152016114e2565b50634e487b7160e01b600052601160045260246000fd5b6001906000198114611526570190565b61152e6114ff565b0190565b50634e487b7160e01b600052603260045260246000fd5b919081101561158b575b60051b81013590601e198136030182121561013b5701908135916001600160401b03831161013b57602001823603811361013b579190565b611593611532565b611553565b908092918237016000815290565b6020906001600160401b0381116115c3575b601f01601f19160190565b6115cb6104ef565b6115b8565b3d156115fb573d906115e1826115a6565b916115ef6040519384610577565b82523d6000602084013e565b606090565b60208183031261013b578051906001600160401b03821161013b570181601f8201121561013b578051611632816115a6565b926116406040519485610577565b8184526020828401011161013b5761165e91602080850191016111e3565b90565b90602061165e928181520190611218565b6020918151811015611687575b60051b010190565b61168f611532565b61167f565b1561013b57565b156116a257565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b60043561165e81610155565b60243561165e81610155565b60843561165e81610155565b60643561165e816105f2565b60443561165e816105f2565b9081602091031261013b575161165e81610155565b506040513d6000823e3d90fd5b6001600160801b0381160361013b57565b51908160020b820361013b57565b519060ff8216820361013b57565b5190811515820361013b57565b91908261010091031261013b57815161178d81610155565b9160208101516bffffffffffffffffffffffff8116810361013b579160408201516117b78161173b565b916117c46060820161174c565b91608082015163ffffffff8116810361013b579160a08101518060060b810361013b579161165e60e06117f960c0850161175a565b9301611768565b60e43561165e8161173b565b60a43561165e81610155565b60c43561165e81610155565b6000811280156001600160ff1b03839003841316611850575b600160ff1b829003831216611526570190565b6118586114ff565b61183d565b906118cb9161187361012082015142111561169b565b80516020820180519092916001600160a01b0390811691811690611898828410611694565b6118f761074f61074f6118d1604096878901966118b8885162ffffff1690565b9060608b019d8e5160018060a01b031690565b926127b9565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2612827565b9083519763c19d93fb60e01b895261010090818a600481875afa8015611c20575b600090819b8291611bf4575b5015611be3576119659a61198e91858061195360a08d01948461194d875160018060a01b031690565b91611d0f565b9451949f90946001600160a01b031690565b92169116109b8c15611bdc57505b61197f60008213611694565b61198881611dcd565b90611824565b9460c08801518015600014611bd757506000195b8611611bbf579186959493918b9384600014611ba65789516119e4906119d6906001600160a01b0316925b5162ffffff1690565b92516001600160a01b031690565b9a8515611b9557516001600160a01b03165b8851606092831b6bffffffffffffffffffffffff19908116602083015260e89490941b6001600160e81b03191660348201529b821b831660378d0152901b16604b8a0152603f8952601f1991611a4d605f8b610577565b611a556105d8565b998a523360208b015260808901516001600160a01b0316918901516001600160a01b031690811615600014611abd600094611ad993611ab193611b8f5750868614611b75576401000276a45b9c5b8a5193849160208301611c51565b03908101835282610577565b8751630251596160e31b81529a8b978896879560048701611c97565b03925af1948515611b68575b6000938496611b33575b5015611b285760e0611b0086611cd0565b9201518210611b0f5750509190565b51636b19f1cf60e11b8152600481019190915260249150fd5b60e0611b0084611cd0565b90955081611b579294503d8511611b61575b611b4f8183610577565b810190611c81565b9290929438611aef565b503d611b45565b611b7061172e565b611ae5565b73fffd8963efd1fc6a506488495d951d5263988d25611aa1565b9c611aa3565b5089516001600160a01b03166119f6565b8a516119e4906119d6906001600160a01b0316926119cd565b8651639c56bf3160e01b815260048101879052602490fd5b6119a2565b9050611973565b865163486aa30760e01b8152600490fd5b915050611c0f919a50823d8411610c6457610c4e8183610577565b9f9694955050505050909a38611924565b611c2861172e565b611918565b6001600160a01b039182169116818110611c45570390565b611c4d6114ff565b0390565b602081526040611c6c83518260208501526060840190611218565b6020909301516001600160a01b031691015290565b919082604091031261013b576020825192015190565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a06080820181905261165e92910190611218565b600160ff1b8114611ce2575b60000390565b611cea6114ff565b611cdc565b8115611cf9570490565b634e487b7160e01b600052601260045260246000fd5b6001600160a01b038084169493926001600160801b038316928282169060601b6fffffffffffffffffffffffffffffffff60601b16611d5882611d528a84611cef565b92611cef565b90600082128015600160ff1b8401831216611dc0575b6001600160ff1b038301821316611db3575b03961015611da65790611d9a61165e94611da19493611c2d565b1690611df7565b611cd0565b611d9a9061165e94611c2d565b611dbb6114ff565b611d80565b611dc86114ff565b611d6e565b620f3e58906103e8908060001904821181151516611dea57020490565b611df26114ff565b020490565b6000198282099082810292838084109303928084039314611e3357600160601b918383111561013b570990828211900360a01b910360601c1790565b50505060601c90565b61ffff81160361013b57565b908160e091031261013b578051611e5e81610155565b91611e6b6020830161174c565b916040810151611e7a81611e3c565b916060820151611e8981611e3c565b916080810151611e9881611e3c565b9161165e60c06117f960a0850161175a565b9081602091031261013b575161165e81611e3c565b60643561165e81611e3c565b9081606091031261013b578051916040602083015192015190565b6001600160801b0361165e949360609360018060a01b031683521660208201528160408201520190611218565b80516120859291906001600160a01b0316602082015190929060609061205b906001600160a01b031694611f9c604096611f8d611f558989015162ffffff1690565b88870151611f82906001600160a01b031693611f726109586105e5565b6001600160a01b03166020870152565b62ffffff16848a0152565b6001600160a01b031682850152565b611fcc61074f61074f837f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2612827565b60808601519091906000906001600160a01b0316612069611ff760a08a01516001600160801b031690565b936120006105d8565b8181523360209182019081528c5183516001600160a01b039081168285015292840151831660408083019190915284015162ffffff166060808301919091529093015182166080840152511660a082015295869060c0820190565b03601f198101875286610577565b88516392f026ad60e01b8152998a958694859360048501611ee6565b03925af18015612125575b600093849585926120ee575b50819386959660c082015181106120d5575060e0015182106120bc575050565b5163787bc1e760e11b8152600481019190915260249150fd5b8251637f7e554360e01b81526004810191909152602490fd5b9150935061211491945060603d811161211e575b61210c8183610577565b810190611ecb565b909491933861209c565b503d612102565b61212d61172e565b612090565b60018060a01b03807f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141633149081156121a7575b501561216e57565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2165afa90811561222f575b600091612201575b5038612166565b612222915060203d8111612228575b61221a8183610577565b810190612340565b386121fa565b503d612210565b61223761172e565b6121f2565b9081602091031261013b575190565b1561225257565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b60008092918192604051918360208401938085106001600160401b038611176122f2575b84604052525af16122bf6115d0565b50156122c757565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b6122fa6104ef565b6122b0565b1561230657565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b9081602091031261013b5761165e90611768565b60405163a9059cbb60e01b602082019081526001600160a01b039390931660248201526044808201949094529283526000928392908390612396606482610577565b51925af16123a26115d0565b816123da575b50156123b057565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b80518015925082156123ef575b5050386123a8565b6124029250602080918301019101612340565b38806123e7565b4761241057565b610173473361228c565b6001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b148116949290828116861480612540575b1561251e57505050823b1561013b576124c592602092604051630d0e30db60e41b815260008160048187875af18015612511575b6124fe575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af180156124f1575b6124d75750565b6124ee9060203d81116122285761221a8183610577565b50565b6124f961172e565b6124d0565b8061045361250b92610549565b3861248c565b61251961172e565b612487565b9194509192919081163003612537575061017392612354565b6101739361254a565b5083471015612453565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b03809216602485015216604483015260648201526064815261258d8161055c565b51925af16125996115d0565b816125d2575b50156125a757565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b80518015925082156125e7575b50503861259f565b6125fa9250602080918301019101612340565b38806125df565b6001600160a01b039161261391612827565b169081330361261e57565b604051635cf3778960e01b8152600490fd5b61265d9161264f916001600160a01b0316906126549083908390611df7565b61267a565b9360601b611cef565b6001600160801b038181169083161015612675575090565b905090565b6001600160801b039081811161268e571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608490fd5b90601482511061275657602082015160601c91601781511061271a5760178101519061271761271182612793565b916127a6565b92565b60405162461bcd60e51b8152602060048201526014602482015273746f55696e7432345f6f75744f66426f756e647360601b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274746f416464726573735f6f75744f66426f756e647360581b6044820152606490fd5b602b815110612756576037015160601c90565b603f81511061275657604b015160601c90565b92909162ffffff90600060606040516127d18161052e565b828152602081018390526040810183905201526001600160a01b0393849080821687831611612821575b81604051976128098961052e565b16875216602086015216604084015216606082015290565b956127fb565b81519192916020906001600160a01b0316848201516001600160a01b0316906128b161286d606061285e60408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa92831561290b575b6000936128eb575b508216156128d957565b604051630f509b1160e01b8152600490fd5b61290491935060203d8111610d3157610d238183610577565b91386128cf565b61291361172e565b6128c756fea26469706673582212205e7d8658860dd4418aba1d15496ccefd09ada31b7f67c996dd0a97e1e1429c8c64736f6c634300080f0033

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

000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14

-----Decoded View---------------
Arg [0] : _factory (address): 0xa85D1A8f20d1D51612Ffa969f8594166A855c3C2
Arg [1] : _WETH9 (address): 0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2
Arg [1] : 000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ 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.