Sepolia Testnet

Contract

0x0e090Cdf42b985F7F05eAf4dD165515E309eDC2c

Overview

ETH Balance

0 ETH

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Mint63357792024-07-18 23:09:004 hrs ago1721344140IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000458031.50066603
Mint63296982024-07-17 21:54:2429 hrs ago1721253264IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000458121.50089025
Mint63296922024-07-17 21:53:0029 hrs ago1721253180IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000458231.50121363
Mint63237392024-07-16 22:25:242 days ago1721168724IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000704912.30979175
Mint63142362024-07-15 9:33:363 days ago1721036016IN
0x0e090Cdf...E309eDC2c
0.01251255 ETH0.0073167623.6696716
Mint63142262024-07-15 9:31:363 days ago1721035896IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.0081569125.29220147
Ignite63111982024-07-14 21:38:484 days ago1720993128IN
0x0e090Cdf...E309eDC2c
0 ETH0.000533772.18876121
Mint63111712024-07-14 21:32:124 days ago1720992732IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000859492.66723164
Mint62930012024-07-12 0:38:007 days ago1720744680IN
0x0e090Cdf...E309eDC2c
0.062067 ETH0.002778578.51953225
Ignite62929692024-07-12 0:31:007 days ago1720744260IN
0x0e090Cdf...E309eDC2c
0 ETH0.002025648.12231941
Mint62901192024-07-11 14:05:247 days ago1720706724IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.0070883721.98552693
Mint62794972024-07-09 23:15:489 days ago1720566948IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.001503864.66347306
Mint62786352024-07-09 20:04:489 days ago1720555488IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.000781812.56021301
Mint62770872024-07-09 14:27:489 days ago1720535268IN
0x0e090Cdf...E309eDC2c
0.0227964 ETH0.0114590437.08740323
Lock62758342024-07-09 9:53:369 days ago1720518816IN
0x0e090Cdf...E309eDC2c
0 ETH0.0026591222.89193743
Ignite62757702024-07-09 9:40:249 days ago1720518024IN
0x0e090Cdf...E309eDC2c
0 ETH0.0048361920.31058432
Ignite62733382024-07-09 0:44:0010 days ago1720485840IN
0x0e090Cdf...E309eDC2c
0 ETH0.001016434.16943075
Free62733152024-07-09 0:39:1210 days ago1720485552IN
0x0e090Cdf...E309eDC2c
0 ETH0.000519614.5278497
Lock62733092024-07-09 0:37:4810 days ago1720485468IN
0x0e090Cdf...E309eDC2c
0 ETH0.000542414.67538775
Mint62732492024-07-09 0:24:1210 days ago1720484652IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.001324944.34219521
Mint62732202024-07-09 0:18:0010 days ago1720484280IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.00170045.27659523
Mint62731912024-07-09 0:11:2410 days ago1720483884IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.002487997.60181601
Mint62729952024-07-08 23:26:3610 days ago1720481196IN
0x0e090Cdf...E309eDC2c
0.01201199 ETH0.001719645.25120158
Free62721242024-07-08 20:11:0010 days ago1720469460IN
0x0e090Cdf...E309eDC2c
0 ETH0.0012413110.83026372
Mint62719972024-07-08 19:43:1210 days ago1720467792IN
0x0e090Cdf...E309eDC2c
0.022025 ETH0.002278386.98341667
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
63357792024-07-18 23:09:004 hrs ago1721344140
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63357792024-07-18 23:09:004 hrs ago1721344140
0x0e090Cdf...E309eDC2c
0.012 ETH
63296982024-07-17 21:54:2429 hrs ago1721253264
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63296982024-07-17 21:54:2429 hrs ago1721253264
0x0e090Cdf...E309eDC2c
0.012 ETH
63296922024-07-17 21:53:0029 hrs ago1721253180
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63296922024-07-17 21:53:0029 hrs ago1721253180
0x0e090Cdf...E309eDC2c
0.012 ETH
63237392024-07-16 22:25:242 days ago1721168724
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63237392024-07-16 22:25:242 days ago1721168724
0x0e090Cdf...E309eDC2c
0.012 ETH
63142362024-07-15 9:33:363 days ago1721036016
0x0e090Cdf...E309eDC2c
0.0000125 ETH
63142362024-07-15 9:33:363 days ago1721036016
0x0e090Cdf...E309eDC2c
0.00050004 ETH
63142362024-07-15 9:33:363 days ago1721036016
0x0e090Cdf...E309eDC2c
0.012 ETH
63142262024-07-15 9:31:363 days ago1721035896
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63142262024-07-15 9:31:363 days ago1721035896
0x0e090Cdf...E309eDC2c
0.012 ETH
63111982024-07-14 21:38:484 days ago1720993128
0x0e090Cdf...E309eDC2c
0.012 ETH
63111982024-07-14 21:38:484 days ago1720993128
0x0e090Cdf...E309eDC2c
0.012 ETH
63111982024-07-14 21:38:484 days ago1720993128
0x0e090Cdf...E309eDC2c
0.012 ETH
63111982024-07-14 21:38:484 days ago1720993128
0x0e090Cdf...E309eDC2c
0.012 ETH
63111712024-07-14 21:32:124 days ago1720992732
0x0e090Cdf...E309eDC2c
0.00001199 ETH
63111712024-07-14 21:32:124 days ago1720992732
0x0e090Cdf...E309eDC2c
0.012 ETH
62930012024-07-12 0:38:007 days ago1720744680
0x0e090Cdf...E309eDC2c
0.000062 ETH
62930012024-07-12 0:38:007 days ago1720744680
0x0e090Cdf...E309eDC2c
0.050005 ETH
62930012024-07-12 0:38:007 days ago1720744680
0x0e090Cdf...E309eDC2c
0.012 ETH
62929692024-07-12 0:31:007 days ago1720744260
0x0e090Cdf...E309eDC2c
0.012 ETH
62929692024-07-12 0:31:007 days ago1720744260
0x0e090Cdf...E309eDC2c
0.012 ETH
62929692024-07-12 0:31:007 days ago1720744260
0x0e090Cdf...E309eDC2c
0.012 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
NonfungiblePositionManager

Compiler Version
v0.8.15+commit.e14f2714

Optimization Enabled:
Yes with 200 runs

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

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

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

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

import {PeripheryImmutableState} from "./base/PeripheryImmutableState.sol";
import {PositionManagement} from "./base/PositionManagement.sol";
import {PositionState} from "./base/PositionState.sol";
import {PoolAddress} from "./libraries/PoolAddress.sol";
import {PositionAmounts} from "./libraries/PositionAmounts.sol";

import {INonfungibleTokenPositionDescriptor} from "./interfaces/INonfungibleTokenPositionDescriptor.sol";
import {INonfungiblePositionManager} from "./interfaces/INonfungiblePositionManager.sol";

/// @title Non-fungible token for Marginal v1 leverage positions
/// @notice Wraps Marginal v1 leverage positions in the ERC721 non-fungible token interface
contract NonfungiblePositionManager is
    INonfungiblePositionManager,
    Multicall,
    ERC721,
    PeripheryImmutableState,
    PositionManagement,
    PositionState,
    PeripheryValidation
{
    struct Position {
        address pool;
        uint96 id;
    }
    mapping(uint256 => Position) private _positions;

    uint256 private _nextId = 1;
    address private immutable _tokenDescriptor;

    modifier onlyApprovedOrOwner(uint256 tokenId) {
        if (!_isApprovedOrOwner(msg.sender, tokenId)) revert Unauthorized();
        _;
    }

    event Mint(
        uint256 indexed tokenId,
        address sender,
        address indexed recipient,
        uint256 positionId,
        uint256 size,
        uint256 debt,
        uint256 margin,
        uint256 fees,
        uint256 rewards
    );
    event Lock(
        uint256 indexed tokenId,
        address indexed sender,
        uint256 marginAfter
    );
    event Free(
        uint256 indexed tokenId,
        address indexed sender,
        address recipient,
        uint256 marginAfter
    );
    event Burn(
        uint256 indexed tokenId,
        address indexed sender,
        address recipient,
        uint256 amountIn,
        uint256 amountOut,
        uint256 rewards
    );
    event Ignite(
        uint256 indexed tokenId,
        address indexed sender,
        address recipient,
        uint256 amountOut,
        uint256 rewards
    );

    error Unauthorized();
    error InvalidPoolKey();

    constructor(
        address _factory,
        address _WETH9,
        address _tokenDescriptor_
    )
        ERC721("Marginal V1 Position Token", "MARGV1-POS")
        PeripheryImmutableState(_factory, _WETH9)
    {
        _tokenDescriptor = _tokenDescriptor_;
    }

    /// @notice Returns the Uniform Resource Identifier (URI) for `tokenId` token
    /// @param tokenId The NFT token id associated with the position
    /// @return The URI for the position with given NFT token id
    function tokenURI(
        uint256 tokenId
    ) public view override(ERC721, IERC721Metadata) returns (string memory) {
        require(_exists(tokenId));
        return
            INonfungibleTokenPositionDescriptor(_tokenDescriptor).tokenURI(
                this,
                tokenId
            );
    }

    /// @inheritdoc INonfungiblePositionManager
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            address pool,
            uint96 positionId,
            bool zeroForOne,
            uint128 size,
            uint128 debt,
            uint128 margin,
            uint128 safeMarginMinimum,
            bool liquidated,
            bool safe,
            uint256 rewards
        )
    {
        Position memory position = _positions[tokenId];
        pool = position.pool;
        positionId = position.id;
        (
            zeroForOne,
            size,
            debt,
            margin,
            safeMarginMinimum,
            liquidated,
            safe,
            rewards
        ) = getPositionSynced(pool, address(this), positionId);
    }

    /// @inheritdoc INonfungiblePositionManager
    function mint(
        MintParams calldata params
    )
        external
        payable
        checkDeadline(params.deadline)
        returns (
            uint256 tokenId,
            uint256 size,
            uint256 debt,
            uint256 margin,
            uint256 fees,
            uint256 rewards
        )
    {
        IMarginalV1Pool pool = getPool(
            PoolAddress.PoolKey({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle
            })
        );

        (uint160 sqrtPriceX96, , uint128 liquidity, , , , , ) = pool.state();
        uint128 liquidityDelta = PositionAmounts.getLiquidityForSize(
            liquidity,
            sqrtPriceX96,
            params.maintenance,
            params.zeroForOne,
            params.sizeDesired
        );

        uint256 positionId;
        (positionId, size, debt, margin, fees, rewards) = open(
            OpenParams({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle,
                recipient: address(this),
                zeroForOne: params.zeroForOne,
                liquidityDelta: liquidityDelta,
                sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0
                    ? (
                        params.zeroForOne
                            ? TickMath.MIN_SQRT_RATIO + 1
                            : TickMath.MAX_SQRT_RATIO - 1
                    )
                    : params.sqrtPriceLimitX96,
                margin: params.margin,
                sizeMinimum: params.sizeMinimum,
                debtMaximum: params.debtMaximum == 0
                    ? type(uint128).max
                    : params.debtMaximum,
                amountInMaximum: params.amountInMaximum == 0
                    ? type(uint256).max
                    : params.amountInMaximum
            })
        );

        // @dev ok to call before set position since _safeMint not used so no callback
        _mint(params.recipient, (tokenId = _nextId++));

        _positions[tokenId] = Position({
            pool: address(pool),
            id: uint96(positionId)
        });

        // refund any excess ETH from escrowed rewards to sender at end of function to avoid re-entrancy with fallback
        refundETH();

        emit Mint(
            tokenId,
            msg.sender,
            params.recipient,
            positionId,
            size,
            debt,
            margin,
            fees,
            rewards
        );
    }

    /// @inheritdoc INonfungiblePositionManager
    function lock(
        LockParams calldata params
    )
        external
        payable
        onlyApprovedOrOwner(params.tokenId)
        checkDeadline(params.deadline)
        returns (uint256 margin)
    {
        Position memory position = _positions[params.tokenId];
        if (
            address(
                getPool(
                    PoolAddress.PoolKey({
                        token0: params.token0,
                        token1: params.token1,
                        maintenance: params.maintenance,
                        oracle: params.oracle
                    })
                )
            ) != position.pool
        ) revert InvalidPoolKey();

        (uint256 margin0, uint256 margin1) = adjust(
            AdjustParams({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle,
                recipient: msg.sender, // rebates to sender if dust leftover
                id: position.id,
                marginDelta: int128(params.marginIn)
            })
        );
        margin = margin0 > 0 ? margin0 : margin1;

        emit Lock(params.tokenId, msg.sender, margin);
    }

    /// @inheritdoc INonfungiblePositionManager
    function free(
        FreeParams calldata params
    )
        external
        onlyApprovedOrOwner(params.tokenId)
        checkDeadline(params.deadline)
        returns (uint256 margin)
    {
        Position memory position = _positions[params.tokenId];
        if (
            address(
                getPool(
                    PoolAddress.PoolKey({
                        token0: params.token0,
                        token1: params.token1,
                        maintenance: params.maintenance,
                        oracle: params.oracle
                    })
                )
            ) != position.pool
        ) revert InvalidPoolKey();

        (uint256 margin0, uint256 margin1) = adjust(
            AdjustParams({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle,
                recipient: params.recipient,
                id: position.id,
                marginDelta: -int128(params.marginOut)
            })
        );
        margin = margin0 > 0 ? margin0 : margin1;

        emit Free(params.tokenId, msg.sender, params.recipient, margin);
    }

    /// @inheritdoc INonfungiblePositionManager
    function burn(
        BurnParams calldata params
    )
        external
        payable
        onlyApprovedOrOwner(params.tokenId)
        checkDeadline(params.deadline)
        returns (uint256 amountIn, uint256 amountOut, uint256 rewards)
    {
        Position memory position = _positions[params.tokenId];
        if (
            address(
                getPool(
                    PoolAddress.PoolKey({
                        token0: params.token0,
                        token1: params.token1,
                        maintenance: params.maintenance,
                        oracle: params.oracle
                    })
                )
            ) != position.pool
        ) revert InvalidPoolKey();

        // @dev delete the position and burn token before settling on pool to avoid re-entrancy view issues
        delete _positions[params.tokenId];
        _burn(params.tokenId);

        (int256 amount0, int256 amount1, uint256 rewards) = settle(
            SettleParams({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle,
                recipient: params.recipient,
                id: position.id
            })
        );
        amountIn = amount0 > 0
            ? uint256(amount0)
            : (amount1 > 0 ? uint256(amount1) : 0);
        amountOut = amount0 < 0
            ? uint256(-amount0)
            : (amount1 < 0 ? uint256(-amount1) : 0);

        emit Burn(
            params.tokenId,
            msg.sender,
            params.recipient,
            amountIn,
            amountOut,
            rewards
        );
    }

    /// @inheritdoc INonfungiblePositionManager
    function ignite(
        IgniteParams calldata params
    )
        external
        onlyApprovedOrOwner(params.tokenId)
        checkDeadline(params.deadline)
        returns (uint256 amountOut, uint256 rewards)
    {
        Position memory position = _positions[params.tokenId];
        if (
            address(
                getPool(
                    PoolAddress.PoolKey({
                        token0: params.token0,
                        token1: params.token1,
                        maintenance: params.maintenance,
                        oracle: params.oracle
                    })
                )
            ) != position.pool
        ) revert InvalidPoolKey();

        // @dev delete the position and burn token before settling on pool to avoid re-entrancy view issues
        delete _positions[params.tokenId];
        _burn(params.tokenId);

        (amountOut, rewards) = flash(
            FlashParams({
                token0: params.token0,
                token1: params.token1,
                maintenance: params.maintenance,
                oracle: params.oracle,
                recipient: params.recipient,
                id: position.id,
                amountOutMinimum: params.amountOutMinimum
            })
        );

        emit Ignite(
            params.tokenId,
            msg.sender,
            params.recipient,
            amountOut,
            rewards
        );
    }
}

File 2 of 54 : 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 3 of 54 : 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 4 of 54 : 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 5 of 54 : 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 6 of 54 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 7 of 54 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

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

pragma solidity ^0.8.0;

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

File 9 of 54 : PositionManagement.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;

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 {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";

import {IMarginalV1AdjustCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1AdjustCallback.sol";
import {IMarginalV1OpenCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1OpenCallback.sol";
import {IMarginalV1SettleCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1SettleCallback.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {Position as PositionLibrary} from "@marginal/v1-core/contracts/libraries/Position.sol";

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

abstract contract PositionManagement is
    IMarginalV1AdjustCallback,
    IMarginalV1OpenCallback,
    IMarginalV1SettleCallback,
    IUniswapV3SwapCallback,
    PeripheryImmutableState,
    PeripheryPayments
{
    struct PositionCallbackData {
        PoolAddress.PoolKey poolKey;
        address payer;
    }

    error SizeLessThanMin(uint256 size);
    error DebtGreaterThanMax(uint256 debt);
    error AmountInGreaterThanMax(uint256 amountIn);
    error AmountOutLessThanMin(uint256 amountOut);
    error RewardsLessThanMin(uint256 rewardsMinimum);

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

    struct OpenParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        bool zeroForOne;
        uint128 liquidityDelta;
        uint160 sqrtPriceLimitX96;
        uint128 margin;
        uint128 sizeMinimum;
        uint128 debtMaximum;
        uint256 amountInMaximum;
    }

    /// @notice Opens a new position on pool
    /// @param params The parameters necessary to open the position on the pool
    /// @return id The position ID stored in the pool
    /// @return size The position size on the pool in the margin token
    /// @return debt The position debt owed to the pool in the non-margin token
    /// @return margin The margin backing the position opened on the pool
    /// @return fees The fees paid in margin token to open the position on the pool
    /// @return rewards The rewards escrowed in opened position available to liquidators when position not safe
    function open(
        OpenParams memory params
    )
        internal
        virtual
        returns (
            uint256 id,
            uint256 size,
            uint256 debt,
            uint256 margin,
            uint256 fees,
            uint256 rewards
        )
    {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        rewards = PositionLibrary.liquidationRewards(
            block.basefee,
            PoolConstants.blockBaseFeeMin,
            PoolConstants.gasLiquidate,
            PoolConstants.rewardPremium
        ); // deposited for liquidation reward escrow
        // @dev use address(this).balance and not msg.value to avoid issues with multicall
        if (address(this).balance < rewards) revert RewardsLessThanMin(rewards); // only send the min required

        uint256 amount0;
        uint256 amount1;
        (id, size, debt, amount0, amount1) = pool.open{value: rewards}(
            params.recipient,
            params.zeroForOne,
            params.liquidityDelta,
            params.sqrtPriceLimitX96,
            params.margin,
            abi.encode(
                PositionCallbackData({poolKey: poolKey, payer: msg.sender})
            )
        );
        if (size < uint256(params.sizeMinimum)) revert SizeLessThanMin(size);
        if (debt > uint256(params.debtMaximum)) revert DebtGreaterThanMax(debt);

        uint256 amountIn = (!params.zeroForOne) ? amount0 : amount1; // in margin token
        if (amountIn > params.amountInMaximum)
            revert AmountInGreaterThanMax(amountIn);

        margin = params.margin;
        fees = amountIn - margin;
    }

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

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

    struct AdjustParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint96 id;
        int128 marginDelta;
    }

    /// @notice Adjusts margin backing position on pool
    /// @param params The parameters necessary to adjust the position on the pool
    /// @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(
        AdjustParams memory params
    ) internal virtual returns (uint256 margin0, uint256 margin1) {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        // manager receives flashed out margin and must handle delta in callback
        (margin0, margin1) = pool.adjust(
            address(this),
            params.id,
            params.marginDelta,
            abi.encode(
                PositionCallbackData({poolKey: poolKey, payer: msg.sender})
            )
        );

        // sweep any freed margin remaining in contract
        address tokenOut = margin0 > 0 ? params.token0 : params.token1;
        uint256 amountOut = balance(tokenOut);
        if (amountOut > 0)
            pay(tokenOut, address(this), params.recipient, amountOut);
    }

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

        if (amount0Owed > 0) {
            uint256 balance0 = balance(decoded.poolKey.token0);
            if (amount0Owed > balance0)
                pay(
                    decoded.poolKey.token0,
                    decoded.payer,
                    address(this),
                    amount0Owed - balance0
                );
            pay(decoded.poolKey.token0, address(this), msg.sender, amount0Owed);
        }
        if (amount1Owed > 0) {
            uint256 balance1 = balance(decoded.poolKey.token1);
            if (amount1Owed > balance1)
                pay(
                    decoded.poolKey.token1,
                    decoded.payer,
                    address(this),
                    amount1Owed - balance1
                );
            pay(decoded.poolKey.token1, address(this), msg.sender, amount1Owed);
        }
    }

    struct SettleParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint96 id;
    }

    /// @notice Settles a position on pool via external payer of debt
    /// @dev Beware of re-entrancy issues given implicit ETH transfer at end of function
    /// @param params The parameters necessary to settle the position on the pool
    /// @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 `params.recipient`
    function settle(
        SettleParams memory params
    )
        internal
        virtual
        returns (int256 amount0, int256 amount1, uint256 rewards)
    {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        (amount0, amount1, rewards) = pool.settle(
            params.recipient,
            params.id,
            abi.encode(
                PositionCallbackData({poolKey: poolKey, payer: msg.sender})
            )
        );

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

    struct FlashParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        address recipient;
        uint96 id;
        uint256 amountOutMinimum;
    }

    /// @notice Settles a position by repaying debt with portion of size swapped through spot
    /// @dev Beware of re-entrancy issues given implicit ETH transfer at end of function
    /// @param params The parameters necessary to flash settle the position on the pool
    /// @return amountOut The amount of margin token received from pool less debts repaid via swapping on spot
    /// @return rewards The amount of escrowed native (gas) token released by pool after flash settling the position
    function flash(
        FlashParams memory params
    ) internal virtual returns (uint256 amountOut, uint256 rewards) {
        PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
            token0: params.token0,
            token1: params.token1,
            maintenance: params.maintenance,
            oracle: params.oracle
        });
        IMarginalV1Pool pool = getPool(poolKey);

        address payer = address(this);
        int256 amount0;
        int256 amount1;
        (amount0, amount1, rewards) = pool.settle(
            payer,
            params.id,
            abi.encode(PositionCallbackData({poolKey: poolKey, payer: payer}))
        );

        address tokenOut = amount0 < 0 ? params.token0 : params.token1;
        amountOut = balance(tokenOut);

        if (amountOut < params.amountOutMinimum)
            revert AmountOutLessThanMin(amountOut);
        if (amountOut > 0) pay(tokenOut, payer, params.recipient, amountOut);

        // any remaining WETH in contract from liquidation rewards return as ETH
        unwrapWETH9(0, params.recipient);
    }

    /// @inheritdoc IMarginalV1SettleCallback
    function marginalV1SettleCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external virtual {
        if (amount0Delta <= 0 && amount1Delta <= 0) revert SizeLessThanMin(0); // can't settle position with zero size; Q: ok? necessary?
        PositionCallbackData memory decoded = abi.decode(
            data,
            (PositionCallbackData)
        );
        CallbackValidation.verifyCallback(factory, decoded.poolKey);

        if (decoded.payer == address(this)) {
            // wrap ETH balance from liquidation rewards returned for possible use in settlement
            wrapETH();

            // swap portion of flashed size through spot to repay debt
            bool zeroForOne = amount1Delta > 0; // owe 1 to marginal if true
            IUniswapV3Pool(decoded.poolKey.oracle).swap(
                msg.sender,
                zeroForOne,
                (zeroForOne ? -amount1Delta : -amount0Delta),
                (
                    zeroForOne
                        ? TickMath.MIN_SQRT_RATIO + 1
                        : TickMath.MAX_SQRT_RATIO - 1
                ),
                abi.encode(decoded.poolKey)
            );
        } else {
            // simply pay debt from external payer
            if (amount0Delta > 0)
                pay(
                    decoded.poolKey.token0,
                    decoded.payer,
                    msg.sender,
                    uint256(amount0Delta)
                );
            if (amount1Delta > 0)
                pay(
                    decoded.poolKey.token1,
                    decoded.payer,
                    msg.sender,
                    uint256(amount1Delta)
                );
        }
    }

    /// @inheritdoc IUniswapV3SwapCallback
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external virtual {
        require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
        PoolAddress.PoolKey memory poolKey = abi.decode(
            data,
            (PoolAddress.PoolKey)
        );
        CallbackValidation.verifyUniswapV3Callback(factory, poolKey);

        if (amount0Delta > 0)
            pay(
                poolKey.token0,
                address(this),
                msg.sender,
                uint256(amount0Delta)
            );
        if (amount1Delta > 0)
            pay(
                poolKey.token1,
                address(this),
                msg.sender,
                uint256(amount1Delta)
            );
    }
}

