ETH Price: $3,274.59 (-1.70%)

Contract

0x54522dA62a15225C95b01bD61fF58b866C50471f
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

More Info

Private Name Tags

TokenTracker

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Set Approval For...205480432024-08-17 11:27:47128 days ago1723894067IN
0x54522dA6...66C50471f
0 ETH0.000024321
Set Approval For...205480322024-08-17 11:25:35128 days ago1723893935IN
0x54522dA6...66C50471f
0 ETH0.000024231
Multicall195441832024-03-30 3:44:35268 days ago1711770275IN
0x54522dA6...66C50471f
0 ETH0.00465121.64125673
Multicall187542972023-12-10 7:23:47379 days ago1702193027IN
0x54522dA6...66C50471f
0 ETH0.0052646325.68252131
Set Approval For...179345992023-08-17 12:40:35494 days ago1692276035IN
0x54522dA6...66C50471f
0 ETH0.0011517324.91050369
Multicall174825432023-06-15 3:12:35557 days ago1686798755IN
0x54522dA6...66C50471f
0 ETH0.0034875617.01102379
Multicall174825112023-06-15 3:06:11557 days ago1686798371IN
0x54522dA6...66C50471f
0 ETH0.0039841418.2167095
Multicall174824732023-06-15 2:58:35557 days ago1686797915IN
0x54522dA6...66C50471f
0 ETH0.0041154918.81980218
Multicall174053702023-06-04 6:07:35568 days ago1685858855IN
0x54522dA6...66C50471f
0 ETH0.0040150618.35809511
Multicall169829722023-04-05 13:47:47628 days ago1680702467IN
0x54522dA6...66C50471f
0 ETH0.0072994235.60207544
Multicall168668022023-03-20 5:28:11644 days ago1679290091IN
0x54522dA6...66C50471f
0 ETH0.0028089613.70231107
Multicall168518892023-03-18 3:10:59646 days ago1679109059IN
0x54522dA6...66C50471f
0 ETH0.003494317.04549126
Multicall163749472023-01-10 7:35:11713 days ago1673336111IN
0x54522dA6...66C50471f
0 ETH0.0030823315.04077564
Multicall163550372023-01-07 12:55:11716 days ago1673096111IN
0x54522dA6...66C50471f
0 ETH0.0035195516.09462336
Multicall163550322023-01-07 12:54:11716 days ago1673096051IN
0x54522dA6...66C50471f
0 ETH0.0034944515.97983448
Multicall163550252023-01-07 12:52:47716 days ago1673095967IN
0x54522dA6...66C50471f
0 ETH0.0033976715.54140911
Multicall163550182023-01-07 12:51:23716 days ago1673095883IN
0x54522dA6...66C50471f
0 ETH0.0034856115.9394301
Multicall163549932023-01-07 12:46:11716 days ago1673095571IN
0x54522dA6...66C50471f
0 ETH0.0034784915.90473698
Multicall163549702023-01-07 12:41:35716 days ago1673095295IN
0x54522dA6...66C50471f
0 ETH0.0033521516.34975122
Multicall163549392023-01-07 12:35:23716 days ago1673094923IN
0x54522dA6...66C50471f
0 ETH0.0033131416.15949662
Multicall163549342023-01-07 12:34:23716 days ago1673094863IN
0x54522dA6...66C50471f
0 ETH0.0031758515.48988285
Multicall163546652023-01-07 11:40:23716 days ago1673091623IN
0x54522dA6...66C50471f
0 ETH0.003208515.64912168
Multicall163546602023-01-07 11:39:23716 days ago1673091563IN
0x54522dA6...66C50471f
0 ETH0.0033055816.12486095
Multicall163546542023-01-07 11:38:11716 days ago1673091491IN
0x54522dA6...66C50471f
0 ETH0.0035088716.0436339
Multicall163546452023-01-07 11:36:23716 days ago1673091383IN
0x54522dA6...66C50471f
0 ETH0.0035006616.00822829
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block
From
To
195441832024-03-30 3:44:35268 days ago1711770275
0x54522dA6...66C50471f
0.10921794 ETH
195441832024-03-30 3:44:35268 days ago1711770275
0x54522dA6...66C50471f
0.10921794 ETH
187542972023-12-10 7:23:47379 days ago1702193027
0x54522dA6...66C50471f
0.04422029 ETH
187542972023-12-10 7:23:47379 days ago1702193027
0x54522dA6...66C50471f
0.04422029 ETH
174825432023-06-15 3:12:35557 days ago1686798755
0x54522dA6...66C50471f
0.00228496 ETH
174825432023-06-15 3:12:35557 days ago1686798755
0x54522dA6...66C50471f
0.00228496 ETH
174825112023-06-15 3:06:11557 days ago1686798371
0x54522dA6...66C50471f
0.29999983 ETH
174825112023-06-15 3:06:11557 days ago1686798371
0x54522dA6...66C50471f
0.29999983 ETH
174824732023-06-15 2:58:35557 days ago1686797915
0x54522dA6...66C50471f
0.00182797 ETH
174824732023-06-15 2:58:35557 days ago1686797915
0x54522dA6...66C50471f
0.00182797 ETH
174053702023-06-04 6:07:35568 days ago1685858855
0x54522dA6...66C50471f
0.2001311 ETH
174053702023-06-04 6:07:35568 days ago1685858855
0x54522dA6...66C50471f
0.2001311 ETH
169829722023-04-05 13:47:47628 days ago1680702467
0x54522dA6...66C50471f
0.31692244 ETH
169829722023-04-05 13:47:47628 days ago1680702467
0x54522dA6...66C50471f
0.31692244 ETH
168668022023-03-20 5:28:11644 days ago1679290091
0x54522dA6...66C50471f
0.00002845 ETH
168668022023-03-20 5:28:11644 days ago1679290091
0x54522dA6...66C50471f
0.00002845 ETH
168518892023-03-18 3:10:59646 days ago1679109059
0x54522dA6...66C50471f
0.07160288 ETH
168518892023-03-18 3:10:59646 days ago1679109059
0x54522dA6...66C50471f
0.07160288 ETH
163749472023-01-10 7:35:11713 days ago1673336111
0x54522dA6...66C50471f
0.01113664 ETH
163749472023-01-10 7:35:11713 days ago1673336111
0x54522dA6...66C50471f
0.01113664 ETH
163550372023-01-07 12:55:11716 days ago1673096111
0x54522dA6...66C50471f
0.00003175 ETH
163550372023-01-07 12:55:11716 days ago1673096111
0x54522dA6...66C50471f
0.00003175 ETH
163550322023-01-07 12:54:11716 days ago1673096051
0x54522dA6...66C50471f
0.00003175 ETH
163550322023-01-07 12:54:11716 days ago1673096051
0x54522dA6...66C50471f
0.00003175 ETH
163550252023-01-07 12:52:47716 days ago1673095967
0x54522dA6...66C50471f
0.00003078 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PrimitiveManager

Compiler Version
v0.8.6+commit.11564f7e

Optimization Enabled:
Yes with 400 runs

Other Settings:
default evmVersion
File 1 of 48 : PrimitiveManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/engine/IPrimitiveEngineView.sol";
import "./interfaces/IPrimitiveManager.sol";
import "./base/Multicall.sol";
import "./base/CashManager.sol";
import "./base/SelfPermit.sol";
import "./base/PositionManager.sol";
import "./base/SwapManager.sol";
import "./libraries/TransferHelper.sol";

/// @title   PrimitiveManager contract
/// @author  Primitive
/// @notice  Interacts with Primitive Engine contracts
contract PrimitiveManager is IPrimitiveManager, Multicall, CashManager, SelfPermit, PositionManager, SwapManager {
    using TransferHelper for IERC20;
    using Margin for Margin.Data;

    /// EFFECT FUNCTIONS ///

    /// @param factory_             Address of a PrimitiveFactory
    /// @param WETH9_               Address of WETH9
    /// @param positionDescriptor_  Address of PositionDescriptor
    constructor(
        address factory_,
        address WETH9_,
        address positionDescriptor_
    ) ManagerBase(factory_, WETH9_, positionDescriptor_) {}

    /// @inheritdoc IPrimitiveManager
    function create(
        address risky,
        address stable,
        uint128 strike,
        uint32 sigma,
        uint32 maturity,
        uint32 gamma,
        uint256 riskyPerLp,
        uint256 delLiquidity
    )
        external
        payable
        override
        lock
        returns (
            bytes32 poolId,
            uint256 delRisky,
            uint256 delStable
        )
    {
        address engine = EngineAddress.computeAddress(factory, risky, stable);
        if (engine.code.length == 0) revert EngineAddress.EngineNotDeployedError();

        if (delLiquidity == 0) revert ZeroLiquidityError();

        CallbackData memory callbackData = CallbackData({risky: risky, stable: stable, payer: msg.sender});

        (poolId, delRisky, delStable) = IPrimitiveEngineActions(engine).create(
            strike,
            sigma,
            maturity,
            gamma,
            riskyPerLp,
            delLiquidity,
            abi.encode(callbackData)
        );

        // Mints {delLiquidity - MIN_LIQUIDITY} of liquidity tokens
        uint256 MIN_LIQUIDITY = IPrimitiveEngineView(engine).MIN_LIQUIDITY();
        _allocate(msg.sender, engine, poolId, delLiquidity - MIN_LIQUIDITY);

        emit Create(msg.sender, engine, poolId, strike, sigma, maturity, gamma, delLiquidity - MIN_LIQUIDITY);
    }

    address private _engine;

    /// @inheritdoc IPrimitiveManager
    function allocate(
        address recipient,
        bytes32 poolId,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable,
        bool fromMargin,
        uint256 minLiquidityOut
    ) external payable override lock returns (uint256 delLiquidity) {
        _engine = EngineAddress.computeAddress(factory, risky, stable);
        if (_engine.code.length == 0) revert EngineAddress.EngineNotDeployedError();

        if (delRisky == 0 && delStable == 0) revert ZeroLiquidityError();

        (delLiquidity) = IPrimitiveEngineActions(_engine).allocate(
            poolId,
            address(this),
            delRisky,
            delStable,
            fromMargin,
            abi.encode(CallbackData({risky: risky, stable: stable, payer: msg.sender}))
        );

        if (delLiquidity < minLiquidityOut) revert MinLiquidityOutError();

        if (fromMargin) margins[msg.sender][_engine].withdraw(delRisky, delStable);

        // Mints {delLiquidity} of liquidity tokens
        _allocate(recipient, _engine, poolId, delLiquidity);

        emit Allocate(msg.sender, recipient, _engine, poolId, delLiquidity, delRisky, delStable, fromMargin);

        _engine = address(0);
    }

    /// @inheritdoc IPrimitiveManager
    function remove(
        address engine,
        bytes32 poolId,
        uint256 delLiquidity,
        uint256 minRiskyOut,
        uint256 minStableOut
    ) external override lock returns (uint256 delRisky, uint256 delStable) {
        if (delLiquidity == 0) revert ZeroLiquidityError();

        (delRisky, delStable) = IPrimitiveEngineActions(engine).remove(poolId, delLiquidity);
        if (delRisky < minRiskyOut || delStable < minStableOut) revert MinRemoveOutError();

        _remove(msg.sender, poolId, delLiquidity);
        margins[msg.sender][engine].deposit(delRisky, delStable);

        emit Remove(msg.sender, engine, poolId, delLiquidity, delRisky, delStable);
    }

    /// CALLBACK IMPLEMENTATIONS ///

    /// @inheritdoc IPrimitiveCreateCallback
    function createCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external override {
        CallbackData memory decoded = abi.decode(data, (CallbackData));

        address engine = EngineAddress.computeAddress(factory, decoded.risky, decoded.stable);
        if (msg.sender != engine) revert NotEngineError();

        if (delRisky != 0) pay(decoded.risky, decoded.payer, msg.sender, delRisky);
        if (delStable != 0) pay(decoded.stable, decoded.payer, msg.sender, delStable);
    }

    /// @inheritdoc IPrimitiveLiquidityCallback
    function allocateCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external override {
        CallbackData memory decoded = abi.decode(data, (CallbackData));

        address engine = EngineAddress.computeAddress(factory, decoded.risky, decoded.stable);
        if (msg.sender != engine) revert NotEngineError();

        if (delRisky != 0) pay(decoded.risky, decoded.payer, msg.sender, delRisky);
        if (delStable != 0) pay(decoded.stable, decoded.payer, msg.sender, delStable);
    }
}

File 2 of 48 : IPrimitiveEngineView.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  View functions of the Primitive Engine contract
/// @author Primitive
interface IPrimitiveEngineView {
    // ===== View =====

    /// @notice             Fetches the current invariant, notation is usually `k`, based on risky and stable token reserves of pool with `poolId`
    /// @param  poolId      Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
    /// @return invariant   Signed fixed point 64.64 number, invariant of `poolId`
    function invariantOf(bytes32 poolId) external view returns (int128 invariant);

    // ===== Constants =====

    /// @return Precision units to scale to when doing token related calculations
    function PRECISION() external view returns (uint256);

    /// @return Amount of seconds after pool expiry which allows swaps, no swaps after buffer
    function BUFFER() external view returns (uint256);

    // ===== Immutables =====

    /// @return Amount of liquidity burned on `create()` calls
    function MIN_LIQUIDITY() external view returns (uint256);

    //// @return Factory address which deployed this engine contract
    function factory() external view returns (address);

    //// @return Risky token address, a more accurate name is the underlying token
    function risky() external view returns (address);

    /// @return Stable token address, a more accurate name is the quote token
    function stable() external view returns (address);

    /// @return Multiplier to scale amounts to/from, equal to 10^(18 - riskyDecimals)
    function scaleFactorRisky() external view returns (uint256);

    /// @return Multiplier to scale amounts to/from, equal to 10^(18 - stableDecimals)
    function scaleFactorStable() external view returns (uint256);

    // ===== Pool State =====

    /// @notice                      Fetches the global reserve state for a pool with `poolId`
    /// @param  poolId               Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
    /// @return reserveRisky         Risky token balance in the reserve
    /// @return reserveStable        Stable token balance in the reserve
    /// @return liquidity            Total supply of liquidity for the curve
    /// @return blockTimestamp       Timestamp when the cumulative reserve values were last updated
    /// @return cumulativeRisky      Cumulative sum of risky token reserves of the previous update
    /// @return cumulativeStable     Cumulative sum of stable token reserves of the previous update
    /// @return cumulativeLiquidity  Cumulative sum of total supply of liquidity of the previous update
    function reserves(bytes32 poolId)
        external
        view
        returns (
            uint128 reserveRisky,
            uint128 reserveStable,
            uint128 liquidity,
            uint32 blockTimestamp,
            uint256 cumulativeRisky,
            uint256 cumulativeStable,
            uint256 cumulativeLiquidity
        );

    /// @notice                 Fetches `Calibration` pool parameters
    /// @param  poolId          Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
    /// @return strike          Marginal price of the pool's risky token at maturity, with the same decimals as the stable token, valid [0, 2^128-1]
    /// @return sigma           AKA Implied Volatility in basis points, determines the price impact of swaps, valid for (1, 10_000_000)
    /// @return maturity        Timestamp which starts the BUFFER countdown until swaps will cease, in seconds, valid for (block.timestamp, 2^32-1]
    /// @return lastTimestamp   Last timestamp used to calculate time until expiry, aka "tau"
    /// @return gamma           Multiplied against swap in amounts to apply fee, equal to 1 - fee % but units are in basis points, valid for (9_000, 10_000)
    function calibrations(bytes32 poolId)
        external
        view
        returns (
            uint128 strike,
            uint32 sigma,
            uint32 maturity,
            uint32 lastTimestamp,
            uint32 gamma
        );

    /// @notice             Fetches position liquidity an account address and poolId
    /// @param  poolId      Keccak256 hash of the engine address, strike, sigma, maturity, and gamma
    /// @return liquidity   Liquidity owned by `account` in `poolId`
    function liquidity(address account, bytes32 poolId) external view returns (uint256 liquidity);

    /// @notice                 Fetches the margin balances of `account`
    /// @param  account         Margin account to fetch
    /// @return balanceRisky    Balance of the risky token
    /// @return balanceStable   Balance of the stable token
    function margins(address account) external view returns (uint128 balanceRisky, uint128 balanceStable);
}

File 3 of 48 : IPrimitiveManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/callback/IPrimitiveCreateCallback.sol";
import "@primitivefi/rmm-core/contracts/interfaces/callback/IPrimitiveLiquidityCallback.sol";

/// @title   Interface of PrimitiveManager contract
/// @author  Primitive
interface IPrimitiveManager is IPrimitiveCreateCallback, IPrimitiveLiquidityCallback {
    /// ERRORS ///

    /// @notice  Thrown when trying to add or remove zero liquidity
    error ZeroLiquidityError();

    /// @notice  Thrown when the received liquidity is lower than the expected
    error MinLiquidityOutError();

    /// @notice  Thrown when the received risky / stable amounts are lower than the expected
    error MinRemoveOutError();

    /// EVENTS ///

    /// @notice               Emitted when a new pool is created
    /// @param payer          Payer sending liquidity
    /// @param engine         Primitive Engine where the pool is created
    /// @param poolId         Id of the new pool
    /// @param strike         Strike of the new pool
    /// @param sigma          Sigma of the new pool
    /// @param maturity       Maturity of the new pool
    /// @param gamma          Gamma of the new pool
    /// @param delLiquidity   Amount of liquidity allocated (minus the minimum liquidity)
    event Create(
        address indexed payer,
        address indexed engine,
        bytes32 indexed poolId,
        uint128 strike,
        uint32 sigma,
        uint32 maturity,
        uint32 gamma,
        uint256 delLiquidity
    );

    /// @notice              Emitted when liquidity is allocated
    /// @param payer         Payer sending liquidity
    /// @param recipient     Address that receives minted ERC-1155 Primitive liquidity tokens
    /// @param engine        Primitive Engine receiving liquidity
    /// @param poolId        Id of the pool receiving liquidity
    /// @param delLiquidity  Amount of liquidity allocated
    /// @param delRisky      Amount of risky tokens allocated
    /// @param delStable     Amount of stable tokens allocated
    /// @param fromMargin    True if liquidity was paid from margin
    event Allocate(
        address payer,
        address indexed recipient,
        address indexed engine,
        bytes32 indexed poolId,
        uint256 delLiquidity,
        uint256 delRisky,
        uint256 delStable,
        bool fromMargin
    );

    /// @notice              Emitted when liquidity is removed
    /// @param payer         Payer receiving liquidity
    /// @param engine        Engine where liquidity is removed from
    /// @param poolId        Id of the pool where liquidity is removed from
    /// @param delLiquidity  Amount of liquidity removed
    /// @param delRisky      Amount of risky tokens allocated
    /// @param delStable     Amount of stable tokens allocated
    event Remove(
        address indexed payer,
        address indexed engine,
        bytes32 indexed poolId,
        uint256 delLiquidity,
        uint256 delRisky,
        uint256 delStable
    );

    /// EFFECT FUNCTIONS ///

    /// @notice              Creates a new pool using the specified parameters
    /// @param risky         Address of the risky asset
    /// @param stable        Address of the stable asset
    /// @param strike        Strike price of the pool to calibrate to, with the same decimals as the stable token
    /// @param sigma         Volatility to calibrate to as an unsigned 256-bit integer w/ precision of 1e4, 10000 = 100%
    /// @param maturity      Maturity timestamp of the pool, in seconds
    /// @param gamma         Multiplied against swap in amounts to apply fee, equal to 1 - fee %, an unsigned 32-bit integer, w/ precision of 1e4, 10000 = 100%
    /// @param riskyPerLp    Risky reserve per liq. with risky decimals, = 1 - N(d1), d1 = (ln(S/K)+(r*sigma^2/2))/sigma*sqrt(tau)
    /// @param delLiquidity  Amount of liquidity to allocate to the curve, wei value with 18 decimals of precision
    /// @return poolId       Id of the new created pool (Keccak256 hash of the engine address, maturity, sigma and strike)
    /// @return delRisky     Amount of risky tokens allocated into the pool
    /// @return delStable    Amount of stable tokens allocated into the pool
    function create(
        address risky,
        address stable,
        uint128 strike,
        uint32 sigma,
        uint32 maturity,
        uint32 gamma,
        uint256 riskyPerLp,
        uint256 delLiquidity
    )
        external
        payable
        returns (
            bytes32 poolId,
            uint256 delRisky,
            uint256 delStable
        );

    /// @notice               Allocates liquidity into a pool
    /// @param recipient      Address that receives minted ERC-1155 Primitive liquidity tokens
    /// @param poolId         Id of the pool
    /// @param risky          Address of the risky asset
    /// @param stable         Address of the stable asset
    /// @param delRisky       Amount of risky tokens to allocate
    /// @param delStable      Amount of stable tokens to allocate
    /// @param fromMargin     True if the funds of the sender should be used
    /// @return delLiquidity  Amount of liquidity allocated into the pool
    function allocate(
        address recipient,
        bytes32 poolId,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable,
        bool fromMargin,
        uint256 minLiquidityOut
    ) external payable returns (uint256 delLiquidity);

