Sepolia Testnet

Contract

0x0E936b2Fd793Df6BFa254c4c5ED49365b95Beeb0

Overview

ETH Balance

0 ETH

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Execute63166932024-07-15 19:01:483 days ago1721070108IN
0x0E936b2F...5b95Beeb0
0 ETH0.000058440.29969149
Execute62934262024-07-12 2:10:247 days ago1720750224IN
0x0E936b2F...5b95Beeb0
0 ETH0.000599953.10761871
Execute62901502024-07-11 14:12:007 days ago1720707120IN
0x0E936b2F...5b95Beeb0
0 ETH0.00330216.92304936
Execute62794782024-07-09 23:11:129 days ago1720566672IN
0x0E936b2F...5b95Beeb0
0 ETH0.000448142.2958691
Execute62786362024-07-09 20:05:009 days ago1720555500IN
0x0E936b2F...5b95Beeb0
0 ETH0.000243551.24887949
Execute62776292024-07-09 16:24:369 days ago1720542276IN
0x0E936b2F...5b95Beeb0
0 ETH0.000414732.12528397
Execute62731852024-07-09 0:09:4810 days ago1720483788IN
0x0E936b2F...5b95Beeb0
0 ETH0.001003515.14539908
Execute62721612024-07-08 20:19:1210 days ago1720469952IN
0x0E936b2F...5b95Beeb0
0 ETH0.001594568.17281332
Execute62721532024-07-08 20:17:3610 days ago1720469856IN
0x0E936b2F...5b95Beeb0
0 ETH0.001748139.0602034
Execute62719182024-07-08 19:26:3610 days ago1720466796IN
0x0E936b2F...5b95Beeb0
0 ETH0.000250621.28493141
Execute62701682024-07-08 12:58:4810 days ago1720443528IN
0x0E936b2F...5b95Beeb0
0 ETH0.0024688212.71797038
Execute62701672024-07-08 12:58:3610 days ago1720443516IN
0x0E936b2F...5b95Beeb0
0 ETH0.0029394312.57356114
Execute62653262024-07-07 18:49:3611 days ago1720378176IN
0x0E936b2F...5b95Beeb0
0 ETH0.000906774.64968025
Execute62653252024-07-07 18:49:1211 days ago1720378152IN
0x0E936b2F...5b95Beeb0
0 ETH0.001029644.38725947
Execute62607362024-07-07 1:36:4812 days ago1720316208IN
0x0E936b2F...5b95Beeb0
0 ETH0.001433297.34162301
Execute62607162024-07-07 1:32:1212 days ago1720315932IN
0x0E936b2F...5b95Beeb0
0 ETH0.001335956.84883391
Execute62592202024-07-06 19:56:0012 days ago1720295760IN
0x0E936b2F...5b95Beeb0
0 ETH0.000604883.15187405
Execute62584652024-07-06 17:07:1212 days ago1720285632IN
0x0E936b2F...5b95Beeb0
0 ETH0.001505987.71911986
Execute62408942024-07-03 23:26:4815 days ago1720049208IN
0x0E936b2F...5b95Beeb0
0 ETH0.000433182.25643806
Execute62408522024-07-03 23:18:0015 days ago1720048680IN
0x0E936b2F...5b95Beeb0
0 ETH0.000483792.47784949
Execute62405072024-07-03 22:01:1215 days ago1720044072IN
0x0E936b2F...5b95Beeb0
0 ETH0.000505332.63156356
Execute62402982024-07-03 21:14:1215 days ago1720041252IN
0x0E936b2F...5b95Beeb0
0 ETH0.001031465.31012608
Execute62402972024-07-03 21:13:4815 days ago1720041228IN
0x0E936b2F...5b95Beeb0
0 ETH0.001218795.21064445
Execute62400672024-07-03 20:20:1215 days ago1720038012IN
0x0E936b2F...5b95Beeb0
0 ETH0.001152235.78283216
Execute62400062024-07-03 20:07:0015 days ago1720037220IN
0x0E936b2F...5b95Beeb0
0 ETH0.000820564.27029203
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
63166932024-07-15 19:01:483 days ago1721070108
0x0E936b2F...5b95Beeb0
0.00014211 ETH
63166932024-07-15 19:01:483 days ago1721070108
0x0E936b2F...5b95Beeb0
0.00014211 ETH
62934262024-07-12 2:10:247 days ago1720750224
0x0E936b2F...5b95Beeb0
0.00089872 ETH
62934262024-07-12 2:10:247 days ago1720750224
0x0E936b2F...5b95Beeb0
0.00089872 ETH
62901502024-07-11 14:12:007 days ago1720707120
0x0E936b2F...5b95Beeb0
0.00484112 ETH
62901502024-07-11 14:12:007 days ago1720707120
0x0E936b2F...5b95Beeb0
0.00484112 ETH
62794782024-07-09 23:11:129 days ago1720566672
0x0E936b2F...5b95Beeb0
0.00090628 ETH
62794782024-07-09 23:11:129 days ago1720566672
0x0E936b2F...5b95Beeb0
0.00090628 ETH
62786362024-07-09 20:05:009 days ago1720555500
0x0E936b2F...5b95Beeb0
0.00036917 ETH
62786362024-07-09 20:05:009 days ago1720555500
0x0E936b2F...5b95Beeb0
0.00036917 ETH
62776292024-07-09 16:24:369 days ago1720542276
0x0E936b2F...5b95Beeb0
0.00059877 ETH
62776292024-07-09 16:24:369 days ago1720542276
0x0E936b2F...5b95Beeb0
0.00059877 ETH
62731852024-07-09 0:09:4810 days ago1720483788
0x0E936b2F...5b95Beeb0
0.00318663 ETH
62731852024-07-09 0:09:4810 days ago1720483788
0x0E936b2F...5b95Beeb0
0.00318663 ETH
62721612024-07-08 20:19:1210 days ago1720469952
0x0E936b2F...5b95Beeb0
0.00020306 ETH
62721612024-07-08 20:19:1210 days ago1720469952
0x0E936b2F...5b95Beeb0
0.00020306 ETH
62721532024-07-08 20:17:3610 days ago1720469856
0x0E936b2F...5b95Beeb0
0.00000843 ETH
62721532024-07-08 20:17:3610 days ago1720469856
0x0E936b2F...5b95Beeb0
0.00000843 ETH
62719182024-07-08 19:26:3610 days ago1720466796
0x0E936b2F...5b95Beeb0
0.00037097 ETH
62719182024-07-08 19:26:3610 days ago1720466796
0x0E936b2F...5b95Beeb0
0.00037097 ETH
62701682024-07-08 12:58:4810 days ago1720443528
0x0E936b2F...5b95Beeb0
0.00497781 ETH
62701682024-07-08 12:58:4810 days ago1720443528
0x0E936b2F...5b95Beeb0
0.00497781 ETH
62701672024-07-08 12:58:3610 days ago1720443516
0x0E936b2F...5b95Beeb0
0.00497781 ETH
62653262024-07-07 18:49:3611 days ago1720378176
0x0E936b2F...5b95Beeb0
0.01035348 ETH
62653262024-07-07 18:49:3611 days ago1720378176
0x0E936b2F...5b95Beeb0
0.01035348 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PairArbitrageur