File 10 of 54 : IMarginalV1AdjustCallback.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

/// @title The interface for the Marginal v1 adjust callback
/// @notice Callbacks called by Marginal v1 pools when adjusting the margin backing a position
/// @dev Any contract that calls IMarginalV1Pool#adjust must implement this interface
interface IMarginalV1AdjustCallback {
    /// @notice Called to `msg.sender` after adjusting the margin backing a position via IMarginalV1Pool#adjust
    /// @dev In the implementation you must pay the pool tokens owed to adjust the margin backing a position. The tokens owed
    /// is the new position margin, as the original margin is flashed out to `recipient` in the IMarginalV1Pool#adjust call.
    /// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
    /// @param amount0Owed The amount of token0 that must be payed to pool to successfully adjust the margin backing a position
    /// @param amount1Owed The amount of token1 that must be payed to pool to successfully adjust the margin backing a position
    /// @param data Any data passed through by the caller via the IMarginalV1Pool#adjust call
    function marginalV1AdjustCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;
}

File 11 of 54 : PoolConstants.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

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

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

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

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

File 12 of 54 : IMarginalV1OpenCallback.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

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

File 13 of 54 : 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 14 of 54 : 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 15 of 54 : 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 16 of 54 : 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 17 of 54 : 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 18 of 54 : 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 19 of 54 : 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 20 of 54 : 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 54 : 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 22 of 54 : 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 23 of 54 : IMarginalV1SettleCallback.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;

/// @title The interface for the Marginal v1 settle callback
/// @notice Callbacks called by Marginal v1 pools when settling the debt owed by a position to the pool
/// @dev Any contract that calls IMarginalV1Pool#settle must implement this interface
interface IMarginalV1SettleCallback {
    /// @notice Called to `msg.sender` after settling a position via IMarginalV1Pool#settle
    /// @dev In the implementation you must pay the pool tokens owed to settle the debt owed by a position to the pool.
    /// Position size and margin are flashed out to `recipient` in the IMarginalV1Pool#settle call prior to enable debt repayment via swaps.
    /// 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#open would have reverted otherwise.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of position settlement. 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 position settlement. 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#settle call
    function marginalV1SettleCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 24 of 54 : 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 25 of 54 : 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 26 of 54 : 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 27 of 54 : 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 28 of 54 : 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 29 of 54 : 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 30 of 54 : 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 31 of 54 : 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 32 of 54 : 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 33 of 54 : Position.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

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

import {FixedPoint64} from "./FixedPoint64.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {FixedPoint192} from "./FixedPoint192.sol";

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

/// @title Position library
/// @notice Facilitates calculations, updates, and retrieval of leverage position info
/// @dev Positions are represented in (x, y) space
library Position {
    using SafeCast for uint256;

    // info stored for each trader's leverage position
    struct Info {
        // size of position in token1 if zeroForOne = true or token0 if zeroForOne = false
        uint128 size;
        // debt owed by trader at settlement if zeroForOne = true, otherwise used for internal accounting only
        uint128 debt0;
        // debt owed by trader at settlement if zeroForOne = false, otherwise used for internal accounting only
        uint128 debt1;
        // insurance balances set aside by LPs to prevent liquidity shortfall in case of late liquidation
        uint128 insurance0;
        uint128 insurance1;
        // whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
        bool zeroForOne;
        // whether the position has been liquidated
        bool liquidated;
        // tick before position was opened, used in maintenance margin requirements
        int24 tick;
        // timestamp when position was last synced for funding payments
        uint32 blockTimestamp;
        // delta between oracle and pool tick cumulatives at last funding sync (bar{a}_t - a_t)
        int56 tickCumulativeDelta;
        // margin backing position in token1 if zeroForOne = true or token0 if zeroForOne = false
        uint128 margin;
        // liquidity locked by LPs to collateralize the position. liability owed to pool
        uint128 liquidityLocked;
        // liquidation rewards escrowed with position in the native (gas) token to incentivize liquidations
        uint256 rewards;
    }

    /// @notice Gets a position from positions mapping
    /// @param positions The pool mapping that stores the leverage positions
    /// @param owner The owner of the position
    /// @param id The ID of the position
    /// @return The position info associated with the (owner, ID) key
    function get(
        mapping(bytes32 => Info) storage positions,
        address owner,
        uint96 id
    ) internal view returns (Info memory) {
        return positions[keccak256(abi.encodePacked(owner, id))];
    }

    /// @notice Stores the given position in positions mapping
    /// @dev Used to create a new position or to update existing positions
    /// @param positions The pool mapping that stores the leverage positions
    /// @param owner The owner of the position
    /// @param id The ID of the position
    /// @param position The position information to store
    function set(
        mapping(bytes32 => Info) storage positions,
        address owner,
        uint96 id,
        Info memory position
    ) internal {
        positions[keccak256(abi.encodePacked(owner, id))] = position;
    }

    /// @notice Realizes funding payments via updates to position debt amounts
    /// @param position The position to sync
    /// @param blockTimestampLast The latest `block.timestamp` to sync to
    /// @param tickCumulativeLast The `tickCumulative` from the pool at `blockTimestampLast`
    /// @param oracleTickCumulativeLast The `tickCumulative` from the oracle at `blockTimestampLast`
    /// @param tickCumulativeRateMax The maximum rate of change in tick cumulative between the oracle and pool `tickCumulative` values
    /// @param fundingPeriod The pool funding period to benchmark funding payments to
    /// @return The synced position
    function sync(
        Info memory position,
        uint32 blockTimestampLast,
        int56 tickCumulativeLast,
        int56 oracleTickCumulativeLast,
        uint24 tickCumulativeRateMax,
        uint32 fundingPeriod
    ) internal pure returns (Info memory) {
        // early exit if nothing to update
        if (blockTimestampLast == position.blockTimestamp) return position;

        // oracle tick - marginal tick (bar{a}_t - a_t)
        int56 tickCumulativeDeltaLast = OracleLibrary.oracleTickCumulativeDelta(
            tickCumulativeLast,
            oracleTickCumulativeLast
        );
        (uint128 debt0, uint128 debt1) = debtsAfterFunding(
            position,
            blockTimestampLast,
            tickCumulativeDeltaLast,
            tickCumulativeRateMax,
            fundingPeriod
        );

        position.debt0 = debt0;
        position.debt1 = debt1;
        position.blockTimestamp = blockTimestampLast;
        position.tickCumulativeDelta = tickCumulativeDeltaLast;
        return position;
    }

    /// @notice Liquidates an existing position
    /// @param position The position to liquidate
    /// @return positionAfter The liquidated position info
    function liquidate(
        Info memory position
    ) internal pure returns (Info memory positionAfter) {
        positionAfter.zeroForOne = position.zeroForOne;
        positionAfter.liquidated = true;
        positionAfter.tick = position.tick;
        positionAfter.blockTimestamp = position.blockTimestamp;
        positionAfter.tickCumulativeDelta = position.tickCumulativeDelta;
    }

    /// @notice Settles existing position
    /// @param position The position to settle
    /// @return positionAfter The settled position info
    function settle(
        Info memory position
    ) internal pure returns (Info memory positionAfter) {
        positionAfter.zeroForOne = position.zeroForOne;
        positionAfter.liquidated = position.liquidated;
        positionAfter.tick = position.tick;
        positionAfter.blockTimestamp = position.blockTimestamp;
        positionAfter.tickCumulativeDelta = position.tickCumulativeDelta;
    }

    /// @notice Assembles a new position from pool state
    /// @dev zeroForOne = true means short position (long token1, short token0)
    /// @param liquidity The pool liquidity before opening the position
    /// @param sqrtPriceX96 The pool sqrt price before opening the position
    /// @param sqrtPriceX96Next The pool sqrt price after opening the position
    /// @param liquidityDelta The delta in pool liquidity used to collateralize the position
    /// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @param tick The pool tick before opening the position
    /// @param blockTimestampStart The timestamp at which the pool state was last synced before opening the position
    /// @param tickCumulativeStart The tick cumulative value from the pool at `blockTimestampStart`
    /// @param oracleTickCumulativeStart The tick cumulative value from the oracle at `blockTimestampStart`
    /// @return position The assembled position info
    function assemble(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint160 sqrtPriceX96Next,
        uint128 liquidityDelta,
        bool zeroForOne,
        int24 tick,
        uint32 blockTimestampStart,
        int56 tickCumulativeStart,
        int56 oracleTickCumulativeStart
    ) internal pure returns (Info memory position) {
        position.zeroForOne = zeroForOne;
        position.tick = tick;
        position.blockTimestamp = blockTimestampStart;
        position.tickCumulativeDelta =
            oracleTickCumulativeStart -
            tickCumulativeStart;
        position.liquidityLocked = liquidityDelta;

        position.size = size(
            liquidity,
            sqrtPriceX96,
            sqrtPriceX96Next,
            zeroForOne
        );
        (position.insurance0, position.insurance1) = insurances(
            liquidity,
            sqrtPriceX96,
            sqrtPriceX96Next,
            liquidityDelta,
            zeroForOne
        );
        (position.debt0, position.debt1) = debts(
            sqrtPriceX96Next,
            liquidityDelta,
            position.insurance0,
            position.insurance1
        );
    }

    /// @notice Size of position in (x, y) amounts
    /// @dev Size amount in token1 if zeroForOne = true, or in token0 if zeroForOne = false
    /// @param liquidity The pool liquidity before opening the position
    /// @param sqrtPriceX96 The pool sqrt price before opening the position
    /// @param sqrtPriceX96Next The pool sqrt price after opening the position
    /// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @return The position size
    function size(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint160 sqrtPriceX96Next,
        bool zeroForOne
    ) internal pure returns (uint128) {
        if (!zeroForOne) {
            // L / sqrt(P) - L / sqrt(P')
            return
                ((uint256(liquidity) << FixedPoint96.RESOLUTION) /
                    sqrtPriceX96 -
                    (uint256(liquidity) << FixedPoint96.RESOLUTION) /
                    sqrtPriceX96Next).toUint128();
        } else {
            // L * sqrt(P) - L * sqrt(P')
            return
                (
                    Math.mulDiv(
                        liquidity,
                        sqrtPriceX96 - sqrtPriceX96Next,
                        FixedPoint96.Q96
                    )
                ).toUint128();
        }
    }

    /// @notice Insurance balances to back position in (x, y) amounts
    /// @param liquidity The pool liquidity before opening the position
    /// @param sqrtPriceX96 The pool sqrt price before opening the position
    /// @param sqrtPriceX96Next The pool sqrt price after opening the position
    /// @param liquidityDelta The delta in pool liquidity used to collateralize the position
    /// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @return insurance0 The insurance reserves in token0 needed to prevent liquidity shortfall for late liquidations
    /// @return insurance1 The insurance reserves in token1 needed to prevent liquidity shortfall for late liquidations
    function insurances(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint160 sqrtPriceX96Next,
        uint128 liquidityDelta,
        bool zeroForOne
    ) internal pure returns (uint128 insurance0, uint128 insurance1) {
        uint256 prod = !zeroForOne
            ? Math.mulDiv(
                liquidity - liquidityDelta,
                sqrtPriceX96Next,
                sqrtPriceX96
            ) // iy / y = 1 - sqrt(P'/P) * (1 - del L / L)
            : Math.mulDiv(
                liquidity - liquidityDelta,
                sqrtPriceX96,
                sqrtPriceX96Next
            ); // iy / y = 1 - sqrt(P/P') * (1 - del L / L)

        insurance0 = (((uint256(liquidity) - prod) << FixedPoint96.RESOLUTION) /
            sqrtPriceX96).toUint128();
        insurance1 = (
            Math.mulDiv(
                uint256(liquidity) - prod,
                sqrtPriceX96,
                FixedPoint96.Q96
            )
        ).toUint128();
    }

    /// @notice Debts owed by position in (x, y) amounts
    /// @dev Uses invariant (insurance0 + debt0) * (insurance1 + debt1) = liquidityDelta * sqrtPriceNext
    /// @param sqrtPriceX96Next The pool sqrt price after opening the position
    /// @param liquidityDelta The delta in pool liquidity used to collateralize the position
    /// @param insurance0 The position insurance reserves in token0
    /// @param insurance1 The position insurance reserves in token1
    /// @return debt0 The debt in token0 the position owes to the pool
    /// @return debt1 The debt in token1 the position owes to the pool
    function debts(
        uint160 sqrtPriceX96Next,
        uint128 liquidityDelta,
        uint128 insurance0,
        uint128 insurance1
    ) internal pure returns (uint128 debt0, uint128 debt1) {
        // ix + dx = del L / sqrt(P'); iy + dy = del L * sqrt(P')
        debt0 = ((uint256(liquidityDelta) << FixedPoint96.RESOLUTION) /
            sqrtPriceX96Next -
            uint256(insurance0)).toUint128();
        debt1 = (Math.mulDiv(
            liquidityDelta,
            sqrtPriceX96Next,
            FixedPoint96.Q96
        ) - uint256(insurance1)).toUint128();
    }

    /// @notice Fees owed when opening the position in (x, y) amounts
    /// @dev Fees taken proportional to size
    /// @param size The position size
    /// @param fee The fee rate charged on position size
    /// @return The amount of fees charged to open the position
    function fees(uint128 size, uint24 fee) internal pure returns (uint256) {
        return (uint256(size) * fee) / 1e6;
    }

    /// @notice Liquidation rewards required to set aside for liquidator in native (gas) token amount
    /// @dev Returned on settle to position owner or used as incentive for liquidator to liquidate position when unsafe
    /// @param blockBaseFee Current block base fee
    /// @param blockBaseFeeMin Minimum block base fee to use in calculating cost to execute call to liquidate
    /// @param gas Estimated gas required to execute call to liquidate
    /// @param premium Liquidation premium to incentivize potential liquidators with
    /// @return The liquidation rewards to set aside for liquidator if position unsafe
    function liquidationRewards(
        uint256 blockBaseFee,
        uint256 blockBaseFeeMin,
        uint256 gas,
        uint24 premium
    ) internal pure returns (uint256) {
        uint256 baseFee = (
            blockBaseFee > blockBaseFeeMin ? blockBaseFee : blockBaseFeeMin
        );
        // need base fee of ~4e62 for possible overflow with gas limit of 30e6
        return (baseFee * gas * uint256(premium)) / 1e6;
    }

    /// @notice Absolute minimum margin amount required to be held in position
    /// @dev Uses `position.tick` prior to position open (alongside insurance balances) to ensure repayment to pool of at least liquidityDelta liability if ignore funding
    /// @param position The position to check minimum margin amounts for
    /// @param maintenance The minimum maintenance margin requirement for the pool
    /// @return The minimum amount of margin the position must hold
    function marginMinimum(
        Info memory position,
        uint24 maintenance
    ) internal pure returns (uint128) {
        uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(position.tick); // price before open
        if (!position.zeroForOne) {
            // cx >= (1+M) * dy / P - sx
            uint256 debt1Adjusted = (uint256(position.debt1) *
                (1e6 + uint256(maintenance))) / 1e6;

            uint256 prod = sqrtPriceX96 <= type(uint128).max
                ? Math.mulDiv(
                    debt1Adjusted,
                    FixedPoint192.Q192,
                    uint256(sqrtPriceX96) * uint256(sqrtPriceX96)
                )
                : Math.mulDiv(
                    debt1Adjusted,
                    FixedPoint128.Q128,
                    Math.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint64.Q64)
                );
            return
                prod > uint256(position.size)
                    ? (prod - uint256(position.size)).toUint128()
                    : 0; // check necessary due to funding
        } else {
            // cy >= (1+M) * dx * P - sy
            uint256 debt0Adjusted = (uint256(position.debt0) *
                (1e6 + uint256(maintenance))) / 1e6;

            uint256 prod = sqrtPriceX96 <= type(uint128).max
                ? Math.mulDiv(
                    debt0Adjusted,
                    uint256(sqrtPriceX96) * uint256(sqrtPriceX96),
                    FixedPoint192.Q192
                )
                : Math.mulDiv(
                    debt0Adjusted,
                    Math.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint64.Q64),
                    FixedPoint128.Q128
                );
            return
                prod > uint256(position.size)
                    ? (prod - uint256(position.size)).toUint128()
                    : 0; // check necessary due to funding
        }
    }

    /// @notice Amounts (x, y) of pool reserves locked in position
    /// @dev Includes margin in the event position were to be liquidated
    /// @param position The position
    /// @return amount0 The amount of token0 set aside for the position
    /// @return amount1 The amount of token1 set aside for the position
    function amountsLocked(
        Info memory position
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (!position.zeroForOne) {
            amount0 =
                uint256(position.size) +
                uint256(position.margin) +
                uint256(position.debt0) +
                uint256(position.insurance0);
            amount1 = position.insurance1;
        } else {
            amount0 = position.insurance0;
            amount1 =
                uint256(position.size) +
                uint256(position.margin) +
                uint256(position.debt1) +
                uint256(position.insurance1);
        }
    }

    /// @notice Debt adjusted for funding
    /// @dev Ref @with-backed/papr/src/UniswapOracleFundingRateController.sol#L156
    /// Follows debt0Next = debt0 * (oracleTwap / poolTwap) ** (dt / fundingPeriod) if zeroForOne = true
    //  or debt1Next = debt1 * (poolTwap / oracleTwap) ** (dt / fundingPeriod) if zeroForOne = false
    /// @param position The position to update debts for funding
    /// @param blockTimestampLast The block timestamp at the last pool state sync
    /// @param tickCumulativeDeltaLast The delta in oracle tick cumulative minus pool tick cumulative values at `blockTimestampLast`
    /// @param tickCumulativeRateMax The maximum rate of change in tick cumulative between the oracle and pool `tickCumulative` values
    /// @param fundingPeriod The pool funding period to benchmark funding payments to
    /// @return debt0 The position debt in token0 after funding
    /// @return debt1 The position debt in token1 after funding
    function debtsAfterFunding(
        Info memory position,
        uint32 blockTimestampLast,
        int56 tickCumulativeDeltaLast,
        uint24 tickCumulativeRateMax,
        uint32 fundingPeriod
    ) internal pure returns (uint128 debt0, uint128 debt1) {
        int56 deltaMax;
        unchecked {
            deltaMax =
                int56(uint56(tickCumulativeRateMax)) *
                int56(uint56(blockTimestampLast - position.blockTimestamp));
        }
        if (!position.zeroForOne) {
            // debt1Now = debt1Start * (P / bar{P}) ** (now - start) / fundingPeriod
            // delta = (a_t - bar{a}_t) - (a_0 - bar{a}_0), clamped by funding rate bounds
            int56 delta = OracleLibrary.oracleTickCumulativeDelta(
                tickCumulativeDeltaLast,
                position.tickCumulativeDelta
            );
            if (delta > deltaMax) delta = deltaMax;
            else if (delta < -deltaMax) delta = -deltaMax;

            // @dev ok as position is unsafe well before arithmeticMeanTick reaches min/max tick given fundingPeriod, tickCumulativeRateMax values
            uint160 numeratorX96 = OracleLibrary.oracleSqrtPriceX96(
                delta,
                fundingPeriod / 2 // div by 2 given sqrt price result
            );
            debt0 = position.debt0;
            debt1 = Math
                .mulDiv(position.debt1, numeratorX96, FixedPoint96.Q96)
                .toUint128();
        } else {
            // debt0Now = debt0Start * (bar{P} / P) ** (now - start) / fundingPeriod
            // delta = (bar{a}_t - a_t) - (bar{a}_0 - a_0), clamped by funding rate bounds
            int56 delta = OracleLibrary.oracleTickCumulativeDelta(
                position.tickCumulativeDelta,
                tickCumulativeDeltaLast
            );
            if (delta > deltaMax) delta = deltaMax;
            else if (delta < -deltaMax) delta = -deltaMax;

            // @dev ok as position is unsafe well before arithmeticMeanTick reaches min/max tick given fundingPeriod, tickCumulativeRateMax values
            uint160 numeratorX96 = OracleLibrary.oracleSqrtPriceX96(
                delta,
                fundingPeriod / 2 // div by 2 given sqrt price result
            );
            debt0 = Math
                .mulDiv(position.debt0, numeratorX96, FixedPoint96.Q96)
                .toUint128();
            debt1 = position.debt1;
        }
    }

    /// @notice Whether the position is safe from liquidation
    /// @dev If not safe, position can be liquidated
    /// Considered safe if (`position.margin` + `position.size`) / oracleTwap >= (1 + `maintenance`) * `position.debt0` when position.zeroForOne = true
    /// or (`position.margin` + `position.size`) * oracleTwap >= (1 + `maintenance`) * `position.debt1` when position.zeroForOne = false
    /// @param position The position to check safety of
    /// @param sqrtPriceX96 The oracle time weighted average sqrt price
    /// @param maintenance The minimum maintenance margin requirement for the pool
    /// @return true if safe and false if not safe
    function safe(
        Info memory position,
        uint160 sqrtPriceX96,
        uint24 maintenance
    ) internal pure returns (bool) {
        if (!position.zeroForOne) {
            uint256 debt1Adjusted = (uint256(position.debt1) *
                (1e6 + uint256(maintenance))) / 1e6;
            uint256 liquidityCollateral = Math.mulDiv(
                uint256(position.margin) + uint256(position.size),
                sqrtPriceX96,
                FixedPoint96.Q96
            );
            uint256 liquidityDebt = (debt1Adjusted << FixedPoint96.RESOLUTION) /
                sqrtPriceX96;
            return liquidityCollateral >= liquidityDebt;
        } else {
            uint256 debt0Adjusted = (uint256(position.debt0) *
                (1e6 + uint256(maintenance))) / 1e6;
            uint256 liquidityCollateral = ((uint256(position.margin) +
                uint256(position.size)) << FixedPoint96.RESOLUTION) /
                sqrtPriceX96;
            uint256 liquidityDebt = Math.mulDiv(
                debt0Adjusted,
                sqrtPriceX96,
                FixedPoint96.Q96
            );
            return liquidityCollateral >= liquidityDebt;
        }
    }
}