    /// @notice              Removes liquidity from a pool
    /// @param engine        Address of the engine
    /// @param poolId        Id of the pool
    /// @param delLiquidity  Amount of liquidity to remove
    /// @param minRiskyOut   Minimum amount of risky tokens expected to be received
    /// @param minStableOut  Minimum amount of stable tokens expected to be received
    /// @return delRisky     Amount of risky tokens removed from the pool
    /// @return delStable    Amount of stable tokens removed from the pool
    function remove(
        address engine,
        bytes32 poolId,
        uint256 delLiquidity,
        uint256 minRiskyOut,
        uint256 minStableOut
    ) external returns (uint256 delRisky, uint256 delStable);
}

File 4 of 48 : Multicall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.6;

import "../interfaces/IMulticall.sol";

/// @title   Multicall contract
/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
/// @notice  Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(bytes[] calldata data) external 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 5 of 48 : CashManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "../interfaces/ICashManager.sol";
import "../base/ManagerBase.sol";
import "../libraries/TransferHelper.sol";
import "../interfaces/external/IWETH9.sol";

/// @title   CashManager contract
/// @author  Primitive
/// @notice  Utils contract to manage ETH and token balances
abstract contract CashManager is ICashManager, ManagerBase {
    /// @notice Only WETH9 can send ETH to this contract
    receive() external payable {
        if (msg.sender != WETH9) revert OnlyWETHError();
    }

    /// @inheritdoc ICashManager
    function wrap(uint256 value) external payable override {
        if (address(this).balance < value) {
            revert BalanceTooLowError(address(this).balance, value);
        }

        IWETH9(WETH9).deposit{value: value}();
        IWETH9(WETH9).transfer(msg.sender, value);
    }

    /// @inheritdoc ICashManager
    function unwrap(uint256 amountMin, address recipient) external payable override {
        uint256 balance = IWETH9(WETH9).balanceOf(address(this));

        if (balance < amountMin) revert BalanceTooLowError(balance, amountMin);

        if (balance != 0) {
            IWETH9(WETH9).withdraw(balance);
            TransferHelper.safeTransferETH(recipient, balance);
        }
    }

    /// @inheritdoc ICashManager
    function sweepToken(
        address token,
        uint256 amountMin,
        address recipient
    ) external payable override {
        uint256 balance = IERC20(token).balanceOf(address(this));
        if (balance < amountMin) revert BalanceTooLowError(balance, amountMin);

        if (balance != 0) {
            TransferHelper.safeTransfer(token, recipient, balance);
        }
    }

    /// @inheritdoc ICashManager
    function refundETH() external payable override {
        if (address(this).balance != 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
    }

    /// @dev              Pays `value` of `token` to `recipient` from `payer` wallet
    /// @param token      Token to transfer as payment
    /// @param payer      Account that pays
    /// @param recipient  Account that receives payment
    /// @param value      Amount to pay
    function pay(
        address token,
        address payer,
        address recipient,
        uint256 value
    ) internal {
        if (token == WETH9 && address(this).balance >= value) {
            IWETH9(WETH9).deposit{value: value}();
            IWETH9(WETH9).transfer(recipient, value);
        } else if (payer == address(this)) {
            TransferHelper.safeTransfer(token, recipient, value);
        } else {
            TransferHelper.safeTransferFrom(token, payer, recipient, value);
        }
    }
}

File 6 of 48 : SelfPermit.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "../interfaces/external/IERC20.sol";
import "../interfaces/external/IERC20PermitAllowed.sol";
import "../interfaces/ISelfPermit.sol";

/// @title   SelfPermit contract
/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/SelfPermit.sol
/// @notice  Functionality to call permit on any EIP-2612-compliant token
/// @dev     These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
///          that requires an approval in a single transaction
abstract contract SelfPermit is ISelfPermit {
    /// @inheritdoc ISelfPermit
    function selfPermit(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable override {
        IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitIfNecessary(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable override {
        if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitAllowed(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable override {
        IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
    }

    /// @inheritdoc ISelfPermit
    function selfPermitAllowedIfNecessary(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable override {
        if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
            selfPermitAllowed(token, nonce, expiry, v, r, s);
    }
}

File 7 of 48 : PositionManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "./ERC1155Permit.sol";
import "../base/ManagerBase.sol";
import "../interfaces/IPositionDescriptor.sol";

/// @title   PositionManager contract
/// @author  Primitive
/// @notice  Wraps the positions into ERC1155 tokens
abstract contract PositionManager is ManagerBase, ERC1155Permit {
    /// @dev  Ties together pool ids with engine addresses, this is necessary because
    ///       there is no way to get the Primitive Engine address from a pool id
    mapping(uint256 => address) private cache;

    /// @dev  Empty variable to pass to the _mint function
    bytes constant private _empty = "";

    /// @notice         Returns the metadata of a token
    /// @param tokenId  Token id to look for (same as pool id)
    /// @return         Metadata of the token as a string
    function uri(uint256 tokenId) public view override returns (string memory) {
        return IPositionDescriptor(positionDescriptor).getMetadata(cache[tokenId], tokenId);
    }

    /// @notice         Allocates {amount} of {poolId} liquidity to {account} balance
    /// @param account  Recipient of the liquidity
    /// @param engine   Address of the Primitive Engine
    /// @param poolId   Id of the pool
    /// @param amount   Amount of liquidity to allocate
    function _allocate(
        address account,
        address engine,
        bytes32 poolId,
        uint256 amount
    ) internal {
        _mint(account, uint256(poolId), amount, _empty);

        if (cache[uint256(poolId)] == address(0)) cache[uint256(poolId)] = engine;
    }

    /// @notice         Removes {amount} of {poolId} liquidity from {account} balance
    /// @param account  Account to remove from
    /// @param poolId   Id of the pool
    /// @param amount   Amount of liquidity to remove
    function _remove(
        address account,
        bytes32 poolId,
        uint256 amount
    ) internal {
        _burn(account, uint256(poolId), amount);
    }
}

File 8 of 48 : SwapManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/engine/IPrimitiveEngineActions.sol";
import "@primitivefi/rmm-core/contracts/interfaces/engine/IPrimitiveEngineView.sol";
import "@primitivefi/rmm-core/contracts/libraries/ReplicationMath.sol";

import "../interfaces/ISwapManager.sol";
import "../interfaces/external/IERC20.sol";
import "./MarginManager.sol";
import "./CashManager.sol";

/// @title   SwapManager contract
/// @author  Primitive
/// @dev     Manages the swaps
abstract contract SwapManager is ISwapManager, CashManager, MarginManager {
    using TransferHelper for IERC20;
    using Margin for Margin.Data;

    /// @notice Reverts the transaction is the deadline is reached
    modifier checkDeadline(uint256 deadline) {
        if (block.timestamp > deadline) revert DeadlineReachedError();
        _;
    }

    /// EFFECT FUNCTIONS ///

    /// @inheritdoc ISwapManager
    function swap(SwapParams calldata params) external payable override lock checkDeadline(params.deadline) {
        CallbackData memory callbackData = CallbackData({
            payer: msg.sender,
            risky: params.risky,
            stable: params.stable
        });

        address engine = EngineAddress.computeAddress(factory, params.risky, params.stable);
        if (engine.code.length == 0) revert EngineAddress.EngineNotDeployedError();

        IPrimitiveEngineActions(engine).swap(
            params.toMargin ? address(this) : params.recipient,
            params.poolId,
            params.riskyForStable,
            params.deltaIn,
            params.deltaOut,
            params.fromMargin,
            params.toMargin,
            abi.encode(callbackData)
        );

        if (params.fromMargin) {
            margins[msg.sender][engine].withdraw(
                params.riskyForStable ? params.deltaIn : 0,
                params.riskyForStable ? 0 : params.deltaIn
            );
        }

        if (params.toMargin) {
            margins[params.recipient][engine].deposit(
                params.riskyForStable ? 0 : params.deltaOut,
                params.riskyForStable ? params.deltaOut : 0
            );
        }

        emit Swap(
            msg.sender,
            params.recipient,
            engine,
            params.poolId,
            params.riskyForStable,
            params.deltaIn,
            params.deltaOut,
            params.fromMargin,
            params.toMargin
        );
    }

    /// CALLBACK IMPLEMENTATIONS ///

    /// @inheritdoc IPrimitiveSwapCallback
    function swapCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external override {
        CallbackData memory decoded = abi.decode(data, (CallbackData));

        address engine = EngineAddress.computeAddress(factory, decoded.risky, decoded.stable);
        if (msg.sender != engine) revert NotEngineError();

        if (delRisky != 0) pay(decoded.risky, decoded.payer, msg.sender, delRisky);
        if (delStable != 0) pay(decoded.stable, decoded.payer, msg.sender, delStable);
    }
}

File 9 of 48 : TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.6;

import "../interfaces/external/IERC20.sol";

/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/TransferHelper.sol
/// @notice  Utils functions to transfer tokens and ETH
library TransferHelper {
    /// ERRORS ///

    /// @notice Thrown when a transfer reverts
    error TransferError();

    /// @notice Thrown when an approval reverts
    error ApproveError();

    /// FUNCTIONS ///

    /// @notice       Transfers tokens from the targeted address to the given destination
    /// @param token  Contract address of the token to be transferred
    /// @param from   Originating address from which the tokens will be transferred
    /// @param to     Destination address of the transfer
    /// @param value  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)
        );

        if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert TransferError();
    }

    /// @notice       Transfers tokens from msg.sender to a recipient
    /// @param token  Contract address of the token which will be transferred
    /// @param to     Recipient of the transfer
    /// @param value  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));
        if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert TransferError();
    }

    /// @notice       Approves the stipulated contract to spend the given allowance in the given token
    /// @param token  Contract address of the token to be approved
    /// @param to     Target of the approval
    /// @param value  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));
        if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert ApproveError();
    }

    /// @notice       Transfers ETH to the recipient address
    /// @param to     Destination of the transfer
    /// @param value  Value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        if (success == false) revert TransferError();
    }
}

File 10 of 48 : IPrimitiveCreateCallback.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  Primitive Create Callback
/// @author Primitive
interface IPrimitiveCreateCallback {
    /// @notice              Triggered when creating a new pool for an Engine
    /// @param  delRisky     Amount of risky tokens required to initialize risky reserve
    /// @param  delStable    Amount of stable tokens required to initialize stable reserve
    /// @param  data         Calldata passed on create function call
    function createCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external;
}

File 11 of 48 : IPrimitiveLiquidityCallback.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  Primitive Liquidity Callback
/// @author Primitive
interface IPrimitiveLiquidityCallback {
    /// @notice              Triggered when providing liquidity to an Engine
    /// @param  delRisky     Amount of risky tokens required to provide to risky reserve
    /// @param  delStable    Amount of stable tokens required to provide to stable reserve
    /// @param  data         Calldata passed on allocate function call
    function allocateCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external;
}

File 12 of 48 : IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.6;

/// @title   Interface of Multicall contract
/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/IMulticall.sol
interface IMulticall {
    /// @notice          Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev             `msg.value` should not be trusted for any method callable from Multicall
    /// @param data      Encoded function data for each of the calls to make to this contract
    /// @return results  Results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

File 13 of 48 : ICashManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

/// @title   Interface of CashManager contract
/// @author  Primitive
interface ICashManager {
    /// ERRORS ///

    /// @notice  Thrown when the sender is not WETH
    error OnlyWETHError();

    /// @notice                Thrown when the amount required is above balance
    /// @param balance         Actual ETH or token balance of the contract
    /// @param requiredAmount  ETH or token amount required by the user
    error BalanceTooLowError(uint256 balance, uint256 requiredAmount);

    /// EFFECT FUNCTIONS ///

    /// @notice       Wraps ETH into WETH and transfers to the msg.sender
    /// @param value  Amount of ETH to wrap
    function wrap(uint256 value) external payable;

    /// @notice           Unwraps WETH to ETH and transfers to a recipient
    /// @param amountMin  Minimum amount to unwrap
    /// @param recipient  Address of the recipient
    function unwrap(uint256 amountMin, address recipient) external payable;

    /// @notice           Transfers the tokens in the contract to a recipient
    /// @param token      Address of the token to sweep
    /// @param amountMin  Minimum amount to transfer
    /// @param recipient  Recipient of the tokens
    function sweepToken(
        address token,
        uint256 amountMin,
        address recipient
    ) external payable;

    /// @notice  Transfers the ETH balance of the contract to the caller
    function refundETH() external payable;
}

File 14 of 48 : ManagerBase.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "../interfaces/IManagerBase.sol";
import "../interfaces/IPrimitiveManager.sol";
import "./Reentrancy.sol";
import "../libraries/EngineAddress.sol";

/// @title   ManagerBase contract
/// @author  Primitive
/// @notice  Base contract of the Manager
abstract contract ManagerBase is IManagerBase, Reentrancy {
    /// @notice Data struct reused by callbacks
    struct CallbackData {
        address payer;
        address risky;
        address stable;
    }

    /// @inheritdoc IManagerBase
    address public immutable override factory;

    /// @inheritdoc IManagerBase
    address public immutable override WETH9;

    /// @inheritdoc IManagerBase
    address public immutable override positionDescriptor;

    /// @param factory_  Address of a PrimitiveFactory
    /// @param WETH9_    Address of WETH9
    /// @param positionDescriptor_    Address of the position renderer
    constructor(
        address factory_,
        address WETH9_,
        address positionDescriptor_
    ) {
        if (factory_ == address(0) || WETH9_ == address(0) || positionDescriptor_ == address(0))
            revert WrongConstructorParametersError();

        factory = factory_;
        WETH9 = WETH9_;
        positionDescriptor = positionDescriptor_;
    }
}

File 15 of 48 : IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.6;

import "./IERC20.sol";

/// @title   Interface for WETH9
/// @author  Primitive
interface IWETH9 is IERC20 {
    /// @notice Wraps ETH into WETH
    function deposit() external payable;

    /// @notice Unwraps WETH into ETH
    function withdraw(uint256) external;
}

File 16 of 48 : IManagerBase.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

/// @title   Interface of ManagerBase contract
/// @author  Primitive
interface IManagerBase {
    /// ERRORS ///

    /// @notice Thrown when the sender is not a Primitive Engine contract
    error NotEngineError();

    /// @notice Thrown when the constructor parameters are wrong
    error WrongConstructorParametersError();

    /// VIEW FUNCTIONS ///

    /// @notice Returns the address of the factory
    function factory() external view returns (address);

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

    /// @notice Returns the address of the PositionDescriptor
    function positionDescriptor() external view returns (address);
}

File 17 of 48 : Reentrancy.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

/// @title   Reentrancy contract
/// @author  Primitive
/// @notice  Prevents reentrancy
contract Reentrancy {
    /// @notice  Thrown when a call to the contract is made during a locked state
    error LockedError();

    /// @dev Reentrancy guard initialized to state
    uint256 private _locked = 1;

    /// @notice  Locks the contract to prevent reentrancy
    modifier lock() {
        if (_locked != 1) revert LockedError();

        _locked = 2;
        _;
        _locked = 1;
    }
}

File 18 of 48 : EngineAddress.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

/// @author  Primitive
/// @notice  Small library to compute the address of the engines
library EngineAddress {
    /// @notice Thrown when the target Engine is not deployed
    error EngineNotDeployedError();

    /// @notice Hash of the bytecode of the PrimitiveEngine
    bytes32 internal constant ENGINE_INIT_CODE_HASH =
        0xf8e63833fcbf190bd32bc64a1c450bd59b356b4b7cf79cad298a369fb369aaae;

    /// @notice         Computes the address of an engine
    /// @param factory  Address of the factory
    /// @param risky    Address of the risky token
    /// @param stable   Address of the stable token
    /// @return engine  Computed address of the engine
    function computeAddress(
        address factory,
        address risky,
        address stable
    ) internal pure returns (address engine) {
        engine = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(hex"ff", factory, keccak256(abi.encode(risky, stable)), ENGINE_INIT_CODE_HASH)
                    )
                )
            )
        );
    }
}

File 19 of 48 : IERC20.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

/// @title   ERC20 Interface
/// @author  Primitive
interface IERC20 {
    function totalSupply() external view returns (uint256);

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

    function transfer(address recipient, uint256 amount) external returns (bool);

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

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

    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);

    event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 20 of 48 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 21 of 48 : IERC20PermitAllowed.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.6;

/// @title   Interface for permit
/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/external/IERC20PermitAllowed.sol
/// @notice  Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
    /// @notice         Approve the spender to spend some tokens via the holder signature
    /// @dev            This is the permit interface used by DAI and CHAI
    /// @param holder   Address of the token holder, the token owner
    /// @param spender  Address of the token spender
    /// @param nonce    Holder's nonce, increases at each call to permit
    /// @param expiry   Timestamp at which the permit is no longer valid
    /// @param allowed  Boolean that sets approval amount, true for type(uint256).max and false for 0
    /// @param v        Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r        Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s        Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address holder,
        address spender,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

File 22 of 48 : ISelfPermit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.6;

/// @title   Interface of SelfPermit contract
/// @author  https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISelfPermit.sol
interface ISelfPermit {
    /// @notice          Permits this contract to spend a given token from `msg.sender`
    /// @dev             `owner` is always msg.sender and the `spender` is always address(this)
    /// @param token     Address of the token spent
    /// @param value     Amount that can be spent of token
    /// @param deadline  A timestamp, the current blocktime must be less than or equal to this timestamp
    /// @param v         Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r         Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s         Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermit(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice          Permits this contract to spend a given token from `msg.sender`
    /// @dev             `owner` is always msg.sender and the `spender` is always address(this)
    ///                  Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
    /// @param token     Address of the token spent
    /// @param value     Amount that can be spent of token
    /// @param deadline  A timestamp, the current blocktime must be less than or equal to this timestamp
    /// @param v         Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r         Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s         Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitIfNecessary(
        address token,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice        Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
    /// @dev           `owner` is always msg.sender and the `spender` is always address(this)
    /// @param token   Address of the token spent
    /// @param nonce   Current nonce of the owner
    /// @param expiry  Timestamp at which the permit is no longer valid
    /// @param v       Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r       Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s       Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitAllowed(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;

    /// @notice        Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
    /// @dev           `owner` is always msg.sender and the `spender` is always address(this)
    ///                Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed
    /// @param token   Address of the token spent
    /// @param nonce   Current nonce of the owner
    /// @param expiry  Timestamp at which the permit is no longer valid
    /// @param v       Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r       Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s       Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function selfPermitAllowedIfNecessary(
        address token,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

File 23 of 48 : ERC1155Permit.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "./ERC1155.sol";
import "../interfaces/IERC1155Permit.sol";

/// @title   ERC1155Permit contract
/// @author  Primitive
/// @notice  ERC1155 contract with permit extension allowing approvals to be made via signatures
contract ERC1155Permit is ERC1155, IERC1155Permit, EIP712 {
    /// @inheritdoc IERC1155Permit
    mapping(address => uint256) public override nonces;

    /// @dev Typehash of the permit function
    bytes32 private immutable _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address operator,bool approved,uint256 nonce,uint256 deadline)");

    constructor() ERC1155("") EIP712("PrimitiveManager", "1") {}

    /// @inheritdoc IERC1155Permit
    function permit(
        address owner,
        address operator,
        bool approved,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external override {
        if (block.timestamp > deadline) revert SigExpiredError();

        unchecked {
            bytes32 structHash = keccak256(
                abi.encode(_PERMIT_TYPEHASH, owner, operator, approved, nonces[owner]++, deadline)
            );

            bytes32 hash = _hashTypedDataV4(structHash);
            address signer = ECDSA.recover(hash, v, r, s);

            if (signer != owner) revert InvalidSigError();
        }

        _setApprovalForAll(owner, operator, approved);
    }

    /// @inheritdoc IERC1155Permit
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }
}

File 24 of 48 : IPositionDescriptor.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

/// @title   Interface of PositionDescriptor contract
/// @author  Primitive
interface IPositionDescriptor {
    /// VIEW FUNCTIONS ///

    /// @notice  Returns the address of the PositionRenderer contract
    function positionRenderer() external view returns (address);

    /// @notice         Returns the metadata of a position token
    /// @param engine   Address of the PrimitiveEngine contract
    /// @param tokenId  Id of the position token (pool id)
    /// @return         Metadata as a base64 encoded JSON string
    function getMetadata(address engine, uint256 tokenId) external view returns (string memory);
}