Compiler Version
v0.8.15+commit.e14f2714

Optimization Enabled:
Yes with 200 runs

Other Settings:
london EvmVersion
File 1 of 31 : PairArbitrageur.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;

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

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

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

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

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

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

/// @title PairAribtrageur
/// @notice Simple flash arbitrageur between Marginal v1 and their associated Uniswap v3 spot oracle pools
/// @dev WARNING: This contract is unaudited. Use at your own risk
contract PairArbitrageur is
    IMarginalV1SwapCallback,
    IUniswapV3SwapCallback,
    PeripheryImmutableState,
    PeripheryPayments,
    PeripheryValidation,
    Multicall
{
    /// @dev Used as the placeholder value for sqrtPriceLimit1X96
    uint160 private constant DEFAULT_SQRT_PRICE_LIMIT_X96_CACHED = 0;

    /// @dev Transient storage variable used for returning the computed amount in for an exact output swap.
    uint160 private sqrtPriceLimit1X96Cached = DEFAULT_SQRT_PRICE_LIMIT_X96_CACHED;

    error PoolNotInitialized();
    error PoolInvalid();
    error ArbitrageNotAvailable();
    error AmountOutLessThanMin(uint256 amountOut);

    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) = Path.decodeFirstPool(data.path);
        CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, maintenance, oracle);

        (bool isExactInput, uint256 amountToPay) =
            amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));

        if (!isExactInput) {
            // token combos for next swap
            address tokenIn_ = tokenIn;
            address tokenOut_ = tokenOut;

            // swap in/out because exact output swaps are reversed
            tokenIn = tokenOut_;
            tokenOut = tokenIn_;

            // swap on Uniswap for second swap if this is exactOutput (since first swap)
            // amount specified on second pool swap is exactInput
            bool zeroForOne = amount0Delta < 0; // sending token0 pulled from marginal in to uniswap
            int256 amountSpecified = zeroForOne ? -amount0Delta : -amount1Delta;

            uint24 uniswapV3Fee = IUniswapV3Pool(oracle).fee();
            SwapCallbackData memory data_ =
                SwapCallbackData({path: abi.encodePacked(tokenIn_, maintenance, oracle, tokenOut_), payer: data.payer});
            IUniswapV3Pool(oracle).swap(
                data.payer,
                zeroForOne,
                amountSpecified,
                sqrtPriceLimit1X96Cached == 0
                    ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                    : sqrtPriceLimit1X96Cached,
                abi.encode(data_)
            );
            // pay Marginal pool for what is still owed
            pay(tokenIn, data.payer, msg.sender, amountToPay);
        } else {
            // otherwise this is second swap and simply need to pay marginal pool
            pay(tokenIn, data.payer, msg.sender, amountToPay);
        }
    }

    /// @inheritdoc IUniswapV3SwapCallback
    function uniswapV3SwapCallback(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) = Path.decodeFirstPool(data.path);

        PoolAddress.PoolKey memory key = PoolAddress.getPoolKey(tokenIn, tokenOut, maintenance, oracle);
        CallbackValidation.verifyUniswapV3Callback(factory, key);

        (bool isExactInput, uint256 amountToPay) =
            amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));

        if (!isExactInput) {
            // token combos for next swap
            address tokenIn_ = tokenIn;
            address tokenOut_ = tokenOut;

            // swap in/out because exact output swaps are reversed
            tokenIn = tokenOut_;
            tokenOut = tokenIn_;

            // swap on Marginal for second swap if this is exactOutput (since first swap)
            // amount specified on second pool swap is exactInput
            bool zeroForOne = amount0Delta < 0; // sending token0 pulled from marginal in to uniswap
            int256 amountSpecified = zeroForOne ? -amount0Delta : -amount1Delta;

            address pool = PoolAddress.getAddress(factory, key);
            uint24 maintenance = IMarginalV1Pool(pool).maintenance();
            SwapCallbackData memory data_ = SwapCallbackData({
                path: abi.encodePacked(
                    tokenIn_, // tokenIn
                    maintenance, // maintenance
                    msg.sender, // oracle
                    tokenOut_ // tokenOut
                ),
                payer: data.payer
            });
            IMarginalV1Pool(pool).swap(
                data.payer,
                zeroForOne,
                amountSpecified,
                sqrtPriceLimit1X96Cached == 0
                    ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                    : sqrtPriceLimit1X96Cached,
                abi.encode(data_)
            );
            // pay Marginal pool for what is still owed
            pay(tokenIn, data.payer, msg.sender, amountToPay);
        } else {
            // otherwise this is second swap and simply need to pay marginal pool
            pay(tokenIn, data.payer, msg.sender, amountToPay);
        }
    }

    struct ExecuteParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        address tokenOut;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimit0X96; // limit on first pool swap
        uint160 sqrtPriceLimit1X96; // limit on second pool swap
        uint256 deadline;
        bool sweepAsETH;
    }

    /// @notice Executes the arb between Marginal v1 pool and its associated Uniswap v3 oracle
    /// @dev Naively assumes x*y=L^2 for both pools, so works for swaps within a tick on Uniswap v3.
    /// Also ignores fees in calculation for size to arb with.
    function execute(ExecuteParams calldata params)
        external
        payable
        checkDeadline(params.deadline)
        returns (uint256 amountOut)
    {
        require(params.token0 < params.token1);
        require(params.tokenOut == params.token0 || params.tokenOut == params.token1);
        address pool = PoolAddress.getAddress(
            factory, PoolAddress.getPoolKey(params.token0, params.token1, params.maintenance, params.oracle)
        );

        (uint160 sqrtPriceX96,, uint128 liquidity,,,,, bool initialized) = IMarginalV1Pool(pool).state();
        if (!initialized) revert PoolNotInitialized();
        (uint160 oracleSqrtPriceX96,,,,,,) = IUniswapV3Pool(params.oracle).slot0();
        uint128 oracleLiquidity = IUniswapV3Pool(params.oracle).liquidity();

        // for access in callback
        sqrtPriceLimit1X96Cached = params.sqrtPriceLimit1X96;

        // del y = ((L0 * L1) / (L0 + L1)) * (sqrtPrice1X96 - sqrtPrice0X96) is y amount to add to (> 0) or take out of (< 0)
        // or del x = ((L0 * L1) / (L0 + L1)) * (1 / sqrtPrice1X96 - 1 / sqrtPrice0X96) is x amount to add to (> 0) or take out of (< 0)
        // first pool and send to second pool for prices to align post arbitrage. Ignores fees and assumes x*y = L^2 for both pools
        if (sqrtPriceX96 == oracleSqrtPriceX96) revert ArbitrageNotAvailable();
        if (
            (sqrtPriceX96 > oracleSqrtPriceX96 && params.tokenOut == params.token0)
                || (sqrtPriceX96 < oracleSqrtPriceX96 && params.tokenOut == params.token1)
        ) {
            // swap on marginal first then uniswap second
            bool zeroForOne = sqrtPriceX96 > oracleSqrtPriceX96; // zeroForOne on Marginal v1 pool
            uint256 prod =
                (uint256(liquidity) * uint256(oracleLiquidity)) / (uint256(liquidity) + uint256(oracleLiquidity)); // no overflow since uint128 for liquidity
            int256 amountSpecified = zeroForOne
                ? -int256(Math.mulDiv(prod, sqrtPriceX96 - oracleSqrtPriceX96, FixedPoint96.Q96))
                : -int256(
                    (prod << FixedPoint96.RESOLUTION) / sqrtPriceX96
                        - (prod << FixedPoint96.RESOLUTION) / oracleSqrtPriceX96
                );

            // amount specified on first pool swap is exactOutput
            // second swap on Uniswap occurs in IMarginalV1SwapCallback
            SwapCallbackData memory data = SwapCallbackData({
                path: abi.encodePacked(
                    zeroForOne ? params.token1 : params.token0, // tokenOut
                    params.maintenance,
                    params.oracle,
                    zeroForOne ? params.token0 : params.token1 // tokenIn
                ),
                payer: address(this)
            });
            IMarginalV1Pool(pool).swap(
                address(this),
                zeroForOne,
                amountSpecified,
                params.sqrtPriceLimit0X96 == 0
                    ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                    : params.sqrtPriceLimit0X96,
                abi.encode(data)
            );
        } else {
            // swap on uniswap first then marginal second
            bool zeroForOne = oracleSqrtPriceX96 > sqrtPriceX96; // zeroForOne on Uniswap v3 pool
            uint256 prod =
                (uint256(liquidity) * uint256(oracleLiquidity)) / (uint256(liquidity) + uint256(oracleLiquidity)); // no overflow since uint128 for liquidity
            int256 amountSpecified = zeroForOne
                ? -int256(Math.mulDiv(prod, oracleSqrtPriceX96 - sqrtPriceX96, FixedPoint96.Q96))
                : -int256(
                    (prod << FixedPoint96.RESOLUTION) / oracleSqrtPriceX96
                        - (prod << FixedPoint96.RESOLUTION) / sqrtPriceX96
                );

            // amount specified on first pool swap is exactOutput
            // second swap on Marginal occurs in IUniswapV3SwapCallback
            SwapCallbackData memory data = SwapCallbackData({
                path: abi.encodePacked(
                    zeroForOne ? params.token1 : params.token0, // tokenOut
                    params.maintenance,
                    params.oracle,
                    zeroForOne ? params.token0 : params.token1 // tokenIn
                ),
                payer: address(this)
            });
            IUniswapV3Pool(params.oracle).swap(
                address(this),
                zeroForOne,
                amountSpecified,
                params.sqrtPriceLimit0X96 == 0
                    ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
                    : params.sqrtPriceLimit0X96,
                abi.encode(data)
            );
        }

        // reset for next call to execute
        sqrtPriceLimit1X96Cached = DEFAULT_SQRT_PRICE_LIMIT_X96_CACHED;

        // send profits to recipient
        amountOut = balance(params.tokenOut);
        if (amountOut < params.amountOutMinimum) {
            revert AmountOutLessThanMin(amountOut);
        }

        if (params.sweepAsETH && params.tokenOut == WETH9) {
            IWETH9(WETH9).withdraw(amountOut);
            sweepETH(amountOut, params.recipient);
        } else {
            sweepToken(params.tokenOut, amountOut, params.recipient);
        }
    }
}