File 34 of 54 : FixedPoint64.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

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

File 35 of 54 : 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 36 of 54 : 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 37 of 54 : FixedPoint128.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 39 of 54 : FixedPoint192.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;

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

File 40 of 54 : OracleLibrary.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

/// @title Oracle library
/// @notice Enables calculation of the geometric time weighted average price
library OracleLibrary {
    /// @notice Returns the geometric time weighted average sqrtP
    /// @dev Rounds toward zero for both positive and negative tick delta
    /// @param tickCumulativeDelta The delta in tick cumulative over the averaging interval
    /// @param timeDelta The time to average over
    /// @return The geometric time weighted average price
    function oracleSqrtPriceX96(
        int56 tickCumulativeDelta,
        uint32 timeDelta
    ) internal pure returns (uint160) {
        // @uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol#L35
        int24 arithmeticMeanTick = int24(
            tickCumulativeDelta / int56(uint56(timeDelta))
        );
        return TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
    }

    /// @notice Returns the tick cumulative delta over an interval
    /// @dev Allows for tick cumulative overflow
    /// @param tickCumulativeStart The tick cumulative value at the start of the interval
    /// @param tickCumulativeEnd The tick cumulative value at the end of the interval
    /// @return The delta in tick cumulative over the averaging interval
    function oracleTickCumulativeDelta(
        int56 tickCumulativeStart,
        int56 tickCumulativeEnd
    ) internal pure returns (int56) {
        unchecked {
            return tickCumulativeEnd - tickCumulativeStart;
        }
    }
}

File 41 of 54 : ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}

File 42 of 54 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 43 of 54 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 44 of 54 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 45 of 54 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

File 46 of 54 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

File 47 of 54 : INonfungibleTokenPositionDescriptor.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

/// @title Non-fungible token descriptor for Marginal v1 leverage positions
/// @notice Describes position NFT tokens via URI
interface INonfungibleTokenPositionDescriptor {
    /// @notice Produces the URI describing a particular token ID for a position manager
    /// @dev Note this URI may be a data: URI with the JSON contents directly inlined
    /// @param positionManager The position manager for which to describe the token
    /// @param tokenId The ID of the token for which to produce a description, which may not be valid
    /// @return The URI of the ERC721-compliant metadata
    function tokenURI(
        INonfungiblePositionManager positionManager,
        uint256 tokenId
    ) external view returns (string memory);
}

File 48 of 54 : INonfungiblePositionManager.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;

import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

import {IPeripheryImmutableState} from "./IPeripheryImmutableState.sol";
import {IPeripheryPayments} from "./IPeripheryPayments.sol";

/// @title The interface of the non-fungible token for Marginal v1 leverage positions
/// @notice Wraps Marginal v1 leverage positions in a non-fungible token to allow for transfers
interface INonfungiblePositionManager is IERC721Metadata {
    /// @notice Returns details of an existing position
    /// @param tokenId The NFT token id associated with the position
    /// @dev Do *NOT* use in callback. Vulnerable to re-entrancy view issues.
    /// @return pool The pool address position taken out on
    /// @return positionId The position ID stored in the pool for the associated position
    /// @return zeroForOne Whether position settlement requires debt in of token0 for size + margin out of token1
    /// @return size The position size on the pool in the margin token
    /// @return debt The position debt owed to the pool in the non-margin token
    /// @return margin The margin backing the position on the pool
    /// @return safeMarginMinimum The minimum margin requirements necessary to keep position open on pool while also being safe from liquidation
    /// @return liquidated Whether the position has been liquidated
    /// @return safe Whether the position can be liquidated
    /// @return rewards The reward available to liquidators when position not safe
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            address pool,
            uint96 positionId,
            bool zeroForOne,
            uint128 size,
            uint128 debt,
            uint128 margin,
            uint128 safeMarginMinimum,
            bool liquidated,
            bool safe,
            uint256 rewards
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        bool zeroForOne;
        uint128 sizeDesired;
        uint128 sizeMinimum;
        uint128 debtMaximum;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
        uint128 margin;
        address recipient;
        uint256 deadline;
    }

    /// @notice Mints a new position, opening on pool
    /// @dev If a contract, `msg.sender` must implement a `receive()` function to receive any refunded excess liquidation rewards in the native (gas) token from the manager.
    /// @param params The parameters necessary for the position mint, encoded as `MintParams` in calldata
    /// @return tokenId The NFT token id associated with the minted position
    /// @return size The position size on the pool in the margin token
    /// @return debt The position debt owed to the pool in the non-margin token
    /// @return margin The amount of margin token in used to open the position
    /// @return fees The amount of fees in margin token paid to open the position
    /// @return rewards The amount of liquidation rewards in native (gas) token escrowed in opened position
    function mint(
        MintParams calldata params
    )
        external
        payable
        returns (
            uint256 tokenId,
            uint256 size,
            uint256 debt,
            uint256 margin,
            uint256 fees,
            uint256 rewards
        );

    struct LockParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        uint256 tokenId;
        uint128 marginIn;
        uint256 deadline;
    }

    /// @dev Adds margin to an existing position
    /// @param params The parameters necessary for adding margin to the position, encoded as `LockParams` in calldata
    /// @return margin The margin backing the position after calling lock
    function lock(
        LockParams calldata params
    ) external payable returns (uint256 margin);

    struct FreeParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        uint256 tokenId;
        uint128 marginOut;
        address recipient;
        uint256 deadline;
    }

    /// @notice Removes margin from an existing position
    /// @param params The parameters necessary for removing margin from the position, encoded as `FreeParams` in calldata
    /// @return margin The margin backing the position after calling free
    function free(FreeParams calldata params) external returns (uint256 margin);

    struct BurnParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        uint256 tokenId;
        address recipient;
        uint256 deadline;
    }

    /// @notice Burns an existing position, settling on pool via external payer
    /// @dev If a contract, `msg.sender` must implement a `receive()` function to receive any refunded excess debt payment in the native (gas) token from the manager.
    /// @param params The parameters necessary for settling the position, encoded as `BurnParams` in calldata
    /// @return amountIn The amount of debt token in used to settle position
    /// @return amountOut The amount of margin token received after settling position
    /// @return rewards The amount of escrowed liquidation rewards in native (gas) token released by pool after settling position
    function burn(
        BurnParams calldata params
    )
        external
        payable
        returns (uint256 amountIn, uint256 amountOut, uint256 rewards);

    struct IgniteParams {
        address token0;
        address token1;
        uint24 maintenance;
        address oracle;
        uint256 tokenId;
        uint256 amountOutMinimum;
        address recipient;
        uint256 deadline;
    }

    /// @notice Burns an existing position, settling on pool via swap through spot
    /// @dev If a contract, `recipient` must implement a `receive()` function to receive any excess liquidation rewards unused by the spot swap in the native (gas) token from the manager.
    /// @param params The parameters necessary for settling the position, encoded as `IgniteParams` in calldata
    /// @return amountOut The amount of margin token received after settling position
    /// @return rewards The amount of escrowed liquidation rewards in native (gas) token released by pool after settling position
    function ignite(
        IgniteParams calldata params
    ) external returns (uint256 amountOut, uint256 rewards);
}

File 49 of 54 : PositionAmounts.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

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

/// @title Position amounts library
/// @notice Calculates liquidity from desired size amounts
library PositionAmounts {
    using SafeCast for uint256;

    error SizeGreaterThanReserve(uint256 reserve);

    /// @notice Gets the pool liquidity to be utilized for a given position size
    /// @param liquidity The available liquidity of the pool
    /// @param sqrtPriceX96 The sqrt price of the pool
    /// @param maintenance The minimum maintenance requirement of the pool
    /// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @param size The desired size of the position in token1 if zeroForOne = true, or token0 if zeroForOne = false
    /// @return liquidityDelta The pool liquidity to be utilized
    function getLiquidityForSize(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint24 maintenance,
        bool zeroForOne,
        uint128 size
    ) internal pure returns (uint128 liquidityDelta) {
        // del L / L = (sx / x) / (1 - (1 - sx / x) ** 2 / (1 + M))
        (uint256 reserve0, uint256 reserve1) = LiquidityMath.toAmounts(
            liquidity,
            sqrtPriceX96
        );
        uint256 reserve = !zeroForOne ? reserve0 : reserve1;
        if (size >= reserve) revert SizeGreaterThanReserve(reserve);

        uint256 prod = (reserve - uint256(size)) ** 2 / reserve;
        uint256 denom = reserve - (prod * 1e6) / (1e6 + maintenance);
        liquidityDelta = ((uint256(liquidity) * uint256(size)) / denom)
            .toUint128();
    }
}

File 50 of 54 : LiquidityMath.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

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

/// @title Math library for liquidity
/// @notice Facilitates transformations between (L, sqrtP) space and (x, y) token reserves
library LiquidityMath {
    using SafeCast for uint256;

    /// @notice Transforms (L, sqrtP) values into (x, y) reserve amounts
    /// @param liquidity Pool liquidity in (L, sqrtP) space
    /// @param sqrtPriceX96 Pool price in (L, sqrtP) space
    /// @return amount0 The amount of token0 associated with the given (L, sqrtP) values
    /// @return amount1 The amount of token1 associated with the given (L, sqrtP) values
    function toAmounts(
        uint128 liquidity,
        uint160 sqrtPriceX96
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        // x = L / sqrt(P); y = L * sqrt(P)
        amount0 =
            (uint256(liquidity) << FixedPoint96.RESOLUTION) /
            sqrtPriceX96;
        amount1 = Math.mulDiv(liquidity, sqrtPriceX96, FixedPoint96.Q96);
    }

    /// @notice Transforms (x, y) reserve amounts into (L, sqrtP) values
    /// @dev Reverts on overflow if reserve0 * reserve1 > type(uint256).max as liquidity must fit into uint128
    /// @param reserve0 The amount of token0 in reserves
    /// @param reserve1 The amount of token1 in reserves
    /// @return liquidity Pool liquidity associated with reserve amounts
    /// @return sqrtPriceX96 Pool price associated with reserve amounts
    function toLiquiditySqrtPriceX96(
        uint256 reserve0,
        uint256 reserve1
    ) internal pure returns (uint128 liquidity, uint160 sqrtPriceX96) {
        // L = sqrt(x * y); sqrt(P) = sqrt(y / x)
        liquidity = Math.sqrt(reserve0 * reserve1).toUint128();

        uint256 _sqrtPriceX96 = (uint256(liquidity) <<
            FixedPoint96.RESOLUTION) / reserve0;
        if (
            !(_sqrtPriceX96 >= SqrtPriceMath.MIN_SQRT_RATIO &&
                _sqrtPriceX96 < SqrtPriceMath.MAX_SQRT_RATIO)
        ) revert SqrtPriceMath.InvalidSqrtPriceX96();
        sqrtPriceX96 = uint160(_sqrtPriceX96);
    }

    /// @notice Calculates (L, sqrtP) after adding/removing amounts to/from pool reserves
    /// @param liquidity Pool liquidity before adding/removing reserves
    /// @param sqrtPriceX96 Pool price before adding/removing reserves
    /// @param amount0 The amount of token0 to add (positive) or remove (negative)
    /// @param amount1 The amount of token1 to add (positive) or remove (negative)
    /// @return liquidityNext Pool liquidity after adding/removing reserves
    /// @return sqrtPriceX96Next Pool price after adding/removing reserves
    function liquiditySqrtPriceX96Next(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        int256 amount0,
        int256 amount1
    ) internal pure returns (uint128 liquidityNext, uint160 sqrtPriceX96Next) {
        (uint256 reserve0, uint256 reserve1) = toAmounts(
            liquidity,
            sqrtPriceX96
        );

        if (amount0 < 0 && uint256(-amount0) >= reserve0)
            revert SqrtPriceMath.Amount0ExceedsReserve0();
        if (amount1 < 0 && uint256(-amount1) >= reserve1)
            revert SqrtPriceMath.Amount1ExceedsReserve1();

        uint256 reserve0Next = amount0 >= 0
            ? reserve0 + uint256(amount0)
            : reserve0 - uint256(-amount0);
        uint256 reserve1Next = amount1 >= 0
            ? reserve1 + uint256(amount1)
            : reserve1 - uint256(-amount1);

        (liquidityNext, sqrtPriceX96Next) = toLiquiditySqrtPriceX96(
            reserve0Next,
            reserve1Next
        );
    }
}

File 51 of 54 : SqrtPriceMath.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

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

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