File 25 of 48 : draft-EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 26 of 48 : ERC1155.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 *
 * _Available since v3.1._
 */
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
    using Address for address;

    // Mapping from token ID to account balances
    mapping(uint256 => mapping(address => uint256)) private _balances;

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

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor(string memory uri_) {
        _setURI(uri_);
    }

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

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256) public view virtual override returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
        require(account != address(0), "ERC1155: balance query for the zero address");
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
        public
        view
        virtual
        override
        returns (uint256[] memory)
    {
        require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }

        return batchBalances;
    }

    /**
     * @dev See {IERC1155-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(_msgSender() != operator, "ERC1155: setting approval status for self");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), operator, approved);
    }

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

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not owner nor approved"
        );
        _safeTransferFrom(from, to, id, amount, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: transfer caller is not owner nor approved"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;

        emit TransferSingle(operator, from, to, id, amount);

        _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
            _balances[id][to] += amount;
        }

        emit TransferBatch(operator, from, to, ids, amounts);

        _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the amounts in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(
        address account,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(account != address(0), "ERC1155: mint to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);

        _balances[id][account] += amount;
        emit TransferSingle(operator, address(0), account, id, amount);

        _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; i++) {
            _balances[ids[i]][to] += amounts[i];
        }

        emit TransferBatch(operator, address(0), to, ids, amounts);

        _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
    }

    /**
     * @dev Destroys `amount` tokens of token type `id` from `account`
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens of token type `id`.
     */
    function _burn(
        address account,
        uint256 id,
        uint256 amount
    ) internal virtual {
        require(account != address(0), "ERC1155: burn from the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");

        uint256 accountBalance = _balances[id][account];
        require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][account] = accountBalance - amount;
        }

        emit TransferSingle(operator, account, address(0), id, amount);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     */
    function _burnBatch(
        address account,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        require(account != address(0), "ERC1155: burn from the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, account, address(0), ids, amounts, "");

        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 accountBalance = _balances[id][account];
            require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
            unchecked {
                _balances[id][account] = accountBalance - amount;
            }
        }

        emit TransferBatch(operator, account, address(0), ids, amounts);
    }

    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal {
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `id` and `amount` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) private {
        if (to.code.length != 0) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) private {
        if (to.code.length != 0) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
        uint256[] memory array = new uint256[](1);
        array[0] = element;

        return array;
    }
}

File 27 of 48 : IERC1155Permit.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";

/// @title   Interface of ERC1155Permit contract
/// @author  Primitive
interface IERC1155Permit is IERC1155 {
    /// ERRORS ///

    /// @notice Thrown when the signature has expired
    error SigExpiredError();

    /// @notice Thrown when the signature is invalid
    error InvalidSigError();

    /// EFFECT FUNCTIONS ///

    /// @notice          Grants or revokes the approval for an operator to transfer any of the owner's
    ///                  tokens using their signature
    /// @param owner     Address of the owner
    /// @param operator  Address of the operator
    /// @param approved  True if the approval should be granted, false if revoked
    /// @param deadline  Expiry of the signature, as a timestamp
    /// @param v         Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r         Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s         Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address owner,
        address operator,
        bool approved,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /// VIEW FUNCTIONS ///

    /// @notice Returns the current nonce of an address
    /// @param owner Address to inspect
    /// @return Current nonce of an address
    function nonces(address owner) external view returns (uint256);

    /// @notice Returns the domain separator
    /// @return Hash of the domain separator
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 28 of 48 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 29 of 48 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @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] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

File 30 of 48 : IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

File 31 of 48 : IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

File 32 of 48 : IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity ^0.8.0;

import "../IERC1155.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

File 33 of 48 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 34 of 48 : 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 35 of 48 : 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 36 of 48 : 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 37 of 48 : IPrimitiveEngineActions.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  Action functions for the Primitive Engine contract
/// @author Primitive
interface IPrimitiveEngineActions {
    // ===== Pool Updates =====

    /// @notice             Updates the time until expiry of the pool by setting its last timestamp value
    /// @param  poolId      Keccak256 hash of engine address, strike, sigma, maturity, and gamma
    /// @return lastTimestamp Timestamp loaded into the state of the pool's Calibration.lastTimestamp
    function updateLastTimestamp(bytes32 poolId) external returns (uint32 lastTimestamp);

    /// @notice             Initializes a curve with parameters in the `calibrations` storage mapping in the Engine
    /// @param  strike      Marginal price of the pool's risky token at maturity, with the same decimals as the stable token, valid [0, 2^128-1]
    /// @param  sigma       AKA Implied Volatility in basis points, determines the price impact of swaps, valid for (1, 10_000_000)
    /// @param  maturity    Timestamp which starts the BUFFER countdown until swaps will cease, in seconds, valid for (block.timestamp, 2^32-1]
    /// @param  gamma       Multiplied against swap in amounts to apply fee, equal to 1 - fee % but units are in basis points, valid for (9_000, 10_000)
    /// @param  riskyPerLp  Risky reserve per liq. with risky decimals, = 1 - N(d1), d1 = (ln(S/K)+(r*σ^2/2))/σ√τ, valid for [0, 1e^(risky token decimals))
    /// @param  delLiquidity Amount of liquidity units to allocate to the curve, wei value with 18 decimals of precision
    /// @param  data        Arbitrary data that is passed to the createCallback function
    /// @return poolId      Keccak256 hash of engine address, strike, sigma, maturity, and gamma
    /// @return delRisky    Total amount of risky tokens provided to reserves
    /// @return delStable   Total amount of stable tokens provided to reserves
    function create(
        uint128 strike,
        uint32 sigma,
        uint32 maturity,
        uint32 gamma,
        uint256 riskyPerLp,
        uint256 delLiquidity,
        bytes calldata data
    )
        external
        returns (
            bytes32 poolId,
            uint256 delRisky,
            uint256 delStable
        );

    // ===== Margin ====

    /// @notice             Adds risky and/or stable tokens to a `recipient`'s internal balance account
    /// @param  recipient   Recipient margin account of the deposited tokens
    /// @param  delRisky    Amount of risky tokens to deposit
    /// @param  delStable   Amount of stable tokens to deposit
    /// @param  data        Arbitrary data that is passed to the depositCallback function
    function deposit(
        address recipient,
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external;

    /// @notice             Removes risky and/or stable tokens from a `msg.sender`'s internal balance account
    /// @param  recipient   Address that tokens are transferred to
    /// @param  delRisky    Amount of risky tokens to withdraw
    /// @param  delStable   Amount of stable tokens to withdraw
    function withdraw(
        address recipient,
        uint256 delRisky,
        uint256 delStable
    ) external;

    // ===== Liquidity =====

    /// @notice             Allocates risky and stable tokens to a specific curve with `poolId`
    /// @param  poolId      Keccak256 hash of engine address, strike, sigma, maturity, and gamma
    /// @param  recipient   Address to give the allocated liquidity to
    /// @param  delRisky    Amount of risky tokens to add
    /// @param  delStable   Amount of stable tokens to add
    /// @param  fromMargin  Whether the `msg.sender` pays with their margin balance, or must send tokens
    /// @param  data        Arbitrary data that is passed to the allocateCallback function
    /// @return delLiquidity Amount of liquidity given to `recipient`
    function allocate(
        bytes32 poolId,
        address recipient,
        uint256 delRisky,
        uint256 delStable,
        bool fromMargin,
        bytes calldata data
    ) external returns (uint256 delLiquidity);

    /// @notice               Unallocates risky and stable tokens from a specific curve with `poolId`
    /// @param  poolId        Keccak256 hash of engine address, strike, sigma, maturity, and gamma
    /// @param  delLiquidity  Amount of liquidity to remove
    /// @return delRisky      Amount of risky tokens received from removed liquidity
    /// @return delStable     Amount of stable tokens received from removed liquidity
    function remove(bytes32 poolId, uint256 delLiquidity) external returns (uint256 delRisky, uint256 delStable);

    // ===== Swaps =====

    /// @notice             Swaps between `risky` and `stable` tokens
    /// @param  recipient   Address that receives output token `deltaOut` amount
    /// @param  poolId      Keccak256 hash of engine address, strike, sigma, maturity, and gamma
    /// @param  riskyForStable If true, swap risky to stable, else swap stable to risky
    /// @param  deltaIn     Amount of tokens to swap in
    /// @param  deltaOut    Amount of tokens to swap out
    /// @param  fromMargin  Whether the `msg.sender` uses their margin balance, or must send tokens
    /// @param  toMargin    Whether the `deltaOut` amount is transferred or deposited into margin
    /// @param  data        Arbitrary data that is passed to the swapCallback function
    function swap(
        address recipient,
        bytes32 poolId,
        bool riskyForStable,
        uint256 deltaIn,
        uint256 deltaOut,
        bool fromMargin,
        bool toMargin,
        bytes calldata data
    ) external;
}

File 38 of 48 : ReplicationMath.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.4;

import "./ABDKMath64x64.sol";
import "./CumulativeNormalDistribution.sol";
import "./Units.sol";

/// @title   Replication Math
/// @author  Primitive
/// @notice  Alex Evans, Guillermo Angeris, and Tarun Chitra. Replicating Market Makers.
///          https://stanford.edu/~guillean/papers/rmms.pdf
library ReplicationMath {
    using ABDKMath64x64 for int128;
    using ABDKMath64x64 for uint256;
    using CumulativeNormalDistribution for int128;
    using Units for int128;
    using Units for uint256;

    int128 internal constant ONE_INT = 0x10000000000000000;

    /// @notice         Normalizes volatility with respect to square root of time until expiry
    /// @param   sigma  Unsigned 256-bit percentage as an integer with precision of 1e4, 10000 = 100%
    /// @param   tau    Time until expiry in seconds as an unsigned 256-bit integer
    /// @return  vol    Signed fixed point 64.64 number equal to sigma * sqrt(tau)
    function getProportionalVolatility(uint256 sigma, uint256 tau) internal pure returns (int128 vol) {
        int128 sqrtTauX64 = tau.toYears().sqrt();
        int128 sigmaX64 = sigma.percentageToX64();
        vol = sigmaX64.mul(sqrtTauX64);
    }

    /// @notice                 Uses riskyPerLiquidity and invariant to calculate stablePerLiquidity
    /// @dev                    Converts unsigned 256-bit values to fixed point 64.64 numbers w/ decimals of precision
    /// @param   invariantLastX64   Signed 64.64 fixed point number. Calculated w/ same `tau` as the parameter `tau`
    /// @param   scaleFactorRisky   Unsigned 256-bit integer scaling factor for `risky`, 10^(18 - risky.decimals())
    /// @param   scaleFactorStable  Unsigned 256-bit integer scaling factor for `stable`, 10^(18 - stable.decimals())
    /// @param   riskyPerLiquidity  Unsigned 256-bit integer of Pool's risky reserves *per liquidity*, 0 <= x <= 1
    /// @param   strike         Unsigned 256-bit integer value with precision equal to 10^(18 - scaleFactorStable)
    /// @param   sigma          Volatility of the Pool as an unsigned 256-bit integer w/ precision of 1e4, 10000 = 100%
    /// @param   tau            Time until expiry in seconds as an unsigned 256-bit integer
    /// @return  stablePerLiquidity = K*CDF(CDF^-1(1 - riskyPerLiquidity) - sigma*sqrt(tau)) + invariantLastX64 as uint
    function getStableGivenRisky(
        int128 invariantLastX64,
        uint256 scaleFactorRisky,
        uint256 scaleFactorStable,
        uint256 riskyPerLiquidity,
        uint256 strike,
        uint256 sigma,
        uint256 tau
    ) internal pure returns (uint256 stablePerLiquidity) {
        int128 strikeX64 = strike.scaleToX64(scaleFactorStable);
        int128 riskyX64 = riskyPerLiquidity.scaleToX64(scaleFactorRisky); // mul by 2^64, div by precision
        int128 oneMinusRiskyX64 = ONE_INT.sub(riskyX64);
        if (tau != 0) {
            int128 volX64 = getProportionalVolatility(sigma, tau);
            int128 phi = oneMinusRiskyX64.getInverseCDF();
            int128 input = phi.sub(volX64);
            int128 stableX64 = strikeX64.mul(input.getCDF()).add(invariantLastX64);
            stablePerLiquidity = stableX64.scaleFromX64(scaleFactorStable);
        } else {
            stablePerLiquidity = (strikeX64.mul(oneMinusRiskyX64).add(invariantLastX64)).scaleFromX64(
                scaleFactorStable
            );
        }
    }

    /// @notice                 Calculates the invariant of a curve
    /// @dev                    Per unit of replication, aka per unit of liquidity
    /// @param   scaleFactorRisky   Unsigned 256-bit integer scaling factor for `risky`, 10^(18 - risky.decimals())
    /// @param   scaleFactorStable  Unsigned 256-bit integer scaling factor for `stable`, 10^(18 - stable.decimals())
    /// @param   riskyPerLiquidity  Unsigned 256-bit integer of Pool's risky reserves *per liquidity*, 0 <= x <= 1
    /// @param   stablePerLiquidity Unsigned 256-bit integer of Pool's stable reserves *per liquidity*, 0 <= x <= strike
    /// @return  invariantX64       = stablePerLiquidity - K * CDF(CDF^-1(1 - riskyPerLiquidity) - sigma * sqrt(tau))
    function calcInvariant(
        uint256 scaleFactorRisky,
        uint256 scaleFactorStable,
        uint256 riskyPerLiquidity,
        uint256 stablePerLiquidity,
        uint256 strike,
        uint256 sigma,
        uint256 tau
    ) internal pure returns (int128 invariantX64) {
        uint256 output = getStableGivenRisky(
            0,
            scaleFactorRisky,
            scaleFactorStable,
            riskyPerLiquidity,
            strike,
            sigma,
            tau
        );
        int128 outputX64 = output.scaleToX64(scaleFactorStable);
        int128 stableX64 = stablePerLiquidity.scaleToX64(scaleFactorStable);
        invariantX64 = stableX64.sub(outputX64);
    }
}

File 39 of 48 : ISwapManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/callback/IPrimitiveSwapCallback.sol";

/// @title   Interface of SwapManager contract
/// @author  Primitive
interface ISwapManager is IPrimitiveSwapCallback {
    /// @notice                Parameters for the swap function
    /// @param recipient       Address of the recipient
    /// @param risky           Address of the risky token
    /// @param stable          Address of the stable token
    /// @param poolId          Id of the pool
    /// @param riskyForStable  True if swapping risky for stable
    /// @param deltaIn         Exact amount to send
    /// @param deltaOut        Exact amount to receive
    /// @param fromMargin      True if the sent amount should be taken from the margin
    /// @param toMargin        True if the received amount should be sent to the margin
    /// @param deadline        Transaction will revert above this deadline
    struct SwapParams {
        address recipient;
        address risky;
        address stable;
        bytes32 poolId;
        bool riskyForStable;
        uint256 deltaIn;
        uint256 deltaOut;
        bool fromMargin;
        bool toMargin;
        uint256 deadline;
    }

    /// ERRORS ///

    /// @notice Thrown when the deadline is reached
    error DeadlineReachedError();

    /// EVENTS ///

    /// @notice                Emitted when a swap occurs
    /// @param payer           Address of the payer
    /// @param recipient       Address of the recipient
    /// @param engine          Address of the engine
    /// @param poolId          Id of the pool
    /// @param riskyForStable  True if swapping risky for stable
    /// @param deltaIn         Sent amount
    /// @param deltaOut        Received amount
    /// @param fromMargin      True if the sent amount is taken from the margin
    /// @param toMargin        True if the received amount is sent to the margin
    event Swap(
        address indexed payer,
        address recipient,
        address indexed engine,
        bytes32 indexed poolId,
        bool riskyForStable,
        uint256 deltaIn,
        uint256 deltaOut,
        bool fromMargin,
        bool toMargin
    );

    /// EFFECTS FUNCTIONS ///