File 2 of 31 : 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 3 of 31 : 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 4 of 31 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#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 UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @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 IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 5 of 31 : 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 6 of 31 : 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 7 of 31 : 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 8 of 31 : 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 9 of 31 : 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 10 of 31 : 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 31 : 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 12 of 31 : 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 13 of 31 : 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 14 of 31 : 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 15 of 31 : 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 16 of 31 : 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 17 of 31 : 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 18 of 31 : 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 19 of 31 : 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 20 of 31 : 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 21 of 31 : 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 22 of 31 : 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 31 : 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 24 of 31 : 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 25 of 31 : 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 26 of 31 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 27 of 31 : 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 28 of 31 : 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 29 of 31 : 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 30 of 31 : 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 31 : 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;
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v2-core/=lib/v2-core/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@marginal/v1-core/=lib/v1-core/",
    "base64-sol/=lib/base64/",
    "base64/=lib/base64/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "v1-core/=lib/v1-core/contracts/",
    "v2-core/=lib/v2-core/contracts/",
    "v3-core/=lib/v3-core/contracts/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "viaIR": true,
  "libraries": {}
}

Contract ABI

[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"AmountOutLessThanMin","type":"error"},{"inputs":[],"name":"ArbitrageNotAvailable","type":"error"},{"inputs":[],"name":"OracleNotSender","type":"error"},{"inputs":[],"name":"PoolInactive","type":"error"},{"inputs":[],"name":"PoolInvalid","type":"error"},{"inputs":[],"name":"PoolNotInitialized","type":"error"},{"inputs":[],"name":"PoolNotSender","type":"error"},{"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":"address","name":"oracle","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimit0X96","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceLimit1X96","type":"uint160"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"sweepAsETH","type":"bool"}],"internalType":"struct PairArbitrageur.ExecuteParams","name":"params","type":"tuple"}],"name":"execute","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","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":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","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"}]