/// @title Math library for sqrt price changes
/// @notice Determines sqrt price changes after a opening leverage position and swapping on the pool
library SqrtPriceMath {
    /// @dev Adopts Uni V3 tick limits of (-887272, 887272)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    uint160 internal constant MAX_SQRT_RATIO =
        1461446703485210103287273052203988822378723970342;

    error InvalidSqrtPriceX96();
    error Amount0ExceedsReserve0();
    error Amount1ExceedsReserve1();

    /// @notice Calculates sqrtP after opening a leverage position
    /// @dev Choice of insurance function made in this function
    /// @param liquidity Pool liquidity before opening the position
    /// @param sqrtPriceX96 Pool price before opening the position
    /// @param liquidityDelta Liquidity removed from pool to collateralize position
    /// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
    /// @param maintenance Minimum maintenance margin for the pool
    /// @return The price after opening the position
    function sqrtPriceX96NextOpen(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        uint128 liquidityDelta,
        bool zeroForOne,
        uint24 maintenance
    ) internal pure returns (uint160) {
        uint256 prod = uint256(liquidityDelta) *
            uint256(liquidity - liquidityDelta);
        prod = Math.mulDiv(prod, 1e6, 1e6 + uint256(maintenance));

        // root round down ensures no free size but can have nextX96 go opposite of intended direction
        // as liquidityDelta -> 0. position.assemble will revert tho if so
        uint256 under = uint256(liquidity) ** 2 - 4 * prod;
        uint256 root = Math.sqrt(under);

        uint256 nextX96 = !zeroForOne
            ? Math.mulDiv(
                sqrtPriceX96,
                uint256(liquidity) + root,
                2 * uint256(liquidity - liquidityDelta)
            )
            : Math.mulDiv(
                sqrtPriceX96,
                2 * uint256(liquidity - liquidityDelta),
                uint256(liquidity) + root
            );
        if (!(nextX96 >= MIN_SQRT_RATIO && nextX96 < MAX_SQRT_RATIO))
            revert InvalidSqrtPriceX96();

        return uint160(nextX96);
    }

    /// @notice Calculates sqrtP after swapping tokens
    /// @dev Assumes amountSpecified != 0
    /// @param liquidity Pool liquidity before swapping
    /// @param sqrtPriceX96 Pool price before swapping
    /// @param zeroForOne Whether swapping token0 for token1 (true), or token1 for token0 (false)
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @return The price after swapping
    function sqrtPriceX96NextSwap(
        uint128 liquidity,
        uint160 sqrtPriceX96,
        bool zeroForOne,
        int256 amountSpecified
    ) internal pure returns (uint160) {
        bool exactInput = amountSpecified > 0;

        uint256 nextX96;
        if (exactInput) {
            if (!zeroForOne) {
                // 1 is known
                // sqrt(P') = sqrt(P) + del y / L
                uint256 prod = (
                    uint256(amountSpecified) <= type(uint160).max
                        ? (uint256(amountSpecified) <<
                            FixedPoint96.RESOLUTION) / liquidity
                        : Math.mulDiv(
                            uint256(amountSpecified),
                            FixedPoint96.Q96,
                            liquidity
                        )
                );
                nextX96 = uint256(sqrtPriceX96) + prod;
            } else {
                // 0 is known
                // sqrt(P') = sqrt(P) - (del x * sqrt(P)) / (L / sqrt(P) + del x)
                uint256 reserve0 = (uint256(liquidity) <<
                    FixedPoint96.RESOLUTION) / sqrtPriceX96;
                uint256 prod = (
                    uint256(amountSpecified) <= type(uint96).max
                        ? (uint256(amountSpecified) * uint256(sqrtPriceX96)) /
                            (reserve0 + uint256(amountSpecified))
                        : Math.mulDiv(
                            uint256(amountSpecified),
                            sqrtPriceX96,
                            reserve0 + uint256(amountSpecified)
                        )
                );
                nextX96 = uint256(sqrtPriceX96) - prod;
            }
        } else {
            if (!zeroForOne) {
                // 0 is known
                // sqrt(P') = sqrt(P) - (del x * sqrt(P)) / (L / sqrt(P) + del x)
                uint256 reserve0 = (uint256(liquidity) <<
                    FixedPoint96.RESOLUTION) / sqrtPriceX96;
                if (reserve0 <= uint256(-amountSpecified))
                    revert Amount0ExceedsReserve0();

                uint256 prod = (
                    uint256(-amountSpecified) <= type(uint96).max
                        ? (uint256(-amountSpecified) * uint256(sqrtPriceX96)) /
                            (reserve0 - uint256(-amountSpecified))
                        : Math.mulDiv(
                            uint256(-amountSpecified),
                            sqrtPriceX96,
                            reserve0 - uint256(-amountSpecified)
                        )
                );
                nextX96 = uint256(sqrtPriceX96) + prod;
            } else {
                // 1 is known
                // sqrt(P') = sqrt(P) + del y / L
                uint256 reserve1 = Math.mulDiv(
                    liquidity,
                    sqrtPriceX96,
                    FixedPoint96.Q96
                );
                if (reserve1 <= uint256(-amountSpecified))
                    revert Amount1ExceedsReserve1();

                uint256 prod = (
                    uint256(-amountSpecified) <= type(uint160).max
                        ? (uint256(-amountSpecified) <<
                            FixedPoint96.RESOLUTION) / liquidity
                        : Math.mulDiv(
                            uint256(-amountSpecified),
                            FixedPoint96.Q96,
                            liquidity
                        )
                );
                nextX96 = uint256(sqrtPriceX96) - prod;
            }
        }
        if (!(nextX96 >= MIN_SQRT_RATIO && nextX96 < MAX_SQRT_RATIO))
            revert InvalidSqrtPriceX96();
        return uint160(nextX96);
    }
}

File 52 of 54 : PositionState.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;

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

import {Position as PositionLibrary} from "@marginal/v1-core/contracts/libraries/Position.sol";
import {OracleLibrary} from "@marginal/v1-core/contracts/libraries/OracleLibrary.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";

import {PoolConstants} from "../libraries/PoolConstants.sol";

abstract contract PositionState {
    using PositionLibrary for PositionLibrary.Info;

    /// @notice Gets pool state synced for pool oracle updates
    /// @param pool The pool to get state of
    function getStateSynced(
        address pool
    )
        internal
        view
        returns (
            uint160 sqrtPriceX96,
            uint96 totalPositions,
            uint128 liquidity,
            int24 tick,
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint8 feeProtocol,
            bool initialized
        )
    {
        (
            sqrtPriceX96,
            totalPositions,
            liquidity,
            tick,
            blockTimestamp,
            tickCumulative,
            feeProtocol,
            initialized
        ) = IMarginalV1Pool(pool).state();

        // oracle update
        unchecked {
            tickCumulative +=
                int56(tick) *
                int56(uint56(uint32(block.timestamp) - blockTimestamp)); // overflow desired
            blockTimestamp = uint32(block.timestamp);
        }
    }

    /// @notice Gets external oracle tick cumulative values for time deltas: [secondsAgo, 0]
    /// @param pool The pool to get external oracle state for
    function getOracleSynced(
        address pool
    ) internal view returns (int56[] memory oracleTickCumulatives) {
        address oracle = IMarginalV1Pool(pool).oracle();

        // zero seconds ago for oracle tickCumulative
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = PoolConstants.secondsAgo;

        (oracleTickCumulatives, ) = IUniswapV3Pool(oracle).observe(secondsAgos);
    }

    /// @notice Gets pool position synced for funding updates
    /// @param pool The pool the position is on
    /// @param recipient The recipient of the position at open
    /// @param id The position id
    function getPositionSynced(
        address pool,
        address recipient,
        uint96 id
    )
        internal
        view
        returns (
            bool zeroForOne,
            uint128 size,
            uint128 debt,
            uint128 margin,
            uint128 safeMarginMinimum,
            bool liquidated,
            bool safe,
            uint256 rewards
        )
    {
        PositionLibrary.Info memory info;
        {
            bytes32 key = keccak256(abi.encodePacked(recipient, id));

            uint128 _debt0;
            uint128 _debt1;
            int24 _tick;
            uint32 _blockTimestamp;
            int56 _tickCumulativeDelta;
            (
                size,
                _debt0,
                _debt1,
                ,
                ,
                zeroForOne,
                liquidated,
                _tick,
                _blockTimestamp,
                _tickCumulativeDelta,
                margin,
                ,
                rewards
            ) = IMarginalV1Pool(pool).positions(key);
            info = PositionLibrary.Info({
                size: size,
                debt0: _debt0,
                debt1: _debt1,
                insurance0: 0, // @dev irrelevant for sync
                insurance1: 0,
                zeroForOne: zeroForOne,
                liquidated: liquidated,
                tick: _tick,
                blockTimestamp: _blockTimestamp,
                tickCumulativeDelta: _tickCumulativeDelta,
                margin: margin,
                liquidityLocked: 0, // @dev irrelevant for sync
                rewards: rewards
            });
        }

        uint24 maintenance = IMarginalV1Pool(pool).maintenance();
        uint128 marginMinimum = info.marginMinimum(maintenance);

        // sync if not settled or liquidated
        if (info.size > 0) {
            int56 oracleTickCumulativeDelta;
            {
                (
                    ,
                    ,
                    ,
                    ,
                    uint32 blockTimestampLast,
                    int56 tickCumulativeLast,
                    ,

                ) = getStateSynced(pool);

                int56[] memory oracleTickCumulativesLast = getOracleSynced(
                    pool
                );
                oracleTickCumulativeDelta = OracleLibrary
                    .oracleTickCumulativeDelta(
                        oracleTickCumulativesLast[0],
                        oracleTickCumulativesLast[1]
                    );

                info.sync(
                    blockTimestampLast,
                    tickCumulativeLast,
                    oracleTickCumulativesLast[1], // zero seconds ago
                    PoolConstants.tickCumulativeRateMax,
                    PoolConstants.fundingPeriod
                );
            }

            safe = info.safe(
                OracleLibrary.oracleSqrtPriceX96(
                    oracleTickCumulativeDelta,
                    PoolConstants.secondsAgo
                ),
                maintenance
            );
            safeMarginMinimum = _safeMarginMinimum(
                info,
                marginMinimum,
                maintenance,
                oracleTickCumulativeDelta
            );
        }

        debt = zeroForOne ? info.debt0 : info.debt1;
    }

    /// @notice Calculates the minimum margin requirement for the position to remain safe from liquidation
    /// @dev c_y (safe) >= (1+M) * d_x * max(P, TWAP) - s_y when zeroForOne = true when no funding
    /// or c_x (safe) >= (1+M) * d_y / min(P, TWAP) - s_x when zeroForOne = false when no funding
    /// @param info The synced position info
    /// @param marginMinimum The margin minimum when ignoring funding and liquidation
    /// @param maintenance The minimum maintenance margin requirement
    /// @param oracleTickCumulativeDelta The difference in oracle tick cumulatives averaged over to assess position safety with
    function _safeMarginMinimum(
        PositionLibrary.Info memory info,
        uint128 marginMinimum,
        uint24 maintenance,
        int56 oracleTickCumulativeDelta
    ) internal pure returns (uint128 safeMarginMinimum) {
        int24 positionTick = info.tick;
        int24 oracleTick = int24(
            oracleTickCumulativeDelta / int56(uint56(PoolConstants.secondsAgo))
        );

        // change to using oracle tick for safe margin minimum calculation with liquidation and funding
        info.tick = oracleTick;
        safeMarginMinimum = info.marginMinimum(maintenance);
        if (marginMinimum > safeMarginMinimum)
            safeMarginMinimum = marginMinimum;

        info.tick = positionTick; // in case reuse info, return to actual position tick
    }
}

File 53 of 54 : 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 54 of 54 : 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);
}

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

Contract ABI