    /// @notice        Swaps an exact amount of risky OR stable tokens for some risky OR stable tokens
    /// @dev           Funds are swapped from a specific pool located into a specific engine
    /// @param params  A struct of type SwapParameters
    function swap(SwapParams calldata params) external payable;
}

File 40 of 48 : MarginManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/engine/IPrimitiveEngineActions.sol";
import "@primitivefi/rmm-core/contracts/interfaces/engine/IPrimitiveEngineView.sol";
import "../interfaces/IMarginManager.sol";
import "./CashManager.sol";
import "../libraries/TransferHelper.sol";
import "../libraries/Margin.sol";

/// @title   MarginManager contract
/// @author  Primitive
/// @notice  Manages the margins
abstract contract MarginManager is IMarginManager, CashManager {
    using TransferHelper for IERC20;
    using Margin for Margin.Data;

    /// @inheritdoc IMarginManager
    mapping(address => mapping(address => Margin.Data)) public override margins;

    /// EFFECT FUNCTIONS ///

    /// @inheritdoc IMarginManager
    function deposit(
        address recipient,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable
    ) external payable override lock {
        if (delRisky == 0 && delStable == 0) revert ZeroDelError();

        address engine = EngineAddress.computeAddress(factory, risky, stable);
        if (engine.code.length == 0) revert EngineAddress.EngineNotDeployedError();

        IPrimitiveEngineActions(engine).deposit(
            address(this),
            delRisky,
            delStable,
            abi.encode(CallbackData({payer: msg.sender, risky: risky, stable: stable}))
        );

        margins[recipient][engine].deposit(delRisky, delStable);

        emit Deposit(msg.sender, recipient, engine, risky, stable, delRisky, delStable);
    }

    /// @inheritdoc IMarginManager
    function withdraw(
        address recipient,
        address engine,
        uint256 delRisky,
        uint256 delStable
    ) external override lock {
        if (delRisky == 0 && delStable == 0) revert ZeroDelError();

        // Reverts the call early if margins are insufficient
        margins[msg.sender][engine].withdraw(delRisky, delStable);

        // Setting address(0) as the recipient will result in the tokens
        // being sent into the contract itself, useful to unwrap WETH for example
        IPrimitiveEngineActions(engine).withdraw(
            recipient == address(0) ? address(this) : recipient,
            delRisky,
            delStable
        );

        emit Withdraw(
            msg.sender,
            recipient == address(0) ? msg.sender : recipient,
            engine,
            IPrimitiveEngineView(engine).risky(),
            IPrimitiveEngineView(engine).stable(),
            delRisky,
            delStable
        );
    }

    /// CALLBACK IMPLEMENTATIONS ///

    /// @inheritdoc IPrimitiveDepositCallback
    function depositCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external override {
        CallbackData memory decoded = abi.decode(data, (CallbackData));

        address engine = EngineAddress.computeAddress(factory, decoded.risky, decoded.stable);
        if (msg.sender != engine) revert NotEngineError();

        if (delStable != 0) pay(decoded.stable, decoded.payer, msg.sender, delStable);
        if (delRisky != 0) pay(decoded.risky, decoded.payer, msg.sender, delRisky);
    }
}

File 41 of 48 : ABDKMath64x64.sol
// SPDX-License-Identifier: BSD-4-Clause
/*
 * ABDK Math 64.64 Smart Contract Library.  Copyright © 2019 by ABDK Consulting.
 * Author: Mikhail Vladimirov <[email protected]>
 */
pragma solidity ^0.8.0;

/**
 * Smart contract library of mathematical functions operating with signed
 * 64.64-bit fixed point numbers.  Signed 64.64-bit fixed point number is
 * basically a simple fraction whose numerator is signed 128-bit integer and
 * denominator is 2^64.  As long as denominator is always the same, there is no
 * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
 * represented by int128 type holding only the numerator.
 */
library ABDKMath64x64 {
    /*
     * Minimum value signed 64.64-bit fixed point number may have.
     */
    int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;

    /*
     * Maximum value signed 64.64-bit fixed point number may have.
     */
    int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

    /**
     * Convert signed 256-bit integer number into signed 64.64-bit fixed point
     * number.  Revert on overflow.
     *
     * @param x signed 256-bit integer number
     * @return signed 64.64-bit fixed point number
     */
    function fromInt(int256 x) internal pure returns (int128) {
        unchecked {
            require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
            return int128(x << 64);
        }
    }

    /**
     * Convert signed 64.64 fixed point number into signed 64-bit integer number
     * rounding down.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64-bit integer number
     */
    function toInt(int128 x) internal pure returns (int64) {
        unchecked {
            return int64(x >> 64);
        }
    }

    /**
     * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
     * number.  Revert on overflow.
     *
     * @param x unsigned 256-bit integer number
     * @return signed 64.64-bit fixed point number
     */
    function fromUInt(uint256 x) internal pure returns (int128) {
        unchecked {
            require(x <= 0x7FFFFFFFFFFFFFFF);
            return int128(int256(x << 64));
        }
    }

    /**
     * Convert signed 64.64 fixed point number into unsigned 64-bit integer
     * number rounding down.  Revert on underflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @return unsigned 64-bit integer number
     */
    function toUInt(int128 x) internal pure returns (uint64) {
        unchecked {
            require(x >= 0);
            return uint64(uint128(x >> 64));
        }
    }

    /**
     * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
     * number rounding down.  Revert on overflow.
     *
     * @param x signed 128.128-bin fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function from128x128(int256 x) internal pure returns (int128) {
        unchecked {
            int256 result = x >> 64;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Convert signed 64.64 fixed point number into signed 128.128 fixed point
     * number.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 128.128 fixed point number
     */
    function to128x128(int128 x) internal pure returns (int256) {
        unchecked {
            return int256(x) << 64;
        }
    }

    /**
     * Calculate x + y.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function add(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            int256 result = int256(x) + y;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate x - y.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function sub(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            int256 result = int256(x) - y;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate x * y rounding down.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function mul(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            int256 result = (int256(x) * y) >> 64;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
     * number and y is signed 256-bit integer number.  Revert on overflow.
     *
     * @param x signed 64.64 fixed point number
     * @param y signed 256-bit integer number
     * @return signed 256-bit integer number
     */
    function muli(int128 x, int256 y) internal pure returns (int256) {
        unchecked {
            if (x == MIN_64x64) {
                require(
                    y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
                        y <= 0x1000000000000000000000000000000000000000000000000
                );
                return -y << 63;
            } else {
                bool negativeResult = false;
                if (x < 0) {
                    x = -x;
                    negativeResult = true;
                }
                if (y < 0) {
                    y = -y; // We rely on overflow behavior here
                    negativeResult = !negativeResult;
                }
                uint256 absoluteResult = mulu(x, uint256(y));
                if (negativeResult) {
                    require(absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000);
                    return -int256(absoluteResult); // We rely on overflow behavior here
                } else {
                    require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
                    return int256(absoluteResult);
                }
            }
        }
    }

    /**
     * Calculate x * y rounding down, where x is signed 64.64 fixed point number
     * and y is unsigned 256-bit integer number.  Revert on overflow.
     *
     * @param x signed 64.64 fixed point number
     * @param y unsigned 256-bit integer number
     * @return unsigned 256-bit integer number
     */
    function mulu(int128 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            if (y == 0) return 0;

            require(x >= 0);

            uint256 lo = (uint256(int256(x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
            uint256 hi = uint256(int256(x)) * (y >> 128);

            require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
            hi <<= 64;

            require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
            return hi + lo;
        }
    }

    /**
     * Calculate x / y rounding towards zero.  Revert on overflow or when y is
     * zero.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function div(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            require(y != 0);
            int256 result = (int256(x) << 64) / y;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate x / y rounding towards zero, where x and y are signed 256-bit
     * integer numbers.  Revert on overflow or when y is zero.
     *
     * @param x signed 256-bit integer number
     * @param y signed 256-bit integer number
     * @return signed 64.64-bit fixed point number
     */
    function divi(int256 x, int256 y) internal pure returns (int128) {
        unchecked {
            require(y != 0);

            bool negativeResult = false;
            if (x < 0) {
                x = -x; // We rely on overflow behavior here
                negativeResult = true;
            }
            if (y < 0) {
                y = -y; // We rely on overflow behavior here
                negativeResult = !negativeResult;
            }
            uint128 absoluteResult = divuu(uint256(x), uint256(y));
            if (negativeResult) {
                require(absoluteResult <= 0x80000000000000000000000000000000);
                return -int128(absoluteResult); // We rely on overflow behavior here
            } else {
                require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
                return int128(absoluteResult); // We rely on overflow behavior here
            }
        }
    }

    /**
     * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
     * integer numbers.  Revert on overflow or when y is zero.
     *
     * @param x unsigned 256-bit integer number
     * @param y unsigned 256-bit integer number
     * @return signed 64.64-bit fixed point number
     */
    function divu(uint256 x, uint256 y) internal pure returns (int128) {
        unchecked {
            require(y != 0);
            uint128 result = divuu(x, y);
            require(result <= uint128(MAX_64x64));
            return int128(result);
        }
    }

    /**
     * Calculate -x.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function neg(int128 x) internal pure returns (int128) {
        unchecked {
            require(x != MIN_64x64);
            return -x;
        }
    }

    /**
     * Calculate |x|.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function abs(int128 x) internal pure returns (int128) {
        unchecked {
            require(x != MIN_64x64);
            return x < 0 ? -x : x;
        }
    }

    /**
     * Calculate 1 / x rounding towards zero.  Revert on overflow or when x is
     * zero.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function inv(int128 x) internal pure returns (int128) {
        unchecked {
            require(x != 0);
            int256 result = int256(0x100000000000000000000000000000000) / x;
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function avg(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            return int128((int256(x) + int256(y)) >> 1);
        }
    }

    /**
     * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
     * Revert on overflow or in case x * y is negative.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function gavg(int128 x, int128 y) internal pure returns (int128) {
        unchecked {
            int256 m = int256(x) * int256(y);
            require(m >= 0);
            require(m < 0x4000000000000000000000000000000000000000000000000000000000000000);
            return int128(sqrtu(uint256(m)));
        }
    }

    /**
     * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
     * and y is unsigned 256-bit integer number.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @param y uint256 value
     * @return signed 64.64-bit fixed point number
     */
    function pow(int128 x, uint256 y) internal pure returns (int128) {
        unchecked {
            bool negative = x < 0 && y & 1 == 1;

            uint256 absX = uint128(x < 0 ? -x : x);
            uint256 absResult;
            absResult = 0x100000000000000000000000000000000;

            if (absX <= 0x10000000000000000) {
                absX <<= 63;
                while (y != 0) {
                    if (y & 0x1 != 0) {
                        absResult = (absResult * absX) >> 127;
                    }
                    absX = (absX * absX) >> 127;

                    if (y & 0x2 != 0) {
                        absResult = (absResult * absX) >> 127;
                    }
                    absX = (absX * absX) >> 127;

                    if (y & 0x4 != 0) {
                        absResult = (absResult * absX) >> 127;
                    }
                    absX = (absX * absX) >> 127;

                    if (y & 0x8 != 0) {
                        absResult = (absResult * absX) >> 127;
                    }
                    absX = (absX * absX) >> 127;

                    y >>= 4;
                }

                absResult >>= 64;
            } else {
                uint256 absXShift = 63;
                if (absX < 0x1000000000000000000000000) {
                    absX <<= 32;
                    absXShift -= 32;
                }
                if (absX < 0x10000000000000000000000000000) {
                    absX <<= 16;
                    absXShift -= 16;
                }
                if (absX < 0x1000000000000000000000000000000) {
                    absX <<= 8;
                    absXShift -= 8;
                }
                if (absX < 0x10000000000000000000000000000000) {
                    absX <<= 4;
                    absXShift -= 4;
                }
                if (absX < 0x40000000000000000000000000000000) {
                    absX <<= 2;
                    absXShift -= 2;
                }
                if (absX < 0x80000000000000000000000000000000) {
                    absX <<= 1;
                    absXShift -= 1;
                }

                uint256 resultShift = 0;
                while (y != 0) {
                    require(absXShift < 64);

                    if (y & 0x1 != 0) {
                        absResult = (absResult * absX) >> 127;
                        resultShift += absXShift;
                        if (absResult > 0x100000000000000000000000000000000) {
                            absResult >>= 1;
                            resultShift += 1;
                        }
                    }
                    absX = (absX * absX) >> 127;
                    absXShift <<= 1;
                    if (absX >= 0x100000000000000000000000000000000) {
                        absX >>= 1;
                        absXShift += 1;
                    }

                    y >>= 1;
                }

                require(resultShift < 64);
                absResult >>= 64 - resultShift;
            }
            int256 result = negative ? -int256(absResult) : int256(absResult);
            require(result >= MIN_64x64 && result <= MAX_64x64);
            return int128(result);
        }
    }

    /**
     * Calculate sqrt (x) rounding down.  Revert if x < 0.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function sqrt(int128 x) internal pure returns (int128) {
        unchecked {
            require(x >= 0);
            return int128(sqrtu(uint256(int256(x)) << 64));
        }
    }

    /**
     * Calculate binary logarithm of x.  Revert if x <= 0.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function log_2(int128 x) internal pure returns (int128) {
        unchecked {
            require(x > 0);

            int256 msb = 0;
            int256 xc = x;
            if (xc >= 0x10000000000000000) {
                xc >>= 64;
                msb += 64;
            }
            if (xc >= 0x100000000) {
                xc >>= 32;
                msb += 32;
            }
            if (xc >= 0x10000) {
                xc >>= 16;
                msb += 16;
            }
            if (xc >= 0x100) {
                xc >>= 8;
                msb += 8;
            }
            if (xc >= 0x10) {
                xc >>= 4;
                msb += 4;
            }
            if (xc >= 0x4) {
                xc >>= 2;
                msb += 2;
            }
            if (xc >= 0x2) msb += 1; // No need to shift xc anymore

            int256 result = (msb - 64) << 64;
            uint256 ux = uint256(int256(x)) << uint256(127 - msb);
            for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
                ux *= ux;
                uint256 b = ux >> 255;
                ux >>= 127 + b;
                result += bit * int256(b);
            }

            return int128(result);
        }
    }

    /**
     * Calculate natural logarithm of x.  Revert if x <= 0.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function ln(int128 x) internal pure returns (int128) {
        unchecked {
            require(x > 0);

            return int128(int256((uint256(int256(log_2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128));
        }
    }

    /**
     * Calculate binary exponent of x.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function exp_2(int128 x) internal pure returns (int128) {
        unchecked {
            require(x < 0x400000000000000000); // Overflow

            if (x < -0x400000000000000000) return 0; // Underflow

            uint256 result = 0x80000000000000000000000000000000;

            if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
            if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
            if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
            if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
            if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
            if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
            if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
            if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
            if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
            if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
            if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
            if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
            if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
            if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
            if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
            if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
            if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
            if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
            if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
            if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
            if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
            if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
            if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
            if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
            if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
            if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
            if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
            if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
            if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
            if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
            if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
            if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
            if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
            if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
            if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
            if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
            if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
            if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
            if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
            if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
            if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
            if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
            if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
            if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
            if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
            if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
            if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
            if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
            if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
            if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
            if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
            if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
            if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
            if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
            if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
            if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
            if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
            if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
            if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
            if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
            if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
            if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
            if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
            if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;

            result >>= uint256(int256(63 - (x >> 64)));
            require(result <= uint256(int256(MAX_64x64)));

            return int128(int256(result));
        }
    }

    /**
     * Calculate natural exponent of x.  Revert on overflow.
     *
     * @param x signed 64.64-bit fixed point number
     * @return signed 64.64-bit fixed point number
     */
    function exp(int128 x) internal pure returns (int128) {
        unchecked {
            require(x < 0x400000000000000000); // Overflow

            if (x < -0x400000000000000000) return 0; // Underflow

            return exp_2(int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128));
        }
    }

    /**
     * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
     * integer numbers.  Revert on overflow or when y is zero.
     *
     * @param x unsigned 256-bit integer number
     * @param y unsigned 256-bit integer number
     * @return unsigned 64.64-bit fixed point number
     */
    function divuu(uint256 x, uint256 y) private pure returns (uint128) {
        unchecked {
            require(y != 0);

            uint256 result;

            if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
            else {
                uint256 msb = 192;
                uint256 xc = x >> 192;
                if (xc >= 0x100000000) {
                    xc >>= 32;
                    msb += 32;
                }
                if (xc >= 0x10000) {
                    xc >>= 16;
                    msb += 16;
                }
                if (xc >= 0x100) {
                    xc >>= 8;
                    msb += 8;
                }
                if (xc >= 0x10) {
                    xc >>= 4;
                    msb += 4;
                }
                if (xc >= 0x4) {
                    xc >>= 2;
                    msb += 2;
                }
                if (xc >= 0x2) msb += 1; // No need to shift xc anymore

                result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
                require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);

                uint256 hi = result * (y >> 128);
                uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);

                uint256 xh = x >> 192;
                uint256 xl = x << 64;

                if (xl < lo) xh -= 1;
                xl -= lo; // We rely on overflow behavior here
                lo = hi << 128;
                if (xl < lo) xh -= 1;
                xl -= lo; // We rely on overflow behavior here

                assert(xh == hi >> 128);

                result += xl / y;
            }

            require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
            return uint128(result);
        }
    }

    /**
     * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
     * number.
     *
     * @param x unsigned 256-bit integer number
     * @return unsigned 128-bit integer number
     */
    function sqrtu(uint256 x) private pure returns (uint128) {
        unchecked {
            if (x == 0) return 0;
            else {
                uint256 xx = x;
                uint256 r = 1;
                if (xx >= 0x100000000000000000000000000000000) {
                    xx >>= 128;
                    r <<= 64;
                }
                if (xx >= 0x10000000000000000) {
                    xx >>= 64;
                    r <<= 32;
                }
                if (xx >= 0x100000000) {
                    xx >>= 32;
                    r <<= 16;
                }
                if (xx >= 0x10000) {
                    xx >>= 16;
                    r <<= 8;
                }
                if (xx >= 0x100) {
                    xx >>= 8;
                    r <<= 4;
                }
                if (xx >= 0x10) {
                    xx >>= 4;
                    r <<= 2;
                }
                if (xx >= 0x8) {
                    r <<= 1;
                }
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1;
                r = (r + x / r) >> 1; // Seven iterations should be enough
                uint256 r1 = x / r;
                return uint128(r < r1 ? r : r1);
            }
        }
    }
}

File 42 of 48 : CumulativeNormalDistribution.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.4;

import "./ABDKMath64x64.sol";

/// @title   Cumulative Normal Distribution Math Library
/// @author  Primitive
library CumulativeNormalDistribution {
    using ABDKMath64x64 for int128;
    using ABDKMath64x64 for uint256;

    /// @notice Thrown on passing an arg that is out of the input range for these math functions
    error InverseOutOfBounds(int128 value);

    int128 public constant ONE_INT = 0x10000000000000000;
    int128 public constant TWO_INT = 0x20000000000000000;
    int128 public constant CDF0 = 0x53dd02a4f5ee2e46;
    int128 public constant CDF1 = 0x413c831bb169f874;
    int128 public constant CDF2 = -0x48d4c730f051a5fe;
    int128 public constant CDF3 = 0x16a09e667f3bcc908;
    int128 public constant CDF4 = -0x17401c57014c38f14;
    int128 public constant CDF5 = 0x10fb844255a12d72e;

    /// @notice Uses Abramowitz and Stegun approximation:
    ///         https://en.wikipedia.org/wiki/Abramowitz_and_Stegun
    /// @dev    Maximum error: 3.15x10-3
    /// @return Standard Normal Cumulative Distribution Function of `x`
    function getCDF(int128 x) internal pure returns (int128) {
        int128 z = x.div(CDF3);
        int128 t = ONE_INT.div(ONE_INT.add(CDF0.mul(z.abs())));
        int128 erf = getErrorFunction(z, t);
        if (z < 0) {
            erf = erf.neg();
        }
        int128 result = (HALF_INT).mul(ONE_INT.add(erf));
        return result;
    }

    /// @notice Uses Abramowitz and Stegun approximation:
    ///         https://en.wikipedia.org/wiki/Error_function
    /// @dev    Maximum error: 1.5×10−7
    /// @return Error Function for approximating the Standard Normal CDF
    function getErrorFunction(int128 z, int128 t) internal pure returns (int128) {
        int128 step1 = t.mul(CDF3.add(t.mul(CDF4.add(t.mul(CDF5)))));
        int128 step2 = CDF1.add(t.mul(CDF2.add(step1)));
        int128 result = ONE_INT.sub(t.mul(step2.mul((z.mul(z).neg()).exp())));
        return result;
    }

    int128 public constant HALF_INT = 0x8000000000000000;
    int128 public constant INVERSE0 = 0x26A8F3C1F21B336E;
    int128 public constant INVERSE1 = -0x87C57E5DA70D3C90;
    int128 public constant INVERSE2 = 0x15D71F5721242C787;
    int128 public constant INVERSE3 = 0x21D0A04B0E9B94F1;
    int128 public constant INVERSE4 = -0xC2BF5D74C724E53F;

    int128 public constant LOW_TAIL = 0x666666666666666; // 0.025
    int128 public constant HIGH_TAIL = 0xF999999999999999; // 0.975

    /// @notice  Returns the inverse CDF, or quantile function of `p`.
    /// @dev     Source: https://arxiv.org/pdf/1002.0567.pdf
    ///          Maximum error of central region is 1.16x10−4
    /// @return  fcentral(p) = q * (a2 + (a1r + a0) / (r^2 + b1r +b0))
    function getInverseCDF(int128 p) internal pure returns (int128) {
        if (p >= ONE_INT || p <= 0) revert InverseOutOfBounds(p);
        // Short circuit for the central region, central region inclusive of tails
        if (p <= HIGH_TAIL && p >= LOW_TAIL) {
            return central(p);
        } else if (p < LOW_TAIL) {
            return tail(p);
        } else {
            int128 negativeTail = -tail(ONE_INT.sub(p));
            return negativeTail;
        }
    }

    /// @dev    Maximum error: 1.16x10−4
    /// @return Inverse CDF around the central area of 0.025 <= p <= 0.975
    function central(int128 p) internal pure returns (int128) {
        int128 q = p.sub(HALF_INT);
        int128 r = q.mul(q);
        int128 result = q.mul(
            INVERSE2.add((INVERSE1.mul(r).add(INVERSE0)).div((r.mul(r).add(INVERSE4.mul(r)).add(INVERSE3))))
        );
        return result;
    }

    int128 public constant C0 = 0x10E56D75CE8BCE9FAE;
    int128 public constant C1 = -0x2CB2447D36D513DAE;
    int128 public constant C2 = -0x8BB4226952BD69EDF;
    int128 public constant C3 = -0x1000BF627FA188411;
    int128 public constant C0_D = 0x10AEAC93F55267A9A5;
    int128 public constant C1_D = 0x41ED34A2561490236;
    int128 public constant C2_D = 0x7A1E70F720ECA43;
    int128 public constant D0 = 0x72C7D592D021FB1DB;
    int128 public constant D1 = 0x8C27B4617F5F800EA;

    /// @dev    Maximum error: 2.458x10-5
    /// @return Inverse CDF of the tail, defined for p < 0.0465, used with p < 0.025
    function tail(int128 p) internal pure returns (int128) {
        int128 r = ONE_INT.div(p.mul(p)).ln().sqrt();
        int128 step0 = C3.mul(r).add(C2_D);
        int128 numerator = C1_D.mul(r).add(C0_D);
        int128 denominator = r.mul(r).add(D1.mul(r)).add(D0);
        int128 result = step0.add(numerator.div(denominator));
        return result;
    }
}

File 43 of 48 : Units.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;

import "./ABDKMath64x64.sol";

/// @title   Units library
/// @author  Primitive
/// @notice  Utility functions for unit conversions
library Units {
    using ABDKMath64x64 for int128;
    using ABDKMath64x64 for uint256;

    uint256 internal constant YEAR = 31556952; // 365.24219 ephemeris day = 1 year, in seconds
    uint256 internal constant PRECISION = 1e18; // precision to scale to
    uint256 internal constant PERCENTAGE = 1e4; // precision of percentages

    // ===== Unit Conversion =====

    /// @notice             Scales a wei value to a precision of 1e18 using the scaling factor
    /// @param   value      Unsigned 256-bit wei amount to convert with native decimals
    /// @param   factor     Scaling factor to multiply by, i.e. 10^(18 - value.decimals())
    /// @return  y          Unsigned 256-bit wei amount scaled to a precision of 1e18
    function scaleUp(uint256 value, uint256 factor) internal pure returns (uint256 y) {
        y = value * factor;
    }

    /// @notice             Scales a wei value from a precision of 1e18 to 10^(18 - precision)
    /// @param   value      Unsigned 256-bit wei amount with 18 decimals
    /// @param   factor     Scaling factor to divide by, i.e. 10^(18 - value.decimals())
    /// @return  y          Unsigned 256-bit wei amount scaled to 10^(18 - factor)
    function scaleDown(uint256 value, uint256 factor) internal pure returns (uint256 y) {
        y = value / factor;
    }

    /// @notice             Converts unsigned 256-bit wei value into a fixed point 64.64 number
    /// @param   value      Unsigned 256-bit wei amount, in native precision
    /// @param   factor     Scaling factor for `value`, used to calculate decimals of `value`
    /// @return  y          Signed 64.64 fixed point number scaled from native precision
    function scaleToX64(uint256 value, uint256 factor) internal pure returns (int128 y) {
        uint256 scaleFactor = PRECISION / factor;
        y = value.divu(scaleFactor);
    }

    /// @notice             Converts signed fixed point 64.64 number into unsigned 256-bit wei value
    /// @param   value      Signed fixed point 64.64 number to convert from precision of 10^18
    /// @param   factor     Scaling factor for `value`, used to calculate decimals of `value`
    /// @return  y          Unsigned 256-bit wei amount scaled to native precision of 10^(18 - factor)
    function scaleFromX64(int128 value, uint256 factor) internal pure returns (uint256 y) {
        uint256 scaleFactor = PRECISION / factor;
        y = value.mulu(scaleFactor);
    }

    /// @notice         Converts denormalized percentage integer to a fixed point 64.64 number
    /// @dev            Convert unsigned 256-bit integer number into signed 64.64 fixed point number
    /// @param denorm   Unsigned percentage integer with precision of 1e4
    /// @return         Signed 64.64 fixed point percentage with precision of 1e4
    function percentageToX64(uint256 denorm) internal pure returns (int128) {
        return denorm.divu(PERCENTAGE);
    }

    /// @notice         Converts unsigned seconds integer into years as a signed 64.64 fixed point number
    /// @dev            Convert unsigned 256-bit integer number into signed 64.64 fixed point number
    /// @param s        Unsigned 256-bit integer amount of seconds to convert into year units
    /// @return         Fixed point 64.64 number of years equal to `seconds`
    function toYears(uint256 s) internal pure returns (int128) {
        return s.divu(YEAR);
    }
}