60e0806040523462000151576040816200241b803803809162000023828562000156565b8339810103126200015157600460206200004a81620000428562000190565b940162000190565b6080849052604051632daa48c160e11b815290939092839182906001600160a01b03165afa908115620001455760009162000101575b5060a05260c052600080546001600160a01b03191690556040516122759081620001a682396080518181816101dd01528181610b9d01528181610fcd015281816110750152611335015260a05181610ac8015260c0518181816104630152818161053c0152818161097f01528181610a82015281816112a901526118150152f35b906020823d82116200013c575b816200011d6020938362000156565b81010312620001395750620001329062000190565b3862000080565b80fd5b3d91506200010e565b6040513d6000823e3d90fd5b600080fd5b601f909101601f19168101906001600160401b038211908210176200017a57604052565b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b0382168203620001515756fe60806040526004361015610023575b361561001957600080fd5b61002161129f565b005b60003560e01c806312210e8a146100ff578063132078b2146100f65780631e121fe8146100ed57806349404b7c146100e45780634aa4a4fc146100db5780635b549182146100d257806374d328d2146100c9578063ac9650d8146100c0578063c45a0155146100b7578063df2ab5bb146100ae5763fa461e330361000e576100a961102e565b61000e565b506100a9610ffc565b506100a9610fb6565b506100a9610eb3565b506100a9610b48565b506100a9610ab1565b506100a9610a6b565b506100a9610949565b506100a9610925565b506100a9610136565b506100a9610118565b600091031261011357565b600080fd5b506000366003190112610113574761012c57005b61002147336121cc565b50610160366003190112610113576101243542116108cc5761015661193b565b610181610170610164611947565b6001600160a01b031690565b6001600160a01b03928316106115bb565b610189611953565b8161019561016461193b565b91161480156108aa575b6101a8906115bb565b6102016101646101646101db6101bc61193b565b6101c4611947565b6101cc611977565b906101d561195f565b92611cbc565b7f0000000000000000000000000000000000000000000000000000000000000000611d3f565b906040805163c19d93fb60e01b8152610100600494828281888096855afa801561089d575b60009182948392610860575b5050156108505760e061024961016461016461195f565b865195868092633850c7bd851b82525afa938415610843575b60009461080d575b5061027961016461016461195f565b8551948591630d34328160e11b8352828a60209889935afa918215610800575b6000926107d1575b506102ca6102ad611abf565b60018060a01b03166001600160601b0360a01b6000541617600055565b87811692888116928484146107c1579189918493868b9998979611978880996107a4575b801561077d575b15610633579061031f610325926001600160801b0380911692166103198184611ad8565b92611af7565b90611b0f565b938715610605575061034d94506103489392916103419161173e565b1690611e40565b6116ba565b915b80156105f257600088610412610363611947565b6103f689610397610372611977565b61037a61195f565b8989146105e45761038961193b565b915b8d5196879586016116fe565b036103aa601f1991828101855284611431565b6103b26115c2565b928352308b8401528c6103c3611acc565b161586146105d6578686146105bc576401000276a45b9a5b6103ea8b519485928301611762565b03908101835282611431565b8751630251596160e31b815298899788968795309087016117a8565b03925af180156105af575b610583575b505b600080546001600160a01b031916905561044461043f611953565b611b47565b9160c435831061056357610456611b3a565b8061052f575b1561050a577f00000000000000000000000000000000000000000000000000000000000000001692833b15610113578151632e1a7d4d60e01b81529081018381526104e09460009183919082908490829060200103925af180156104fd575b6104e4575b506104d26104cc61196b565b83611569565b519081529081906020820190565b0390f35b806104f16104f7926113c0565b80610108565b386104c0565b610505611461565b6104bb565b506104e0925061052a61051b611953565b8361052461196b565b916114af565b6104d2565b50610538611953565b81167f000000000000000000000000000000000000000000000000000000000000000082161461045c565b5051636b19f1cf60e11b81528083019182529081906020010390fd5b0390fd5b6105a290823d84116105a8575b61059a8183611431565b810190611792565b50610422565b503d610590565b6105b7611461565b61041d565b73fffd8963efd1fc6a506488495d951d5263988d256103d9565b6105de611acc565b9a6103db565b6105ec611947565b9161038b565b60008861041261060061193b565b610363565b9250505061062761062d936106216103489460601b9384611b0f565b92611b0f565b90611b2f565b9161034f565b975084965061031f61065b9294958711986001600160801b0380911692166103198184611ad8565b93861561075b575061067794506103489392916103419161173e565b905b801561074d57610687611947565b905b600088610700610697611977565b946106c16106a361195f565b86861461073f576106b261193b565b905b8a519889948d86016116fe565b03946106d5601f1996878101835282611431565b6106dd6115c2565b90815230898201526103f66106f661016461016461195f565b968c6103c3611acc565b03925af18015610732575b610716575b50610424565b61072c90823d84116105a85761059a8183611431565b50610710565b61073a611461565b61070b565b610747611947565b906106b4565b61075561193b565b90610689565b92505050610627610777936106216103489460601b9384611b0f565b90610679565b5086861080156102f55750610790611953565b8561079c610164611947565b9116146102f5565b506107ad611953565b856107b961016461193b565b9116146102ee565b8851636d79b6f960e01b81528b90fd5b6107f2919250863d88116107f9575b6107ea8183611431565b810190611aab565b90386102a1565b503d6107e0565b610808611461565b610299565b61082f91945060e03d811161083c575b6108278183611431565b810190611a46565b505050505050923861026a565b503d61081d565b61084b611461565b610262565b845163486aa30760e01b81528490fd5b91509150610884929350803d10610896575b61087c8183611431565b8101906119b3565b97969495505050505090923880610232565b503d610872565b6108a5611461565b610226565b506101a86108b6611953565b826108c2610164611947565b911614905061019f565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b6001600160a01b0381160361011357565b359061092382610907565b565b5060403660031901126101135761002160243561094181610907565b600435611569565b5060403660031901126101135760243561096281610907565b6040516370a0823160e01b81523060048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691602082602481865afa918215610a5e575b600092610a2e575b506109c860043583101561146e565b816109cf57005b823b1561011357604051632e1a7d4d60e01b815260048101839052610021936000908290602490829084905af18015610a21575b610a0e575b506121cc565b806104f1610a1b926113c0565b38610a08565b610a29611461565b610a03565b610a5091925060203d8111610a57575b610a488183611431565b810190611452565b90386109b9565b503d610a3e565b610a66611461565b6109b1565b5034610113576000366003190112610113576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5034610113576000366003190112610113576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b9060606003198301126101135760043591602435916044356001600160401b039283821161011357806023830112156101135781600401359384116101135760248483010111610113576024019190565b503461011357610b7c610b5a36610af7565b919293906000851392838015610ded575b610b74906115bb565b81019061160b565b92610b878451611c0c565b9290939194610bc1610b9b85878986611cbc565b7f0000000000000000000000000000000000000000000000000000000000000000611ba8565b5015610dd85790948591906001600160a01b03868116908316105b610dbc5796610d1e94936000808895610cf7610ccd60206040986100219f8686128714610daa5750610c4a610c10866116ba565b9b5b8b5163ddca3f4360e01b815284816004816001600160a01b038f165afa8015610d9d575b610d70575b50898c519e8f948686016116fe565b0397610c5f601f19998d8b820190528d611431565b018051909a90610c8d906001600160a01b0316610c7a6115c2565b9283526001600160a01b03166020830152565b8a5185546001600160a01b0391821699610cd99290911680158814610d6a57508686128714610d50576401000276a45b925b8b5194859160208301611762565b03908101845283611431565b8851630251596160e31b8152998a98899788961290600487016117a8565b03926001600160a01b03165af18015610d43575b610d25575b50516001600160a01b031690565b339161180b565b610d3d9060403d6040116105a85761059a8183611431565b50610d10565b610d4b611461565b610d0b565b73fffd8963efd1fc6a506488495d951d5263988d25610cbd565b92610cbf565b610d8f90853d8711610d96575b610d878183611431565b8101906116e6565b5038610c3b565b503d610d7d565b610da5611461565b610c36565b610db6610c4a916116ba565b9b610c12565b509350505050610d1e602061002194015160018060a01b031690565b856001600160a01b0382811690871610610bdc565b5060008513610b6b565b918091926000905b828210610e17575011610e10575050565b6000910152565b91508060209183015181860152018291610dff565b90602091610e4581518092818552858086019101610df7565b601f01601f1916010190565b602080820190808352835180925260408301928160408460051b8301019501936000915b848310610e855750505050505090565b9091929394958480610ea3600193603f198682030187528a51610e2c565b9801930193019194939290610e75565b50602036600319011261011357600480356001600160401b03918282116101135736602383011215610113578181013592831161011357602490818301928236918660051b01011161011357610f0884611eab565b9360005b818110610f2157604051806104e08882610e51565b600080610f2f838589611f1c565b60409391610f41855180938193611f6b565b0390305af490610f4f611f79565b91829015610f7e57505090610f7991610f688289612018565b52610f738188612018565b50611ef5565b610f0c565b868387926044825110610113578261057f9385610fa19401518301019101611fa9565b925162461bcd60e51b81529283928301612007565b5034610113576000366003190112610113576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5060603660031901126101135761002160043561101881610907565b6044359061102582610907565b602435906114af565b50346101135761103d36610af7565b91611059600094928584139485801561129657610b74906115bb565b926110736110678551611c0c565b90828495939794611cbc565b7f00000000000000000000000000000000000000000000000000000000000000009361109f8286611bd7565b501561127d57856001600160a01b03868116908516105b61125d576101646101648796959493838c6110e59512958660001461125357506110df906116ba565b96611d3f565b9260409384928a845195636c376cc560e01b875260209687918282600481895afa918215611246575b8492611227575b5087519b8c9233908585019361112a946116fe565b039b601f199c8d81018c5261113f908c611431565b0180519099906001600160a01b03166111566115c2565b9182526001600160a01b03168782015289516001600160a01b031682549091906001600160a01b03166111fa9d6111d492916111b891906001600160a01b0381166105de575086156105bc576401000276a49a6103ea8b519485928301611762565b8751630251596160e31b815298899788968795600487016117a8565b03925af1801561121a575b6111ff575b505090513391906001600160a01b03169061180b565b604051f35b8161121592903d106105a85761059a8183611431565b6111e4565b611222611461565b6111df565b61123f919250833d8511610d9657610d878183611431565b9038611115565b61124e611461565b61110e565b6110df91506116ba565b505050602094909401516111fa9492506001600160a01b03169050610d1e565b90948591906001600160a01b03848116908716106110b6565b50868413610b6b565b60018060a01b03807f0000000000000000000000000000000000000000000000000000000000000000163314908115611314575b50156112db57565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f0000000000000000000000000000000000000000000000000000000000000000165afa90811561139c575b60009161136e575b50386112d3565b61138f915060203d8111611395575b6113878183611431565b8101906117f6565b38611367565b503d61137d565b6113a4611461565b61135f565b50634e487b7160e01b600052604160045260246000fd5b6001600160401b0381116113d357604052565b6113db6113a9565b604052565b604081019081106001600160401b038211176113d357604052565b608081019081106001600160401b038211176113d357604052565b60a081019081106001600160401b038211176113d357604052565b90601f801991011681019081106001600160401b038211176113d357604052565b90816020910312610113575190565b506040513d6000823e3d90fd5b1561147557565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b6040516370a0823160e01b8152306004820152909290916020836024816001600160a01b0388165afa92831561155c575b60009361153c575b50821061150257816114f957505050565b61092392612117565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b61155591935060203d8111610a5757610a488183611431565b91386114e8565b611564611461565b6114e0565b47908110611583578061157a575050565b610923916121cc565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b1561011357565b60405190604082018281106001600160401b038211176113d357604052565b6020906001600160401b0381116115fe575b601f01601f19160190565b6116066113a9565b6115f3565b9060209081838203126101135782356001600160401b039384821161011357016040818303126101135760405193611642856113e0565b81359081116101135781019082601f8301121561011357813592611665846115e1565b906116736040519283611431565b848252858585010111610113576000858561169c96828097018386013783010152855201610918565b9082015290565b50634e487b7160e01b600052601160045260246000fd5b600160ff1b81146116cc575b60000390565b6116d46116a3565b6116c6565b62ffffff81160361011357565b9081602091031261011357516116fb816116d9565b90565b9290603f94916001600160601b03199384809360601b16865262ffffff60e81b9060e81b16601486015260601b16601784015260601b16602b8201520190565b6001600160a01b039182169116818110611756570390565b61175e6116a3565b0390565b60208152604061177d83518260208501526060840190610e2c565b6020909301516001600160a01b031691015290565b9190826040910312610113576020825192015190565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a0608082018190526116fb92910190610e2c565b8015150361011357565b5190610923826117e1565b9081602091031261011357516116fb816117e1565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116949290828116861480611931575b1561190f57505050823b15610113576118b692602092604051630d0e30db60e41b815260008160048187875af18015611902575b6118ef575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af180156118e2575b6118c85750565b6118df9060203d8111611395576113878183611431565b50565b6118ea611461565b6118c1565b806104f16118fc926113c0565b3861187d565b61190a611461565b611878565b9194509192919081163003611928575061092392612117565b61092393612060565b5083471015611844565b6004356116fb81610907565b6024356116fb81610907565b60a4356116fb81610907565b6064356116fb81610907565b6084356116fb81610907565b6044356116fb816116d9565b51906001600160801b038216820361011357565b51908160020b820361011357565b519060ff8216820361011357565b9190826101009103126101135781516119cb81610907565b9160208101516001600160601b038116810361011357916119ee60408301611983565b916119fb60608201611997565b91608082015163ffffffff81168103610113579160a08101518060060b810361011357916116fb60e0611a3060c085016119a5565b93016117eb565b519061ffff8216820361011357565b908160e0910312610113578051611a5c81610907565b91611a6960208301611997565b91611a7660408201611a37565b91611a8360608301611a37565b91611a9060808201611a37565b9160c0611a9f60a084016119a5565b9201516116fb816117e1565b90816020910312610113576116fb90611983565b610104356116fb81610907565b60e4356116fb81610907565b8060001904821181151516611aeb570290565b611af36116a3565b0290565b81198111611b03570190565b611b0b6116a3565b0190565b8115611b19570490565b634e487b7160e01b600052601260045260246000fd5b818110611756570390565b610144356116fb816117e1565b6040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa908115611b9b575b600091611b83575090565b6116fb915060203d8111610a5757610a488183611431565b611ba3611461565b611b78565b6001600160a01b0391611bba91611d3f565b1690813303611bc557565b604051635cf3778960e01b8152600490fd5b81611be191611d3f565b50606001516001600160a01b03169033829003611bfa57565b6040516383b1c28760e01b8152600490fd5b906014825110611c7f57602082015160601c916017815110611c4357601781015190611c40611c3a8261203a565b9161204d565b92565b60405162461bcd60e51b8152602060048201526014602482015273746f55696e7432345f6f75744f66426f756e647360601b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274746f416464726573735f6f75744f66426f756e647360581b6044820152606490fd5b92909162ffffff9060006060604051611cd4816113fb565b828152602081018390526040810183905201526001600160a01b0393849080821687831611611d24575b8160405197611d0c896113fb565b16875216602086015216604084015216606082015290565b95611cfe565b9081602091031261011357516116fb81610907565b81519192916020906001600160a01b0316848201516001600160a01b031690611dc9611d856060611d7660408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa928315611e33575b600093611e03575b50821615611df157565b604051630f509b1160e01b8152600490fd5b611e2591935060203d8111611e2c575b611e1d8183611431565b810190611d2a565b9138611de7565b503d611e13565b611e3b611461565b611ddf565b6000198282099082810292838084109303928084039314611e7c57600160601b9183831115610113570990828211900360a01b910360601c1790565b50505060601c90565b6020906001600160401b038111611e9e575b60051b0190565b611ea66113a9565b611e97565b90611eb582611e85565b611ec26040519182611431565b8281528092611ed3601f1991611e85565b019060005b828110611ee457505050565b806060602080938501015201611ed8565b6001906000198114611b03570190565b50634e487b7160e01b600052603260045260246000fd5b9190811015611f5e575b60051b81013590601e19813603018212156101135701908135916001600160401b038311610113576020018236038113610113579190565b611f66611f05565b611f26565b908092918237016000815290565b3d15611fa4573d90611f8a826115e1565b91611f986040519384611431565b82523d6000602084013e565b606090565b602081830312610113578051906001600160401b038211610113570181601f82011215610113578051611fdb816115e1565b92611fe96040519485611431565b81845260208284010111610113576116fb9160208085019101610df7565b9060206116fb928181520190610e2c565b602091815181101561202d575b60051b010190565b612035611f05565b612025565b602b815110611c7f576037015160601c90565b603f815110611c7f57604b015160601c90565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b0380921660248501521660448301526064820152606481526120a381611416565b51925af16120af611f79565b816120e8575b50156120bd57565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b80518015925082156120fd575b5050386120b5565b61211092506020809183010191016117f6565b38806120f5565b60405163a9059cbb60e01b602082019081526001600160a01b039390931660248201526044808201949094529283526000928392908390612159606482611431565b51925af1612165611f79565b8161219d575b501561217357565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b80518015925082156121b2575b50503861216b565b6121c592506020809183010191016117f6565b38806121aa565b60008092918192604051918360208401938085106001600160401b03861117612232575b84604052525af16121ff611f79565b501561220757565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b61223a6113a9565b6121f056fea264697066735822122068859a9f99bcb5f128ea1f0462db5044e0cff662ebcd2b69e8f6f7b2ca5476fa64736f6c634300080f0033000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14