[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"},{"internalType":"address","name":"_tokenDescriptor_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"AmountInGreaterThanMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"AmountOutLessThanMin","type":"error"},{"inputs":[{"internalType":"uint256","name":"debt","type":"uint256"}],"name":"DebtGreaterThanMax","type":"error"},{"inputs":[],"name":"InvalidPoolKey","type":"error"},{"inputs":[],"name":"OracleNotSender","type":"error"},{"inputs":[],"name":"PoolInactive","type":"error"},{"inputs":[],"name":"PoolNotSender","type":"error"},{"inputs":[{"internalType":"uint256","name":"rewardsMinimum","type":"uint256"}],"name":"RewardsLessThanMin","type":"error"},{"inputs":[{"internalType":"uint256","name":"reserve","type":"uint256"}],"name":"SizeGreaterThanReserve","type":"error"},{"inputs":[{"internalType":"uint256","name":"size","type":"uint256"}],"name":"SizeLessThanMin","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginAfter","type":"uint256"}],"name":"Free","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Ignite","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginAfter","type":"uint256"}],"name":"Lock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"positionId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"size","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fees","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.BurnParams","name":"params","type":"tuple"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"marginOut","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.FreeParams","name":"params","type":"tuple"}],"name":"free","outputs":[{"internalType":"uint256","name":"margin","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","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":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.IgniteParams","name":"params","type":"tuple"}],"name":"ignite","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"marginIn","type":"uint128"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.LockParams","name":"params","type":"tuple"}],"name":"lock","outputs":[{"internalType":"uint256","name":"margin","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1AdjustCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1OpenCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1SettleCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"uint128","name":"sizeDesired","type":"uint128"},{"internalType":"uint128","name":"sizeMinimum","type":"uint128"},{"internalType":"uint128","name":"debtMaximum","type":"uint128"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"margin","type":"uint256"},{"internalType":"uint256","name":"fees","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"positions","outputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"uint96","name":"positionId","type":"uint96"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"uint128","name":"size","type":"uint128"},{"internalType":"uint128","name":"debt","type":"uint128"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"uint128","name":"safeMarginMinimum","type":"uint128"},{"internalType":"bool","name":"liquidated","type":"bool"},{"internalType":"bool","name":"safe","type":"bool"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","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":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","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"}]

61010060409080825234620004ae5760608162005b158038038091620000268285620004cf565b833981010312620004ae576200003c81620004f3565b602091620000598462000051858401620004f3565b9201620004f3565b928451926200006884620004b3565b601a84527f4d617267696e616c20563120506f736974696f6e20546f6b656e0000000000008285015285516200009e81620004b3565b600a8152694d41524756312d504f5360b01b8382015284516001600160401b03929083811162000498576000928354916001988984811c941680156200048d575b8885101462000479578190601f9485811162000426575b508890858311600114620003c2578792620003b6575b5050600019600383901b1c191690891b1784555b8051948511620003a25787548881811c9116801562000397575b87821014620003835790818388959493116200032c575b5083918611600114620002c45760049591859183620002b8575b5050600019600383901b1c191690881b1787555b60808190528851632daa48c160e11b815293849182906001600160a01b03165afa928315620002ac57819362000268575b50505060a05260c05260075560e0525161560c90816200050982396080518181816106ba0152818161092401528181610bf101528181610e1a0152818161180f01528181611dc7015281816123210152818161265c01528181613392015281816137f801528181613e87015281816140d70152614235015260a05181610ba8015260c051818181610a5601528181610b62015281816133060152818161347301528181613bed01526143df015260e05181611e4f0152f35b9091809350813d8311620002a4575b620002838183620004cf565b81010312620002a157506200029890620004f3565b388080620001b0565b80fd5b503d62000277565b508651903d90823e3d90fd5b0151905038806200016b565b948891601f1982169083875285872091875b818110620003135750978360049910620002f9575b505050811b0187556200017f565b015160001960f88460031b161c19169055388080620002eb565b828a015184558a978d96909401939283019201620002d6565b90919293508885528685208380880160051c82019289891062000379575b918b918a97969594930160051c01915b8281106200036a57505062000151565b8781558996508b91016200035a565b925081926200034a565b634e487b7160e01b85526022600452602485fd5b90607f16906200013a565b634e487b7160e01b84526041600452602484fd5b0151905038806200010c565b8780528988208c94509190601f198416895b8c8282106200040f5750508411620003f5575b505050811b01845562000120565b015160001960f88460031b161c19169055388080620003e7565b8385015186558f97909501949384019301620003d4565b9091508680528887208580850160051c8201928b86106200046f575b918d91869594930160051c01915b82811062000460575050620000f6565b8981558594508d910162000450565b9250819262000442565b634e487b7160e01b86526022600452602486fd5b93607f1693620000df565b634e487b7160e01b600052604160045260246000fd5b600080fd5b604081019081106001600160401b038211176200049857604052565b601f909101601f19168101906001600160401b038211908210176200049857604052565b51906001600160a01b0382168203620004ae5756fe60806040526004361015610023575b361561001957600080fd5b6100216132fc565b005b60003560e01c806301ffc9a71461028f57806306fdde0314610286578063081812fc1461027d578063095ea7b31461027457806312210e8a1461026b578063156e1ef4146102625780631e121fe81461025957806321e818e01461025057806323b872dd1461024757806342842e0e1461023e57806349404b7c146102355780634aa4a4fc1461022c5780635b549182146102235780635f1c4fdc1461021a5780636352211e146102115780636bf392631461020857806370a08231146101ff57806389051db6146101f657806395d89b41146101ed57806399fbab88146101e4578063a22cb465146101db578063a24e4f7a146101d2578063ac9650d8146101c9578063b88d4fde146101c0578063c45a0155146101b7578063c87b56dd146101ae578063d3e17b03146101a5578063d44959461461019c578063df2ab5bb14610193578063e985e9c51461018a5763fa461e330361000e5761018561261a565b61000e565b506101856125b1565b5061018561250a565b50610185612251565b50610185611ec4565b50610185611df6565b50610185611db0565b50610185611d1f565b50610185611a8d565b506101856117d6565b506101856116e5565b50610185611329565b50610185611267565b50610185611063565b50610185610fac565b50610185610d2a565b50610185610d0b565b50610185610bd7565b50610185610b91565b50610185610b4b565b50610185610a20565b506101856109f7565b506101856109cd565b506101856108fe565b50610185610842565b506101856105e4565b506101856105bd565b506101856104e4565b506101856104a2565b50610185610397565b506101856102af565b6001600160e01b03198116036102aa57565b600080fd5b50346102aa5760203660031901126102aa5760206004356102cf81610298565b63ffffffff60e01b166380ac58cd60e01b811490811561030d575b81156102fc575b506040519015158152f35b6301ffc9a760e01b149050386102f1565b635b5e139f60e01b811491506102ea565b60009103126102aa57565b918091926000905b828210610349575011610342575050565b6000910152565b91508060209183015181860152018291610331565b9060209161037781518092818552858086019101610329565b601f01601f1916010190565b90602061039492818152019061035e565b90565b50346102aa5760008060031936011261049f57604051908080549060019180831c92808216928315610495575b60209283861085146104815785885260208801949081156104605750600114610408575b610404876103f881890382611c18565b60405191829182610383565b0390f35b6000805294509192917f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5635b83861061044f57505050910190506103f88261040438806103e8565b805485870152948201948101610433565b60ff191685525050505090151560051b0190506103f88261040438806103e8565b634e487b7160e01b82526022600452602482fd5b93607f16936103c4565b80fd5b50346102aa5760203660031901126102aa5760206104c16004356127bf565b6040516001600160a01b039091168152f35b6001600160a01b038116036102aa57565b50346102aa5760403660031901126102aa57600435610502816104d3565b60243561050e8161272a565b916001600160a01b03808416908216811461056e576100219361053b913314908115610540575b5061274d565b612b1b565b6001600160a01b0316600090815260056020908152604080832033845290915290205460ff16905038610535565b60405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e656044820152603960f91b6064820152608490fd5b5060003660031901126102aa57610021613674565b6101009060031901126102aa57600490565b50346102aa576101003660031901126102aa57610600366105d2565b608081013561060f81336128ea565b156108315761062460e0830135421115612f16565b610638816000526006602052604060002090565b61064190612ed3565b61064a83612f89565b92602081019061065982612f89565b946040938483019161066a83612fac565b9760608501986106798a612f89565b91610682611c39565b6001600160a01b0390941684526001600160a01b0316602084015262ffffff16828801526001600160a01b031660608201526106de907f0000000000000000000000000000000000000000000000000000000000000000615342565b81516001600160a01b0390811691160361082057610706866000526006602052604060002090565b600090556107138661326e565b61071c83612f89565b9361072690612f89565b9161073090612fac565b9661073a90612f89565b60c084019761074889612f89565b6020909301516001600160601b031693610760611c58565b6001600160a01b0390971687526001600160a01b0316602087015262ffffff16858701526001600160a01b031660608501526001600160a01b031660808401526001600160601b031660a083015260a0013560c08201526107c0906141c6565b926107cb8295612f89565b83516001600160a01b0391909116815260208101929092526040820184905233917f34270365a3c76bc9895ec91ac488337da0e12eee459cd8eec127882f8dd29a5990606090a3519182526020820152604090f35b845163c256622b60e01b8152600490fd5b6040516282b42960e81b8152600490fd5b5060403660031901126102aa5760243561085b816104d3565b476004358110610875578061086c57005b61002191613515565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b9060606003198301126102aa5760043591602435916044356001600160401b03928382116102aa57806023830112156102aa5781600401359384116102aa57602484830101116102aa576024019190565b50346102aa5761091c610910366108ad565b81949293940190613bab565b9161094883517f00000000000000000000000000000000000000000000000000000000000000006152de565b508061097a575b508061095757005b81516020908101519201516100219233916001600160a01b039081169116613be3565b825151602084015161099b929133916001600160a01b039081169116613be3565b3861094f565b60609060031901126102aa576004356109b9816104d3565b906024356109c6816104d3565b9060443590565b50346102aa576100216109df366109a1565b916109f26109ed84336128ea565b6127fd565b6129bc565b50346102aa57610021610a09366109a1565b9060405192610a1784611be2565b6000845261285f565b5060403660031901126102aa57602435610a39816104d3565b6040516370a0823160e01b81523060048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691602082602481865afa918215610b3e575b600092610b0e575b50610a9f600435831015613415565b81610aa657005b823b156102aa57604051632e1a7d4d60e01b815260048101839052610021936000908290818381602481015b03925af18015610b01575b610ae8575b50613515565b80610af5610afb92611bcf565b8061031e565b38610ae2565b610b09612bc7565b610add565b610b3091925060203d8111610b37575b610b288183611c18565b810190613406565b9038610a90565b503d610b1e565b610b46612bc7565b610a88565b50346102aa5760003660031901126102aa576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102aa5760003660031901126102aa576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102aa57610be9610910366108ad565b91610c1583517f00000000000000000000000000000000000000000000000000000000000000006152de565b5080610ca1575b5080610c2457005b815160209081015161002193610c5f9291610c47906001600160a01b0316613fbf565b808511610c68575b505101516001600160a01b031690565b33903090613be3565b8151830151610c9b91906001600160a01b031683850151610c93906001600160a01b03169288613748565b913091613be3565b38610c4f565b825151610cd59190610cbb906001600160a01b0316613fbf565b808211610cdb575b508351516001600160a01b0316610c5f565b38610c1c565b845151610d0591906001600160a01b03166020870151610c93906001600160a01b03169285613748565b38610cc3565b50346102aa5760203660031901126102aa5760206104c160043561272a565b50346102aa576101003660031901126102aa57610d46366105d2565b608081013590610d5682336128ea565b156108315780610d6f60e0610dd2930135421115612f16565b610d8b610d86846000526006602052604060002090565b612ed3565b90610d9581612f89565b916020820191610da483612f89565b91610e4a610e3e610e3e604097610e1889870197610e08610dc48a612fac565b610dfd60608b019e8f612f89565b93610ded610dde611c39565b6001600160a01b039098168852565b6001600160a01b03166020870152565b62ffffff16848d0152565b6001600160a01b03166060830152565b7f0000000000000000000000000000000000000000000000000000000000000000615342565b6001600160a01b031690565b8151610e5e906001600160a01b0316610e3e565b6001600160a01b039091160361082057610e7782612f89565b93610e8190612f89565b92610e8b90612fac565b95610e9590612f89565b60c0830196610ea388612f89565b6020909301516001600160601b03169360a001610ebf906130cc565b6001600160801b0316600f0b610ed49061322e565b94610edd611c58565b6001600160a01b0390971687526001600160a01b0316602087015262ffffff16858701526001600160a01b031660608501526001600160a01b031660808401526001600160601b031660a0830152600f0b60c0820152610f3c90613e17565b6104049491610f52918115610fa4575093612f89565b82516001600160a01b039091168152602081018490523391907f352b6077a9209bc984c0f5dd020d42bf741232cd6401c9bbac47115f7a741d8d9080604081015b0390a3519081529081906020820190565b905093612f89565b50346102aa5760203660031901126102aa57600435610fca816104d3565b6001600160a01b03168015610ffb576000526003602052610404604060002054604051918291829190602083019252565b60405162461bcd60e51b815260206004820152602960248201527f4552433732313a2061646472657373207a65726f206973206e6f7420612076616044820152683634b21037bbb732b960b91b6064820152608490fd5b60e09060031901126102aa57600490565b5060e03660031901126102aa5761107936611052565b608081013561108881336128ea565b1561083157816110a160c0610e3e940135421115612f16565b6110b8610d86836000526006602052604060002090565b906110c281612f89565b9060208101926110d184612f89565b92611138610e3e6040988993610e1885880198610e086110f08b612fac565b60608b019861112c6111018b612f89565b9461111c61110d611c39565b6001600160a01b039099168952565b6001600160a01b03166020880152565b85019062ffffff169052565b825161114c906001600160a01b0316610e3e565b6001600160a01b03909116036112565761116583612f89565b9461116f90612f89565b9361117990612fac565b9061118390612f89565b6020909201516001600160601b03169260a00161119f906130cc565b6001600160801b0316600f0b936111b4611c58565b6001600160a01b0390961686526001600160a01b0316602086015262ffffff16848701526001600160a01b031660608401523360808401526001600160601b031660a0830152600f0b60c082015261120b90613e17565b610404939190811561124e5750915b81518381523391907f8738fac4c3f6ded3649d1d6c64679bd1a81c89414e861f2ca28b5fc585c0e33d908060208101610f93565b90509161121a565b865163c256622b60e01b8152600490fd5b50346102aa5760008060031936011261049f576040519080600190815480831c9280821692831561131f575b602092838610851461048157858852602088019490811561046057506001146112c657610404876103f881890382611c18565b600160005294509192917fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf65b83861061130e57505050910190506103f88261040438806103e8565b8054858701529482019481016112f2565b93607f1693611293565b50346102aa576020806003193601126102aa576000600435815260068252816113f060408320926040519361135d85611ba7565b546001600160a01b03811680865260a09190911c95909401859052808061138261444a565b506040513060601b6bffffffffffffffffffffffff191686820190815260a089901b6001600160a01b03191660148201526101a0916113ce81602084015b03601f198101835282611c18565b5190206040518096819263514ea4bf60e01b8352600483019190602083019252565b0381895afa9384156116ce575b82839084918592868a818283918499859e61167e575b5061141c611c77565b6001600160801b03891681529384019661143f9088906001600160801b03169052565b60408401956114579087906001600160801b03169052565b606084018590526080840185905288151560a08501528b151560c085015260020b60e084015263ffffffff1661010083015260060b6101208201526001600160801b038716610140820152816101608201528a6101808201528c604051636c376cc560e01b81528d8183815a91600492fa9081159e6104049f611671575b8592611644575b50506114e88184614769565b6115086114fc85516001600160801b031690565b6001600160801b031690565b6115af575b50505050508360001461159d5750516001600160801b0316915b604080516001600160a01b03909b168b526001600160601b03909b1660208b01521515998901999099526001600160801b03988916606089015288166080880152871660a08701529590951660c085015293151560e0840152921515610100830152610120820192909252908190610140820190565b516001600160801b0316905091611527565b9091929b5061163a9399506116158c6115d96115ca86614f75565b505095945099925050506151ad565b9561160f6115ef6116096115f66115ef8b612e83565b5160060b90565b6116026115ef8c612e99565b0360060b90565b98612e99565b92614596565b50611634828d61162e61a8c08760060b0560020b614c05565b906148d0565b9b615297565b95388c818061150d565b6116639250803d1061166a575b61165b8183611c18565b810190614581565b38806114dc565b503d611651565b611679612bc7565b6114d5565b9850505050975098505050506116ae91506101a03d6101a0116116c7575b6116a68183611c18565b8101906144ca565b9f959d919b969a96999698509596509394509138611413565b503d61169c565b6116d6612bc7565b6113fd565b801515036102aa57565b50346102aa5760403660031901126102aa57600435611703816104d3565b60243561170f816116db565b6001600160a01b03821691338314611791578161174e61175f9233600052600560205260406000209060018060a01b0316600052602052604060002090565b9060ff801983541691151516179055565b604051901515815233907f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3190602090a3005b60405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c6572000000000000006044820152606490fd5b50346102aa576117e5366108ad565b92909160009384831393841580611a21575b611a045761180791810190613bab565b9261183384517f00000000000000000000000000000000000000000000000000000000000000006152de565b506020840180519091906001600160a01b0316906001600160a01b03821630036119a257505050916040916118f69361186a6143d5565b82516060015186821391879161188a90610e3e906001600160a01b031681565b938315611992575061189b9061325d565b915b8015611974576119046401000276a4955b5187519889916020830181516001600160a01b03908116825260208084015182169083015260408084015162ffffff1690830152606092830151169181019190915260800190565b03601f198101895288611c18565b611924865197889687958694630251596160e31b8652336004870161439c565b03925af18015611967575b61193a575b50604051f35b61195a9060403d8111611960575b6119528183611c18565b810190613dca565b50611934565b503d611948565b61196f612bc7565b61192f565b61190473fffd8963efd1fc6a506488495d951d5263988d25956118ae565b61199c915061325d565b9161189d565b93909192936119e6575b50508382136119be575b505050604051f35b91516020015191516119de926001600160a01b0390811691163391613be3565b3880806119b6565b8451516119fd9233916001600160a01b0316613be3565b38806119ac565b604051636d24d5ef60e01b815260006004820152602490fd5b0390fd5b50858313156117f7565b602080820190808352835180925260408301928160408460051b8301019501936000915b848310611a5f5750505050505090565b9091929394958480611a7d600193603f198682030187528a5161035e565b9801930193019194939290611a4f565b5060203660031901126102aa57600480356001600160401b03918282116102aa57366023830112156102aa57818101359283116102aa57602490818301928236918660051b0101116102aa57611ae284612d34565b9360005b818110611afb57604051806104048882611a2b565b600080611b09838589612dc8565b60409391611b1b855180938193612e17565b0390305af490611b29612bd4565b91829015611b5857505090611b5391611b428289612eaa565b52611b4d8188612eaa565b50612d95565b611ae6565b8683879260448251106102aa5782611a1d9385611b7b9401518301019101612e25565b925162461bcd60e51b81529283928301610383565b50634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b03821117611bc257604052565b611bca611b90565b604052565b6001600160401b038111611bc257604052565b602081019081106001600160401b03821117611bc257604052565b60a081019081106001600160401b03821117611bc257604052565b90601f801991011681019081106001600160401b03821117611bc257604052565b60405190608082018281106001600160401b03821117611bc257604052565b6040519060e082018281106001600160401b03821117611bc257604052565b604051906101a082018281106001600160401b03821117611bc257604052565b6040519061018082018281106001600160401b03821117611bc257604052565b60405190604082018281106001600160401b03821117611bc257604052565b6040519060c082018281106001600160401b03821117611bc257604052565b6020906001600160401b038111611d12575b601f01601f19160190565b611d1a611b90565b611d07565b50346102aa5760803660031901126102aa57600435611d3d816104d3565b602435611d49816104d3565b606435916001600160401b0383116102aa57366023840112156102aa57826004013591611d7583611cf5565b92611d836040519485611c18565b80845236602482870101116102aa576020816000926024610021980183880137850101526044359161285f565b50346102aa5760003660031901126102aa576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102aa5760203660031901126102aa576004356000818152600260205260409020546001600160a01b0316156102aa5760405163e9dc637560e01b81523060048201526024810191909152610404906000816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115611eb7575b600091611e96575b5060405191829182610383565b611eb1913d8091833e611ea98183611c18565b810190612e25565b38611e89565b611ebf612bc7565b611e81565b506101a03660031901126102aa57611ee161018435421115612f16565b611f1f610e3e610e3e611ef2612f58565b610e18611efd612f64565b610e08611f08612fa0565b611f13610dd2612f70565b62ffffff166040850152565b60405163c19d93fb60e01b81526101009190611f6f908381600481865afa908115612244575b600090819261220d575b50611f58612fa0565b611f6061308f565b91611f6961309b565b936154e6565b91611f78612f58565b90611f81612f64565b90611f8a612fa0565b90611f93612f70565b90611f9c61308f565b6001600160a01b039790919088611fb16130d6565b166121ff57611fbe61308f565b156121e5576401000276a45b905b611fd46130a7565b93611fdd6130b4565b956001600160801b0380611fef6130c0565b166121d657975b61010435806121d05750600019995b61200d611c97565b6001600160a01b03909c168c526001600160a01b031660208c015262ffffff1660408b01526001600160a01b031660608a01523060808a0152151560a08901526001600160801b031660c08801526001600160a01b031660e08701526001600160801b03909116908501526001600160801b03166101208401526001600160801b03166101408301526101608201526120a59061375f565b9395949092966120b3612f7c565b90600754968792836120c481612d95565b6007556120d09161312f565b6120d8611cb7565b6001600160a01b0390911681526001600160601b0384166020820152612108836000526006602052604060002090565b9061213591815160209092015160a01b6001600160a01b0319166001600160a01b03909216919091179055565b61213d613674565b612145612f7c565b6040805133815260208101959095528401899052606084018a90526080840185905260a0840186905260c0840187905216917f2285d52eb6c0af06e33f4610840cc004ae11e19814110bf092b80f3f04e4012e9060e090a360405195869561040495879260a094919796959260c0850198855260208501526040840152606083015260808201520152565b99612005565b506121df6130c0565b97611ff6565b73fffd8963efd1fc6a506488495d951d5263988d25611fca565b6122076130d6565b90611fcc565b905061222f9150843d861161223d575b6122278183611c18565b81019061300c565b505050505091905038611f4f565b503d61221d565b61224c612bc7565b611f45565b5060e03660031901126102aa5761226736611052565b608081013561227681336128ea565b156108315761228b60c0830135421115612f16565b61229f816000526006602052604060002090565b6122a890612ed3565b916122b281612f89565b92602082016122c081612f89565b94604092838501916122d183612fac565b9760608701986122e08a612f89565b916122e9611c39565b6001600160a01b0390941684526001600160a01b0316602084015262ffffff16828701526001600160a01b03166060820152612345907f0000000000000000000000000000000000000000000000000000000000000000615342565b81516001600160a01b039081169116036124f95760009485612371886000526006602052604060002090565b5561237b8761326e565b61238481612f89565b9361238e90612f89565b9261239890612fac565b976123a290612f89565b9060a001976123b089612f89565b6020909301516001600160601b0316936123c8611cd6565b6001600160a01b0390961686526001600160a01b0316602086015262ffffff16848601526001600160a01b031660608401526001600160a01b031660808301526001600160601b031660a082015261241f90614068565b918495919550848113600014612478610404967f39f70f0fcd9366a4cc0388b64242d1bba1933d1d50cdd337b894d88c4258a680936124a9936124e35780995b828212156124c95750612472915061325d565b98612f89565b85516001600160a01b0390911681526020810188905260408101899052606081019490945233939081906080820190565b0390a3519283928360409060009294936060820195825260208201520152565b9050818112156124dd57612472915061325d565b50612472565b818a13156124f357895b9961245f565b816124ed565b835163c256622b60e01b8152600490fd5b5060603660031901126102aa57600435612523816104d3565b60443561252f816104d3565b6040516370a0823160e01b8152306004820152906020826024816001600160a01b0387165afa9182156125a4575b600092612584575b5061257460243583101561356c565b8161257b57005b610021926135c2565b61259d91925060203d8111610b3757610b288183611c18565b9038612565565b6125ac612bc7565b61255d565b50346102aa5760403660031901126102aa57602060ff61260e6004356125d6816104d3565b602435906125e3826104d3565b60018060a01b03166000526005845260406000209060018060a01b0316600052602052604060002090565b54166040519015158152f35b50346102aa57612629366108ad565b919092600093848213938480156126d5575b156126d15781016080828203126126d15761265591613b2d565b92612680847f000000000000000000000000000000000000000000000000000000000000000061530d565b506126b6575b50828113612695575b82604051f35b602091909101516126af91906001600160a01b0316610c5f565b388061268f565b82516126cb91906001600160a01b0316610c5f565b38612686565b8580fd5b5085841361263b565b156126e557565b60405162461bcd60e51b815260206004820152601860248201527f4552433732313a20696e76616c696420746f6b656e20494400000000000000006044820152606490fd5b6000908152600260205260409020546001600160a01b03166103948115156126de565b1561275457565b60405162461bcd60e51b815260206004820152603d60248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f7420746f60448201527f6b656e206f776e6572206f7220617070726f76656420666f7220616c6c0000006064820152608490fd5b6000818152600260205260409020546127e2906001600160a01b031615156126de565b6000908152600460205260409020546001600160a01b031690565b1561280457565b60405162461bcd60e51b815260206004820152602d60248201527f4552433732313a2063616c6c6572206973206e6f7420746f6b656e206f776e6560448201526c1c881bdc88185c1c1c9bdd9959609a1b6064820152608490fd5b906128839392916128736109ed84336128ea565b61287e8383836129bc565b612c04565b1561288a57565b60405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b6001600160a01b03806128fc8461272a565b169281831692848414948515612932575b5050831561291c575b50505090565b612928919293506127bf565b1614388080612916565b60009081526005602090815260408083206001600160a01b03949094168352929052205460ff169350388061290d565b1561296957565b60405162461bcd60e51b815260206004820152602560248201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060448201526437bbb732b960d91b6064820152608490fd5b6129e0906129c98461272a565b6001600160a01b0382811693909182168414612962565b8316928315612aca57612a47612aa192612a0685612a00610e3e8a61272a565b14612962565b612a2d612a1d886000526004602052604060002090565b80546001600160a01b0319169055565b6001600160a01b0316600090815260036020526040902090565b80546000190190556001600160a01b038116600090815260036020526040902060018154019055612a82856000526002602052604060002090565b80546001600160a01b0319166001600160a01b03909216919091179055565b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6000604051a4565b60405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b600082815260046020526040902080546001600160a01b0319166001600160a01b0383161790556001600160a01b0380612b548461272a565b169116907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9256000604051a4565b908160209103126102aa575161039481610298565b6001600160a01b0391821681529116602082015260408101919091526080606082018190526103949291019061035e565b506040513d6000823e3d90fd5b3d15612bff573d90612be582611cf5565b91612bf36040519384611c18565b82523d6000602084013e565b606090565b92909190823b15612d0557612c37926020926000604051809681958294630a85bd0160e11b9a8b85523360048601612b96565b03926001600160a01b03165af160009181612cd5575b50612cc757612c5a612bd4565b80519081612cc25760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b602001fd5b6001600160e01b0319161490565b612cf791925060203d8111612cfe575b612cef8183611c18565b810190612b81565b9038612c4d565b503d612ce5565b50505050600190565b6020906001600160401b038111612d27575b60051b0190565b612d2f611b90565b612d20565b90612d3e82612d0e565b612d4b6040519182611c18565b8281528092612d5c601f1991612d0e565b019060005b828110612d6d57505050565b806060602080938501015201612d61565b50634e487b7160e01b600052601160045260246000fd5b6001906000198114612da5570190565b612dad612d7e565b0190565b50634e487b7160e01b600052603260045260246000fd5b9190811015612e0a575b60051b81013590601e19813603018212156102aa5701908135916001600160401b0383116102aa5760200182360381136102aa579190565b612e12612db1565b612dd2565b908092918237016000815290565b6020818303126102aa578051906001600160401b0382116102aa570181601f820112156102aa578051612e5781611cf5565b92612e656040519485611c18565b818452602082840101116102aa576103949160208085019101610329565b602090805115612e91570190565b612dad612db1565b604090805160011015612e91570190565b6020918151811015612ebf575b60051b010190565b612ec7612db1565b612eb7565b156102aa57565b90604051604081018181106001600160401b03821117612f09575b60405291546001600160a01b038116835260a01c6020830152565b612f11611b90565b612eee565b15612f1d57565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b600435610394816104d3565b602435610394816104d3565b606435610394816104d3565b61016435610394816104d3565b35610394816104d3565b62ffffff8116036102aa57565b60443561039481612f93565b3561039481612f93565b6001600160801b038116036102aa57565b5190612fd282612fb6565b565b51908160020b82036102aa57565b519063ffffffff821682036102aa57565b51908160060b82036102aa57565b5190612fd2826116db565b9190826101009103126102aa578151613024816104d3565b9160208101516001600160601b03811681036102aa5791604082015161304981612fb6565b9161305660608201612fd4565b9161306360808301612fe2565b9161307060a08201612ff3565b9160c082015160ff811681036102aa5760e090920151610394816116db565b608435610394816116db565b60a43561039481612fb6565b6101443561039481612fb6565b60c43561039481612fb6565b60e43561039481612fb6565b3561039481612fb6565b61012435610394816104d3565b156130ea57565b60405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606490fd5b6001600160a01b0381169081156131ea576000838152600260205260409020546131c0919061316a906001600160a01b031615155b156130e3565b60008481526002602052604090205461318d906001600160a01b03161515613164565b6001600160a01b038116600090815260036020526040902060018154019055612a82846000526002602052604060002090565b60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef81604051a4565b606460405162461bcd60e51b815260206004820152602060248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152fd5b600f0b6f7fffffffffffffffffffffffffffffff198114613250575b60000390565b613258612d7e565b61324a565b600160ff1b81146132505760000390565b6132778161272a565b506132818161272a565b600082815260046020908152604080832080546001600160a01b03199081169091556001600160a01b0390941680845260038352818420805460001901905585845260029092528220919290919081541690557fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef82604051a4565b60018060a01b03807f0000000000000000000000000000000000000000000000000000000000000000163314908115613371575b501561333857565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f0000000000000000000000000000000000000000000000000000000000000000165afa9081156133f9575b6000916133cb575b5038613330565b6133ec915060203d81116133f2575b6133e48183611c18565b8101906135ad565b386133c4565b503d6133da565b613401612bc7565b6133bc565b908160209103126102aa575190565b1561341c57565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b6040516370a0823160e01b81523060048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691602082602481865afa918215613508575b6000926134e8575b50816134b857505050565b823b156102aa57604051632e1a7d4d60e01b815260048101839052612fd293600090829081838160248101610ad2565b61350191925060203d8111610b3757610b288183611c18565b90386134ad565b613510612bc7565b6134a5565b60008092918192602060405161352a81611be2565b84815201915af1613539612bd4565b501561354157565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b1561357357565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b908160209103126102aa5751610394816116db565b60405163a9059cbb60e01b602082019081526001600160a01b0390931660248201526044810193909352600092839290839061360181606481016113c0565b51925af161360d612bd4565b81613645575b501561361b57565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b805180159250821561365a575b505038613613565b61366d92506020809183010191016135ad565b3880613652565b4761367b57565b612fd24733613515565b815180516001600160a01b03908116835260208083015182169084015260408083015162ffffff1690840152606091820151169082015260a081019291608090602001516001600160a01b0316910152565b908160a09103126102aa578051916020820151916040810151916080606083015192015190565b6001600160a01b03918216815291151560208301526001600160801b0392831660408301529092166060830152909116608082015260c060a082018190526103949291019061035e565b818110613753570390565b61375b612d7e565b0390565b80519091906001600160a01b031660208301519091906001600160a01b0316926137ef6040946137df6137978785015162ffffff1690565b60608501516137d4906001600160a01b0316936137c46137b5611c39565b6001600160a01b03909a168a52565b6001600160a01b03166020890152565b62ffffff1686880152565b6001600160a01b03166060850152565b61381c610e3e847f0000000000000000000000000000000000000000000000000000000000000000615342565b9161382648613ac4565b804710613a2c576080830151869060a0906001600160a01b03168186019661384e8851151590565b8561386360c08a01516001600160801b031690565b60e08a01519094906138e0906138b7906001600160a01b03169d6101008d01996138c56138978c516001600160801b031690565b926138a0611cb7565b908152336020820152825194859160208301613685565b03601f198101855284611c18565b5163f6b9a60160e01b81529e8f9889978896600488016136fe565b0392600180871b03165af1968715613a1f575b6000968798889789928a926139df575b50888b9a9b6139206114fc6101208c01516001600160801b031690565b81106139c6575061393f6114fc6101408b01516001600160801b031690565b81116139ad57509061395c613958610160949351151590565b1590565b156139a55750955b0151851161398e57506139846114fc61398b92516001600160801b031690565b8094613748565b91565b51639c56bf3160e01b815260048101859052602490fd5b905095613964565b84516315481e3160e01b81526004810191909152602490fd5b8551636d24d5ef60e01b81526004810191909152602490fd5b93995097505050613a0891975060a03d8111613a18575b613a008183611c18565b8101906136d7565b9299939891979192909138613903565b503d6139f6565b613a27612bc7565b6138f3565b8551630b46947360e11b81526004810191909152602490fd5b620f4240908060001904821181151516613a5d570290565b613a65612d7e565b0290565b8060001904821181151516613a5d570290565b50634e487b7160e01b600052601260045260246000fd5b8015613aa1575b6000190490565b613aa9613a7c565b613a9a565b8115613ab8570490565b613ac0613a7c565b0490565b6445d964b800620f4240916409502f9000808211600014613b2657505b600019620249f0821515838304821116613b19575b82028015159104621e84801116613b0c57020490565b613b14612d7e565b020490565b613b21612d7e565b613af6565b9050613ae1565b91908260809103126102aa57604051608081018181106001600160401b03821117613b9e575b60405260608082948035613b66816104d3565b84526020810135613b76816104d3565b60208501526040810135613b8981612f93565b6040850152013591613b9a836104d3565b0152565b613ba6611b90565b613b53565b60a0818303126102aa57608090613bce60405193613bc885611ba7565b82613b2d565b83520135613bdb816104d3565b602082015290565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116949290828116861480613d09575b15613ce757505050823b156102aa57613c8e92602092604051630d0e30db60e41b815260008160048187875af18015613cda575b613cc7575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af18015613cba575b613ca05750565b613cb79060203d81116133f2576133e48183611c18565b50565b613cc2612bc7565b613c99565b80610af5613cd492611bcf565b38613c55565b613ce2612bc7565b613c50565b9194509192919081163003613d005750612fd2926135c2565b612fd293613d13565b5083471015613c1c565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b038092166024850152166044830152606482015260648152613d5681611bfd565b51925af1613d62612bd4565b81613d9b575b5015613d7057565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b8051801592508215613db0575b505038613d68565b613dc392506020809183010191016135ad565b3880613da8565b91908260409103126102aa576020825192015190565b90926001600160601b03608093610394969560018060a01b03168452166020830152600f0b6040820152816060820152019061035e565b8051613e7b92906001600160a01b0316602083018051909391613f1e91613ef3906001600160a01b0316916040978893610e08613e598689015162ffffff1690565b6060890151613e70906001600160a01b0316610dd2565b62ffffff1684870152565b613eab610e3e610e3e837f0000000000000000000000000000000000000000000000000000000000000000615342565b906000613ec260a08801516001600160601b031690565b613f01613ed360c08a0151600f0b90565b93613edc611cb7565b908152336020820152875196879160208301613685565b03601f198101875286611c18565b855163462278df60e01b8152968795869485933060048601613de0565b03925af1908115613fb2575b6000958692613f8d575b50909390508415613f7e575080516001600160a01b03165b613f5581613fbf565b9081613f6057505050565b60809290920151612fd292906001600160a01b03165b903090613be3565b516001600160a01b0316613f4c565b613fa893965080919250903d10611960576119528183611c18565b9390933880613f34565b613fba612bc7565b613f2a565b6040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa908115614013575b600091613ffb575090565b610394915060203d8111610b3757610b288183611c18565b61401b612bc7565b613ff0565b908160609103126102aa578051916040602083015192015190565b6001600160601b03610394949360609360018060a01b03168352166020820152816040820152019061035e565b805161416491606091613ef391906001600160a01b031660208201516140c9906001600160a01b03166140ba6140a4604086015162ffffff1690565b85880151611f13906001600160a01b0316610dd2565b6001600160a01b031682860152565b60006140fb610e3e610e3e847f0000000000000000000000000000000000000000000000000000000000000000615342565b9261414761412660a0614117608085015160018060a01b031690565b9301516001600160601b031690565b9361412f611cb7565b90815233602082015260405196879160208301613685565b60405163bf25901d60e01b8152968795869485936004850161403b565b03925af19081156141b9575b60009182918391614188575b50909192612fd2613674565b9150506141ac915060603d81116141b2575b6141a48183611c18565b810190614020565b3861417c565b503d61419a565b6141c1612bc7565b614170565b805190916142b1916001600160a01b031660606138b7602086019261422c6141f4855160018060a01b031690565b61421d61420760408b015162ffffff1690565b8a870151611f13906001600160a01b0316610dd2565b6001600160a01b031682850152565b614259610e3e827f0000000000000000000000000000000000000000000000000000000000000000615342565b9061429261427160a08a01516001600160601b031690565b9161427a611cb7565b90815230602082015260405194859160208301613685565b600060405180988195829463bf25901d60e01b8452306004850161403b565b03926001600160a01b03165af1801561438f575b6000938491614369575b509260001315614359575082516001600160a01b0316925b6142f084613fbf565b9360c08201518510614340576080612fd29261431d928780614322575b505001516001600160a01b031690565b613456565b8284015161433992906001600160a01b0316613f76565b388761430d565b604051636b19f1cf60e11b815260048101869052602490fd5b516001600160a01b0316926142e7565b905061438491935060603d81116141b2576141a48183611c18565b9391905092386142cf565b614397612bc7565b6142c5565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a0608082018190526103949291019061035e565b476143dc57565b477f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156102aa57600090600460405180948193630d0e30db60e41b83525af1801561443d575b6144345750565b612fd290611bcf565b614445612bc7565b61442d565b604051906101a082018281106001600160401b038211176144bd575b604052816101806000918281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201520152565b6144c5611b90565b614466565b90816101a09103126102aa5780516144e181612fb6565b9160208201516144f081612fb6565b9160408101516144ff81612fb6565b9161450c60608301612fc7565b9161451960808201612fc7565b9161452660a08301613001565b9161453360c08201613001565b9161454060e08301612fd4565b9161454e6101008201612fe2565b9161455c6101208301612ff3565b9161456a6101408201612fc7565b9161018061457b6101608401612fc7565b92015190565b908160209103126102aa575161039481612f93565b9291906145a161444a565b5061010084019063ffffffff91828151169386858585161461474357610394966146a59561469a9360069203820b97860316810b61039802810b90876145ed61395860a0860151151590565b156146e05761463162049d4061468a9461467894614617614673956116026101208b015160060b90565b9182820b818113156146b0575091505b0b0560020b614c05565b6001600160801b03614661604061465260208901516001600160801b031690565b9701516001600160801b031690565b6001600160a01b0390921691166149c6565b614b9c565b915b6001600160801b031660208a0152565b6001600160801b03166040880152565b9063ffffffff169052565b60060b610120830152565b6146c26146bc836148b8565b60060b90565b136146ce575b50614627565b6146d99192506148b8565b90386146c8565b6146739261470a9261461762049d409361470261012061472699015160060b90565b900360060b90565b6001600160801b0361466160208c01516001600160801b031690565b61468a61473d60408a01516001600160801b031690565b9161467a565b5050505050505090565b620f424081198111612da5570190565b81198111612da5570190565b9061478061477b60e084015160020b90565b614c05565b9061479161395860a0850151151590565b1561484c57614814916147d86147cf6114fc936147c962ffffff6147c26114fc60408b01516001600160801b031690565b921661474d565b90613a69565b620f4240900490565b6001600160a01b03909116906001600160801b038211614833576147ff8261480593613a69565b90614b6c565b925b516001600160801b031690565b9060008282111561482d57506103949161467391613748565b91505090565b6148408261484693614a0b565b90614adf565b92614807565b614814916148786147cf6114fc936147c962ffffff6147c26114fc60208b01516001600160801b031690565b6001600160a01b03909116906001600160801b0382116148a55761489f8261480593613a69565b90614a9a565b6148b28261484693614a0b565b90614a55565b60060b667fffffffffffff1981146132505760000390565b91906148e261395860a0850151151590565b1561495b5761494d61493a6149156147cf614956956147c962ffffff6147c26114fc60408c01516001600160801b031690565b946149346114fc6148056114fc6101408501516001600160801b031690565b9061475d565b6001600160a01b039092169182906149c6565b9260601b613aae565b111590565b6149c46149b16149ab61498c6147cf614956966147c962ffffff6147c26114fc60208d01516001600160801b031690565b956149346114fc6148056114fc6101408501516001600160801b031690565b60601b90565b6001600160a01b03909216918290613aae565b925b6000198282099082810292838084109303928084039314614a0257600160601b91838311156102aa570990828211900360a01b910360601c1790565b50505060601c90565b6000198282099082810292838084109303928084039314614a4c576801000000000000000091838311156102aa570990828211900360c01b910360401c1790565b50505060401c90565b6000198282099082810292838084109303928084039314614a9157600160801b91838311156102aa570990828211900360801b910360801c1790565b50505060801c90565b6000198282099082810292838084109303928084039314614ad657600160c01b91838311156102aa570990828211900360401b910360c01c1790565b50505060c01c90565b600160801b91600019838309928260801b92838086109503948086039514614b5f57908291614b0f868411612ecc565b096001821901821680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b5050906103949250613aae565b600160c01b91600019838309928260c01b92838086109503948086039514614b5f57908291614b0f868411612ecc565b6001600160801b0390818111614bb0571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608490fd5b60020b6000811215614f6f5780600003905b620d89e88211614f5d576001821615614f4b576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b169160028116614f2f575b60048116614f13575b60088116614ef7575b60108116614edb575b60208116614ebf575b60408116614ea3575b608090818116614e88575b6101008116614e6d575b6102008116614e52575b6104008116614e37575b6108008116614e1c575b6110008116614e01575b6120008116614de6575b6140008116614dcb575b6180008116614db0575b620100008116614d95575b620200008116614d7b575b620400008116614d61575b6208000016614d46575b50600012614d38575b63ffffffff8116614d30576000905b60201c60ff91909116016001600160a01b031690565b600190614d1a565b614d4190613a93565b614d0b565b6b048a170391f7dc42444e8fa26000929302901c9190614d02565b6d2216e584f5fa1ea926041bedfe98909302811c92614cf8565b926e5d6af8dedb81196699c329225ee60402811c92614ced565b926f09aa508b5b7a84e1c677de54f3e99bc902811c92614ce2565b926f31be135f97d08fd981231505542fcfa602811c92614cd7565b926f70d869a156d2a1b890bb3df62baf32f702811c92614ccd565b926fa9f746462d870fdf8a65dc1f90e061e502811c92614cc3565b926fd097f3bdfd2022b8845ad8f792aa582502811c92614cb9565b926fe7159475a2c29b7443b29c7fa6e889d902811c92614caf565b926ff3392b0822b70005940c7a398e4b70f302811c92614ca5565b926ff987a7253ac413176f2b074cf7815e5402811c92614c9b565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92614c91565b926ffe5dee046a99a2a811c461f1969c305302811c92614c87565b916fff2ea16466c96a3843ec78b326b528610260801c91614c7c565b916fff973b41fa98c081472e6896dfb254c00260801c91614c73565b916fffcb9843d60f6159c9db58835c9266440260801c91614c6a565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91614c61565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91614c58565b916ffff97272373d413259a46990580e213a0260801c91614c4f565b6001600160881b03600160801b614c44565b6040516315e4079d60e11b8152600490fd5b80614c17565b60405163c19d93fb60e01b815261010092918390829060049082906001600160a01b03165afa90811561500b575b6000928392849285968692879288928992614fe1575b50509091889596979863ffffffff8042169586031660060b9060020b0260060b0160060b9293565b965096505050505093506150019250803d1061223d576122278183611c18565b9397933880614fb9565b615013612bc7565b614fa3565b908160209103126102aa5751610394816104d3565b60405190606082018281106001600160401b0382111761505a575b60405260028252604082602036910137565b615062611b90565b615048565b81601f820112156102aa5780519161507e83612d0e565b9261508c6040519485611c18565b808452602092838086019260051b8201019283116102aa578301905b8282106150b6575050505090565b83809183516150c4816104d3565b8152019101906150a8565b9190916040818403126102aa578051926001600160401b03938481116102aa5782019381601f860112156102aa57845161510881612d0e565b906151166040519283611c18565b808252602096878084019260051b820101918583116102aa5788809201905b8382106151555750505050948301519081116102aa576103949201615067565b82809161516184612ff3565b815201910190615135565b6020908160408183019282815285518094520193019160005b828110615193575050505090565b835163ffffffff1685529381019392810192600101615185565b60006152186040516307dc0d1d60e41b815260208160048160018060a01b038098165afa90811561528a575b839161525c575b506151e961502d565b6151fc6151f582612e83565b61a8c09052565b60405194858094819363883bdbfd60e01b83526004830161516c565b0392165afa90811561524f575b600091615230575090565b61524b913d8091833e6152438183611c18565b8101906150cf565b5090565b615257612bc7565b615225565b61527d915060203d8111615283575b6152758183611c18565b810190615018565b386151e0565b503d61526b565b615292612bc7565b6151d9565b916152b9909493919460e084019361a8c085519460060b0560020b8552614769565b936001600160801b03808616908216116152d6575b5060020b9052565b9350386152ce565b6001600160a01b03916152f091615342565b16908133036152fb57565b604051635cf3778960e01b8152600490fd5b8161531791615342565b50606001516001600160a01b0316903382900361533057565b6040516383b1c28760e01b8152600490fd5b81519192916020906001600160a01b0316848201516001600160a01b0316906153cc615388606061537960408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa928315615426575b600093615406575b508216156153f457565b604051630f509b1160e01b8152600490fd5b61541f91935060203d8111615283576152758183611c18565b91386153ea565b61542e612bc7565b6153e2565b80156154c75780806001146154c0576002146154ba576001908161013382101682600b831016176154b257906002815b80821161547b57505081600019048111613a5d570290565b9092806000190481116154a5575b81841661549c575b800292811c90615463565b80920291615491565b6154ad612d7e565b615489565b600291500a90565b50600490565b5050600190565b50600090565b62ffffff8091169081620f424091038111612da5570190565b6001600160801b0380821695939490926001600160a01b0316919082156155c9575b61551283886149c6565b906155c0575060601b6fffffffffffffffffffffffffffffffff60601b1604915b1691818310156155a757826155948361558e615570946146739761039499971061559a575b61558861558061557a615575866155708a8203615433565b613aae565b613a45565b926154cd565b62ffffff1690565b90613aae565b90613748565b92613a69565b6155a2612d7e565b615558565b60405163c74656a760e01b815260048101839052602490fd5b91505091615533565b6155d1613a7c565b61550856fea2646970667358221220f65bfcb6e1f353c07efe8010508e022f4f20a95397d131d48576cb3ea4fa805464736f6c634300080f0033000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b1400000000000000000000000036fc580af2cd4baf325c26aac8b95a8fd464c1a8

Deployed Bytecode

0x60806040526004361015610023575b361561001957600080fd5b6100216132fc565b005b60003560e01c806301ffc9a71461028f57806306fdde0314610286578063081812fc1461027d578063095ea7b31461027457806312210e8a1461026b578063156e1ef4146102625780631e121fe81461025957806321e818e01461025057806323b872dd1461024757806342842e0e1461023e57806349404b7c146102355780634aa4a4fc1461022c5780635b549182146102235780635f1c4fdc1461021a5780636352211e146102115780636bf392631461020857806370a08231146101ff57806389051db6146101f657806395d89b41146101ed57806399fbab88146101e4578063a22cb465146101db578063a24e4f7a146101d2578063ac9650d8146101c9578063b88d4fde146101c0578063c45a0155146101b7578063c87b56dd146101ae578063d3e17b03146101a5578063d44959461461019c578063df2ab5bb14610193578063e985e9c51461018a5763fa461e330361000e5761018561261a565b61000e565b506101856125b1565b5061018561250a565b50610185612251565b50610185611ec4565b50610185611df6565b50610185611db0565b50610185611d1f565b50610185611a8d565b506101856117d6565b506101856116e5565b50610185611329565b50610185611267565b50610185611063565b50610185610fac565b50610185610d2a565b50610185610d0b565b50610185610bd7565b50610185610b91565b50610185610b4b565b50610185610a20565b506101856109f7565b506101856109cd565b506101856108fe565b50610185610842565b506101856105e4565b506101856105bd565b506101856104e4565b506101856104a2565b50610185610397565b506101856102af565b6001600160e01b03198116036102aa57565b600080fd5b50346102aa5760203660031901126102aa5760206004356102cf81610298565b63ffffffff60e01b166380ac58cd60e01b811490811561030d575b81156102fc575b506040519015158152f35b6301ffc9a760e01b149050386102f1565b635b5e139f60e01b811491506102ea565b60009103126102aa57565b918091926000905b828210610349575011610342575050565b6000910152565b91508060209183015181860152018291610331565b9060209161037781518092818552858086019101610329565b601f01601f1916010190565b90602061039492818152019061035e565b90565b50346102aa5760008060031936011261049f57604051908080549060019180831c92808216928315610495575b60209283861085146104815785885260208801949081156104605750600114610408575b610404876103f881890382611c18565b60405191829182610383565b0390f35b6000805294509192917f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5635b83861061044f57505050910190506103f88261040438806103e8565b805485870152948201948101610433565b60ff191685525050505090151560051b0190506103f88261040438806103e8565b634e487b7160e01b82526022600452602482fd5b93607f16936103c4565b80fd5b50346102aa5760203660031901126102aa5760206104c16004356127bf565b6040516001600160a01b039091168152f35b6001600160a01b038116036102aa57565b50346102aa5760403660031901126102aa57600435610502816104d3565b60243561050e8161272a565b916001600160a01b03808416908216811461056e576100219361053b913314908115610540575b5061274d565b612b1b565b6001600160a01b0316600090815260056020908152604080832033845290915290205460ff16905038610535565b60405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e656044820152603960f91b6064820152608490fd5b5060003660031901126102aa57610021613674565b6101009060031901126102aa57600490565b50346102aa576101003660031901126102aa57610600366105d2565b608081013561060f81336128ea565b156108315761062460e0830135421115612f16565b610638816000526006602052604060002090565b61064190612ed3565b61064a83612f89565b92602081019061065982612f89565b946040938483019161066a83612fac565b9760608501986106798a612f89565b91610682611c39565b6001600160a01b0390941684526001600160a01b0316602084015262ffffff16828801526001600160a01b031660608201526106de907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b81516001600160a01b0390811691160361082057610706866000526006602052604060002090565b600090556107138661326e565b61071c83612f89565b9361072690612f89565b9161073090612fac565b9661073a90612f89565b60c084019761074889612f89565b6020909301516001600160601b031693610760611c58565b6001600160a01b0390971687526001600160a01b0316602087015262ffffff16858701526001600160a01b031660608501526001600160a01b031660808401526001600160601b031660a083015260a0013560c08201526107c0906141c6565b926107cb8295612f89565b83516001600160a01b0391909116815260208101929092526040820184905233917f34270365a3c76bc9895ec91ac488337da0e12eee459cd8eec127882f8dd29a5990606090a3519182526020820152604090f35b845163c256622b60e01b8152600490fd5b6040516282b42960e81b8152600490fd5b5060403660031901126102aa5760243561085b816104d3565b476004358110610875578061086c57005b61002191613515565b60405162461bcd60e51b815260206004820152601060248201526f092dce6eaccccd2c6d2cadce8408aa8960831b6044820152606490fd5b9060606003198301126102aa5760043591602435916044356001600160401b03928382116102aa57806023830112156102aa5781600401359384116102aa57602484830101116102aa576024019190565b50346102aa5761091c610910366108ad565b81949293940190613bab565b9161094883517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26152de565b508061097a575b508061095757005b81516020908101519201516100219233916001600160a01b039081169116613be3565b825151602084015161099b929133916001600160a01b039081169116613be3565b3861094f565b60609060031901126102aa576004356109b9816104d3565b906024356109c6816104d3565b9060443590565b50346102aa576100216109df366109a1565b916109f26109ed84336128ea565b6127fd565b6129bc565b50346102aa57610021610a09366109a1565b9060405192610a1784611be2565b6000845261285f565b5060403660031901126102aa57602435610a39816104d3565b6040516370a0823160e01b81523060048201526001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141691602082602481865afa918215610b3e575b600092610b0e575b50610a9f600435831015613415565b81610aa657005b823b156102aa57604051632e1a7d4d60e01b815260048101839052610021936000908290818381602481015b03925af18015610b01575b610ae8575b50613515565b80610af5610afb92611bcf565b8061031e565b38610ae2565b610b09612bc7565b610add565b610b3091925060203d8111610b37575b610b288183611c18565b810190613406565b9038610a90565b503d610b1e565b610b46612bc7565b610a88565b50346102aa5760003660031901126102aa576040517f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b146001600160a01b03168152602090f35b50346102aa5760003660031901126102aa576040517f0000000000000000000000000227628f3f023bb0b980b67d528571c95c6dac1c6001600160a01b03168152602090f35b50346102aa57610be9610910366108ad565b91610c1583517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26152de565b5080610ca1575b5080610c2457005b815160209081015161002193610c5f9291610c47906001600160a01b0316613fbf565b808511610c68575b505101516001600160a01b031690565b33903090613be3565b8151830151610c9b91906001600160a01b031683850151610c93906001600160a01b03169288613748565b913091613be3565b38610c4f565b825151610cd59190610cbb906001600160a01b0316613fbf565b808211610cdb575b508351516001600160a01b0316610c5f565b38610c1c565b845151610d0591906001600160a01b03166020870151610c93906001600160a01b03169285613748565b38610cc3565b50346102aa5760203660031901126102aa5760206104c160043561272a565b50346102aa576101003660031901126102aa57610d46366105d2565b608081013590610d5682336128ea565b156108315780610d6f60e0610dd2930135421115612f16565b610d8b610d86846000526006602052604060002090565b612ed3565b90610d9581612f89565b916020820191610da483612f89565b91610e4a610e3e610e3e604097610e1889870197610e08610dc48a612fac565b610dfd60608b019e8f612f89565b93610ded610dde611c39565b6001600160a01b039098168852565b6001600160a01b03166020870152565b62ffffff16848d0152565b6001600160a01b03166060830152565b7f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b6001600160a01b031690565b8151610e5e906001600160a01b0316610e3e565b6001600160a01b039091160361082057610e7782612f89565b93610e8190612f89565b92610e8b90612fac565b95610e9590612f89565b60c0830196610ea388612f89565b6020909301516001600160601b03169360a001610ebf906130cc565b6001600160801b0316600f0b610ed49061322e565b94610edd611c58565b6001600160a01b0390971687526001600160a01b0316602087015262ffffff16858701526001600160a01b031660608501526001600160a01b031660808401526001600160601b031660a0830152600f0b60c0820152610f3c90613e17565b6104049491610f52918115610fa4575093612f89565b82516001600160a01b039091168152602081018490523391907f352b6077a9209bc984c0f5dd020d42bf741232cd6401c9bbac47115f7a741d8d9080604081015b0390a3519081529081906020820190565b905093612f89565b50346102aa5760203660031901126102aa57600435610fca816104d3565b6001600160a01b03168015610ffb576000526003602052610404604060002054604051918291829190602083019252565b60405162461bcd60e51b815260206004820152602960248201527f4552433732313a2061646472657373207a65726f206973206e6f7420612076616044820152683634b21037bbb732b960b91b6064820152608490fd5b60e09060031901126102aa57600490565b5060e03660031901126102aa5761107936611052565b608081013561108881336128ea565b1561083157816110a160c0610e3e940135421115612f16565b6110b8610d86836000526006602052604060002090565b906110c281612f89565b9060208101926110d184612f89565b92611138610e3e6040988993610e1885880198610e086110f08b612fac565b60608b019861112c6111018b612f89565b9461111c61110d611c39565b6001600160a01b039099168952565b6001600160a01b03166020880152565b85019062ffffff169052565b825161114c906001600160a01b0316610e3e565b6001600160a01b03909116036112565761116583612f89565b9461116f90612f89565b9361117990612fac565b9061118390612f89565b6020909201516001600160601b03169260a00161119f906130cc565b6001600160801b0316600f0b936111b4611c58565b6001600160a01b0390961686526001600160a01b0316602086015262ffffff16848701526001600160a01b031660608401523360808401526001600160601b031660a0830152600f0b60c082015261120b90613e17565b610404939190811561124e5750915b81518381523391907f8738fac4c3f6ded3649d1d6c64679bd1a81c89414e861f2ca28b5fc585c0e33d908060208101610f93565b90509161121a565b865163c256622b60e01b8152600490fd5b50346102aa5760008060031936011261049f576040519080600190815480831c9280821692831561131f575b602092838610851461048157858852602088019490811561046057506001146112c657610404876103f881890382611c18565b600160005294509192917fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf65b83861061130e57505050910190506103f88261040438806103e8565b8054858701529482019481016112f2565b93607f1693611293565b50346102aa576020806003193601126102aa576000600435815260068252816113f060408320926040519361135d85611ba7565b546001600160a01b03811680865260a09190911c95909401859052808061138261444a565b506040513060601b6bffffffffffffffffffffffff191686820190815260a089901b6001600160a01b03191660148201526101a0916113ce81602084015b03601f198101835282611c18565b5190206040518096819263514ea4bf60e01b8352600483019190602083019252565b0381895afa9384156116ce575b82839084918592868a818283918499859e61167e575b5061141c611c77565b6001600160801b03891681529384019661143f9088906001600160801b03169052565b60408401956114579087906001600160801b03169052565b606084018590526080840185905288151560a08501528b151560c085015260020b60e084015263ffffffff1661010083015260060b6101208201526001600160801b038716610140820152816101608201528a6101808201528c604051636c376cc560e01b81528d8183815a91600492fa9081159e6104049f611671575b8592611644575b50506114e88184614769565b6115086114fc85516001600160801b031690565b6001600160801b031690565b6115af575b50505050508360001461159d5750516001600160801b0316915b604080516001600160a01b03909b168b526001600160601b03909b1660208b01521515998901999099526001600160801b03988916606089015288166080880152871660a08701529590951660c085015293151560e0840152921515610100830152610120820192909252908190610140820190565b516001600160801b0316905091611527565b9091929b5061163a9399506116158c6115d96115ca86614f75565b505095945099925050506151ad565b9561160f6115ef6116096115f66115ef8b612e83565b5160060b90565b6116026115ef8c612e99565b0360060b90565b98612e99565b92614596565b50611634828d61162e61a8c08760060b0560020b614c05565b906148d0565b9b615297565b95388c818061150d565b6116639250803d1061166a575b61165b8183611c18565b810190614581565b38806114dc565b503d611651565b611679612bc7565b6114d5565b9850505050975098505050506116ae91506101a03d6101a0116116c7575b6116a68183611c18565b8101906144ca565b9f959d919b969a96999698509596509394509138611413565b503d61169c565b6116d6612bc7565b6113fd565b801515036102aa57565b50346102aa5760403660031901126102aa57600435611703816104d3565b60243561170f816116db565b6001600160a01b03821691338314611791578161174e61175f9233600052600560205260406000209060018060a01b0316600052602052604060002090565b9060ff801983541691151516179055565b604051901515815233907f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3190602090a3005b60405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c6572000000000000006044820152606490fd5b50346102aa576117e5366108ad565b92909160009384831393841580611a21575b611a045761180791810190613bab565b9261183384517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26152de565b506020840180519091906001600160a01b0316906001600160a01b03821630036119a257505050916040916118f69361186a6143d5565b82516060015186821391879161188a90610e3e906001600160a01b031681565b938315611992575061189b9061325d565b915b8015611974576119046401000276a4955b5187519889916020830181516001600160a01b03908116825260208084015182169083015260408084015162ffffff1690830152606092830151169181019190915260800190565b03601f198101895288611c18565b611924865197889687958694630251596160e31b8652336004870161439c565b03925af18015611967575b61193a575b50604051f35b61195a9060403d8111611960575b6119528183611c18565b810190613dca565b50611934565b503d611948565b61196f612bc7565b61192f565b61190473fffd8963efd1fc6a506488495d951d5263988d25956118ae565b61199c915061325d565b9161189d565b93909192936119e6575b50508382136119be575b505050604051f35b91516020015191516119de926001600160a01b0390811691163391613be3565b3880806119b6565b8451516119fd9233916001600160a01b0316613be3565b38806119ac565b604051636d24d5ef60e01b815260006004820152602490fd5b0390fd5b50858313156117f7565b602080820190808352835180925260408301928160408460051b8301019501936000915b848310611a5f5750505050505090565b9091929394958480611a7d600193603f198682030187528a5161035e565b9801930193019194939290611a4f565b5060203660031901126102aa57600480356001600160401b03918282116102aa57366023830112156102aa57818101359283116102aa57602490818301928236918660051b0101116102aa57611ae284612d34565b9360005b818110611afb57604051806104048882611a2b565b600080611b09838589612dc8565b60409391611b1b855180938193612e17565b0390305af490611b29612bd4565b91829015611b5857505090611b5391611b428289612eaa565b52611b4d8188612eaa565b50612d95565b611ae6565b8683879260448251106102aa5782611a1d9385611b7b9401518301019101612e25565b925162461bcd60e51b81529283928301610383565b50634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b03821117611bc257604052565b611bca611b90565b604052565b6001600160401b038111611bc257604052565b602081019081106001600160401b03821117611bc257604052565b60a081019081106001600160401b03821117611bc257604052565b90601f801991011681019081106001600160401b03821117611bc257604052565b60405190608082018281106001600160401b03821117611bc257604052565b6040519060e082018281106001600160401b03821117611bc257604052565b604051906101a082018281106001600160401b03821117611bc257604052565b6040519061018082018281106001600160401b03821117611bc257604052565b60405190604082018281106001600160401b03821117611bc257604052565b6040519060c082018281106001600160401b03821117611bc257604052565b6020906001600160401b038111611d12575b601f01601f19160190565b611d1a611b90565b611d07565b50346102aa5760803660031901126102aa57600435611d3d816104d3565b602435611d49816104d3565b606435916001600160401b0383116102aa57366023840112156102aa57826004013591611d7583611cf5565b92611d836040519485611c18565b80845236602482870101116102aa576020816000926024610021980183880137850101526044359161285f565b50346102aa5760003660031901126102aa576040517f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c26001600160a01b03168152602090f35b50346102aa5760203660031901126102aa576004356000818152600260205260409020546001600160a01b0316156102aa5760405163e9dc637560e01b81523060048201526024810191909152610404906000816044817f00000000000000000000000036fc580af2cd4baf325c26aac8b95a8fd464c1a86001600160a01b03165afa908115611eb7575b600091611e96575b5060405191829182610383565b611eb1913d8091833e611ea98183611c18565b810190612e25565b38611e89565b611ebf612bc7565b611e81565b506101a03660031901126102aa57611ee161018435421115612f16565b611f1f610e3e610e3e611ef2612f58565b610e18611efd612f64565b610e08611f08612fa0565b611f13610dd2612f70565b62ffffff166040850152565b60405163c19d93fb60e01b81526101009190611f6f908381600481865afa908115612244575b600090819261220d575b50611f58612fa0565b611f6061308f565b91611f6961309b565b936154e6565b91611f78612f58565b90611f81612f64565b90611f8a612fa0565b90611f93612f70565b90611f9c61308f565b6001600160a01b039790919088611fb16130d6565b166121ff57611fbe61308f565b156121e5576401000276a45b905b611fd46130a7565b93611fdd6130b4565b956001600160801b0380611fef6130c0565b166121d657975b61010435806121d05750600019995b61200d611c97565b6001600160a01b03909c168c526001600160a01b031660208c015262ffffff1660408b01526001600160a01b031660608a01523060808a0152151560a08901526001600160801b031660c08801526001600160a01b031660e08701526001600160801b03909116908501526001600160801b03166101208401526001600160801b03166101408301526101608201526120a59061375f565b9395949092966120b3612f7c565b90600754968792836120c481612d95565b6007556120d09161312f565b6120d8611cb7565b6001600160a01b0390911681526001600160601b0384166020820152612108836000526006602052604060002090565b9061213591815160209092015160a01b6001600160a01b0319166001600160a01b03909216919091179055565b61213d613674565b612145612f7c565b6040805133815260208101959095528401899052606084018a90526080840185905260a0840186905260c0840187905216917f2285d52eb6c0af06e33f4610840cc004ae11e19814110bf092b80f3f04e4012e9060e090a360405195869561040495879260a094919796959260c0850198855260208501526040840152606083015260808201520152565b99612005565b506121df6130c0565b97611ff6565b73fffd8963efd1fc6a506488495d951d5263988d25611fca565b6122076130d6565b90611fcc565b905061222f9150843d861161223d575b6122278183611c18565b81019061300c565b505050505091905038611f4f565b503d61221d565b61224c612bc7565b611f45565b5060e03660031901126102aa5761226736611052565b608081013561227681336128ea565b156108315761228b60c0830135421115612f16565b61229f816000526006602052604060002090565b6122a890612ed3565b916122b281612f89565b92602082016122c081612f89565b94604092838501916122d183612fac565b9760608701986122e08a612f89565b916122e9611c39565b6001600160a01b0390941684526001600160a01b0316602084015262ffffff16828701526001600160a01b03166060820152612345907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b81516001600160a01b039081169116036124f95760009485612371886000526006602052604060002090565b5561237b8761326e565b61238481612f89565b9361238e90612f89565b9261239890612fac565b976123a290612f89565b9060a001976123b089612f89565b6020909301516001600160601b0316936123c8611cd6565b6001600160a01b0390961686526001600160a01b0316602086015262ffffff16848601526001600160a01b031660608401526001600160a01b031660808301526001600160601b031660a082015261241f90614068565b918495919550848113600014612478610404967f39f70f0fcd9366a4cc0388b64242d1bba1933d1d50cdd337b894d88c4258a680936124a9936124e35780995b828212156124c95750612472915061325d565b98612f89565b85516001600160a01b0390911681526020810188905260408101899052606081019490945233939081906080820190565b0390a3519283928360409060009294936060820195825260208201520152565b9050818112156124dd57612472915061325d565b50612472565b818a13156124f357895b9961245f565b816124ed565b835163c256622b60e01b8152600490fd5b5060603660031901126102aa57600435612523816104d3565b60443561252f816104d3565b6040516370a0823160e01b8152306004820152906020826024816001600160a01b0387165afa9182156125a4575b600092612584575b5061257460243583101561356c565b8161257b57005b610021926135c2565b61259d91925060203d8111610b3757610b288183611c18565b9038612565565b6125ac612bc7565b61255d565b50346102aa5760403660031901126102aa57602060ff61260e6004356125d6816104d3565b602435906125e3826104d3565b60018060a01b03166000526005845260406000209060018060a01b0316600052602052604060002090565b54166040519015158152f35b50346102aa57612629366108ad565b919092600093848213938480156126d5575b156126d15781016080828203126126d15761265591613b2d565b92612680847f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c261530d565b506126b6575b50828113612695575b82604051f35b602091909101516126af91906001600160a01b0316610c5f565b388061268f565b82516126cb91906001600160a01b0316610c5f565b38612686565b8580fd5b5085841361263b565b156126e557565b60405162461bcd60e51b815260206004820152601860248201527f4552433732313a20696e76616c696420746f6b656e20494400000000000000006044820152606490fd5b6000908152600260205260409020546001600160a01b03166103948115156126de565b1561275457565b60405162461bcd60e51b815260206004820152603d60248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f7420746f60448201527f6b656e206f776e6572206f7220617070726f76656420666f7220616c6c0000006064820152608490fd5b6000818152600260205260409020546127e2906001600160a01b031615156126de565b6000908152600460205260409020546001600160a01b031690565b1561280457565b60405162461bcd60e51b815260206004820152602d60248201527f4552433732313a2063616c6c6572206973206e6f7420746f6b656e206f776e6560448201526c1c881bdc88185c1c1c9bdd9959609a1b6064820152608490fd5b906128839392916128736109ed84336128ea565b61287e8383836129bc565b612c04565b1561288a57565b60405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b6001600160a01b03806128fc8461272a565b169281831692848414948515612932575b5050831561291c575b50505090565b612928919293506127bf565b1614388080612916565b60009081526005602090815260408083206001600160a01b03949094168352929052205460ff169350388061290d565b1561296957565b60405162461bcd60e51b815260206004820152602560248201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060448201526437bbb732b960d91b6064820152608490fd5b6129e0906129c98461272a565b6001600160a01b0382811693909182168414612962565b8316928315612aca57612a47612aa192612a0685612a00610e3e8a61272a565b14612962565b612a2d612a1d886000526004602052604060002090565b80546001600160a01b0319169055565b6001600160a01b0316600090815260036020526040902090565b80546000190190556001600160a01b038116600090815260036020526040902060018154019055612a82856000526002602052604060002090565b80546001600160a01b0319166001600160a01b03909216919091179055565b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6000604051a4565b60405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b600082815260046020526040902080546001600160a01b0319166001600160a01b0383161790556001600160a01b0380612b548461272a565b169116907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9256000604051a4565b908160209103126102aa575161039481610298565b6001600160a01b0391821681529116602082015260408101919091526080606082018190526103949291019061035e565b506040513d6000823e3d90fd5b3d15612bff573d90612be582611cf5565b91612bf36040519384611c18565b82523d6000602084013e565b606090565b92909190823b15612d0557612c37926020926000604051809681958294630a85bd0160e11b9a8b85523360048601612b96565b03926001600160a01b03165af160009181612cd5575b50612cc757612c5a612bd4565b80519081612cc25760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b602001fd5b6001600160e01b0319161490565b612cf791925060203d8111612cfe575b612cef8183611c18565b810190612b81565b9038612c4d565b503d612ce5565b50505050600190565b6020906001600160401b038111612d27575b60051b0190565b612d2f611b90565b612d20565b90612d3e82612d0e565b612d4b6040519182611c18565b8281528092612d5c601f1991612d0e565b019060005b828110612d6d57505050565b806060602080938501015201612d61565b50634e487b7160e01b600052601160045260246000fd5b6001906000198114612da5570190565b612dad612d7e565b0190565b50634e487b7160e01b600052603260045260246000fd5b9190811015612e0a575b60051b81013590601e19813603018212156102aa5701908135916001600160401b0383116102aa5760200182360381136102aa579190565b612e12612db1565b612dd2565b908092918237016000815290565b6020818303126102aa578051906001600160401b0382116102aa570181601f820112156102aa578051612e5781611cf5565b92612e656040519485611c18565b818452602082840101116102aa576103949160208085019101610329565b602090805115612e91570190565b612dad612db1565b604090805160011015612e91570190565b6020918151811015612ebf575b60051b010190565b612ec7612db1565b612eb7565b156102aa57565b90604051604081018181106001600160401b03821117612f09575b60405291546001600160a01b038116835260a01c6020830152565b612f11611b90565b612eee565b15612f1d57565b60405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b6044820152606490fd5b600435610394816104d3565b602435610394816104d3565b606435610394816104d3565b61016435610394816104d3565b35610394816104d3565b62ffffff8116036102aa57565b60443561039481612f93565b3561039481612f93565b6001600160801b038116036102aa57565b5190612fd282612fb6565b565b51908160020b82036102aa57565b519063ffffffff821682036102aa57565b51908160060b82036102aa57565b5190612fd2826116db565b9190826101009103126102aa578151613024816104d3565b9160208101516001600160601b03811681036102aa5791604082015161304981612fb6565b9161305660608201612fd4565b9161306360808301612fe2565b9161307060a08201612ff3565b9160c082015160ff811681036102aa5760e090920151610394816116db565b608435610394816116db565b60a43561039481612fb6565b6101443561039481612fb6565b60c43561039481612fb6565b60e43561039481612fb6565b3561039481612fb6565b61012435610394816104d3565b156130ea57565b60405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606490fd5b6001600160a01b0381169081156131ea576000838152600260205260409020546131c0919061316a906001600160a01b031615155b156130e3565b60008481526002602052604090205461318d906001600160a01b03161515613164565b6001600160a01b038116600090815260036020526040902060018154019055612a82846000526002602052604060002090565b60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef81604051a4565b606460405162461bcd60e51b815260206004820152602060248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152fd5b600f0b6f7fffffffffffffffffffffffffffffff198114613250575b60000390565b613258612d7e565b61324a565b600160ff1b81146132505760000390565b6132778161272a565b506132818161272a565b600082815260046020908152604080832080546001600160a01b03199081169091556001600160a01b0390941680845260038352818420805460001901905585845260029092528220919290919081541690557fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef82604051a4565b60018060a01b03807f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b14163314908115613371575b501561333857565b60405162461bcd60e51b8152602060048201526011602482015270139bdd0815d155120e481bdc881c1bdbdb607a1b6044820152606490fd5b604051635b16ebb760e01b81523360048201529150602090829060249082907f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2165afa9081156133f9575b6000916133cb575b5038613330565b6133ec915060203d81116133f2575b6133e48183611c18565b8101906135ad565b386133c4565b503d6133da565b613401612bc7565b6133bc565b908160209103126102aa575190565b1561341c57565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b6044820152606490fd5b6040516370a0823160e01b81523060048201526001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b141691602082602481865afa918215613508575b6000926134e8575b50816134b857505050565b823b156102aa57604051632e1a7d4d60e01b815260048101839052612fd293600090829081838160248101610ad2565b61350191925060203d8111610b3757610b288183611c18565b90386134ad565b613510612bc7565b6134a5565b60008092918192602060405161352a81611be2565b84815201915af1613539612bd4565b501561354157565b60405162461bcd60e51b815260206004820152600360248201526253544560e81b6044820152606490fd5b1561357357565b60405162461bcd60e51b815260206004820152601260248201527124b739bab33334b1b4b2b73a103a37b5b2b760711b6044820152606490fd5b908160209103126102aa5751610394816116db565b60405163a9059cbb60e01b602082019081526001600160a01b0390931660248201526044810193909352600092839290839061360181606481016113c0565b51925af161360d612bd4565b81613645575b501561361b57565b60405162461bcd60e51b815260206004820152600260248201526114d560f21b6044820152606490fd5b805180159250821561365a575b505038613613565b61366d92506020809183010191016135ad565b3880613652565b4761367b57565b612fd24733613515565b815180516001600160a01b03908116835260208083015182169084015260408083015162ffffff1690840152606091820151169082015260a081019291608090602001516001600160a01b0316910152565b908160a09103126102aa578051916020820151916040810151916080606083015192015190565b6001600160a01b03918216815291151560208301526001600160801b0392831660408301529092166060830152909116608082015260c060a082018190526103949291019061035e565b818110613753570390565b61375b612d7e565b0390565b80519091906001600160a01b031660208301519091906001600160a01b0316926137ef6040946137df6137978785015162ffffff1690565b60608501516137d4906001600160a01b0316936137c46137b5611c39565b6001600160a01b03909a168a52565b6001600160a01b03166020890152565b62ffffff1686880152565b6001600160a01b03166060850152565b61381c610e3e847f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b9161382648613ac4565b804710613a2c576080830151869060a0906001600160a01b03168186019661384e8851151590565b8561386360c08a01516001600160801b031690565b60e08a01519094906138e0906138b7906001600160a01b03169d6101008d01996138c56138978c516001600160801b031690565b926138a0611cb7565b908152336020820152825194859160208301613685565b03601f198101855284611c18565b5163f6b9a60160e01b81529e8f9889978896600488016136fe565b0392600180871b03165af1968715613a1f575b6000968798889789928a926139df575b50888b9a9b6139206114fc6101208c01516001600160801b031690565b81106139c6575061393f6114fc6101408b01516001600160801b031690565b81116139ad57509061395c613958610160949351151590565b1590565b156139a55750955b0151851161398e57506139846114fc61398b92516001600160801b031690565b8094613748565b91565b51639c56bf3160e01b815260048101859052602490fd5b905095613964565b84516315481e3160e01b81526004810191909152602490fd5b8551636d24d5ef60e01b81526004810191909152602490fd5b93995097505050613a0891975060a03d8111613a18575b613a008183611c18565b8101906136d7565b9299939891979192909138613903565b503d6139f6565b613a27612bc7565b6138f3565b8551630b46947360e11b81526004810191909152602490fd5b620f4240908060001904821181151516613a5d570290565b613a65612d7e565b0290565b8060001904821181151516613a5d570290565b50634e487b7160e01b600052601260045260246000fd5b8015613aa1575b6000190490565b613aa9613a7c565b613a9a565b8115613ab8570490565b613ac0613a7c565b0490565b6445d964b800620f4240916409502f9000808211600014613b2657505b600019620249f0821515838304821116613b19575b82028015159104621e84801116613b0c57020490565b613b14612d7e565b020490565b613b21612d7e565b613af6565b9050613ae1565b91908260809103126102aa57604051608081018181106001600160401b03821117613b9e575b60405260608082948035613b66816104d3565b84526020810135613b76816104d3565b60208501526040810135613b8981612f93565b6040850152013591613b9a836104d3565b0152565b613ba6611b90565b613b53565b60a0818303126102aa57608090613bce60405193613bc885611ba7565b82613b2d565b83520135613bdb816104d3565b602082015290565b6001600160a01b037f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b148116949290828116861480613d09575b15613ce757505050823b156102aa57613c8e92602092604051630d0e30db60e41b815260008160048187875af18015613cda575b613cc7575b5060405163a9059cbb60e01b81526001600160a01b03909116600482015260248101929092529092839190829060009082906044820190565b03925af18015613cba575b613ca05750565b613cb79060203d81116133f2576133e48183611c18565b50565b613cc2612bc7565b613c99565b80610af5613cd492611bcf565b38613c55565b613ce2612bc7565b613c50565b9194509192919081163003613d005750612fd2926135c2565b612fd293613d13565b5083471015613c1c565b9091600080949381946040519160208301946323b872dd60e01b865260018060a01b038092166024850152166044830152606482015260648152613d5681611bfd565b51925af1613d62612bd4565b81613d9b575b5015613d7057565b60405162461bcd60e51b815260206004820152600360248201526229aa2360e91b6044820152606490fd5b8051801592508215613db0575b505038613d68565b613dc392506020809183010191016135ad565b3880613da8565b91908260409103126102aa576020825192015190565b90926001600160601b03608093610394969560018060a01b03168452166020830152600f0b6040820152816060820152019061035e565b8051613e7b92906001600160a01b0316602083018051909391613f1e91613ef3906001600160a01b0316916040978893610e08613e598689015162ffffff1690565b6060890151613e70906001600160a01b0316610dd2565b62ffffff1684870152565b613eab610e3e610e3e837f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b906000613ec260a08801516001600160601b031690565b613f01613ed360c08a0151600f0b90565b93613edc611cb7565b908152336020820152875196879160208301613685565b03601f198101875286611c18565b855163462278df60e01b8152968795869485933060048601613de0565b03925af1908115613fb2575b6000958692613f8d575b50909390508415613f7e575080516001600160a01b03165b613f5581613fbf565b9081613f6057505050565b60809290920151612fd292906001600160a01b03165b903090613be3565b516001600160a01b0316613f4c565b613fa893965080919250903d10611960576119528183611c18565b9390933880613f34565b613fba612bc7565b613f2a565b6040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa908115614013575b600091613ffb575090565b610394915060203d8111610b3757610b288183611c18565b61401b612bc7565b613ff0565b908160609103126102aa578051916040602083015192015190565b6001600160601b03610394949360609360018060a01b03168352166020820152816040820152019061035e565b805161416491606091613ef391906001600160a01b031660208201516140c9906001600160a01b03166140ba6140a4604086015162ffffff1690565b85880151611f13906001600160a01b0316610dd2565b6001600160a01b031682860152565b60006140fb610e3e610e3e847f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b9261414761412660a0614117608085015160018060a01b031690565b9301516001600160601b031690565b9361412f611cb7565b90815233602082015260405196879160208301613685565b60405163bf25901d60e01b8152968795869485936004850161403b565b03925af19081156141b9575b60009182918391614188575b50909192612fd2613674565b9150506141ac915060603d81116141b2575b6141a48183611c18565b810190614020565b3861417c565b503d61419a565b6141c1612bc7565b614170565b805190916142b1916001600160a01b031660606138b7602086019261422c6141f4855160018060a01b031690565b61421d61420760408b015162ffffff1690565b8a870151611f13906001600160a01b0316610dd2565b6001600160a01b031682850152565b614259610e3e827f000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2615342565b9061429261427160a08a01516001600160601b031690565b9161427a611cb7565b90815230602082015260405194859160208301613685565b600060405180988195829463bf25901d60e01b8452306004850161403b565b03926001600160a01b03165af1801561438f575b6000938491614369575b509260001315614359575082516001600160a01b0316925b6142f084613fbf565b9360c08201518510614340576080612fd29261431d928780614322575b505001516001600160a01b031690565b613456565b8284015161433992906001600160a01b0316613f76565b388761430d565b604051636b19f1cf60e11b815260048101869052602490fd5b516001600160a01b0316926142e7565b905061438491935060603d81116141b2576141a48183611c18565b9391905092386142cf565b614397612bc7565b6142c5565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a0608082018190526103949291019061035e565b476143dc57565b477f000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b146001600160a01b0316803b156102aa57600090600460405180948193630d0e30db60e41b83525af1801561443d575b6144345750565b612fd290611bcf565b614445612bc7565b61442d565b604051906101a082018281106001600160401b038211176144bd575b604052816101806000918281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201520152565b6144c5611b90565b614466565b90816101a09103126102aa5780516144e181612fb6565b9160208201516144f081612fb6565b9160408101516144ff81612fb6565b9161450c60608301612fc7565b9161451960808201612fc7565b9161452660a08301613001565b9161453360c08201613001565b9161454060e08301612fd4565b9161454e6101008201612fe2565b9161455c6101208301612ff3565b9161456a6101408201612fc7565b9161018061457b6101608401612fc7565b92015190565b908160209103126102aa575161039481612f93565b9291906145a161444a565b5061010084019063ffffffff91828151169386858585161461474357610394966146a59561469a9360069203820b97860316810b61039802810b90876145ed61395860a0860151151590565b156146e05761463162049d4061468a9461467894614617614673956116026101208b015160060b90565b9182820b818113156146b0575091505b0b0560020b614c05565b6001600160801b03614661604061465260208901516001600160801b031690565b9701516001600160801b031690565b6001600160a01b0390921691166149c6565b614b9c565b915b6001600160801b031660208a0152565b6001600160801b03166040880152565b9063ffffffff169052565b60060b610120830152565b6146c26146bc836148b8565b60060b90565b136146ce575b50614627565b6146d99192506148b8565b90386146c8565b6146739261470a9261461762049d409361470261012061472699015160060b90565b900360060b90565b6001600160801b0361466160208c01516001600160801b031690565b61468a61473d60408a01516001600160801b031690565b9161467a565b5050505050505090565b620f424081198111612da5570190565b81198111612da5570190565b9061478061477b60e084015160020b90565b614c05565b9061479161395860a0850151151590565b1561484c57614814916147d86147cf6114fc936147c962ffffff6147c26114fc60408b01516001600160801b031690565b921661474d565b90613a69565b620f4240900490565b6001600160a01b03909116906001600160801b038211614833576147ff8261480593613a69565b90614b6c565b925b516001600160801b031690565b9060008282111561482d57506103949161467391613748565b91505090565b6148408261484693614a0b565b90614adf565b92614807565b614814916148786147cf6114fc936147c962ffffff6147c26114fc60208b01516001600160801b031690565b6001600160a01b03909116906001600160801b0382116148a55761489f8261480593613a69565b90614a9a565b6148b28261484693614a0b565b90614a55565b60060b667fffffffffffff1981146132505760000390565b91906148e261395860a0850151151590565b1561495b5761494d61493a6149156147cf614956956147c962ffffff6147c26114fc60408c01516001600160801b031690565b946149346114fc6148056114fc6101408501516001600160801b031690565b9061475d565b6001600160a01b039092169182906149c6565b9260601b613aae565b111590565b6149c46149b16149ab61498c6147cf614956966147c962ffffff6147c26114fc60208d01516001600160801b031690565b956149346114fc6148056114fc6101408501516001600160801b031690565b60601b90565b6001600160a01b03909216918290613aae565b925b6000198282099082810292838084109303928084039314614a0257600160601b91838311156102aa570990828211900360a01b910360601c1790565b50505060601c90565b6000198282099082810292838084109303928084039314614a4c576801000000000000000091838311156102aa570990828211900360c01b910360401c1790565b50505060401c90565b6000198282099082810292838084109303928084039314614a9157600160801b91838311156102aa570990828211900360801b910360801c1790565b50505060801c90565b6000198282099082810292838084109303928084039314614ad657600160c01b91838311156102aa570990828211900360401b910360c01c1790565b50505060c01c90565b600160801b91600019838309928260801b92838086109503948086039514614b5f57908291614b0f868411612ecc565b096001821901821680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b5050906103949250613aae565b600160c01b91600019838309928260c01b92838086109503948086039514614b5f57908291614b0f868411612ecc565b6001600160801b0390818111614bb0571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20316044820152663238206269747360c81b6064820152608490fd5b60020b6000811215614f6f5780600003905b620d89e88211614f5d576001821615614f4b576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b169160028116614f2f575b60048116614f13575b60088116614ef7575b60108116614edb575b60208116614ebf575b60408116614ea3575b608090818116614e88575b6101008116614e6d575b6102008116614e52575b6104008116614e37575b6108008116614e1c575b6110008116614e01575b6120008116614de6575b6140008116614dcb575b6180008116614db0575b620100008116614d95575b620200008116614d7b575b620400008116614d61575b6208000016614d46575b50600012614d38575b63ffffffff8116614d30576000905b60201c60ff91909116016001600160a01b031690565b600190614d1a565b614d4190613a93565b614d0b565b6b048a170391f7dc42444e8fa26000929302901c9190614d02565b6d2216e584f5fa1ea926041bedfe98909302811c92614cf8565b926e5d6af8dedb81196699c329225ee60402811c92614ced565b926f09aa508b5b7a84e1c677de54f3e99bc902811c92614ce2565b926f31be135f97d08fd981231505542fcfa602811c92614cd7565b926f70d869a156d2a1b890bb3df62baf32f702811c92614ccd565b926fa9f746462d870fdf8a65dc1f90e061e502811c92614cc3565b926fd097f3bdfd2022b8845ad8f792aa582502811c92614cb9565b926fe7159475a2c29b7443b29c7fa6e889d902811c92614caf565b926ff3392b0822b70005940c7a398e4b70f302811c92614ca5565b926ff987a7253ac413176f2b074cf7815e5402811c92614c9b565b926ffcbe86c7900a88aedcffc83b479aa3a402811c92614c91565b926ffe5dee046a99a2a811c461f1969c305302811c92614c87565b916fff2ea16466c96a3843ec78b326b528610260801c91614c7c565b916fff973b41fa98c081472e6896dfb254c00260801c91614c73565b916fffcb9843d60f6159c9db58835c9266440260801c91614c6a565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91614c61565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91614c58565b916ffff97272373d413259a46990580e213a0260801c91614c4f565b6001600160881b03600160801b614c44565b6040516315e4079d60e11b8152600490fd5b80614c17565b60405163c19d93fb60e01b815261010092918390829060049082906001600160a01b03165afa90811561500b575b6000928392849285968692879288928992614fe1575b50509091889596979863ffffffff8042169586031660060b9060020b0260060b0160060b9293565b965096505050505093506150019250803d1061223d576122278183611c18565b9397933880614fb9565b615013612bc7565b614fa3565b908160209103126102aa5751610394816104d3565b60405190606082018281106001600160401b0382111761505a575b60405260028252604082602036910137565b615062611b90565b615048565b81601f820112156102aa5780519161507e83612d0e565b9261508c6040519485611c18565b808452602092838086019260051b8201019283116102aa578301905b8282106150b6575050505090565b83809183516150c4816104d3565b8152019101906150a8565b9190916040818403126102aa578051926001600160401b03938481116102aa5782019381601f860112156102aa57845161510881612d0e565b906151166040519283611c18565b808252602096878084019260051b820101918583116102aa5788809201905b8382106151555750505050948301519081116102aa576103949201615067565b82809161516184612ff3565b815201910190615135565b6020908160408183019282815285518094520193019160005b828110615193575050505090565b835163ffffffff1685529381019392810192600101615185565b60006152186040516307dc0d1d60e41b815260208160048160018060a01b038098165afa90811561528a575b839161525c575b506151e961502d565b6151fc6151f582612e83565b61a8c09052565b60405194858094819363883bdbfd60e01b83526004830161516c565b0392165afa90811561524f575b600091615230575090565b61524b913d8091833e6152438183611c18565b8101906150cf565b5090565b615257612bc7565b615225565b61527d915060203d8111615283575b6152758183611c18565b810190615018565b386151e0565b503d61526b565b615292612bc7565b6151d9565b916152b9909493919460e084019361a8c085519460060b0560020b8552614769565b936001600160801b03808616908216116152d6575b5060020b9052565b9350386152ce565b6001600160a01b03916152f091615342565b16908133036152fb57565b604051635cf3778960e01b8152600490fd5b8161531791615342565b50606001516001600160a01b0316903382900361533057565b6040516383b1c28760e01b8152600490fd5b81519192916020906001600160a01b0316848201516001600160a01b0316906153cc615388606061537960408a015162ffffff1690565b9801516001600160a01b031690565b604051635d0aec4160e01b81526001600160a01b039384166004820152938316602485015262ffffff90971660448401529516606482015293849081906084820190565b038160018060a01b038095165afa928315615426575b600093615406575b508216156153f457565b604051630f509b1160e01b8152600490fd5b61541f91935060203d8111615283576152758183611c18565b91386153ea565b61542e612bc7565b6153e2565b80156154c75780806001146154c0576002146154ba576001908161013382101682600b831016176154b257906002815b80821161547b57505081600019048111613a5d570290565b9092806000190481116154a5575b81841661549c575b800292811c90615463565b80920291615491565b6154ad612d7e565b615489565b600291500a90565b50600490565b5050600190565b50600090565b62ffffff8091169081620f424091038111612da5570190565b6001600160801b0380821695939490926001600160a01b0316919082156155c9575b61551283886149c6565b906155c0575060601b6fffffffffffffffffffffffffffffffff60601b1604915b1691818310156155a757826155948361558e615570946146739761039499971061559a575b61558861558061557a615575866155708a8203615433565b613aae565b613a45565b926154cd565b62ffffff1690565b90613aae565b90613748565b92613a69565b6155a2612d7e565b615558565b60405163c74656a760e01b815260048101839052602490fd5b91505091615533565b6155d1613a7c565b61550856fea2646970667358221220f65bfcb6e1f353c07efe8010508e022f4f20a95397d131d48576cb3ea4fa805464736f6c634300080f0033

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

000000000000000000000000a85d1a8f20d1d51612ffa969f8594166a855c3c2000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b1400000000000000000000000036fc580af2cd4baf325c26aac8b95a8fd464c1a8

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

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


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.