File 44 of 48 : IPrimitiveSwapCallback.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  Primitive Swap Callback
/// @author Primitive
interface IPrimitiveSwapCallback {
    /// @notice              Triggered when swapping tokens in an Engine
    /// @param  delRisky     Amount of risky tokens required to pay the swap with
    /// @param  delStable    Amount of stable tokens required to pay the swap with
    /// @param  data         Calldata passed on swap function call
    function swapCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external;
}

File 45 of 48 : IMarginManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

import "@primitivefi/rmm-core/contracts/interfaces/callback/IPrimitiveDepositCallback.sol";

/// @title   Interface of MarginManager contract
/// @author  Primitive
interface IMarginManager is IPrimitiveDepositCallback {
    /// ERRORS ///

    /// @notice Thrown when trying to deposit or withdraw 0 risky and stable
    error ZeroDelError();

    /// EVENTS ///

    /// @notice           Emitted when funds are deposited
    /// @param payer      Address depositing the funds
    /// @param recipient  Address receiving the funds in their margin
    /// @param engine     Engine receiving the funds
    /// @param risky      Address of the risky token
    /// @param stable     Address of the stable token
    /// @param delRisky   Amount of deposited risky
    /// @param delStable  Amount of deposited stable
    event Deposit(
        address indexed payer,
        address indexed recipient,
        address indexed engine,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable
    );

    /// @notice           Emitted when funds are withdrawn
    /// @param payer      Address withdrawing the funds
    /// @param recipient  Address receiving the funds in their wallet
    /// @param engine     Engine where the funds are withdrawn from
    /// @param risky      Address of the risky token
    /// @param stable     Address of the stable token
    /// @param delRisky   Amount of withdrawn risky
    /// @param delStable  Amount of withdrawn stable
    event Withdraw(
        address indexed payer,
        address indexed recipient,
        address indexed engine,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable
    );

    /// EFFECT FUNCTIONS ///

    /// @notice           Deposits funds into the margin of a Primitive Engine
    /// @dev              Since the PrimitiveManager contract keeps track of the margins, it
    ///                   will deposit the funds into the Primitive Engine using its own address
    /// @param recipient  Address receiving the funds in their margin
    /// @param risky      Address of the risky token
    /// @param stable     Address of the stable token
    /// @param delRisky   Amount of risky token to deposit
    /// @param delStable  Amount of stable token to deposit
    function deposit(
        address recipient,
        address risky,
        address stable,
        uint256 delRisky,
        uint256 delStable
    ) external payable;

    /// @notice           Withdraws funds from the margin of a Primitive Engine
    /// @param recipient  Address receiving the funds in their wallet
    /// @param engine     Primitive Engine to withdraw from
    /// @param delRisky   Amount of risky token to withdraw
    /// @param delStable  Amount of stable token to withdraw
    function withdraw(
        address recipient,
        address engine,
        uint256 delRisky,
        uint256 delStable
    ) external;

    /// VIEW FUNCTIONS ///

    /// @notice                Returns the margin of an account for a specific Primitive Engine
    /// @param account         Address of the account
    /// @param engine          Address of the engine
    /// @return balanceRisky   Balance of risky in the margin of the user
    /// @return balanceStable  Balance of stable in the margin of the user
    function margins(address account, address engine)
        external
        view
        returns (uint128 balanceRisky, uint128 balanceStable);
}

File 46 of 48 : Margin.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.8.6;

import "@primitivefi/rmm-core/contracts/libraries/SafeCast.sol";

/// @author  Primitive
/// @notice  Utils functions to manage margins
/// @dev     Uses a data struct with two uint128s to optimize for one storage slot
library Margin {
    using SafeCast for uint256;

    struct Data {
        uint128 balanceRisky; // Balance of the risky token, aka underlying asset
        uint128 balanceStable; // Balance of the stable token, aka "quote" asset
    }

    /// @notice             Adds to risky and stable token balances
    /// @param  margin      Margin data of an account in storage to manipulate
    /// @param  delRisky    Amount of risky tokens to add to margin
    /// @param  delStable   Amount of stable tokens to add to margin
    function deposit(
        Data storage margin,
        uint256 delRisky,
        uint256 delStable
    ) internal {
        if (delRisky != 0) margin.balanceRisky += delRisky.toUint128();
        if (delStable != 0) margin.balanceStable += delStable.toUint128();
    }

    /// @notice             Removes risky and stable token balance from an internal margin account
    /// @param  margin      Margin data of an account in storage to manipulate
    /// @param  delRisky    Amount of risky tokens to subtract from margin
    /// @param  delStable   Amount of stable tokens to subtract from margin
    function withdraw(
        Data storage margin,
        uint256 delRisky,
        uint256 delStable
    ) internal {
        if (delRisky != 0) margin.balanceRisky -= delRisky.toUint128();
        if (delStable != 0) margin.balanceStable -= delStable.toUint128();
    }
}

File 47 of 48 : IPrimitiveDepositCallback.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  Primitive Deposit Callback
/// @author Primitive
interface IPrimitiveDepositCallback {
    /// @notice              Triggered when depositing tokens to an Engine
    /// @param  delRisky     Amount of risky tokens required to deposit to risky margin balance
    /// @param  delStable    Amount of stable tokens required to deposit to stable margin balance
    /// @param  data         Calldata passed on deposit function call
    function depositCallback(
        uint256 delRisky,
        uint256 delStable,
        bytes calldata data
    ) external;
}

File 48 of 48 : SafeCast.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.0;