Deployed Bytecode

0x60806040526004361015610023575b361561001957600080fd5b61002161129f565b005b60003560e01c806312210e8a146100ff578063132078b2146100f65780631e121fe8146100ed57806349404b7c146100e45780634aa4a4fc146100db5780635b549182146100d257806374d328d2146100c9578063ac9650d8146100c0578063c45a0155146100b7578063df2ab5bb146100ae5763fa461e330361000e576100a961102e565b61000e565b506100a9610ffc565b506100a9610fb6565b506100a9610eb3565b506100a9610b48565b506100a9610ab1565b506100a9610a6b565b506100a9610949565b506100a9610925565b506100a9610136565b506100a9610118565b600091031261011357565b600080fd5b506000366003190112610113574761012c57005b61002147336121cc565b50610160366003190112610113576101243542116108cc5761015661193b565b610181610170610164611947565b6001600160a01b031690565b6001600160a01b03928316106115bb565b610189611953565b8161019561016461193b565b91161480156108aa575b6101a8906115bb565b6102016101646101646101db6101bc61193b565b6101c4611947565b6101cc611977565b906101d561195f565b92611cbc565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2611d3f565b906040805163c19d93fb60e01b8152610100600494828281888096855afa801561089d575b60009182948392610860575b5050156108505760e061024961016461016461195f565b865195868092633850c7bd851b82525afa938415610843575b60009461080d575b5061027961016461016461195f565b8551948591630d34328160e11b8352828a60209889935afa918215610800575b6000926107d1575b506102ca6102ad611abf565b60018060a01b03166001600160601b0360a01b6000541617600055565b87811692888116928484146107c1579189918493868b9998979611978880996107a4575b801561077d575b15610633579061031f610325926001600160801b0380911692166103198184611ad8565b92611af7565b90611b0f565b938715610605575061034d94506103489392916103419161173e565b1690611e40565b6116ba565b915b80156105f257600088610412610363611947565b6103f689610397610372611977565b61037a61195f565b8989146105e45761038961193b565b915b8d5196879586016116fe565b036103aa601f1991828101855284611431565b6103b26115c2565b928352308b8401528c6103c3611acc565b161586146105d6578686146105bc576401000276a45b9a5b6103ea8b519485928301611762565b03908101835282611431565b8751630251596160e31b815298899788968795309087016117a8565b03925af180156105af575b610583575b505b600080546001600160a01b031916905561044461043f611953565b611b47565b9160c435831061056357610456611b3a565b8061052f575b1561050a577f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141692833b15610113578151632e1a7d4d60e01b81529081018381526104e09460009183919082908490829060200103925af180156104fd575b6104e4575b506104d26104cc61196b565b83611569565b519081529081906020820190565b0390f35b806104f16104f7926113c0565b80610108565b386104c0565b610505611461565b6104bb565b506104e0925061052a61051b611953565b8361052461196b565b916114af565b6104d2565b50610538611953565b81167f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b1482161461045c565b5051636b19f1cf60e11b81528083019182529081906020010390fd5b0390fd5b6105a290823d84116105a8575b61059a8183611431565b810190611792565b50610422565b503d610590565b6105b7611461565b61041d565b73fffd8963efd1fc6a506488495d951d5263988d256103d9565b6105de611acc565b9a6103db565b6105ec611947565b9161038b565b60008861041261060061193b565b610363565b9250505061062761062d936106216103489460601b9384611b0f565b92611b0f565b90611b2f565b9161034f565b975084965061031f61065b9294958711986001600160801b0380911692166103198184611ad8565b93861561075b575061067794506103489392916103419161173e565b905b801561074d57610687611947565b905b600088610700610697611977565b946106c16106a361195f565b86861461073f576106b261193b565b905b8a519889948d86016116fe565b03946106d5601f1996878101835282611431565b6106dd6115c2565b90815230898201526103f66106f661016461016461195f565b968c6103c3611acc565b03925af18015610732575b610716575b50610424565b61072c90823d84116105a85761059a8183611431565b50610710565b61073a611461565b61070b565b610747611947565b906106b4565b61075561193b565b90610689565b92505050610627610777936106216103489460601b9384611b0f565b90610679565b5086861080156102f55750610790611953565b8561079c610164611947565b9116146102f5565b506107ad611953565b856107b961016461193b565b9116146102ee565b8851636d79b6f960e01b81528b90fd5b6107f2919250863d88116107f9575b6107ea8183611431565b810190611aab565b90386102a1565b503d6107e0565b610808611461565b610299565b61082f91945060e03d811161083c575b6108278183611431565b810190611a46565b505050505050923861026a565b503d61081d565b61084b611461565b610262565b845163486aa30760e01b81528490fd5b91509150610884929350803d10610896575b61087c8183611431565b8101906119b3565b97969495505050505090923880610232565b503d610872565b6108a5611461565b610226565b506101a86108b6611953565b826108c2610164611947565b911614905061019f565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b6001600160a01b0381160361011357565b359061092382610907565b565b5060403660031901126101135761002160243561094181610907565b600435611569565b5060403660031901126101135760243561096281610907565b6040516370a0823160e01b81523060048201526001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141691602082602481865afa918215610a5e575b600092610a2e575b506109c860043583101561146e565b816109cf57005b823b1561011357604051632e1a7d4d60e01b815260048101839052610021936000908290602490829084905af18015610a21575b610a0e575b506121cc565b806104f1610a1b926113c0565b38610a08565b610a29611461565b610a03565b610a5091925060203d8111610a57575b610a488183611431565b810190611452565b90386109b9565b503d610a3e565b610a66611461565b6109b1565b5034610113576000366003190112610113576040517f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b146001600160a01b03168152602090f35b5034610113576000366003190112610113576040517f0000000000000000000000000227628f3f023bb0b980b67d528571c95c6dac1c6001600160a01b03168152602090f35b9060606003198301126101135760043591602435916044356001600160401b039283821161011357806023830112156101135781600401359384116101135760248483010111610113576024019190565b503461011357610b7c610b5a36610af7565b919293906000851392838015610ded575b610b74906115bb565b81019061160b565b92610b878451611c0c565b9290939194610bc1610b9b85878986611cbc565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2611ba8565b5015610dd85790948591906001600160a01b03868116908316105b610dbc5796610d1e94936000808895610cf7610ccd60206040986100219f8686128714610daa5750610c4a610c10866116ba565b9b5b8b5163ddca3f4360e01b815284816004816001600160a01b038f165afa8015610d9d575b610d70575b50898c519e8f948686016116fe565b0397610c5f601f19998d8b820190528d611431565b018051909a90610c8d906001600160a01b0316610c7a6115c2565b9283526001600160a01b03166020830152565b8a5185546001600160a01b0391821699610cd99290911680158814610d6a57508686128714610d50576401000276a45b925b8b5194859160208301611762565b03908101845283611431565b8851630251596160e31b8152998a98899788961290600487016117a8565b03926001600160a01b03165af18015610d43575b610d25575b50516001600160a01b031690565b339161180b565b610d3d9060403d6040116105a85761059a8183611431565b50610d10565b610d4b611461565b610d0b565b73fffd8963efd1fc6a506488495d951d5263988d25610cbd565b92610cbf565b610d8f90853d8711610d96575b610d878183611431565b8101906116e6565b5038610c3b565b503d610d7d565b610da5611461565b610c36565b610db6610c4a916116ba565b9b610c12565b509350505050610d1e602061002194015160018060a01b031690565b856001600160a01b0382811690871610610bdc565b5060008513610b6b565b918091926000905b828210610e17575011610e10575050565b6000910152565b91508060209183015181860152018291610dff565b90602091610e4581518092818552858086019101610df7565b601f01601f1916010190565b602080820190808352835180925260408301928160408460051b8301019501936000915b848310610e855750505050505090565b9091929394958480610ea3600193603f198682030187528a51610e2c565b9801930193019194939290610e75565b50602036600319011261011357600480356001600160401b03918282116101135736602383011215610113578181013592831161011357602490818301928236918660051b01011161011357610f0884611eab565b9360005b818110610f2157604051806104e08882610e51565b600080610f2f838589611f1c565b60409391610f41855180938193611f6b565b0390305af490610f4f611f79565b91829015610f7e57505090610f7991610f688289612018565b52610f738188612018565b50611ef5565b610f0c565b868387926044825110610113578261057f9385610fa19401518301019101611fa9565b925162461bcd60e51b81529283928301612007565b5034610113576000366003190112610113576040517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26001600160a01b03168152602090f35b5060603660031901126101135761002160043561101881610907565b6044359061102582610907565b602435906114af565b50346101135761103d36610af7565b91611059600094928584139485801561129657610b74906115bb565b926110736110678551611c0c565b90828495939794611cbc565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c29361109f8286611bd7565b501561127d57856001600160a01b03868116908516105b61125d576101646101648796959493838c6110e59512958660001461125357506110df906116ba565b96611d3f565b9260409384928a845195636c376cc560e01b875260209687918282600481895afa918215611246575b8492611227575b5087519b8c9233908585019361112a946116fe565b039b601f199c8d81018c5261113f908c611431565b0180519099906001600160a01b03166111566115c2565b9182526001600160a01b03168782015289516001600160a01b031682549091906001600160a01b03166111fa9d6111d492916111b891906001600160a01b0381166105de575086156105bc576401000276a49a6103ea8b519485928301611762565b8751630251596160e31b815298899788968795600487016117a8565b03925af1801561121a575b6111ff575b505090513391906001600160a01b03169061180b565b604051f35b8161121592903d106105a85761059a8183611431565b6111e4565b611222611461565b6111df565b61123f919250833d8511610d9657610d878183611431565b9038611115565b61124e611461565b61110e565b6110df91506116ba565b505050602094909401516111fa9492506001600160a01b03169050610d1e565b90948591906001600160a01b03848116908716106110b6565b50868413610b6b565b60018060a01b03807f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14163314908115611314575b50156112db57565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2165afa90811561139c575b60009161136e575b50386112d3565b61138f915060203d8111611395575b6113878183611431565b8101906117f6565b38611367565b503d61137d565b6113a4611461565b61135f565b50634e487b7160e01b600052604160045260246000fd5b6001600160401b0381116113d357604052565b6113db6113a9565b604052565b604081019081106001600160401b038211176113d357604052565b608081019081106001600160401b038211176113d357604052565b60a081019081106001600160401b038211176113d357604052565b90601f801991011681019081106001600160401b038211176113d357604052565b90816020910312610113575190565b506040513d6000823e3d90fd5b1561147557565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b6040516370a0823160e01b8152306004820152909290916020836024816001600160a01b0388165afa92831561155c575b60009361153c575b50821061150257816114f957505050565b61092392612117565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b61155591935060203d8111610a5757610a488183611431565b91386114e8565b611564611461565b6114e0565b47908110611583578061157a575050565b610923916121cc565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b1561011357565b60405190604082018281106001600160401b038211176113d357604052565b6020906001600160401b0381116115fe575b601f01601f19160190565b6116066113a9565b6115f3565b9060209081838203126101135782356001600160401b039384821161011357016040818303126101135760405193611642856113e0565b81359081116101135781019082601f8301121561011357813592611665846115e1565b906116736040519283611431565b848252858585010111610113576000858561169c96828097018386013783010152855201610918565b9082015290565b50634e487b7160e01b600052601160045260246000fd5b600160ff1b81146116cc575b60000390565b6116d46116a3565b6116c6565b62ffffff81160361011357565b9081602091031261011357516116fb816116d9565b90565b9290603f94916001600160601b03199384809360601b16865262ffffff60e81b9060e81b16601486015260601b16601784015260601b16602b8201520190565b6001600160a01b039182169116818110611756570390565b61175e6116a3565b0390565b60208152604061177d83518260208501526060840190610e2c565b6020909301516001600160a01b031691015290565b9190826040910312610113576020825192015190565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a0608082018190526116fb92910190610e2c565b8015150361011357565b5190610923826117e1565b9081602091031261011357516116fb816117e1565b6001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b148116949290828116861480611931575b1561190f57505050823b15610113576118b692602092604051630d0e30db60e41b815260008160048187875af18015611902575b6118ef575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af180156118e2575b6118c85750565b6118df9060203d8111611395576113878183611431565b50565b6118ea611461565b6118c1565b806104f16118fc926113c0565b3861187d565b61190a611461565b611878565b9194509192919081163003611928575061092392612117565b61092393612060565b5083471015611844565b6004356116fb81610907565b6024356116fb81610907565b60a4356116fb81610907565b6064356116fb81610907565b6084356116fb81610907565b6044356116fb816116d9565b51906001600160801b038216820361011357565b51908160020b820361011357565b519060ff8216820361011357565b9190826101009103126101135781516119cb81610907565b9160208101516001600160601b038116810361011357916119ee60408301611983565b916119fb60608201611997565b91608082015163ffffffff81168103610113579160a08101518060060b810361011357916116fb60e0611a3060c085016119a5565b93016117eb565b519061ffff8216820361011357565b908160e0910312610113578051611a5c81610907565b91611a6960208301611997565b91611a7660408201611a37565b91611a8360608301611a37565b91611a9060808201611a37565b9160c0611a9f60a084016119a5565b9201516116fb816117e1565b90816020910312610113576116fb90611983565b610104356116fb81610907565b60e4356116fb81610907565b8060001904821181151516611aeb570290565b611af36116a3565b0290565b81198111611b03570190565b611b0b6116a3565b0190565b8115611b19570490565b634e487b7160e01b600052601260045260246000fd5b818110611756570390565b610144356116fb816117e1565b6040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa908115611b9b575b600091611b83575090565b6116fb915060203d8111610a5757610a488183611431565b611ba3611461565b611b78565b6001600160a01b0391611bba91611d3f565b1690813303611bc557565b604051635cf3778960e01b8152600490fd5b81611be191611d3f565b50606001516001600160a01b03169033829003611bfa57565b6040516383b1c28760e01b8152600490fd5b906014825110611c7f57602082015160601c916017815110611c4357601781015190611c40611c3a8261203a565b9161204d565b92565b60405162461bcd60e51b8152602060048201526014602482015273746f55696e7432345f6f75744f66426f756e647360601b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274746f416464726573735f6f75744f66426f756e647360581b6044820152606490fd5b92909162ffffff9060006060604051611cd4816113fb565b828152602081018390526040810183905201526001600160a01b0393849080821687831611611d24575b8160405197611d0c896113fb565b16875216602086015216604084015216606082015290565b95611cfe565b9081602091031261011357516116fb81610907565b81519192916020906001600160a01b0316848201516001600160a01b031690611dc9611d856060611d7660408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa928315611e33575b600093611e03575b50821615611df157565b604051630f509b1160e01b8152600490fd5b611e2591935060203d8111611e2c575b611e1d8183611431565b810190611d2a565b9138611de7565b503d611e13565b611e3b611461565b611ddf565b6000198282099082810292838084109303928084039314611e7c57600160601b9183831115610113570990828211900360a01b910360601c1790565b50505060601c90565b6020906001600160401b038111611e9e575b60051b0190565b611ea66113a9565b611e97565b90611eb582611e85565b611ec26040519182611431565b8281528092611ed3601f1991611e85565b019060005b828110611ee457505050565b806060602080938501015201611ed8565b6001906000198114611b03570190565b50634e487b7160e01b600052603260045260246000fd5b9190811015611f5e575b60051b81013590601e19813603018212156101135701908135916001600160401b038311610113576020018236038113610113579190565b611f66611f05565b611f26565b908092918237016000815290565b3d15611fa4573d90611f8a826115e1565b91611f986040519384611431565b82523d6000602084013e565b606090565b602081830312610113578051906001600160401b038211610113570181601f82011215610113578051611fdb816115e1565b92611fe96040519485611431565b81845260208284010111610113576116fb9160208085019101610df7565b9060206116fb928181520190610e2c565b602091815181101561202d575b60051b010190565b612035611f05565b612025565b602b815110611c7f576037015160601c90565b603f815110611c7f57604b015160601c90565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b0380921660248501521660448301526064820152606481526120a381611416565b51925af16120af611f79565b816120e8575b50156120bd57565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b80518015925082156120fd575b5050386120b5565b61211092506020809183010191016117f6565b38806120f5565b60405163a9059cbb60e01b602082019081526001600160a01b039390931660248201526044808201949094529283526000928392908390612159606482611431565b51925af1612165611f79565b8161219d575b501561217357565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b80518015925082156121b2575b50503861216b565b6121c592506020809183010191016117f6565b38806121aa565b60008092918192604051918360208401938085106001600160401b03861117612232575b84604052525af16121ff611f79565b501561220757565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b61223a6113a9565b6121f056fea264697066735822122068859a9f99bcb5f128ea1f0462db5044e0cff662ebcd2b69e8f6f7b2ca5476fa64736f6c634300080f0033

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.