/// @title  SafeCast
/// @notice Safely cast between uint256 and uint128
library SafeCast {
    /// @notice reverts if x > type(uint128).max
    function toUint128(uint256 x) internal pure returns (uint128 z) {
        require(x <= type(uint128).max);
        z = uint128(x);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 400
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"factory_","type":"address"},{"internalType":"address","name":"WETH9_","type":"address"},{"internalType":"address","name":"positionDescriptor_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"requiredAmount","type":"uint256"}],"name":"BalanceTooLowError","type":"error"},{"inputs":[],"name":"DeadlineReachedError","type":"error"},{"inputs":[],"name":"EngineNotDeployedError","type":"error"},{"inputs":[],"name":"InvalidSigError","type":"error"},{"inputs":[],"name":"LockedError","type":"error"},{"inputs":[],"name":"MinLiquidityOutError","type":"error"},{"inputs":[],"name":"MinRemoveOutError","type":"error"},{"inputs":[],"name":"NotEngineError","type":"error"},{"inputs":[],"name":"OnlyWETHError","type":"error"},{"inputs":[],"name":"SigExpiredError","type":"error"},{"inputs":[],"name":"TransferError","type":"error"},{"inputs":[],"name":"WrongConstructorParametersError","type":"error"},{"inputs":[],"name":"ZeroDelError","type":"error"},{"inputs":[],"name":"ZeroLiquidityError","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"delLiquidity","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delRisky","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delStable","type":"uint256"},{"indexed":false,"internalType":"bool","name":"fromMargin","type":"bool"}],"name":"Allocate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","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":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"strike","type":"uint128"},{"indexed":false,"internalType":"uint32","name":"sigma","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"maturity","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"gamma","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"delLiquidity","type":"uint256"}],"name":"Create","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":false,"internalType":"address","name":"risky","type":"address"},{"indexed":false,"internalType":"address","name":"stable","type":"address"},{"indexed":false,"internalType":"uint256","name":"delRisky","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delStable","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"delLiquidity","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delRisky","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delStable","type":"uint256"}],"name":"Remove","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"riskyForStable","type":"bool"},{"indexed":false,"internalType":"uint256","name":"deltaIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deltaOut","type":"uint256"},{"indexed":false,"internalType":"bool","name":"fromMargin","type":"bool"},{"indexed":false,"internalType":"bool","name":"toMargin","type":"bool"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"value","type":"string"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"URI","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"engine","type":"address"},{"indexed":false,"internalType":"address","name":"risky","type":"address"},{"indexed":false,"internalType":"address","name":"stable","type":"address"},{"indexed":false,"internalType":"uint256","name":"delRisky","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delStable","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"risky","type":"address"},{"internalType":"address","name":"stable","type":"address"},{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"},{"internalType":"bool","name":"fromMargin","type":"bool"},{"internalType":"uint256","name":"minLiquidityOut","type":"uint256"}],"name":"allocate","outputs":[{"internalType":"uint256","name":"delLiquidity","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"allocateCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"risky","type":"address"},{"internalType":"address","name":"stable","type":"address"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"uint32","name":"sigma","type":"uint32"},{"internalType":"uint32","name":"maturity","type":"uint32"},{"internalType":"uint32","name":"gamma","type":"uint32"},{"internalType":"uint256","name":"riskyPerLp","type":"uint256"},{"internalType":"uint256","name":"delLiquidity","type":"uint256"}],"name":"create","outputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"createCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"risky","type":"address"},{"internalType":"address","name":"stable","type":"address"},{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"depositCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"margins","outputs":[{"internalType":"uint128","name":"balanceRisky","type":"uint128"},{"internalType":"uint128","name":"balanceStable","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"positionDescriptor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"engine","type":"address"},{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"delLiquidity","type":"uint256"},{"internalType":"uint256","name":"minRiskyOut","type":"uint256"},{"internalType":"uint256","name":"minStableOut","type":"uint256"}],"name":"remove","outputs":[{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","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":[{"components":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"risky","type":"address"},{"internalType":"address","name":"stable","type":"address"},{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"riskyForStable","type":"bool"},{"internalType":"uint256","name":"deltaIn","type":"uint256"},{"internalType":"uint256","name":"deltaOut","type":"uint256"},{"internalType":"bool","name":"fromMargin","type":"bool"},{"internalType":"bool","name":"toMargin","type":"bool"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct ISwapManager.SwapParams","name":"params","type":"tuple"}],"name":"swap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMin","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMin","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"uri","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"engine","type":"address"},{"internalType":"uint256","name":"delRisky","type":"uint256"},{"internalType":"uint256","name":"delStable","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"wrap","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101c060405260016000557f7bf72c3e57bc00556754c7454ead7d72d1c0e263909e7c643fbc0d1e0f3c3e746101a0523480156200003c57600080fd5b5060405162004d5f38038062004d5f8339810160408190526200005f91620002cd565b6040518060400160405280601081526020016f283934b6b4ba34bb32a6b0b730b3b2b960811b815250604051806040016040528060018152602001603160f81b8152506040518060200160405280600081525085858560006001600160a01b0316836001600160a01b03161480620000de57506001600160a01b038216155b80620000f157506001600160a01b038116155b156200011057604051639940007160e01b815260040160405180910390fd5b6001600160601b0319606093841b811660805291831b821660a05290911b1660c0526200013d81620001f1565b50815160208084019190912082519183019190912061014082905261016081905246610100527f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f620001d48184846040805160208101859052908101839052606081018290524660808201523060a082015260009060c0016040516020818303038152906040528051906020012090509392505050565b60e0523060601b6101205261018052506200035495505050505050565b8051620002069060039060208401906200020a565b5050565b828054620002189062000317565b90600052602060002090601f0160209004810192826200023c576000855562000287565b82601f106200025757805160ff191683800117855562000287565b8280016001018555821562000287579182015b82811115620002875782518255916020019190600101906200026a565b506200029592915062000299565b5090565b5b808211156200029557600081556001016200029a565b80516001600160a01b0381168114620002c857600080fd5b919050565b600080600060608486031215620002e357600080fd5b620002ee84620002b0565b9250620002fe60208501620002b0565b91506200030e60408501620002b0565b90509250925092565b600181811c908216806200032c57607f821691505b602082108114156200034e57634e487b7160e01b600052602260045260246000fd5b50919050565b60805160601c60a05160601c60c05160601c60e051610100516101205160601c6101405161016051610180516101a05161491a62000445600039600061239601526000612af201526000612b4101526000612b1c01526000612a7501526000612a9f01526000612ac901526000818161030601526109f701526000818161020c01528181610463015281816113650152818161143001528181612157015281816121e201528181612681015281816126c7015261275c0152600081816105de0152818161082601528181610c3101528181610fe6015281816114d601528181611cde0152611fe0015261491a6000f3fe6080604052600436106101fc5760003560e01c80637bfe950c1161010d578063c2e3140a116100a0578063e985e9c51161006f578063e985e9c514610633578063ea598cb01461067c578063f242432a1461068f578063f3995c67146106af578063f51cc7dd146106c257600080fd5b8063c2e3140a146105b9578063c45a0155146105cc578063c536e60514610600578063df2ab5bb1461062057600080fd5b8063a4a78f0c116100dc578063a4a78f0c14610573578063ac9650d814610586578063b1d9f8f5146105a6578063c171d27e1461037d57600080fd5b80637bfe950c146105065780637ecebe0014610526578063923b8a2a1461037d578063a22cb4651461055357600080fd5b80632eb2c2d6116101905780634aa4a4fc1161015f5780634aa4a4fc146104515780634e1273f4146104855780636d8a3646146104b25780637647691d146104c55780637709fabe146104d857600080fd5b80632eb2c2d61461039d57806333c456e3146103bd5780633644e515146104295780634659a4941461043e57600080fd5b8063106d0231116101cc578063106d0231146102f457806311d128681461034057806312210e8a14610375578063151a8bf81461037d57600080fd5b8062fdd58e1461025157806301ffc9a71461028457806302b9446c146102b45780630e89341c146102c757600080fd5b3661024c57336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461024a5760405163395cfd4760e21b815260040160405180910390fd5b005b600080fd5b34801561025d57600080fd5b5061027161026c366004613e5b565b6106e2565b6040519081526020015b60405180910390f35b34801561029057600080fd5b506102a461029f3660046140d3565b61077b565b604051901515815260200161027b565b61024a6102c2366004613a9a565b6107cd565b3480156102d357600080fd5b506102e76102e236600461421a565b6109be565b60405161027b91906145b2565b34801561030057600080fd5b506103287f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161027b565b34801561034c57600080fd5b5061036061035b366004613e17565b610a75565b6040805192835260208301919091520161027b565b61024a610c08565b34801561038957600080fd5b5061024a610398366004614295565b610c1a565b3480156103a957600080fd5b5061024a6103b8366004613af5565b610cc6565b3480156103c957600080fd5b506104096103d8366004613a61565b60066020908152600092835260408084209091529082529020546001600160801b0380821691600160801b90041682565b604080516001600160801b0393841681529290911660208301520161027b565b34801561043557600080fd5b50610271610d68565b61024a61044c366004613ec9565b610d77565b34801561045d57600080fd5b506103287f000000000000000000000000000000000000000000000000000000000000000081565b34801561049157600080fd5b506104a56104a0366004613f23565b610e0c565b60405161027b9190614535565b61024a6104c0366004614201565b610f36565b61024a6104d336600461424c565b61134d565b6104eb6104e6366004613c1a565b6114a3565b6040805193845260208401929092529082015260600161027b565b34801561051257600080fd5b5061024a610521366004613cb5565b611785565b34801561053257600080fd5b50610271610541366004613a20565b60046020526000908152604090205481565b34801561055f57600080fd5b5061024a61056e366004613d64565b6119ec565b61024a610581366004613ec9565b611ac3565b610599610594366004613ff6565b611b58565b60405161027b91906144d3565b6102716105b4366004613d92565b611cb0565b61024a6105c7366004613ec9565b611f36565b3480156105d857600080fd5b506103287f000000000000000000000000000000000000000000000000000000000000000081565b34801561060c57600080fd5b5061024a61061b366004614295565b611fc9565b61024a61062e366004613e87565b61206d565b34801561063f57600080fd5b506102a461064e366004613a61565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205460ff1690565b61024a61068a36600461421a565b61212b565b34801561069b57600080fd5b5061024a6106aa366004613cfb565b61226e565b61024a6106bd366004613ec9565b6122f5565b3480156106ce57600080fd5b5061024a6106dd366004613ba3565b61234c565b60006001600160a01b0383166107535760405162461bcd60e51b815260206004820152602b60248201527f455243313135353a2062616c616e636520717565727920666f7220746865207a60448201526a65726f206164647265737360a81b60648201526084015b60405180910390fd5b5060009081526001602090815260408083206001600160a01b03949094168352929052205490565b60006001600160e01b03198216636cdb3d1360e11b14806107ac57506001600160e01b031982166303a24d0760e21b145b806107c757506301ffc9a760e01b6001600160e01b03198316145b92915050565b6000546001146107f057604051635cd4e48360e01b815260040160405180910390fd5b600260005581158015610801575080155b1561081f576040516354e3f1e960e11b815260040160405180910390fd5b600061084c7f0000000000000000000000000000000000000000000000000000000000000000868661245e565b90506001600160a01b0381163b61087657604051630408af8b60e31b815260040160405180910390fd5b6040805160608082018352338083526001600160a01b0389811660208086019182528a8316958701958652865190810193909352518116828601529251831681830152835180820390920182526080810193849052634f247fad60e11b90935290831691639e48ff5a916108f391309188918891906084016144a5565b600060405180830381600087803b15801561090d57600080fd5b505af1158015610921573d6000803e3d6000fd5b5050506001600160a01b0380881660009081526006602090815260408083209386168352929052206109559150848461253c565b604080516001600160a01b0387811682528681166020830152918101859052606081018490528183169188169033907f53591a88ac47bfe3130a7de575c6a6a8c22f7604cbba61b8390fbff773ed40499060800160405180910390a45050600160005550505050565b60008181526005602052604090819020549051633e1407fb60e21b81526001600160a01b039182166004820152602481018390526060917f0000000000000000000000000000000000000000000000000000000000000000169063f8501fec9060440160006040518083038186803b158015610a3957600080fd5b505afa158015610a4d573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526107c7919081019061410d565b600080600054600114610a9b57604051635cd4e48360e01b815260040160405180910390fd5b600260005584610abe5760405163e5664db760e01b815260040160405180910390fd5b604051634fc67d6f60e11b815260048101879052602481018690526001600160a01b03881690639f8cfade906044016040805180830381600087803b158015610b0657600080fd5b505af1158015610b1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3e9190614271565b909250905083821080610b5057508281105b15610b6e576040516317f5d8a760e01b815260040160405180910390fd5b610b793387876125e5565b3360009081526006602090815260408083206001600160a01b038b1684529091529020610ba790838361253c565b604080518681526020810184905290810182905286906001600160a01b0389169033907ff33725bb6a7845b32545fbba800c27396f5b228a52b6e3e1f1aeedc7e5c2ff379060600160405180910390a4600160005590969095509350505050565b4715610c1857610c1833476125f0565b565b6000610c288284018461418f565b90506000610c5f7f00000000000000000000000000000000000000000000000000000000000000008360200151846040015161245e565b9050336001600160a01b03821614610c8a57604051633f55017760e21b815260040160405180910390fd5b8515610ca457610ca482602001518360000151338961267f565b8415610cbe57610cbe82604001518360000151338861267f565b505050505050565b6001600160a01b038516331480610ce25750610ce2853361064e565b610d545760405162461bcd60e51b815260206004820152603260248201527f455243313135353a207472616e736665722063616c6c6572206973206e6f742060448201527f6f776e6572206e6f7220617070726f7665640000000000000000000000000000606482015260840161074a565b610d61858585858561280f565b5050505050565b6000610d72612a68565b905090565b6040516323f2ebc360e21b815233600482015230602482015260448101869052606481018590526001608482015260ff841660a482015260c4810183905260e481018290526001600160a01b03871690638fcbaf0c90610104015b600060405180830381600087803b158015610dec57600080fd5b505af1158015610e00573d6000803e3d6000fd5b50505050505050505050565b60608151835114610e715760405162461bcd60e51b815260206004820152602960248201527f455243313135353a206163636f756e747320616e6420696473206c656e677468604482015268040dad2e6dac2e8c6d60bb1b606482015260840161074a565b6000835167ffffffffffffffff811115610e8d57610e8d6147f0565b604051908082528060200260200182016040528015610eb6578160200160208202803683370190505b50905060005b8451811015610f2e57610f01858281518110610eda57610eda6147da565b6020026020010151858381518110610ef457610ef46147da565b60200260200101516106e2565b828281518110610f1357610f136147da565b6020908102919091010152610f2781614793565b9050610ebc565b509392505050565b600054600114610f5957604051635cd4e48360e01b815260040160405180910390fd5b600260005561012081013542811015610f855760405163b405b4c960e01b815260040160405180910390fd5b60006040518060600160405280336001600160a01b03168152602001846020016020810190610fb49190613a20565b6001600160a01b03168152602001610fd26060860160408701613a20565b6001600160a01b031690529050600061102a7f00000000000000000000000000000000000000000000000000000000000000006110156040870160208801613a20565b6110256060880160408901613a20565b61245e565b90506001600160a01b0381163b61105457604051630408af8b60e31b815260040160405180910390fd5b6001600160a01b03811663ca28fcd66110756101208701610100880161406b565b61108b576110866020870187613a20565b61108d565b305b60608701356110a260a0890160808a0161406b565b60a089013560c08a01356110bd6101008c0160e08d0161406b565b6110cf6101208d016101008e0161406b565b604080518c516001600160a01b039081166020808401919091528e0151811682840152918d015190911660608201526080016040516020818303038152906040526040518963ffffffff1660e01b8152600401611133989796959493929190614449565b600060405180830381600087803b15801561114d57600080fd5b505af1158015611161573d6000803e3d6000fd5b5061117792505050610100850160e0860161406b565b156111eb576111eb61118f60a086016080870161406b565b61119a5760006111a0565b8460a001355b6111b060a087016080880161406b565b6111be578560a001356111c1565b60005b3360009081526006602090815260408083206001600160a01b038816845290915290209190612b92565b6111fd6101208501610100860161406b565b156112885761128861121560a086016080870161406b565b611223578460c00135611226565b60005b61123660a087016080880161406b565b611241576000611247565b8560c001355b6006600061125860208a018a613a20565b6001600160a01b03908116825260208083019390935260409182016000908120918816815292529020919061253c565b60608401356001600160a01b038216337f45e6b781bd057c809483af8c0f74bf1d164816674295f01beb2a50239a594a406112c66020890189613a20565b6112d660a08a0160808b0161406b565b60a08a013560c08b01356112f16101008d0160e08e0161406b565b6113036101208e016101008f0161406b565b604080516001600160a01b039097168752941515602087015293850192909252606084015215156080830152151560a082015260c0015b60405180910390a4505060016000555050565b6040516370a0823160e01b81523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a082319060240160206040518083038186803b1580156113af57600080fd5b505afa1580156113c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e79190614233565b90508281101561141457604051635c01c81560e11b8152600481018290526024810184905260440161074a565b801561149e57604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b15801561147c57600080fd5b505af1158015611490573d6000803e3d6000fd5b5050505061149e82826125f0565b505050565b600080600080546001146114ca57604051635cd4e48360e01b815260040160405180910390fd5b600260009081556114fc7f00000000000000000000000000000000000000000000000000000000000000008d8d61245e565b90506001600160a01b0381163b61152657604051630408af8b60e31b815260040160405180910390fd5b846115445760405163e5664db760e01b815260040160405180910390fd5b60006040518060600160405280336001600160a01b031681526020018e6001600160a01b031681526020018d6001600160a01b03168152509050816001600160a01b031663be00763a8c8c8c8c8c8c886040516020016115ce919081516001600160a01b039081168252602080840151821690830152604092830151169181019190915260600190565b6040516020818303038152906040526040518863ffffffff1660e01b81526004016115ff97969594939291906145c5565b606060405180830381600087803b15801561161957600080fd5b505af115801561162d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061165191906140a5565b8095508196508297505050506000826001600160a01b03166321b77d636040518163ffffffff1660e01b815260040160206040518083038186803b15801561169857600080fd5b505afa1580156116ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d09190614233565b90506116e73384886116e2858c614723565b612c12565b85836001600160a01b0316336001600160a01b03167f87971656c1d01a8e86f2bf68b1cb8c5e5e03a51f15e8198b243e8365d758bf5d8f8f8f8f888f61172d9190614723565b604080516001600160801b0396909616865263ffffffff948516602087015292841685840152921660608401526080830191909152519081900360a00190a45050506001600081905550985098509895505050505050565b6000546001146117a857604051635cd4e48360e01b815260040160405180910390fd5b6002600055811580156117b9575080155b156117d7576040516354e3f1e960e11b815260040160405180910390fd5b3360009081526006602090815260408083206001600160a01b03871684529091529020611805908383612b92565b6001600160a01b038084169063b5c5f672908616156118245785611826565b305b6040516001600160e01b031960e084901b1681526001600160a01b0390911660048201526024810185905260448101849052606401600060405180830381600087803b15801561187557600080fd5b505af1158015611889573d6000803e3d6000fd5b5050506001600160a01b0384811691508516156118a657846118a8565b335b6001600160a01b0316336001600160a01b03167fba22996accccc21d85180103b1bc5358bcff060b5751cd0033a9a1b028b5af86866001600160a01b031663c08165d46040518163ffffffff1660e01b815260040160206040518083038186803b15801561191557600080fd5b505afa158015611929573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061194d9190613a44565b876001600160a01b03166322be3de16040518163ffffffff1660e01b815260040160206040518083038186803b15801561198657600080fd5b505afa15801561199a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119be9190613a44565b604080516001600160a01b03938416815292909116602083015281018790526060810186905260800161133a565b336001600160a01b0383161415611a575760405162461bcd60e51b815260206004820152602960248201527f455243313135353a2073657474696e6720617070726f76616c20737461747573604482015268103337b91039b2b63360b91b606482015260840161074a565b3360008181526002602090815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b604051636eb1769f60e11b8152336004820152306024820152600019906001600160a01b0388169063dd62ed3e9060440160206040518083038186803b158015611b0c57600080fd5b505afa158015611b20573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b449190614233565b1015610cbe57610cbe868686868686610d77565b60608167ffffffffffffffff811115611b7357611b736147f0565b604051908082528060200260200182016040528015611ba657816020015b6060815260200190600190039081611b915790505b50905060005b82811015611ca95760008030868685818110611bca57611bca6147da565b9050602002810190611bdc919061461e565b604051611bea92919061437c565b600060405180830381855af49150503d8060008114611c25576040519150601f19603f3d011682016040523d82523d6000602084013e611c2a565b606091505b509150915081611c7657604481511015611c4357600080fd5b60048101905080806020019051810190611c5d919061410d565b60405162461bcd60e51b815260040161074a91906145b2565b80848481518110611c8957611c896147da565b602002602001018190525050508080611ca190614793565b915050611bac565b5092915050565b60008054600114611cd457604051635cd4e48360e01b815260040160405180910390fd5b6002600055611d047f0000000000000000000000000000000000000000000000000000000000000000888861245e565b600780546001600160a01b0319166001600160a01b039290921691821790553b611d4157604051630408af8b60e31b815260040160405180910390fd5b84158015611d4d575083155b15611d6b5760405163e5664db760e01b815260040160405180910390fd5b6007546040805160608082018352338083526001600160a01b038c811660208086019182528d831695870195865286519081019390935251811682860152925183168183015283518082039092018252608081019384905263d2957b8f60e01b90935292169163d2957b8f91611ded918c9130918b918b918b91608401614576565b602060405180830381600087803b158015611e0757600080fd5b505af1158015611e1b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e3f9190614233565b905081811015611e615760405162c9028760e01b815260040160405180910390fd5b8215611e97573360009081526006602090815260408083206007546001600160a01b031684529091529020611e97908686612b92565b600754611eb0908a906001600160a01b03168a84612c12565b600754604080513381526020810184905290810187905260608101869052841515608082015289916001600160a01b0390811691908c16907f23fa1381c309f3136b257b35dba382f23c6f3d2122b1c1babad95740626721489060a00160405180910390a4600780546001600160a01b0319169055600160005598975050505050505050565b604051636eb1769f60e11b815233600482015230602482015285906001600160a01b0388169063dd62ed3e9060440160206040518083038186803b158015611f7d57600080fd5b505afa158015611f91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb59190614233565b1015610cbe57610cbe8686868686866122f5565b6000611fd78284018461418f565b9050600061200e7f00000000000000000000000000000000000000000000000000000000000000008360200151846040015161245e565b9050336001600160a01b0382161461203957604051633f55017760e21b815260040160405180910390fd5b84156120535761205382604001518360000151338861267f565b8515610cbe57610cbe82602001518360000151338961267f565b6040516370a0823160e01b81523060048201526000906001600160a01b038516906370a082319060240160206040518083038186803b1580156120af57600080fd5b505afa1580156120c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120e79190614233565b90508281101561211457604051635c01c81560e11b8152600481018290526024810184905260440161074a565b801561212557612125848383612c7b565b50505050565b8047101561215557604051635c01c81560e11b81524760048201526024810182905260440161074a565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b1580156121b057600080fd5b505af11580156121c4573d6000803e3d6000fd5b505060405163a9059cbb60e01b8152336004820152602481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316935063a9059cbb92506044019050602060405180830381600087803b15801561223257600080fd5b505af1158015612246573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061226a9190614088565b5050565b6001600160a01b03851633148061228a575061228a853361064e565b6122e85760405162461bcd60e51b815260206004820152602960248201527f455243313135353a2063616c6c6572206973206e6f74206f776e6572206e6f7260448201526808185c1c1c9bdd995960ba1b606482015260840161074a565b610d618585858585612d60565b60405163d505accf60e01b8152336004820152306024820152604481018690526064810185905260ff8416608482015260a4810183905260c481018290526001600160a01b0387169063d505accf9060e401610dd2565b8342111561236d576040516331c64a7360e01b815260040160405180910390fd5b6001600160a01b03878116600081815260046020908152604080832080546001810190915581517f00000000000000000000000000000000000000000000000000000000000000008185015280830195909552948b166060850152891515608085015260a084019490945260c08084018990528451808503909101815260e0909301909352815191909201209061240382612f02565b9050600061241382878787612f50565b9050896001600160a01b0316816001600160a01b03161461244757604051630811945d60e41b815260040160405180910390fd5b505050612455878787612f78565b50505050505050565b60008383836040516020016124899291906001600160a01b0392831681529116602082015260400190565b60408051601f1981840301815290829052805160209182012061251c939290917ff8e63833fcbf190bd32bc64a1c450bd59b356b4b7cf79cad298a369fb369aaae91017fff00000000000000000000000000000000000000000000000000000000000000815260609390931b6bffffffffffffffffffffffff191660018401526015830191909152603582015260550190565b60408051601f198184030181529190528051602090910120949350505050565b811561258b5761254b82612fe5565b835484906000906125669084906001600160801b03166146b8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b801561149e5761259a81612fe5565b835484906010906125bc908490600160801b90046001600160801b03166146b8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550505050565b61149e838383612fff565b604080516000808252602082019092526001600160a01b03841690839060405161261a919061438c565b60006040518083038185875af1925050503d8060008114612657576040519150601f19603f3d011682016040523d82523d6000602084013e61265c565b606091505b50909150508061149e576040516313ff771f60e21b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316846001600160a01b03161480156126c05750804710155b156127e2577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561272057600080fd5b505af1158015612734573d6000803e3d6000fd5b505060405163a9059cbb60e01b81526001600160a01b038681166004830152602482018690527f000000000000000000000000000000000000000000000000000000000000000016935063a9059cbb92506044019050602060405180830381600087803b1580156127a457600080fd5b505af11580156127b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127dc9190614088565b50612125565b6001600160a01b038316301415612803576127fe848383612c7b565b612125565b6121258484848461317d565b81518351146128715760405162461bcd60e51b815260206004820152602860248201527f455243313135353a2069647320616e6420616d6f756e7473206c656e677468206044820152670dad2e6dac2e8c6d60c31b606482015260840161074a565b6001600160a01b0384166128d55760405162461bcd60e51b815260206004820152602560248201527f455243313135353a207472616e7366657220746f20746865207a65726f206164604482015264647265737360d81b606482015260840161074a565b3360005b8451811015612a025760008582815181106128f6576128f66147da565b602002602001015190506000858381518110612914576129146147da565b60209081029190910181015160008481526001835260408082206001600160a01b038e1683529093529190912054909150818110156129a85760405162461bcd60e51b815260206004820152602a60248201527f455243313135353a20696e73756666696369656e742062616c616e636520666f60448201526939103a3930b739b332b960b11b606482015260840161074a565b60008381526001602090815260408083206001600160a01b038e8116855292528083208585039055908b168252812080548492906129e79084906146e3565b92505081905550505050806129fb90614793565b90506128d9565b50846001600160a01b0316866001600160a01b0316826001600160a01b03167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb8787604051612a52929190614548565b60405180910390a4610cbe81878787878761326a565b6000306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148015612ac157507f000000000000000000000000000000000000000000000000000000000000000046145b15612aeb57507f000000000000000000000000000000000000000000000000000000000000000090565b50604080517f00000000000000000000000000000000000000000000000000000000000000006020808301919091527f0000000000000000000000000000000000000000000000000000000000000000828401527f000000000000000000000000000000000000000000000000000000000000000060608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b90565b8115612be157612ba182612fe5565b83548490600090612bbc9084906001600160801b03166146fb565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b801561149e57612bf081612fe5565b835484906010906125bc908490600160801b90046001600160801b03166146fb565b612c30848360001c836040518060200160405280600081525061341f565b6000828152600560205260409020546001600160a01b031661212557600082815260056020526040902080546001600160a01b0385166001600160a01b031990911617905550505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1790529151600092839290871691612cd7919061438c565b6000604051808303816000865af19150503d8060008114612d14576040519150601f19603f3d011682016040523d82523d6000602084013e612d19565b606091505b5091509150818015612d43575080511580612d43575080806020019051810190612d439190614088565b610d61576040516313ff771f60e21b815260040160405180910390fd5b6001600160a01b038416612dc45760405162461bcd60e51b815260206004820152602560248201527f455243313135353a207472616e7366657220746f20746865207a65726f206164604482015264647265737360d81b606482015260840161074a565b33612ddd818787612dd488613522565b610d6188613522565b60008481526001602090815260408083206001600160a01b038a16845290915290205483811015612e635760405162461bcd60e51b815260206004820152602a60248201527f455243313135353a20696e73756666696369656e742062616c616e636520666f60448201526939103a3930b739b332b960b11b606482015260840161074a565b60008581526001602090815260408083206001600160a01b038b8116855292528083208785039055908816825281208054869290612ea29084906146e3565b909155505060408051868152602081018690526001600160a01b03808916928a821692918616917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a461245582888888888861356d565b60006107c7612f0f612a68565b8360405161190160f01b6020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b6000806000612f6187878787613678565b91509150612f6e81613765565b5095945050505050565b6001600160a01b03838116600081815260026020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b60006001600160801b03821115612ffb57600080fd5b5090565b6001600160a01b0383166130615760405162461bcd60e51b815260206004820152602360248201527f455243313135353a206275726e2066726f6d20746865207a65726f206164647260448201526265737360e81b606482015260840161074a565b336130918185600061307287613522565b61307b87613522565b5050604080516020810190915260009052505050565b60008381526001602090815260408083206001600160a01b0388168452909152902054828110156131105760405162461bcd60e51b8152602060048201526024808201527f455243313135353a206275726e20616d6f756e7420657863656564732062616c604482015263616e636560e01b606482015260840161074a565b60008481526001602090815260408083206001600160a01b03898116808652918452828520888703905582518981529384018890529092908616917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a45050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17905291516000928392908816916131e1919061438c565b6000604051808303816000865af19150503d806000811461321e576040519150601f19603f3d011682016040523d82523d6000602084013e613223565b606091505b509150915081801561324d57508051158061324d57508080602001905181019061324d9190614088565b610cbe576040516313ff771f60e21b815260040160405180910390fd5b6001600160a01b0384163b15610cbe5760405163bc197c8160e01b81526001600160a01b0385169063bc197c81906132ae90899089908890889088906004016143a8565b602060405180830381600087803b1580156132c857600080fd5b505af19250505080156132f8575060408051601f3d908101601f191682019092526132f5918101906140f0565b60015b6133ae57613304614806565b806308c379a0141561333e5750613319614821565b806133245750613340565b8060405162461bcd60e51b815260040161074a91906145b2565b505b60405162461bcd60e51b815260206004820152603460248201527f455243313135353a207472616e7366657220746f206e6f6e204552433131353560448201527f526563656976657220696d706c656d656e746572000000000000000000000000606482015260840161074a565b6001600160e01b0319811663bc197c8160e01b146124555760405162461bcd60e51b815260206004820152602860248201527f455243313135353a204552433131353552656365697665722072656a656374656044820152676420746f6b656e7360c01b606482015260840161074a565b6001600160a01b03841661347f5760405162461bcd60e51b815260206004820152602160248201527f455243313135353a206d696e7420746f20746865207a65726f206164647265736044820152607360f81b606482015260840161074a565b3361349081600087612dd488613522565b60008481526001602090815260408083206001600160a01b0389168452909152812080548592906134c29084906146e3565b909155505060408051858152602081018590526001600160a01b0380881692600092918516917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a4610d618160008787878761356d565b6040805160018082528183019092526060916000919060208083019080368337019050509050828160008151811061355c5761355c6147da565b602090810291909101015292915050565b6001600160a01b0384163b15610cbe5760405163f23a6e6160e01b81526001600160a01b0385169063f23a6e61906135b19089908990889088908890600401614406565b602060405180830381600087803b1580156135cb57600080fd5b505af19250505080156135fb575060408051601f3d908101601f191682019092526135f8918101906140f0565b60015b61360757613304614806565b6001600160e01b0319811663f23a6e6160e01b146124555760405162461bcd60e51b815260206004820152602860248201527f455243313135353a204552433131353552656365697665722072656a656374656044820152676420746f6b656e7360c01b606482015260840161074a565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156136af575060009050600361375c565b8460ff16601b141580156136c757508460ff16601c14155b156136d8575060009050600461375c565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561372c573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166137555760006001925092505061375c565b9150600090505b94509492505050565b6000816004811115613779576137796147c4565b14156137825750565b6001816004811115613796576137966147c4565b14156137e45760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161074a565b60028160048111156137f8576137f86147c4565b14156138465760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161074a565b600381600481111561385a5761385a6147c4565b14156138b35760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b606482015260840161074a565b60048160048111156138c7576138c76147c4565b14156139205760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202776272076616c604482015261756560f01b606482015260840161074a565b50565b600082601f83011261393457600080fd5b813560206139418261466c565b60405161394e8282614766565b8381528281019150858301600585901b8701840188101561396e57600080fd5b60005b8581101561398d57813584529284019290840190600101613971565b5090979650505050505050565b600082601f8301126139ab57600080fd5b81356139b681614690565b6040516139c38282614766565b8281528560208487010111156139d857600080fd5b82602086016020830137600092810160200192909252509392505050565b803563ffffffff81168114613a0a57600080fd5b919050565b803560ff81168114613a0a57600080fd5b600060208284031215613a3257600080fd5b8135613a3d816148ab565b9392505050565b600060208284031215613a5657600080fd5b8151613a3d816148ab565b60008060408385031215613a7457600080fd5b8235613a7f816148ab565b91506020830135613a8f816148ab565b809150509250929050565b600080600080600060a08688031215613ab257600080fd5b8535613abd816148ab565b94506020860135613acd816148ab565b93506040860135613add816148ab565b94979396509394606081013594506080013592915050565b600080600080600060a08688031215613b0d57600080fd5b8535613b18816148ab565b94506020860135613b28816148ab565b9350604086013567ffffffffffffffff80821115613b4557600080fd5b613b5189838a01613923565b94506060880135915080821115613b6757600080fd5b613b7389838a01613923565b93506080880135915080821115613b8957600080fd5b50613b968882890161399a565b9150509295509295909350565b600080600080600080600060e0888a031215613bbe57600080fd5b8735613bc9816148ab565b96506020880135613bd9816148ab565b95506040880135613be9816148c0565b945060608801359350613bfe60808901613a0f565b925060a0880135915060c0880135905092959891949750929550565b600080600080600080600080610100898b031215613c3757600080fd5b8835613c42816148ab565b97506020890135613c52816148ab565b965060408901356001600160801b0381168114613c6e57600080fd5b9550613c7c60608a016139f6565b9450613c8a60808a016139f6565b9350613c9860a08a016139f6565b925060c0890135915060e089013590509295985092959890939650565b60008060008060808587031215613ccb57600080fd5b8435613cd6816148ab565b93506020850135613ce6816148ab565b93969395505050506040820135916060013590565b600080600080600060a08688031215613d1357600080fd5b8535613d1e816148ab565b94506020860135613d2e816148ab565b93506040860135925060608601359150608086013567ffffffffffffffff811115613d5857600080fd5b613b968882890161399a565b60008060408385031215613d7757600080fd5b8235613d82816148ab565b91506020830135613a8f816148c0565b600080600080600080600080610100898b031215613daf57600080fd5b8835613dba816148ab565b9750602089013596506040890135613dd1816148ab565b95506060890135613de1816148ab565b94506080890135935060a0890135925060c0890135613dff816148c0565b8092505060e089013590509295985092959890939650565b600080600080600060a08688031215613e2f57600080fd5b8535613e3a816148ab565b97602087013597506040870135966060810135965060800135945092505050565b60008060408385031215613e6e57600080fd5b8235613e79816148ab565b946020939093013593505050565b600080600060608486031215613e9c57600080fd5b8335613ea7816148ab565b9250602084013591506040840135613ebe816148ab565b809150509250925092565b60008060008060008060c08789031215613ee257600080fd5b8635613eed816148ab565b95506020870135945060408701359350613f0960608801613a0f565b92506080870135915060a087013590509295509295509295565b60008060408385031215613f3657600080fd5b823567ffffffffffffffff80821115613f4e57600080fd5b818501915085601f830112613f6257600080fd5b81356020613f6f8261466c565b604051613f7c8282614766565b8381528281019150858301600585901b870184018b1015613f9c57600080fd5b600096505b84871015613fc8578035613fb4816148ab565b835260019690960195918301918301613fa1565b5096505086013592505080821115613fdf57600080fd5b50613fec85828601613923565b9150509250929050565b6000806020838503121561400957600080fd5b823567ffffffffffffffff8082111561402157600080fd5b818501915085601f83011261403557600080fd5b81358181111561404457600080fd5b8660208260051b850101111561405957600080fd5b60209290920196919550909350505050565b60006020828403121561407d57600080fd5b8135613a3d816148c0565b60006020828403121561409a57600080fd5b8151613a3d816148c0565b6000806000606084860312156140ba57600080fd5b8351925060208401519150604084015190509250925092565b6000602082840312156140e557600080fd5b8135613a3d816148ce565b60006020828403121561410257600080fd5b8151613a3d816148ce565b60006020828403121561411f57600080fd5b815167ffffffffffffffff81111561413657600080fd5b8201601f8101841361414757600080fd5b805161415281614690565b60405161415f8282614766565b82815286602084860101111561417457600080fd5b61418583602083016020870161473a565b9695505050505050565b6000606082840312156141a157600080fd5b6040516060810181811067ffffffffffffffff821117156141c4576141c46147f0565b60405282356141d2816148ab565b815260208301356141e2816148ab565b602082015260408301356141f5816148ab565b60408201529392505050565b6000610140828403121561421457600080fd5b50919050565b60006020828403121561422c57600080fd5b5035919050565b60006020828403121561424557600080fd5b5051919050565b6000806040838503121561425f57600080fd5b823591506020830135613a8f816148ab565b6000806040838503121561428457600080fd5b505080516020909101519092909150565b600080600080606085870312156142ab57600080fd5b8435935060208501359250604085013567ffffffffffffffff808211156142d157600080fd5b818701915087601f8301126142e557600080fd5b8135818111156142f457600080fd5b88602082850101111561430657600080fd5b95989497505060200194505050565b600081518084526020808501945080840160005b8381101561434557815187529582019590820190600101614329565b509495945050505050565b6000815180845261436881602086016020860161473a565b601f01601f19169290920160200192915050565b8183823760009101908152919050565b6000825161439e81846020870161473a565b9190910192915050565b60006001600160a01b03808816835280871660208401525060a060408301526143d460a0830186614315565b82810360608401526143e68186614315565b905082810360808401526143fa8185614350565b98975050505050505050565b60006001600160a01b03808816835280871660208401525084604083015283606083015260a0608083015261443e60a0830184614350565b979650505050505050565b60006101006001600160a01b038b168352896020840152881515604084015287606084015286608084015285151560a084015284151560c08401528060e084015261449681840185614350565b9b9a5050505050505050505050565b6001600160a01b03851681528360208201528260408201526080606082015260006141856080830184614350565b6000602080830181845280855180835260408601915060408160051b870101925083870160005b8281101561452857603f19888603018452614516858351614350565b945092850192908501906001016144fa565b5092979650505050505050565b602081526000613a3d6020830184614315565b60408152600061455b6040830185614315565b828103602084015261456d8185614315565b95945050505050565b8681526001600160a01b0386166020820152846040820152836060820152821515608082015260c060a082015260006143fa60c0830184614350565b602081526000613a3d6020830184614350565b6001600160801b0388168152600063ffffffff808916602084015280881660408401528087166060840152508460808301528360a083015260e060c083015261461160e0830184614350565b9998505050505050505050565b6000808335601e1984360301811261463557600080fd5b83018035915067ffffffffffffffff82111561465057600080fd5b60200191503681900382131561466557600080fd5b9250929050565b600067ffffffffffffffff821115614686576146866147f0565b5060051b60200190565b600067ffffffffffffffff8211156146aa576146aa6147f0565b50601f01601f191660200190565b60006001600160801b038083168185168083038211156146da576146da6147ae565b01949350505050565b600082198211156146f6576146f66147ae565b500190565b60006001600160801b038381169083168181101561471b5761471b6147ae565b039392505050565b600082821015614735576147356147ae565b500390565b60005b8381101561475557818101518382015260200161473d565b838111156121255750506000910152565b601f8201601f1916810167ffffffffffffffff8111828210171561478c5761478c6147f0565b6040525050565b60006000198214156147a7576147a76147ae565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b600060033d1115612b8f5760046000803e5060005160e01c90565b600060443d101561482f5790565b6040516003193d81016004833e81513d67ffffffffffffffff816024840111818411171561485f57505050505090565b82850191508151818111156148775750505050505090565b843d87010160208285010111156148915750505050505090565b6148a060208286010187614766565b509095945050505050565b6001600160a01b038116811461392057600080fd5b801515811461392057600080fd5b6001600160e01b03198116811461392057600080fdfea2646970667358221220a589e7c8d3bb24437ece0111d1f5827cd1d5e49bcc1ef8a81fc5f2c82813859064736f6c634300080600330000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b068000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000d4ea6381c0a7c9565fcdfa35c84a7939300176e7

Deployed Bytecode

0x6080604052600436106101fc5760003560e01c80637bfe950c1161010d578063c2e3140a116100a0578063e985e9c51161006f578063e985e9c514610633578063ea598cb01461067c578063f242432a1461068f578063f3995c67146106af578063f51cc7dd146106c257600080fd5b8063c2e3140a146105b9578063c45a0155146105cc578063c536e60514610600578063df2ab5bb1461062057600080fd5b8063a4a78f0c116100dc578063a4a78f0c14610573578063ac9650d814610586578063b1d9f8f5146105a6578063c171d27e1461037d57600080fd5b80637bfe950c146105065780637ecebe0014610526578063923b8a2a1461037d578063a22cb4651461055357600080fd5b80632eb2c2d6116101905780634aa4a4fc1161015f5780634aa4a4fc146104515780634e1273f4146104855780636d8a3646146104b25780637647691d146104c55780637709fabe146104d857600080fd5b80632eb2c2d61461039d57806333c456e3146103bd5780633644e515146104295780634659a4941461043e57600080fd5b8063106d0231116101cc578063106d0231146102f457806311d128681461034057806312210e8a14610375578063151a8bf81461037d57600080fd5b8062fdd58e1461025157806301ffc9a71461028457806302b9446c146102b45780630e89341c146102c757600080fd5b3661024c57336001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2161461024a5760405163395cfd4760e21b815260040160405180910390fd5b005b600080fd5b34801561025d57600080fd5b5061027161026c366004613e5b565b6106e2565b6040519081526020015b60405180910390f35b34801561029057600080fd5b506102a461029f3660046140d3565b61077b565b604051901515815260200161027b565b61024a6102c2366004613a9a565b6107cd565b3480156102d357600080fd5b506102e76102e236600461421a565b6109be565b60405161027b91906145b2565b34801561030057600080fd5b506103287f000000000000000000000000d4ea6381c0a7c9565fcdfa35c84a7939300176e781565b6040516001600160a01b03909116815260200161027b565b34801561034c57600080fd5b5061036061035b366004613e17565b610a75565b6040805192835260208301919091520161027b565b61024a610c08565b34801561038957600080fd5b5061024a610398366004614295565b610c1a565b3480156103a957600080fd5b5061024a6103b8366004613af5565b610cc6565b3480156103c957600080fd5b506104096103d8366004613a61565b60066020908152600092835260408084209091529082529020546001600160801b0380821691600160801b90041682565b604080516001600160801b0393841681529290911660208301520161027b565b34801561043557600080fd5b50610271610d68565b61024a61044c366004613ec9565b610d77565b34801561045d57600080fd5b506103287f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b34801561049157600080fd5b506104a56104a0366004613f23565b610e0c565b60405161027b9190614535565b61024a6104c0366004614201565b610f36565b61024a6104d336600461424c565b61134d565b6104eb6104e6366004613c1a565b6114a3565b6040805193845260208401929092529082015260600161027b565b34801561051257600080fd5b5061024a610521366004613cb5565b611785565b34801561053257600080fd5b50610271610541366004613a20565b60046020526000908152604090205481565b34801561055f57600080fd5b5061024a61056e366004613d64565b6119ec565b61024a610581366004613ec9565b611ac3565b610599610594366004613ff6565b611b58565b60405161027b91906144d3565b6102716105b4366004613d92565b611cb0565b61024a6105c7366004613ec9565b611f36565b3480156105d857600080fd5b506103287f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b06881565b34801561060c57600080fd5b5061024a61061b366004614295565b611fc9565b61024a61062e366004613e87565b61206d565b34801561063f57600080fd5b506102a461064e366004613a61565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205460ff1690565b61024a61068a36600461421a565b61212b565b34801561069b57600080fd5b5061024a6106aa366004613cfb565b61226e565b61024a6106bd366004613ec9565b6122f5565b3480156106ce57600080fd5b5061024a6106dd366004613ba3565b61234c565b60006001600160a01b0383166107535760405162461bcd60e51b815260206004820152602b60248201527f455243313135353a2062616c616e636520717565727920666f7220746865207a60448201526a65726f206164647265737360a81b60648201526084015b60405180910390fd5b5060009081526001602090815260408083206001600160a01b03949094168352929052205490565b60006001600160e01b03198216636cdb3d1360e11b14806107ac57506001600160e01b031982166303a24d0760e21b145b806107c757506301ffc9a760e01b6001600160e01b03198316145b92915050565b6000546001146107f057604051635cd4e48360e01b815260040160405180910390fd5b600260005581158015610801575080155b1561081f576040516354e3f1e960e11b815260040160405180910390fd5b600061084c7f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b068868661245e565b90506001600160a01b0381163b61087657604051630408af8b60e31b815260040160405180910390fd5b6040805160608082018352338083526001600160a01b0389811660208086019182528a8316958701958652865190810193909352518116828601529251831681830152835180820390920182526080810193849052634f247fad60e11b90935290831691639e48ff5a916108f391309188918891906084016144a5565b600060405180830381600087803b15801561090d57600080fd5b505af1158015610921573d6000803e3d6000fd5b5050506001600160a01b0380881660009081526006602090815260408083209386168352929052206109559150848461253c565b604080516001600160a01b0387811682528681166020830152918101859052606081018490528183169188169033907f53591a88ac47bfe3130a7de575c6a6a8c22f7604cbba61b8390fbff773ed40499060800160405180910390a45050600160005550505050565b60008181526005602052604090819020549051633e1407fb60e21b81526001600160a01b039182166004820152602481018390526060917f000000000000000000000000d4ea6381c0a7c9565fcdfa35c84a7939300176e7169063f8501fec9060440160006040518083038186803b158015610a3957600080fd5b505afa158015610a4d573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526107c7919081019061410d565b600080600054600114610a9b57604051635cd4e48360e01b815260040160405180910390fd5b600260005584610abe5760405163e5664db760e01b815260040160405180910390fd5b604051634fc67d6f60e11b815260048101879052602481018690526001600160a01b03881690639f8cfade906044016040805180830381600087803b158015610b0657600080fd5b505af1158015610b1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3e9190614271565b909250905083821080610b5057508281105b15610b6e576040516317f5d8a760e01b815260040160405180910390fd5b610b793387876125e5565b3360009081526006602090815260408083206001600160a01b038b1684529091529020610ba790838361253c565b604080518681526020810184905290810182905286906001600160a01b0389169033907ff33725bb6a7845b32545fbba800c27396f5b228a52b6e3e1f1aeedc7e5c2ff379060600160405180910390a4600160005590969095509350505050565b4715610c1857610c1833476125f0565b565b6000610c288284018461418f565b90506000610c5f7f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b0688360200151846040015161245e565b9050336001600160a01b03821614610c8a57604051633f55017760e21b815260040160405180910390fd5b8515610ca457610ca482602001518360000151338961267f565b8415610cbe57610cbe82604001518360000151338861267f565b505050505050565b6001600160a01b038516331480610ce25750610ce2853361064e565b610d545760405162461bcd60e51b815260206004820152603260248201527f455243313135353a207472616e736665722063616c6c6572206973206e6f742060448201527f6f776e6572206e6f7220617070726f7665640000000000000000000000000000606482015260840161074a565b610d61858585858561280f565b5050505050565b6000610d72612a68565b905090565b6040516323f2ebc360e21b815233600482015230602482015260448101869052606481018590526001608482015260ff841660a482015260c4810183905260e481018290526001600160a01b03871690638fcbaf0c90610104015b600060405180830381600087803b158015610dec57600080fd5b505af1158015610e00573d6000803e3d6000fd5b50505050505050505050565b60608151835114610e715760405162461bcd60e51b815260206004820152602960248201527f455243313135353a206163636f756e747320616e6420696473206c656e677468604482015268040dad2e6dac2e8c6d60bb1b606482015260840161074a565b6000835167ffffffffffffffff811115610e8d57610e8d6147f0565b604051908082528060200260200182016040528015610eb6578160200160208202803683370190505b50905060005b8451811015610f2e57610f01858281518110610eda57610eda6147da565b6020026020010151858381518110610ef457610ef46147da565b60200260200101516106e2565b828281518110610f1357610f136147da565b6020908102919091010152610f2781614793565b9050610ebc565b509392505050565b600054600114610f5957604051635cd4e48360e01b815260040160405180910390fd5b600260005561012081013542811015610f855760405163b405b4c960e01b815260040160405180910390fd5b60006040518060600160405280336001600160a01b03168152602001846020016020810190610fb49190613a20565b6001600160a01b03168152602001610fd26060860160408701613a20565b6001600160a01b031690529050600061102a7f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b0686110156040870160208801613a20565b6110256060880160408901613a20565b61245e565b90506001600160a01b0381163b61105457604051630408af8b60e31b815260040160405180910390fd5b6001600160a01b03811663ca28fcd66110756101208701610100880161406b565b61108b576110866020870187613a20565b61108d565b305b60608701356110a260a0890160808a0161406b565b60a089013560c08a01356110bd6101008c0160e08d0161406b565b6110cf6101208d016101008e0161406b565b604080518c516001600160a01b039081166020808401919091528e0151811682840152918d015190911660608201526080016040516020818303038152906040526040518963ffffffff1660e01b8152600401611133989796959493929190614449565b600060405180830381600087803b15801561114d57600080fd5b505af1158015611161573d6000803e3d6000fd5b5061117792505050610100850160e0860161406b565b156111eb576111eb61118f60a086016080870161406b565b61119a5760006111a0565b8460a001355b6111b060a087016080880161406b565b6111be578560a001356111c1565b60005b3360009081526006602090815260408083206001600160a01b038816845290915290209190612b92565b6111fd6101208501610100860161406b565b156112885761128861121560a086016080870161406b565b611223578460c00135611226565b60005b61123660a087016080880161406b565b611241576000611247565b8560c001355b6006600061125860208a018a613a20565b6001600160a01b03908116825260208083019390935260409182016000908120918816815292529020919061253c565b60608401356001600160a01b038216337f45e6b781bd057c809483af8c0f74bf1d164816674295f01beb2a50239a594a406112c66020890189613a20565b6112d660a08a0160808b0161406b565b60a08a013560c08b01356112f16101008d0160e08e0161406b565b6113036101208e016101008f0161406b565b604080516001600160a01b039097168752941515602087015293850192909252606084015215156080830152151560a082015260c0015b60405180910390a4505060016000555050565b6040516370a0823160e01b81523060048201526000907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316906370a082319060240160206040518083038186803b1580156113af57600080fd5b505afa1580156113c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e79190614233565b90508281101561141457604051635c01c81560e11b8152600481018290526024810184905260440161074a565b801561149e57604051632e1a7d4d60e01b8152600481018290527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031690632e1a7d4d90602401600060405180830381600087803b15801561147c57600080fd5b505af1158015611490573d6000803e3d6000fd5b5050505061149e82826125f0565b505050565b600080600080546001146114ca57604051635cd4e48360e01b815260040160405180910390fd5b600260009081556114fc7f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b0688d8d61245e565b90506001600160a01b0381163b61152657604051630408af8b60e31b815260040160405180910390fd5b846115445760405163e5664db760e01b815260040160405180910390fd5b60006040518060600160405280336001600160a01b031681526020018e6001600160a01b031681526020018d6001600160a01b03168152509050816001600160a01b031663be00763a8c8c8c8c8c8c886040516020016115ce919081516001600160a01b039081168252602080840151821690830152604092830151169181019190915260600190565b6040516020818303038152906040526040518863ffffffff1660e01b81526004016115ff97969594939291906145c5565b606060405180830381600087803b15801561161957600080fd5b505af115801561162d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061165191906140a5565b8095508196508297505050506000826001600160a01b03166321b77d636040518163ffffffff1660e01b815260040160206040518083038186803b15801561169857600080fd5b505afa1580156116ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d09190614233565b90506116e73384886116e2858c614723565b612c12565b85836001600160a01b0316336001600160a01b03167f87971656c1d01a8e86f2bf68b1cb8c5e5e03a51f15e8198b243e8365d758bf5d8f8f8f8f888f61172d9190614723565b604080516001600160801b0396909616865263ffffffff948516602087015292841685840152921660608401526080830191909152519081900360a00190a45050506001600081905550985098509895505050505050565b6000546001146117a857604051635cd4e48360e01b815260040160405180910390fd5b6002600055811580156117b9575080155b156117d7576040516354e3f1e960e11b815260040160405180910390fd5b3360009081526006602090815260408083206001600160a01b03871684529091529020611805908383612b92565b6001600160a01b038084169063b5c5f672908616156118245785611826565b305b6040516001600160e01b031960e084901b1681526001600160a01b0390911660048201526024810185905260448101849052606401600060405180830381600087803b15801561187557600080fd5b505af1158015611889573d6000803e3d6000fd5b5050506001600160a01b0384811691508516156118a657846118a8565b335b6001600160a01b0316336001600160a01b03167fba22996accccc21d85180103b1bc5358bcff060b5751cd0033a9a1b028b5af86866001600160a01b031663c08165d46040518163ffffffff1660e01b815260040160206040518083038186803b15801561191557600080fd5b505afa158015611929573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061194d9190613a44565b876001600160a01b03166322be3de16040518163ffffffff1660e01b815260040160206040518083038186803b15801561198657600080fd5b505afa15801561199a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119be9190613a44565b604080516001600160a01b03938416815292909116602083015281018790526060810186905260800161133a565b336001600160a01b0383161415611a575760405162461bcd60e51b815260206004820152602960248201527f455243313135353a2073657474696e6720617070726f76616c20737461747573604482015268103337b91039b2b63360b91b606482015260840161074a565b3360008181526002602090815260408083206001600160a01b03871680855290835292819020805460ff191686151590811790915590519081529192917f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a35050565b604051636eb1769f60e11b8152336004820152306024820152600019906001600160a01b0388169063dd62ed3e9060440160206040518083038186803b158015611b0c57600080fd5b505afa158015611b20573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b449190614233565b1015610cbe57610cbe868686868686610d77565b60608167ffffffffffffffff811115611b7357611b736147f0565b604051908082528060200260200182016040528015611ba657816020015b6060815260200190600190039081611b915790505b50905060005b82811015611ca95760008030868685818110611bca57611bca6147da565b9050602002810190611bdc919061461e565b604051611bea92919061437c565b600060405180830381855af49150503d8060008114611c25576040519150601f19603f3d011682016040523d82523d6000602084013e611c2a565b606091505b509150915081611c7657604481511015611c4357600080fd5b60048101905080806020019051810190611c5d919061410d565b60405162461bcd60e51b815260040161074a91906145b2565b80848481518110611c8957611c896147da565b602002602001018190525050508080611ca190614793565b915050611bac565b5092915050565b60008054600114611cd457604051635cd4e48360e01b815260040160405180910390fd5b6002600055611d047f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b068888861245e565b600780546001600160a01b0319166001600160a01b039290921691821790553b611d4157604051630408af8b60e31b815260040160405180910390fd5b84158015611d4d575083155b15611d6b5760405163e5664db760e01b815260040160405180910390fd5b6007546040805160608082018352338083526001600160a01b038c811660208086019182528d831695870195865286519081019390935251811682860152925183168183015283518082039092018252608081019384905263d2957b8f60e01b90935292169163d2957b8f91611ded918c9130918b918b918b91608401614576565b602060405180830381600087803b158015611e0757600080fd5b505af1158015611e1b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e3f9190614233565b905081811015611e615760405162c9028760e01b815260040160405180910390fd5b8215611e97573360009081526006602090815260408083206007546001600160a01b031684529091529020611e97908686612b92565b600754611eb0908a906001600160a01b03168a84612c12565b600754604080513381526020810184905290810187905260608101869052841515608082015289916001600160a01b0390811691908c16907f23fa1381c309f3136b257b35dba382f23c6f3d2122b1c1babad95740626721489060a00160405180910390a4600780546001600160a01b0319169055600160005598975050505050505050565b604051636eb1769f60e11b815233600482015230602482015285906001600160a01b0388169063dd62ed3e9060440160206040518083038186803b158015611f7d57600080fd5b505afa158015611f91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb59190614233565b1015610cbe57610cbe8686868686866122f5565b6000611fd78284018461418f565b9050600061200e7f0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b0688360200151846040015161245e565b9050336001600160a01b0382161461203957604051633f55017760e21b815260040160405180910390fd5b84156120535761205382604001518360000151338861267f565b8515610cbe57610cbe82602001518360000151338961267f565b6040516370a0823160e01b81523060048201526000906001600160a01b038516906370a082319060240160206040518083038186803b1580156120af57600080fd5b505afa1580156120c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120e79190614233565b90508281101561211457604051635c01c81560e11b8152600481018290526024810184905260440161074a565b801561212557612125848383612c7b565b50505050565b8047101561215557604051635c01c81560e11b81524760048201526024810182905260440161074a565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b1580156121b057600080fd5b505af11580156121c4573d6000803e3d6000fd5b505060405163a9059cbb60e01b8152336004820152602481018590527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316935063a9059cbb92506044019050602060405180830381600087803b15801561223257600080fd5b505af1158015612246573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061226a9190614088565b5050565b6001600160a01b03851633148061228a575061228a853361064e565b6122e85760405162461bcd60e51b815260206004820152602960248201527f455243313135353a2063616c6c6572206973206e6f74206f776e6572206e6f7260448201526808185c1c1c9bdd995960ba1b606482015260840161074a565b610d618585858585612d60565b60405163d505accf60e01b8152336004820152306024820152604481018690526064810185905260ff8416608482015260a4810183905260c481018290526001600160a01b0387169063d505accf9060e401610dd2565b8342111561236d576040516331c64a7360e01b815260040160405180910390fd5b6001600160a01b03878116600081815260046020908152604080832080546001810190915581517f7bf72c3e57bc00556754c7454ead7d72d1c0e263909e7c643fbc0d1e0f3c3e748185015280830195909552948b166060850152891515608085015260a084019490945260c08084018990528451808503909101815260e0909301909352815191909201209061240382612f02565b9050600061241382878787612f50565b9050896001600160a01b0316816001600160a01b03161461244757604051630811945d60e41b815260040160405180910390fd5b505050612455878787612f78565b50505050505050565b60008383836040516020016124899291906001600160a01b0392831681529116602082015260400190565b60408051601f1981840301815290829052805160209182012061251c939290917ff8e63833fcbf190bd32bc64a1c450bd59b356b4b7cf79cad298a369fb369aaae91017fff00000000000000000000000000000000000000000000000000000000000000815260609390931b6bffffffffffffffffffffffff191660018401526015830191909152603582015260550190565b60408051601f198184030181529190528051602090910120949350505050565b811561258b5761254b82612fe5565b835484906000906125669084906001600160801b03166146b8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b801561149e5761259a81612fe5565b835484906010906125bc908490600160801b90046001600160801b03166146b8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550505050565b61149e838383612fff565b604080516000808252602082019092526001600160a01b03841690839060405161261a919061438c565b60006040518083038185875af1925050503d8060008114612657576040519150601f19603f3d011682016040523d82523d6000602084013e61265c565b606091505b50909150508061149e576040516313ff771f60e21b815260040160405180910390fd5b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316846001600160a01b03161480156126c05750804710155b156127e2577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561272057600080fd5b505af1158015612734573d6000803e3d6000fd5b505060405163a9059cbb60e01b81526001600160a01b038681166004830152602482018690527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216935063a9059cbb92506044019050602060405180830381600087803b1580156127a457600080fd5b505af11580156127b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127dc9190614088565b50612125565b6001600160a01b038316301415612803576127fe848383612c7b565b612125565b6121258484848461317d565b81518351146128715760405162461bcd60e51b815260206004820152602860248201527f455243313135353a2069647320616e6420616d6f756e7473206c656e677468206044820152670dad2e6dac2e8c6d60c31b606482015260840161074a565b6001600160a01b0384166128d55760405162461bcd60e51b815260206004820152602560248201527f455243313135353a207472616e7366657220746f20746865207a65726f206164604482015264647265737360d81b606482015260840161074a565b3360005b8451811015612a025760008582815181106128f6576128f66147da565b602002602001015190506000858381518110612914576129146147da565b60209081029190910181015160008481526001835260408082206001600160a01b038e1683529093529190912054909150818110156129a85760405162461bcd60e51b815260206004820152602a60248201527f455243313135353a20696e73756666696369656e742062616c616e636520666f60448201526939103a3930b739b332b960b11b606482015260840161074a565b60008381526001602090815260408083206001600160a01b038e8116855292528083208585039055908b168252812080548492906129e79084906146e3565b92505081905550505050806129fb90614793565b90506128d9565b50846001600160a01b0316866001600160a01b0316826001600160a01b03167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb8787604051612a52929190614548565b60405180910390a4610cbe81878787878761326a565b6000306001600160a01b037f00000000000000000000000054522da62a15225c95b01bd61ff58b866c50471f16148015612ac157507f000000000000000000000000000000000000000000000000000000000000000146145b15612aeb57507f494971f781f9b413b5c02bd38029a4c4f6e2171b8503047f2e569eced73bd50390565b50604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6020808301919091527f8a4f9f8c669a1f9b597869bc0ef0bdcb7d24e6942f240f25f2c9aa1322dea43b828401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b90565b8115612be157612ba182612fe5565b83548490600090612bbc9084906001600160801b03166146fb565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505b801561149e57612bf081612fe5565b835484906010906125bc908490600160801b90046001600160801b03166146fb565b612c30848360001c836040518060200160405280600081525061341f565b6000828152600560205260409020546001600160a01b031661212557600082815260056020526040902080546001600160a01b0385166001600160a01b031990911617905550505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1790529151600092839290871691612cd7919061438c565b6000604051808303816000865af19150503d8060008114612d14576040519150601f19603f3d011682016040523d82523d6000602084013e612d19565b606091505b5091509150818015612d43575080511580612d43575080806020019051810190612d439190614088565b610d61576040516313ff771f60e21b815260040160405180910390fd5b6001600160a01b038416612dc45760405162461bcd60e51b815260206004820152602560248201527f455243313135353a207472616e7366657220746f20746865207a65726f206164604482015264647265737360d81b606482015260840161074a565b33612ddd818787612dd488613522565b610d6188613522565b60008481526001602090815260408083206001600160a01b038a16845290915290205483811015612e635760405162461bcd60e51b815260206004820152602a60248201527f455243313135353a20696e73756666696369656e742062616c616e636520666f60448201526939103a3930b739b332b960b11b606482015260840161074a565b60008581526001602090815260408083206001600160a01b038b8116855292528083208785039055908816825281208054869290612ea29084906146e3565b909155505060408051868152602081018690526001600160a01b03808916928a821692918616917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a461245582888888888861356d565b60006107c7612f0f612a68565b8360405161190160f01b6020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b6000806000612f6187878787613678565b91509150612f6e81613765565b5095945050505050565b6001600160a01b03838116600081815260026020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b60006001600160801b03821115612ffb57600080fd5b5090565b6001600160a01b0383166130615760405162461bcd60e51b815260206004820152602360248201527f455243313135353a206275726e2066726f6d20746865207a65726f206164647260448201526265737360e81b606482015260840161074a565b336130918185600061307287613522565b61307b87613522565b5050604080516020810190915260009052505050565b60008381526001602090815260408083206001600160a01b0388168452909152902054828110156131105760405162461bcd60e51b8152602060048201526024808201527f455243313135353a206275726e20616d6f756e7420657863656564732062616c604482015263616e636560e01b606482015260840161074a565b60008481526001602090815260408083206001600160a01b03898116808652918452828520888703905582518981529384018890529092908616917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a45050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17905291516000928392908816916131e1919061438c565b6000604051808303816000865af19150503d806000811461321e576040519150601f19603f3d011682016040523d82523d6000602084013e613223565b606091505b509150915081801561324d57508051158061324d57508080602001905181019061324d9190614088565b610cbe576040516313ff771f60e21b815260040160405180910390fd5b6001600160a01b0384163b15610cbe5760405163bc197c8160e01b81526001600160a01b0385169063bc197c81906132ae90899089908890889088906004016143a8565b602060405180830381600087803b1580156132c857600080fd5b505af19250505080156132f8575060408051601f3d908101601f191682019092526132f5918101906140f0565b60015b6133ae57613304614806565b806308c379a0141561333e5750613319614821565b806133245750613340565b8060405162461bcd60e51b815260040161074a91906145b2565b505b60405162461bcd60e51b815260206004820152603460248201527f455243313135353a207472616e7366657220746f206e6f6e204552433131353560448201527f526563656976657220696d706c656d656e746572000000000000000000000000606482015260840161074a565b6001600160e01b0319811663bc197c8160e01b146124555760405162461bcd60e51b815260206004820152602860248201527f455243313135353a204552433131353552656365697665722072656a656374656044820152676420746f6b656e7360c01b606482015260840161074a565b6001600160a01b03841661347f5760405162461bcd60e51b815260206004820152602160248201527f455243313135353a206d696e7420746f20746865207a65726f206164647265736044820152607360f81b606482015260840161074a565b3361349081600087612dd488613522565b60008481526001602090815260408083206001600160a01b0389168452909152812080548592906134c29084906146e3565b909155505060408051858152602081018590526001600160a01b0380881692600092918516917fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62910160405180910390a4610d618160008787878761356d565b6040805160018082528183019092526060916000919060208083019080368337019050509050828160008151811061355c5761355c6147da565b602090810291909101015292915050565b6001600160a01b0384163b15610cbe5760405163f23a6e6160e01b81526001600160a01b0385169063f23a6e61906135b19089908990889088908890600401614406565b602060405180830381600087803b1580156135cb57600080fd5b505af19250505080156135fb575060408051601f3d908101601f191682019092526135f8918101906140f0565b60015b61360757613304614806565b6001600160e01b0319811663f23a6e6160e01b146124555760405162461bcd60e51b815260206004820152602860248201527f455243313135353a204552433131353552656365697665722072656a656374656044820152676420746f6b656e7360c01b606482015260840161074a565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156136af575060009050600361375c565b8460ff16601b141580156136c757508460ff16601c14155b156136d8575060009050600461375c565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561372c573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166137555760006001925092505061375c565b9150600090505b94509492505050565b6000816004811115613779576137796147c4565b14156137825750565b6001816004811115613796576137966147c4565b14156137e45760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161074a565b60028160048111156137f8576137f86147c4565b14156138465760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161074a565b600381600481111561385a5761385a6147c4565b14156138b35760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b606482015260840161074a565b60048160048111156138c7576138c76147c4565b14156139205760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202776272076616c604482015261756560f01b606482015260840161074a565b50565b600082601f83011261393457600080fd5b813560206139418261466c565b60405161394e8282614766565b8381528281019150858301600585901b8701840188101561396e57600080fd5b60005b8581101561398d57813584529284019290840190600101613971565b5090979650505050505050565b600082601f8301126139ab57600080fd5b81356139b681614690565b6040516139c38282614766565b8281528560208487010111156139d857600080fd5b82602086016020830137600092810160200192909252509392505050565b803563ffffffff81168114613a0a57600080fd5b919050565b803560ff81168114613a0a57600080fd5b600060208284031215613a3257600080fd5b8135613a3d816148ab565b9392505050565b600060208284031215613a5657600080fd5b8151613a3d816148ab565b60008060408385031215613a7457600080fd5b8235613a7f816148ab565b91506020830135613a8f816148ab565b809150509250929050565b600080600080600060a08688031215613ab257600080fd5b8535613abd816148ab565b94506020860135613acd816148ab565b93506040860135613add816148ab565b94979396509394606081013594506080013592915050565b600080600080600060a08688031215613b0d57600080fd5b8535613b18816148ab565b94506020860135613b28816148ab565b9350604086013567ffffffffffffffff80821115613b4557600080fd5b613b5189838a01613923565b94506060880135915080821115613b6757600080fd5b613b7389838a01613923565b93506080880135915080821115613b8957600080fd5b50613b968882890161399a565b9150509295509295909350565b600080600080600080600060e0888a031215613bbe57600080fd5b8735613bc9816148ab565b96506020880135613bd9816148ab565b95506040880135613be9816148c0565b945060608801359350613bfe60808901613a0f565b925060a0880135915060c0880135905092959891949750929550565b600080600080600080600080610100898b031215613c3757600080fd5b8835613c42816148ab565b97506020890135613c52816148ab565b965060408901356001600160801b0381168114613c6e57600080fd5b9550613c7c60608a016139f6565b9450613c8a60808a016139f6565b9350613c9860a08a016139f6565b925060c0890135915060e089013590509295985092959890939650565b60008060008060808587031215613ccb57600080fd5b8435613cd6816148ab565b93506020850135613ce6816148ab565b93969395505050506040820135916060013590565b600080600080600060a08688031215613d1357600080fd5b8535613d1e816148ab565b94506020860135613d2e816148ab565b93506040860135925060608601359150608086013567ffffffffffffffff811115613d5857600080fd5b613b968882890161399a565b60008060408385031215613d7757600080fd5b8235613d82816148ab565b91506020830135613a8f816148c0565b600080600080600080600080610100898b031215613daf57600080fd5b8835613dba816148ab565b9750602089013596506040890135613dd1816148ab565b95506060890135613de1816148ab565b94506080890135935060a0890135925060c0890135613dff816148c0565b8092505060e089013590509295985092959890939650565b600080600080600060a08688031215613e2f57600080fd5b8535613e3a816148ab565b97602087013597506040870135966060810135965060800135945092505050565b60008060408385031215613e6e57600080fd5b8235613e79816148ab565b946020939093013593505050565b600080600060608486031215613e9c57600080fd5b8335613ea7816148ab565b9250602084013591506040840135613ebe816148ab565b809150509250925092565b60008060008060008060c08789031215613ee257600080fd5b8635613eed816148ab565b95506020870135945060408701359350613f0960608801613a0f565b92506080870135915060a087013590509295509295509295565b60008060408385031215613f3657600080fd5b823567ffffffffffffffff80821115613f4e57600080fd5b818501915085601f830112613f6257600080fd5b81356020613f6f8261466c565b604051613f7c8282614766565b8381528281019150858301600585901b870184018b1015613f9c57600080fd5b600096505b84871015613fc8578035613fb4816148ab565b835260019690960195918301918301613fa1565b5096505086013592505080821115613fdf57600080fd5b50613fec85828601613923565b9150509250929050565b6000806020838503121561400957600080fd5b823567ffffffffffffffff8082111561402157600080fd5b818501915085601f83011261403557600080fd5b81358181111561404457600080fd5b8660208260051b850101111561405957600080fd5b60209290920196919550909350505050565b60006020828403121561407d57600080fd5b8135613a3d816148c0565b60006020828403121561409a57600080fd5b8151613a3d816148c0565b6000806000606084860312156140ba57600080fd5b8351925060208401519150604084015190509250925092565b6000602082840312156140e557600080fd5b8135613a3d816148ce565b60006020828403121561410257600080fd5b8151613a3d816148ce565b60006020828403121561411f57600080fd5b815167ffffffffffffffff81111561413657600080fd5b8201601f8101841361414757600080fd5b805161415281614690565b60405161415f8282614766565b82815286602084860101111561417457600080fd5b61418583602083016020870161473a565b9695505050505050565b6000606082840312156141a157600080fd5b6040516060810181811067ffffffffffffffff821117156141c4576141c46147f0565b60405282356141d2816148ab565b815260208301356141e2816148ab565b602082015260408301356141f5816148ab565b60408201529392505050565b6000610140828403121561421457600080fd5b50919050565b60006020828403121561422c57600080fd5b5035919050565b60006020828403121561424557600080fd5b5051919050565b6000806040838503121561425f57600080fd5b823591506020830135613a8f816148ab565b6000806040838503121561428457600080fd5b505080516020909101519092909150565b600080600080606085870312156142ab57600080fd5b8435935060208501359250604085013567ffffffffffffffff808211156142d157600080fd5b818701915087601f8301126142e557600080fd5b8135818111156142f457600080fd5b88602082850101111561430657600080fd5b95989497505060200194505050565b600081518084526020808501945080840160005b8381101561434557815187529582019590820190600101614329565b509495945050505050565b6000815180845261436881602086016020860161473a565b601f01601f19169290920160200192915050565b8183823760009101908152919050565b6000825161439e81846020870161473a565b9190910192915050565b60006001600160a01b03808816835280871660208401525060a060408301526143d460a0830186614315565b82810360608401526143e68186614315565b905082810360808401526143fa8185614350565b98975050505050505050565b60006001600160a01b03808816835280871660208401525084604083015283606083015260a0608083015261443e60a0830184614350565b979650505050505050565b60006101006001600160a01b038b168352896020840152881515604084015287606084015286608084015285151560a084015284151560c08401528060e084015261449681840185614350565b9b9a5050505050505050505050565b6001600160a01b03851681528360208201528260408201526080606082015260006141856080830184614350565b6000602080830181845280855180835260408601915060408160051b870101925083870160005b8281101561452857603f19888603018452614516858351614350565b945092850192908501906001016144fa565b5092979650505050505050565b602081526000613a3d6020830184614315565b60408152600061455b6040830185614315565b828103602084015261456d8185614315565b95945050505050565b8681526001600160a01b0386166020820152846040820152836060820152821515608082015260c060a082015260006143fa60c0830184614350565b602081526000613a3d6020830184614350565b6001600160801b0388168152600063ffffffff808916602084015280881660408401528087166060840152508460808301528360a083015260e060c083015261461160e0830184614350565b9998505050505050505050565b6000808335601e1984360301811261463557600080fd5b83018035915067ffffffffffffffff82111561465057600080fd5b60200191503681900382131561466557600080fd5b9250929050565b600067ffffffffffffffff821115614686576146866147f0565b5060051b60200190565b600067ffffffffffffffff8211156146aa576146aa6147f0565b50601f01601f191660200190565b60006001600160801b038083168185168083038211156146da576146da6147ae565b01949350505050565b600082198211156146f6576146f66147ae565b500190565b60006001600160801b038381169083168181101561471b5761471b6147ae565b039392505050565b600082821015614735576147356147ae565b500390565b60005b8381101561475557818101518382015260200161473d565b838111156121255750506000910152565b601f8201601f1916810167ffffffffffffffff8111828210171561478c5761478c6147f0565b6040525050565b60006000198214156147a7576147a76147ae565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b600060033d1115612b8f5760046000803e5060005160e01c90565b600060443d101561482f5790565b6040516003193d81016004833e81513d67ffffffffffffffff816024840111818411171561485f57505050505090565b82850191508151818111156148775750505050505090565b843d87010160208285010111156148915750505050505090565b6148a060208286010187614766565b509095945050505050565b6001600160a01b038116811461392057600080fd5b801515811461392057600080fd5b6001600160e01b03198116811461392057600080fdfea2646970667358221220a589e7c8d3bb24437ece0111d1f5827cd1d5e49bcc1ef8a81fc5f2c82813859064736f6c63430008060033

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

0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b068000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000d4ea6381c0a7c9565fcdfa35c84a7939300176e7

-----Decoded View---------------
Arg [0] : factory_ (address): 0x5cA2D631a37B21E5de2BcB0CbB892D723A96b068
Arg [1] : WETH9_ (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [2] : positionDescriptor_ (address): 0xD4Ea6381c0A7C9565fCdfA35C84a7939300176e7

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 0000000000000000000000005ca2d631a37b21e5de2bcb0cbb892d723a96b068
Arg [1] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [2] : 000000000000000000000000d4ea6381c0a7c9565fcdfa35c84a7939300176e7


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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