ETH Price: $2,524.21 (-0.04%)

Token

Swaap WETH Fund (swpWETH)
 

Overview

Max Total Supply

241.304805863583226663 swpWETH

Holders

58

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 18 Decimals)

Balance
12.777591650793224965 swpWETH

Value
$0.00
0x9ba1fe40211d2b116240ff0996f4bca1f649b5ca
Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
FundWithShareLockFlashLoansWhitelisting

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 1 runs

Other Settings:
shanghai EvmVersion
File 1 of 44 : FundWithShareLockFlashLoansWhitelisting.sol
// SPDX-License-Identifier: Apache-2.0

/*
                                      sβ–ˆβ–ˆβ–ˆ
                                    β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                              ,sβ–ˆβ–ˆβ–ˆ`
                           ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                          β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ^@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_ 7@β–ˆβ–ˆβ–ˆ_            "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆM
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_     `_              "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                        ^^^^^^^^^^"                         ^"`
                         
                        β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆp   _β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆWT@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                         @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                          @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                           "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                             @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                               %β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ`
                                 ^%β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
                                     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆW"`
                                     1β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                      "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                         7W@β–ˆ
*/

pragma solidity 0.8.21;

import { Fund, Registry, ERC20, Math, SafeTransferLib } from "src/base/Fund.sol";
import { IFlashLoanRecipient, IERC20 } from "@balancer/interfaces/contracts/vault/IFlashLoanRecipient.sol";
import { FundWithShareLockPeriod } from "src/base/permutations/FundWithShareLockPeriod.sol";
import { EIP712, ECDSA } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

/**
 * @title Fund with a Share Lock Period, Flash Loans, and Whitelisting.
 */
contract FundWithShareLockFlashLoansWhitelisting is FundWithShareLockPeriod, EIP712 {
    using SafeTransferLib for ERC20;

    uint256 internal constant WHITELIST_VALIDITY_PERIOD = 5 minutes;
    bytes32 public constant WHITELIST_TYPEHASH =
        keccak256("Whitelist(address sender,address receiver,uint256 signedAt)");

    /// @notice Flag checks if whitelisting is enabled.
    bool public isWhitelistEnabled;

    /// @notice Emitted when the whitelisting requirement to enter is enabled or disabled.
    event WhitelistingChanged(bool isWhitelistEnabled);

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint192 _shareSupplyCap
    )
        FundWithShareLockPeriod(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _shareSupplyCap
        )
        EIP712(_name, "1.0")
    {}

    // ========================================= Flash Loan Support =========================================
    /**
     * @notice External contract attempted to initiate a flash loan.
     */
    error Fund__ExternalInitiator();

    /**
     * @notice receiveFlashLoan was not called by an authorized source.
     */
    error Fund__CallerNotAuthorizedForFlashLoan();

    /**
     * @notice Allows rebalancers to utilize flashloans while rebalancing the fund.
     * @param tokens The tokens being flash loaned.
     * @param amounts The amounts of tokens being flash loaned.
     * @param feeAmounts The fees for the flash loan.
     * @param userData The data for the flash loan.
     */
    function receiveFlashLoan(
        IERC20[] calldata tokens,
        uint256[] calldata amounts,
        uint256[] calldata feeAmounts,
        bytes calldata userData
    ) external {
        if (!registry.approvedFlashLoanSource(msg.sender)) revert Fund__CallerNotAuthorizedForFlashLoan();
        if (!blockExternalReceiver) revert Fund__ExternalInitiator();

        AdaptorCall[] memory data = abi.decode(userData, (AdaptorCall[]));

        // Run all adaptor calls.
        _makeAdaptorCalls(data);

        // Approve pool to repay all debt.
        for (uint256 i; i < amounts.length; ++i) {
            ERC20(address(tokens[i])).safeTransfer(msg.sender, (amounts[i] + feeAmounts[i]));
        }
    }

    // ========================================= Whitelisting Support =========================================

    /**
     * @notice Emitted when the whitelist is enabled and a signature is required to join.
     * @dev The user must use "whitelistDeposit" or "whitelistMint" to deposit or mint shares when
     *      whitelist is enabled.
     */
    error Fund__WhitelistEnabled();

    /**
     * @notice Emitted when the signature deadline is invalid.
     */
    error Fund__InvalidSignatureDeadline();

    /**
     * @notice Emitted when the signature is invalid.
     */
    error Fund__InvalidSignature();

    /**
     * @notice Deposits assets into the fund, and returns shares to receiver.
     * @dev The nonReentrant modifier is defined in the parent contract.
     * @param assets amount of assets deposited by user.
     * @param receiver address to receive the shares.
     * @return shares amount of shares given for deposit.
     */
    function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {
        if (isWhitelistEnabled) revert Fund__WhitelistEnabled();
        return super.deposit(assets, receiver);
    }

    /**
     * @notice Mints shares from the fund, and returns shares to receiver.
     * @dev The nonReentrant modifier is defined in the parent contract.
     * @param shares amount of shares requested by user.
     * @param receiver address to receive the shares.
     * @return assets amount of assets deposited into the fund.
     */
    function mint(uint256 shares, address receiver) public override returns (uint256 assets) {
        if (isWhitelistEnabled) revert Fund__WhitelistEnabled();
        return super.mint(shares, receiver);
    }

    /**
     * @notice Deposits assets into the fund, and returns shares to receiver.
     * @param assets amount of assets deposited by user.
     * @param receiver address to receive the shares.
     * @param signedAt timestamp of when the signature was created.
     * @param signature signature of the whitelist permission.
     * @return shares amount of shares given for deposit.
     */
    function whitelistDeposit(
        uint256 assets,
        address receiver,
        uint256 signedAt,
        bytes memory signature
    ) external returns (uint256 shares) {
        _verifyWhitelistSignature(receiver, signedAt, signature);
        return super.deposit(assets, receiver);
    }

    /**
     * @notice Mints shares from the fund, and returns shares to receiver.
     * @param shares amount of shares requested by user.
     * @param receiver address to receive the shares.
     * @param signedAt timestamp of when the signature was created.
     * @param signature signature of the whitelist permission.
     * @return assets amount of assets deposited into the fund.
     */
    function whitelistMint(
        uint256 shares,
        address receiver,
        uint256 signedAt,
        bytes memory signature
    ) external returns (uint256 assets) {
        _verifyWhitelistSignature(receiver, signedAt, signature);
        return super.mint(shares, receiver);
    }

    function _verifyWhitelistSignature(address receiver, uint256 signedAt, bytes memory signature) internal view {
        if (isWhitelistEnabled) {
            // verify deadline is still valid
            if (block.timestamp > signedAt + WHITELIST_VALIDITY_PERIOD) revert Fund__InvalidSignatureDeadline();
            if (block.timestamp < signedAt) revert Fund__InvalidSignatureDeadline();

            bytes32 digest = _hashTypedDataV4(
                keccak256(abi.encode(WHITELIST_TYPEHASH, msg.sender, receiver, signedAt))
            );

            address signer = ECDSA.recover(digest, signature);

            if (signer != automationActions && signer != owner()) revert Fund__InvalidSignature();
        }
    }

    /**
     * @notice Enables the whitelist.
     */
    function enableWhitelist() external onlyOwner {
        isWhitelistEnabled = true;
        emit WhitelistingChanged(true);
    }

    /**
     * @notice Disables the whitelist.
     */
    function disableWhitelist() external onlyOwner {
        isWhitelistEnabled = false;
        emit WhitelistingChanged(false);
    }
}

File 2 of 44 : Fund.sol
// SPDX-License-Identifier: Apache-2.0

/*
                                      sβ–ˆβ–ˆβ–ˆ
                                    β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                              ,sβ–ˆβ–ˆβ–ˆ`
                           ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                          β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ^@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_ 7@β–ˆβ–ˆβ–ˆ_            "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆM
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_     `_              "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                        ^^^^^^^^^^"                         ^"`
                         
                        β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆp   _β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆWT@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                         @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                          @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                           "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                             @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                               %β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ`
                                 ^%β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
                                     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆW"`
                                     1β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                      "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                         7W@β–ˆ
*/

pragma solidity 0.8.21;

import { Math } from "src/utils/Math.sol";
import { ERC4626, ERC20 } from "src/base/ERC4626.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { Registry } from "src/Registry.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { Uint32Array } from "src/utils/Uint32Array.sol";
import { BaseAdaptor } from "src/modules/adaptors/BaseAdaptor.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Owned } from "@solmate/auth/Owned.sol";
import { FeesManager } from "src/modules/fees/FeesManager.sol";

/**
 * @title Swaap Fund
 * @notice A composable ERC4626 that can use arbitrary DeFi assets/positions using adaptors.
 * @dev Forked from https://github.com/PeggyJV/cellar-contracts
 */
contract Fund is ERC4626, Ownable {
    using Uint32Array for uint32[];
    using SafeTransferLib for ERC20;
    using Math for uint256;
    using Address for address;

    // ========================================= One Slot Values =========================================
    // Below values are frequently accessed in the same TXs. By moving them to the top
    // they will be stored in the same slot, reducing cold access reads.

    /**
     * @notice The maximum amount of shares that can be in circulation.
     * @dev Can be increase or decreased by Fund's Owner.
     */
    uint192 public shareSupplyCap;

    /**
     * @notice `locked` is public, so that the state can be checked even during view function calls.
     */
    bool public locked;

    /**
     * @notice Whether or not the contract is shutdown in case of an emergency.
     */
    bool public isShutdown;

    /**
     * @notice This bool is used to stop rebalancers from abusing Base Adaptor functions(deposit/withdraw).
     */
    bool public blockExternalReceiver;

    /**
     * @notice Stores the position id of the holding position in the creditPositions array.
     */
    uint32 public holdingPosition;

    /**
     * @notice Sets the end date when the fund pause mode will be disregarded whatever its state.
     */
    uint256 public immutable endPauseTimestamp;

    // ========================================= MULTICALL =========================================

    /**
     * @notice Allows caller to call multiple functions in a single TX.
     * @dev Does NOT return the function return values.
     */
    function multicall(bytes[] calldata data) external {
        for (uint256 i; i < data.length; ++i) address(this).functionDelegateCall(data[i]);
    }

    // ========================================= REENTRANCY GUARD =========================================

    error Fund__Reentrancy();

    function _revertWhenReentrant() internal view {
        if (locked) revert Fund__Reentrancy();
    }

    function _nonReentrantAfter() internal {
        locked = false;
    }

    function _nonReentrantBefore() internal {
        _revertWhenReentrant();
        locked = true;
    }

    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    // ========================================= PRICE ROUTER CACHE =========================================
    /// @dev Represents 100% in basis points, where 1 basis point is 1/100th of 1%.
    uint16 internal constant _BPS_ONE_HUNDRED_PER_CENT = 1e4;

    /**
     * @notice Cached price router contract.
     * @dev This way fund has to "opt in" to price router changes.
     */
    PriceRouter public priceRouter;

    /**
     * @notice Updates the fund to use the latest price router in the registry.
     * @param checkTotalAssets If true totalAssets is checked before and after updating the price router,
     *        and is verified to be withing a +- 5% envelope.
     *        If false totalAssets is only called after updating the price router.]
     * @param allowableRange The +- range the total assets may deviate between the old and new price router.
     *                       - 1_000 == 10%
     *                       - 500 == 5%
     * @param expectedPriceRouter The registry price router differed from the expected price router.
     * @dev `allowableRange` reverts from arithmetic underflow if it is greater than 10_000, this is
     *      desired behavior.
     * @dev Callable by the Fund's owner.
     */
    function cachePriceRouter(
        bool checkTotalAssets,
        uint16 allowableRange,
        address expectedPriceRouter
    ) external onlyOwner {
        uint256 minAssets;
        uint256 maxAssets;

        if (checkTotalAssets) {
            uint256 assetsBefore = totalAssets();
            minAssets = assetsBefore.mulDivDown(_BPS_ONE_HUNDRED_PER_CENT - allowableRange, _BPS_ONE_HUNDRED_PER_CENT);
            maxAssets = assetsBefore.mulDivDown(_BPS_ONE_HUNDRED_PER_CENT + allowableRange, _BPS_ONE_HUNDRED_PER_CENT);
        }

        // Make sure expected price router is equal to price router grabbed from registry.
        _checkRegistryAddressAgainstExpected(_PRICE_ROUTER_REGISTRY_SLOT, expectedPriceRouter);

        priceRouter = PriceRouter(expectedPriceRouter);

        if (checkTotalAssets) {
            uint256 assetsAfter = totalAssets();
            if (assetsAfter < minAssets || assetsAfter > maxAssets)
                revert Fund__TotalAssetDeviatedOutsideRange(assetsAfter, minAssets, maxAssets);
        }
    }

    // ========================================= POSITIONS CONFIG =========================================

    /**
     * @notice Emitted when a position is added.
     * @param position id of position that was added
     * @param index index that position was added at
     */
    event PositionAdded(uint32 position, uint256 index);

    /**
     * @notice Emitted when a position is removed.
     * @param position id of position that was removed
     * @param index index that position was removed from
     */
    event PositionRemoved(uint32 position, uint256 index);

    /**
     * @notice Emitted when the positions at two indexes are swapped.
     * @param newPosition1 id of position (previously at index2) that replaced index1.
     * @param newPosition2 id of position (previously at index1) that replaced index2.
     * @param index1 index of first position involved in the swap
     * @param index2 index of second position involved in the swap.
     */
    event PositionSwapped(uint32 newPosition1, uint32 newPosition2, uint256 index1, uint256 index2);

    /**
     * @notice Emitted when owner adds/removes a position to/from the funds catalogue.
     */
    event PositionCatalogueAltered(uint32 positionId, bool inCatalogue);

    /**
     * @notice Emitted when owner adds/removes an adaptor to/from the funds catalogue.
     */
    event AdaptorCatalogueAltered(address adaptor, bool inCatalogue);

    /**
     * @notice Attempted to add a position that is already being used.
     * @param position id of the position
     */
    error Fund__PositionAlreadyUsed(uint32 position);

    /**
     * @notice Attempted to make an unused position the holding position.
     * @param position id of the position
     */
    error Fund__PositionNotUsed(uint32 position);

    /**
     * @notice Attempted to add a position that is not in the catalogue.
     * @param position id of the position
     */
    error Fund__PositionNotInCatalogue(uint32 position);

    /**
     * @notice Attempted an action on a position that is required to be empty before the action can be performed.
     * @param position address of the non-empty position
     * @param sharesRemaining amount of shares remaining in the position
     */
    error Fund__PositionNotEmpty(uint32 position, uint256 sharesRemaining);

    /**
     * @notice Attempted an operation with an asset that was different then the one expected.
     * @param asset address of the asset
     * @param expectedAsset address of the expected asset
     */
    error Fund__AssetMismatch(address asset, address expectedAsset);

    /**
     * @notice Attempted to add a position when the position array is full.
     * @param maxPositions maximum number of positions that can be used
     */
    error Fund__PositionArrayFull(uint256 maxPositions);

    /**
     * @notice Attempted to add a position, with mismatched debt.
     * @param position the posiiton id that was mismatched
     */
    error Fund__DebtMismatch(uint32 position);

    /**
     * @notice Attempted to remove the Funds holding position.
     */
    error Fund__RemovingHoldingPosition();

    /**
     * @notice Attempted to remove an index with an unexpected positionId.
     */
    error Fund__WrongPositionId();

    /**
     * @notice Attempted to add an invalid holding position.
     * @param positionId the id of the invalid position.
     */
    error Fund__InvalidHoldingPosition(uint32 positionId);

    /**
     * @notice Attempted to force out the wrong position.
     */
    error Fund__FailedToForceOutPosition();

    /**
     * @notice Array of uint32s made up of funds credit positions Ids.
     */
    uint32[] public creditPositions;

    /**
     * @notice Array of uint32s made up of funds debt positions Ids.
     */
    uint32[] public debtPositions;

    /**
     * @notice Tell whether a position is currently used.
     */
    mapping(uint256 => bool) public isPositionUsed;

    /**
     * @notice Get position data given position id.
     */
    mapping(uint32 => Registry.PositionData) public getPositionData;

    /**
     * @notice Get the ids of the credit positions currently used by the fund.
     */
    function getCreditPositions() external view returns (uint32[] memory) {
        return creditPositions;
    }

    /**
     * @notice Get the ids of the debt positions currently used by the fund.
     */
    function getDebtPositions() external view returns (uint32[] memory) {
        return debtPositions;
    }

    /**
     * @notice Maximum amount of positions a fund can have in its credit/debt arrays.
     */
    uint256 internal constant _MAX_POSITIONS = 32;

    /**
     * @notice Allows owner to change the holding position.
     * @dev Callable by the Fund's owner.
     */
    function setHoldingPosition(uint32 positionId) public onlyOwner {
        if (!isPositionUsed[positionId]) revert Fund__PositionNotUsed(positionId);
        if (_assetOf(positionId) != asset) revert Fund__AssetMismatch(address(asset), address(_assetOf(positionId)));
        if (getPositionData[positionId].isDebt) revert Fund__InvalidHoldingPosition(positionId);
        holdingPosition = positionId;
    }

    /**
     * @notice Positions the rebalancers can use.
     */
    mapping(uint32 => bool) public positionCatalogue;

    /**
     * @notice Adaptors the rebalancers can use.
     */
    mapping(address => bool) public adaptorCatalogue;

    /**
     * @notice Allows the Owner to add positions to this fund's catalogue.
     * @dev Callable by the Fund's owner.
     */
    function addPositionToCatalogue(uint32 positionId) public onlyOwner {
        // Make sure position is not paused and is trusted.
        registry.revertIfPositionIsNotTrusted(positionId);
        positionCatalogue[positionId] = true;
        emit PositionCatalogueAltered(positionId, true);
    }

    /**
     * @notice Allows owner to remove positions from this fund's catalogue.
     * @dev Callable by the Fund's owner.
     */
    function removePositionFromCatalogue(uint32 positionId) external onlyOwner {
        positionCatalogue[positionId] = false;
        emit PositionCatalogueAltered(positionId, false);
    }

    /**
     * @notice Allows owner to add adaptors to this fund's catalogue.
     * @dev Callable by the Fund's owner.
     */
    function addAdaptorToCatalogue(address adaptor) external onlyOwner {
        // Make sure adaptor is not paused and is trusted.
        registry.revertIfAdaptorIsNotTrusted(adaptor);
        adaptorCatalogue[adaptor] = true;
        emit AdaptorCatalogueAltered(adaptor, true);
    }

    /**
     * @notice Allows owner to remove adaptors from this fund's catalogue.
     * @dev Callable by the Fund's owner.
     */
    function removeAdaptorFromCatalogue(address adaptor) external onlyOwner {
        adaptorCatalogue[adaptor] = false;
        emit AdaptorCatalogueAltered(adaptor, false);
    }

    /**
     * @notice Insert a trusted position to the list of positions used by the fund at a given index.
     * @param index index at which to insert the position
     * @param positionId id of position to add
     * @param configurationData data used to configure how the position behaves
     * @dev Callable by the Fund's owner.
     */
    function addPosition(
        uint32 index,
        uint32 positionId,
        bytes memory configurationData,
        bool inDebtArray
    ) public onlyOwner {
        _whenNotShutdown();

        // Check if position is already being used.
        if (isPositionUsed[positionId]) revert Fund__PositionAlreadyUsed(positionId);

        // Check if position is in the position catalogue.
        if (!positionCatalogue[positionId]) revert Fund__PositionNotInCatalogue(positionId);

        // Grab position data from registry.
        // Also checks if position is not trusted and reverts if so.
        (address adaptor, bool isDebt, bytes memory adaptorData) = registry.addPositionToFund(positionId);

        if (isDebt != inDebtArray) revert Fund__DebtMismatch(positionId);

        // Copy position data from registry to here.
        getPositionData[positionId] = Registry.PositionData({
            adaptor: adaptor,
            isDebt: isDebt,
            adaptorData: adaptorData,
            configurationData: configurationData
        });

        if (isDebt) {
            if (debtPositions.length >= _MAX_POSITIONS) revert Fund__PositionArrayFull(_MAX_POSITIONS);
            // Add new position at a specified index.
            debtPositions.add(index, positionId);
        } else {
            if (creditPositions.length >= _MAX_POSITIONS) revert Fund__PositionArrayFull(_MAX_POSITIONS);
            // Add new position at a specified index.
            creditPositions.add(index, positionId);
        }

        isPositionUsed[positionId] = true;

        emit PositionAdded(positionId, index);
    }

    /**
     * @notice Remove the position at a given index from the list of positions used by the fund.
     * @dev Callable by the Fund's owner.
     * @param index index at which to remove the position
     */
    function removePosition(uint32 index, uint32 expectedPositionId, bool inDebtArray) external onlyOwner {
        // Get position being removed.
        uint32 positionId = inDebtArray ? debtPositions[index] : creditPositions[index];

        if (expectedPositionId != positionId) revert Fund__WrongPositionId();

        // Only remove position if it is empty, and if it is not the holding position.
        uint256 positionBalance = _balanceOf(positionId);
        if (positionBalance > 0) revert Fund__PositionNotEmpty(positionId, positionBalance);

        _removePosition(index, positionId, inDebtArray);
    }

    /**
     * @notice Allows Fund's owner to forceably remove a position from the Fund without checking its balance is zero.
     * @dev Callable by the Fund's owner.
     */
    function forcePositionOut(uint32 index, uint32 positionId, bool inDebtArray) external onlyOwner {
        // Get position being removed.
        uint32 _positionId = inDebtArray ? debtPositions[index] : creditPositions[index];
        // Make sure position id right, and is distrusted.
        if (positionId != _positionId || registry.isPositionTrusted(positionId))
            revert Fund__FailedToForceOutPosition();

        _removePosition(index, positionId, inDebtArray);
    }

    /**
     * @notice Internal helper function to remove positions from funds tracked arrays.
     */
    function _removePosition(uint32 index, uint32 positionId, bool inDebtArray) internal {
        if (positionId == holdingPosition) revert Fund__RemovingHoldingPosition();

        if (inDebtArray) {
            // Remove position at the given index.
            debtPositions.remove(index);
        } else {
            creditPositions.remove(index);
        }

        isPositionUsed[positionId] = false;
        delete getPositionData[positionId];

        emit PositionRemoved(positionId, index);
    }

    /**
     * @notice Swap the positions at two given indexes.
     * @param index1 index of first position to swap
     * @param index2 index of second position to swap
     * @param inDebtArray bool indicating to switch positions in the debt array, or the credit array.
     * @dev Callable by the Fund's owner.
     */
    function swapPositions(uint32 index1, uint32 index2, bool inDebtArray) external onlyOwner {
        // Get the new positions that will be at each index.
        uint32 newPosition1;
        uint32 newPosition2;

        if (inDebtArray) {
            newPosition1 = debtPositions[index2];
            newPosition2 = debtPositions[index1];
            // Swap positions.
            (debtPositions[index1], debtPositions[index2]) = (newPosition1, newPosition2);
        } else {
            newPosition1 = creditPositions[index2];
            newPosition2 = creditPositions[index1];
            // Swap positions.
            (creditPositions[index1], creditPositions[index2]) = (newPosition1, newPosition2);
        }

        emit PositionSwapped(newPosition1, newPosition2, index1, index2);
    }

    // =========================================== EMERGENCY LOGIC ===========================================

    /**
     * @notice Emitted when fund emergency state is changed.
     * @param isShutdown whether the fund is shutdown
     */
    event ShutdownChanged(bool isShutdown);

    /**
     * @notice Attempted action was prevented due to contract being shutdown.
     */
    error Fund__ContractShutdown();

    /**
     * @notice Attempted action was prevented due to contract not being shutdown.
     */
    error Fund__ContractNotShutdown();

    /**
     * @notice Attempted to interact with the fund when it is paused.
     */
    error Fund__Paused();

    /**
     * @notice View function external contracts can use to see if the fund is paused.
     */
    function isPaused() public view returns (bool) {
        if (block.timestamp < endPauseTimestamp) {
            return registry.isCallerPaused(address(this));
        }
        return false;
    }

    /**
     * @notice Pauses all user entry/exits, and rebalances.
     */
    function _whenNotPaused() internal view {
        if (isPaused()) revert Fund__Paused();
    }

    /**
     * @notice Prevent a function from being called during a shutdown.
     */
    function _whenNotShutdown() internal view {
        if (isShutdown) revert Fund__ContractShutdown();
    }

    /**
     * @notice Shutdown the fund. Used in an emergency or if the fund has been deprecated.
     * @dev Callable by the Fund's owner.
     */
    function initiateShutdown() external onlyOwner {
        _whenNotShutdown();
        isShutdown = true;

        emit ShutdownChanged(true);
    }

    /**
     * @notice Restart the fund.
     * @dev Callable by the Fund's owner.
     */
    function liftShutdown() external onlyOwner {
        if (!isShutdown) revert Fund__ContractNotShutdown();
        isShutdown = false;

        emit ShutdownChanged(false);
    }

    // =========================================== CONSTRUCTOR ===========================================

    /**
     * @notice Delay between the creation of the fund and the end of the pause period.
     */
    uint256 internal constant _DELAY_UNTIL_END_PAUSE = 30 days * 9; // 9 months

    /**
     * @notice Id to get the price router from the registry.
     */
    uint256 internal constant _PRICE_ROUTER_REGISTRY_SLOT = 2;

    /**
     * @notice The minimum amount of shares to be minted in the contructor.
     */
    uint256 internal constant _MINIMUM_CONSTRUCTOR_MINT = 1e4;

    uint8 internal constant _FUND_DECIMALS = 18;

    /**
     * @notice Attempted to deploy contract without minting enough shares.
     */
    error Fund__MinimumConstructorMintNotMet();

    /**
     * @notice Address of the platform's registry contract. Used to get the latest address of modules.
     */
    Registry public immutable registry;

    uint8 internal immutable _ASSET_DECIMALS;

    /**
     * @notice Address of the fees manager contract.
     */
    FeesManager public immutable FEES_MANAGER;

    /**
     * @dev Owner should be set to the ProtocolDAO
     * @param _registry address of the platform's registry contract
     * @param _asset address of underlying token used for the for accounting, depositing, and withdrawing
     * @param _name name of this fund's share token
     * @param _symbol symbol of this fund's share token
     * @param _holdingPosition the holding position of the Fund
     *        must use a position that does NOT call back to fund on use(Like ERC20 positions).
     * @param _holdingPositionConfig configuration data for holding position
     * @param _initialDeposit initial amount of assets to deposit into the Fund
     * @param _shareSupplyCap starting share supply cap
     */
    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint192 _shareSupplyCap
    ) ERC4626(_asset) ERC20(_name, _symbol, _FUND_DECIMALS) Ownable() {
        endPauseTimestamp = block.timestamp + _DELAY_UNTIL_END_PAUSE;
        registry = _registry;
        priceRouter = PriceRouter(_registry.getAddress(_PRICE_ROUTER_REGISTRY_SLOT));

        // Initialize holding position.
        addPositionToCatalogue(_holdingPosition);
        addPosition(0, _holdingPosition, _holdingPositionConfig, false);
        setHoldingPosition(_holdingPosition);

        // Update Share Supply Cap.
        shareSupplyCap = _shareSupplyCap;

        if (_initialDeposit < _MINIMUM_CONSTRUCTOR_MINT) revert Fund__MinimumConstructorMintNotMet();

        // Deposit into Fund, and mint shares to Deployer address.
        _asset.safeTransferFrom(_owner, address(this), _initialDeposit);
        // Set the share price as 1:1 * 10**(fund.decimals - asset.decimals) with underlying asset.
        _ASSET_DECIMALS = _asset.decimals(); // reverts if asset decimals > fund decimals
        _mint(msg.sender, _initialDeposit * (10 ** (_FUND_DECIMALS - _ASSET_DECIMALS)));
        // Deposit _initialDeposit into holding position.
        _depositTo(_holdingPosition, _initialDeposit);

        FEES_MANAGER = _registry.FEES_MANAGER();

        transferOwnership(_owner);
    }

    // =========================================== CORE LOGIC ===========================================

    /**
     * @notice Attempted an action with zero shares.
     */
    error Fund__ZeroShares();

    /**
     * @notice Attempted an action with zero assets.
     */
    error Fund__ZeroAssets();

    /**
     * @notice Withdraw did not withdraw all assets.
     * @param assetsOwed the remaining assets owed that were not withdrawn.
     */
    error Fund__IncompleteWithdraw(uint256 assetsOwed);

    /**
     * @notice called at the beginning of deposit.
     */
    function beforeDeposit(uint256, uint256, address) internal view virtual {
        _whenNotShutdown();
        _whenNotPaused();
    }

    /**
     * @notice called at the end of deposit.
     * @param assets amount of assets deposited by user.
     */
    function afterDeposit(uint256 assets, uint256, address) internal virtual {
        _depositTo(holdingPosition, assets);
    }

    /**
     * @notice called at the beginning of withdraw.
     */
    function beforeWithdraw(uint256, uint256, address, address) internal view virtual {
        _whenNotPaused();
    }

    /**
     * @notice Called when users enter the fund via deposit or mint.
     */
    function _enter(uint256 assets, uint256 shares, address receiver) internal {
        beforeDeposit(assets, shares, receiver);

        // Need to transfer before minting or ERC777s could reenter.
        asset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(assets, shares, receiver);
    }

    /**
     * @notice Deposits assets into the fund, and returns shares to receiver.
     * @param assets amount of assets deposited by user.
     * @param receiver address to receive the shares.
     * @return shares amount of shares given for deposit.
     */
    function deposit(uint256 assets, address receiver) public virtual override nonReentrant returns (uint256 shares) {
        // the total supply is the equivalent of total shares after applying the performance and management fees
        (uint256 _totalAssets, uint256 _totalSupply) = _collectFeesAndGetTotalAssetsAndTotalSupply(true);

        if ((shares = _convertToShares(assets, _totalAssets, _totalSupply)) == 0) revert Fund__ZeroShares();

        if ((_totalSupply + shares) > shareSupplyCap) revert Fund__ShareSupplyCapExceeded();

        _enter(assets, shares, receiver);
    }

    /**
     * @notice Mints shares from the fund, and returns shares to receiver.
     * @param shares amount of shares requested by user.
     * @param receiver address to receive the shares.
     * @return assets amount of assets deposited into the fund.
     */
    function mint(uint256 shares, address receiver) public virtual override nonReentrant returns (uint256 assets) {
        // the total supply is the equivalent of total shares after applying the performance and management fees
        (uint256 _totalAssets, uint256 _totalSupply) = _collectFeesAndGetTotalAssetsAndTotalSupply(true);

        // previewMint rounds up, but initial mint could return zero assets, so check for rounding error.
        if ((assets = _previewMint(shares, _totalAssets, _totalSupply)) == 0) revert Fund__ZeroAssets();

        if ((_totalSupply + shares) > shareSupplyCap) revert Fund__ShareSupplyCapExceeded();

        _enter(assets, shares, receiver);
    }

    /**
     * @notice Called when users exit the fund via withdraw or redeem.
     */
    function _exit(uint256 assets, uint256 shares, address receiver, address owner) internal {
        beforeWithdraw(assets, shares, receiver, owner);

        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        _burn(owner, shares);

        emit Withdraw(msg.sender, receiver, owner, assets, shares);
        _withdrawInOrder(assets, receiver);

        /// @notice `afterWithdraw` is currently not used.
        // afterWithdraw(assets, shares, receiver, owner);
    }

    /**
     * @notice Withdraw assets from the fund by redeeming shares.
     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.
     *      Since there are no swaps involved in this function, the receiver may receive multiple
     *      assets. The value of all the assets returned will be equal to the amount defined by
     *      `assets` denominated in the `asset` of the fund (eg. if `asset` is USDC and `assets`
     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many
     *      tokens).
     * @param assets equivalent value of the assets withdrawn, denominated in the fund's asset
     * @param receiver address that will receive withdrawn assets
     * @param owner address that owns the shares being redeemed
     * @return shares amount of shares redeemed
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public override nonReentrant returns (uint256 shares) {
        // the total supply is the equivalent of total shares after applying the performance and management fees
        (uint256 _totalAssets, uint256 _totalSupply) = _collectFeesAndGetTotalAssetsAndTotalSupply(false);

        // No need to check for rounding error, `previewWithdraw` rounds up.
        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);

        _exit(assets, shares, receiver, owner);
    }

    /**
     * @notice Redeem shares to withdraw assets from the fund.
     * @dev Unlike conventional ERC4626 contracts, this may not always return one asset to the receiver.
     *      Since there are no swaps involved in this function, the receiver may receive multiple
     *      assets. The value of all the assets returned will be equal to the amount defined by
     *      `assets` denominated in the `asset` of the fund (eg. if `asset` is USDC and `assets`
     *      is 1000, then the receiver will receive $1000 worth of assets in either one or many
     *      tokens).
     * @param shares amount of shares to redeem
     * @param receiver address that will receive withdrawn assets
     * @param owner address that owns the shares being redeemed
     * @return assets equivalent value of the assets withdrawn, denominated in the fund's asset
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public override nonReentrant returns (uint256 assets) {
        // the total supply is the equivalent of total shares after applying the performance and management fees
        (uint256 _totalAssets, uint256 _totalSupply) = _collectFeesAndGetTotalAssetsAndTotalSupply(false);

        if ((assets = _convertToAssets(shares, _totalAssets, _totalSupply)) == 0) revert Fund__ZeroAssets();

        _exit(assets, shares, receiver, owner);
    }

    /**
     * @notice Called at the beginning of `previewDeposit`, `previewMint`, `previewWithdraw` and `previewRedeem`.
     * @return _totalAssets the virtual total assets in the fund after fees if any
     * @return _totalSupply the virtual total supply of shares after fees if any
     */
    function _previewTotalAssetsAndTotalSupplyAfterFees(
        bool _isEntering
    ) internal view virtual returns (uint256, uint256) {
        uint256 _totalAssets = _calculateTotalAssets();
        uint256 _totalSupply = totalSupply;

        if (isShutdown) {
            return (_totalAssets, _totalSupply);
        }

        (uint16 _enterOrExitFeesRate, uint256 _feesAsShares) = FEES_MANAGER.previewApplyFeesBeforeJoinExit(
            _totalAssets,
            _totalSupply,
            _isEntering
        );

        _totalAssets = _applyEnterOrExitFees(_totalAssets, _enterOrExitFeesRate, _isEntering);

        return (_totalAssets, _totalSupply + _feesAsShares);
    }

    /**
     * @notice Collect fees from the fund.
     * @dev Callable by anyone (permissionless).
     */
    function collectFees() external nonReentrant {
        _whenNotPaused();
        _collectFeesAndGetTotalAssetsAndTotalSupply(false);
    }

    /**
     * @notice Called at the beginning of `deposit`, `mint`, `withdraw` and `redeem`.
     * @dev This function is called before the fund applies fees.
     * @return _totalAssets the virtual total assets in the fund after enter or exit fees
     * @return _totalSupply the total supply of shares after management and performance fees
     */
    function _collectFeesAndGetTotalAssetsAndTotalSupply(bool _isEntering) internal virtual returns (uint256, uint256) {
        uint256 _totalAssets = _calculateTotalAssets();
        uint256 _totalSupply = totalSupply;

        if (isShutdown) {
            return (_totalAssets, _totalSupply);
        }

        try FEES_MANAGER.applyFeesBeforeJoinExit(_totalAssets, _totalSupply, _isEntering) returns (
            uint16 _enterOrExitFeesRate,
            uint256 _feesAsShares
        ) {
            if (_feesAsShares > 0) {
                _mint(address(FEES_MANAGER), _feesAsShares);
                _totalSupply += _feesAsShares;
            }

            _totalAssets = _applyEnterOrExitFees(_totalAssets, _enterOrExitFeesRate, _isEntering);

            return (_totalAssets, _totalSupply);
        } catch {
            // If fees fail to apply, return with 0 fees. (it should not happen in normal cases)
            return (_totalAssets, _totalSupply);
        }
    }

    /// @return virtualTotalAssets the virtual total assets after applying enter or exit fees
    function _applyEnterOrExitFees(
        uint256 _totalAssets,
        uint16 _enterOrExitFeeRate,
        bool _isEntering
    ) internal pure returns (uint256) {
        if (_enterOrExitFeeRate == 0) {
            return _totalAssets;
        }

        if (_isEntering) {
            return _totalAssets.mulDivUp(_BPS_ONE_HUNDRED_PER_CENT + _enterOrExitFeeRate, _BPS_ONE_HUNDRED_PER_CENT);
        }

        return _totalAssets.mulDivDown(_BPS_ONE_HUNDRED_PER_CENT - _enterOrExitFeeRate, _BPS_ONE_HUNDRED_PER_CENT);
    }

    /**
     * @notice Struct used in `_withdrawInOrder` in order to hold multiple pricing values in a single variable.
     * @dev Prevents stack too deep errors.
     */
    struct WithdrawPricing {
        uint256 priceBaseUSD;
        uint256 oneBase;
        uint256 priceQuoteUSD;
        uint256 oneQuote;
    }

    /**
     * @notice Multipler used to insure calculations use very high precision.
     */
    uint256 private constant PRECISION_MULTIPLIER = 1e18;

    /**
     * @dev Withdraw from positions in the order defined by `positions`.
     * @param assets the amount of assets to withdraw from fund
     * @param receiver the address to sent withdrawn assets to
     * @dev Only loop through credit array because debt can not be withdraw by users.
     */
    function _withdrawInOrder(uint256 assets, address receiver) internal {
        // Save asset price in USD, and decimals to reduce external calls.
        WithdrawPricing memory pricingInfo;
        pricingInfo.priceQuoteUSD = priceRouter.getPriceInUSD(asset);
        pricingInfo.oneQuote = 10 ** _ASSET_DECIMALS;
        uint256 creditLength = creditPositions.length;
        for (uint256 i; i < creditLength; ++i) {
            uint32 position = creditPositions[i];
            uint256 withdrawableBalance = _withdrawableFrom(position);
            // Move on to next position if this one is empty.
            if (withdrawableBalance == 0) continue;
            ERC20 positionAsset = _assetOf(position);

            pricingInfo.priceBaseUSD = priceRouter.getPriceInUSD(positionAsset);
            pricingInfo.oneBase = 10 ** positionAsset.decimals();
            uint256 totalWithdrawableBalanceInAssets;
            {
                uint256 withdrawableBalanceInUSD = (PRECISION_MULTIPLIER * withdrawableBalance).mulDivDown(
                    pricingInfo.priceBaseUSD,
                    pricingInfo.oneBase
                );
                totalWithdrawableBalanceInAssets = withdrawableBalanceInUSD.mulDivDown(
                    pricingInfo.oneQuote,
                    pricingInfo.priceQuoteUSD
                );
                totalWithdrawableBalanceInAssets = totalWithdrawableBalanceInAssets / PRECISION_MULTIPLIER;
            }

            // We want to pull as much as we can from this position, but no more than needed.
            uint256 amount;

            if (totalWithdrawableBalanceInAssets > assets) {
                // Convert assets into position asset.
                uint256 assetsInUSD = (PRECISION_MULTIPLIER * assets).mulDivDown(
                    pricingInfo.priceQuoteUSD,
                    pricingInfo.oneQuote
                );
                amount = assetsInUSD.mulDivDown(pricingInfo.oneBase, pricingInfo.priceBaseUSD);
                amount = amount / PRECISION_MULTIPLIER;
                assets = 0;
            } else {
                amount = withdrawableBalance;
                assets = assets - totalWithdrawableBalanceInAssets;
            }

            // Withdraw from position.
            _withdrawFrom(position, amount, receiver);

            // Stop if no more assets to withdraw.
            if (assets == 0) break;
        }
        // If withdraw did not remove all assets owed, revert.
        if (assets > 0) revert Fund__IncompleteWithdraw(assets);
    }

    // ========================================= ACCOUNTING LOGIC =========================================

    function _calculateTotalWithdrawableAssets() internal view returns (uint256 withdrawableAssets) {
        uint256 numOfCreditPositions = creditPositions.length;
        ERC20[] memory creditAssets = new ERC20[](numOfCreditPositions);
        uint256[] memory creditBalances = new uint256[](numOfCreditPositions);

        for (uint256 i; i < numOfCreditPositions; ++i) {
            uint32 position = creditPositions[i];
            // If the withdrawable balance is zero there is no point to query the asset since a zero balance has zero value.
            if ((creditBalances[i] = _withdrawableFrom(position)) == 0) continue;
            creditAssets[i] = _assetOf(position);
        }

        withdrawableAssets = priceRouter.getValues(creditAssets, creditBalances, asset);
    }

    function _calculateTotalAssets() internal view returns (uint256 assets) {
        (ERC20[] memory creditAssets, uint256[] memory creditBalances) = _getCreditOrDebtPositionsData(false);
        (ERC20[] memory debtAssets, uint256[] memory debtBalances) = _getCreditOrDebtPositionsData(true);

        assets = priceRouter.getValuesDelta(creditAssets, creditBalances, debtAssets, debtBalances, asset);
    }

    /**
     * @return _positionAssets the assets of the positions
     * @return _positionBalances the balances of the positions
     */
    function _getCreditOrDebtPositionsData(bool _isDebt) internal view returns (ERC20[] memory, uint256[] memory) {
        uint32[] memory _positions = _isDebt ? debtPositions : creditPositions;

        uint256 numOfPositions = _positions.length;
        ERC20[] memory _positionAssets = new ERC20[](numOfPositions);
        uint256[] memory _positionBalances = new uint256[](numOfPositions);

        for (uint256 i; i < numOfPositions; ++i) {
            uint32 position = _positions[i];
            // If the balance is zero there is no point to query the asset since a zero balance has zero value.
            if ((_positionBalances[i] = _balanceOf(position)) == 0) continue;
            _positionAssets[i] = _assetOf(position);
        }

        return (_positionAssets, _positionBalances);
    }

    /**
     * @notice The total amount of assets in the fund.
     * @dev EIP4626 states totalAssets needs to be inclusive of fees.
     * Since performance fees mint shares, total assets remains unchanged,
     * so this implementation is inclusive of fees even though it does not explicitly show it.
     * @dev EIP4626 states totalAssets must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @dev Run a re-entrancy check because totalAssets can be wrong if re-entering from deposit/withdraws.
     */
    function totalAssets() public view override returns (uint256 assets) {
        _whenNotPaused();
        _revertWhenReentrant();
        assets = _calculateTotalAssets();
    }

    /**
     * @notice The total amount of withdrawable assets in the fund.
     * @dev Run a re-entrancy check because totalAssetsWithdrawable can be wrong if re-entering from deposit/withdraws.
     */
    function totalAssetsWithdrawable() public view returns (uint256 assets) {
        _whenNotPaused();
        _revertWhenReentrant();
        assets = _calculateTotalWithdrawableAssets();
    }

    /**
     * @notice The amount of assets that the fund would exchange for the amount of shares provided.
     * @dev Use preview functions to get accurate assets.
     * @dev Under estimates assets.
     * @param shares amount of shares to convert
     * @return assets the shares can be exchanged for
     */
    function convertToAssets(uint256 shares) public view override returns (uint256) {
        return previewRedeem(shares);
    }

    /**
     * @notice The amount of shares that the fund would exchange for the amount of assets provided.
     * @dev Use preview functions to get accurate shares.
     * @dev Under estimates shares.
     * @param assets amount of assets to convert
     * @return shares the assets can be exchanged for
     */
    function convertToShares(uint256 assets) public view override returns (uint256 shares) {
        return previewDeposit(assets);
    }

    /**
     * @notice Simulate the effects of minting shares at the current block, given current on-chain conditions.
     * @param shares amount of shares to mint
     * @return assets that will be deposited
     */
    function previewMint(uint256 shares) public view override returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(true);
        assets = _previewMint(shares, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of withdrawing assets at the current block, given current on-chain conditions.
     * @param assets amount of assets to withdraw
     * @return shares that will be redeemed
     */
    function previewWithdraw(uint256 assets) public view override returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(false);
        shares = _previewWithdraw(assets, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of depositing assets at the current block, given current on-chain conditions.
     * @param assets amount of assets to deposit
     * @return shares that will be minted
     */
    function previewDeposit(uint256 assets) public view override returns (uint256 shares) {
        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(true);
        shares = _convertToShares(assets, _totalAssets, _totalSupply);
    }

    /**
     * @notice Simulate the effects of redeeming shares at the current block, given current on-chain conditions.
     * @param shares amount of shares to redeem
     * @return assets that will be returned
     */
    function previewRedeem(uint256 shares) public view override returns (uint256 assets) {
        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(false);
        assets = _convertToAssets(shares, _totalAssets, _totalSupply);
    }

    /**
     * @notice Finds the max amount of value an `owner` can remove from the fund.
     * @param owner address of the user to find max value.
     * @param inShares if false, then returns value in terms of assets
     *                 if true then returns value in terms of shares
     */
    function _findMax(address owner, bool inShares) internal view virtual returns (uint256 maxOut) {
        _whenNotPaused();
        // Get amount of assets to withdraw.
        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(false);

        uint256 assets = _convertToAssets(balanceOf[owner], _totalAssets, _totalSupply);

        uint256 withdrawable = _calculateTotalWithdrawableAssets();
        maxOut = assets <= withdrawable ? assets : withdrawable;

        if (inShares) maxOut = _convertToShares(maxOut, _totalAssets, _totalSupply);
        // else leave maxOut in terms of assets.
    }

    /**
     * @notice Returns the max amount withdrawable by a user inclusive of performance fees
     * @dev EIP4626 states maxWithdraw must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @param owner address to check maxWithdraw of.
     * @return the max amount of assets withdrawable by `owner`.
     */
    function maxWithdraw(address owner) public view override returns (uint256) {
        _revertWhenReentrant();
        return _findMax(owner, false);
    }

    /**
     * @notice Returns the max amount shares redeemable by a user
     * @dev EIP4626 states maxRedeem must not revert, but it is possible for `totalAssets` to revert
     * so it does NOT conform to ERC4626 standards.
     * @param owner address to check maxRedeem of.
     * @return the max amount of shares redeemable by `owner`.
     */
    function maxRedeem(address owner) public view override returns (uint256) {
        _revertWhenReentrant();
        return _findMax(owner, true);
    }

    /**
     * @dev Used to more efficiently convert amount of shares to assets using a stored `totalAssets` value.
     */
    function _convertToAssets(
        uint256 shares,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 assets) {
        assets = shares.mulDivDown(_totalAssets, _totalSupply);
    }

    /**
     * @dev Used to more efficiently convert amount of assets to shares using a stored `totalAssets` value.
     */
    function _convertToShares(
        uint256 assets,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 shares) {
        shares = assets.mulDivDown(_totalSupply, _totalAssets);
    }

    /**
     * @dev Used to more efficiently simulate minting shares using a stored `totalAssets` value.
     */
    function _previewMint(
        uint256 shares,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 assets) {
        assets = shares.mulDivUp(_totalAssets, _totalSupply);
    }

    /**
     * @dev Used to more efficiently simulate withdrawing assets using a stored `totalAssets` value.
     */
    function _previewWithdraw(
        uint256 assets,
        uint256 _totalAssets,
        uint256 _totalSupply
    ) internal pure returns (uint256 shares) {
        shares = assets.mulDivUp(_totalSupply, _totalAssets);
    }

    //cap =========================================== AUTOMATION ACTIONS LOGIC ===========================================

    /**
     * Emitted when sender is not approved to call `callOnAdaptor`.
     */
    error Fund__CallerNotApprovedToRebalance();

    /**
     * @notice Emitted when `setAutomationActions` is called.
     */
    event Fund__AutomationActionsUpdated(address indexed newAutomationActions);

    /**
     * @notice The Automation Actions contract that can rebalance this Fund.
     * @dev Set to zero address if not in use.
     */
    address public automationActions;

    /**
     * @notice Set the Automation Actions contract.
     * @param _registryId Registry Id to get the automation action.
     * @param _expectedAutomationActions The registry automation actions differed from the expected automation actions.
     * @dev Callable by the Fund's owner.
     */
    function setAutomationActions(uint256 _registryId, address _expectedAutomationActions) external onlyOwner {
        _checkRegistryAddressAgainstExpected(_registryId, _expectedAutomationActions);
        automationActions = _expectedAutomationActions;
        emit Fund__AutomationActionsUpdated(_expectedAutomationActions);
    }

    // =========================================== ADAPTOR LOGIC ===========================================

    /**
     * @notice Emitted on when the rebalance deviation is changed.
     * @param oldDeviation the old rebalance deviation
     * @param newDeviation the new rebalance deviation
     */
    event RebalanceDeviationChanged(uint256 oldDeviation, uint256 newDeviation);

    /**
     * @notice totalAssets deviated outside the range set by `allowedRebalanceDeviation`.
     * @param assets the total assets in the fund
     * @param min the minimum allowed assets
     * @param max the maximum allowed assets
     */
    error Fund__TotalAssetDeviatedOutsideRange(uint256 assets, uint256 min, uint256 max);

    /**
     * @notice Total shares in a fund changed when they should stay constant.
     * @param current the current amount of total shares
     * @param expected the expected amount of total shares
     */
    error Fund__TotalSharesMustRemainConstant(uint256 current, uint256 expected);

    /**
     * @notice Total shares in a fund changed when they should stay constant.
     * @param requested the requested rebalance  deviation
     * @param max the max rebalance deviation.
     */
    error Fund__InvalidRebalanceDeviation(uint256 requested, uint256 max);

    /**
     * @notice CallOnAdaptor attempted to use an adaptor that is either paused or is not trusted by the Fund.
     * @param adaptor the adaptor address that is paused or not trusted.
     */
    error Fund__CallToAdaptorNotAllowed(address adaptor);

    /**
     * @notice Stores the max possible rebalance deviation for this fund.
     */
    uint256 public constant MAX_REBALANCE_DEVIATION = 0.1e18;

    /**
     * @notice The percent the total assets of a fund may deviate during a `callOnAdaptor`(rebalance) call.
     */
    uint256 public allowedRebalanceDeviation = 0.0003e18;

    /**
     * @notice Allows owner to change this funds rebalance deviation.
     * @param newDeviation the new rebalance deviation value.
     * @dev Callable by the Fund's owner.
     */
    function setRebalanceDeviation(uint256 newDeviation) external onlyOwner {
        if (newDeviation > MAX_REBALANCE_DEVIATION)
            revert Fund__InvalidRebalanceDeviation(newDeviation, MAX_REBALANCE_DEVIATION);

        uint256 oldDeviation = allowedRebalanceDeviation;
        allowedRebalanceDeviation = newDeviation;

        emit RebalanceDeviationChanged(oldDeviation, newDeviation);
    }

    /**
     * @notice Struct used to make calls to adaptors.
     * @param adaptor the address of the adaptor to make calls to
     * @param the abi encoded function calls to make to the `adaptor`
     */
    struct AdaptorCall {
        address adaptor;
        bytes[] callData;
    }

    /**
     * @notice Emitted when adaptor calls are made.
     */
    event AdaptorCalled(address indexed adaptor, bytes data);

    /**
     * @notice Internal helper function that accepts an Adaptor Call array, and makes calls to each adaptor.
     */
    function _makeAdaptorCalls(AdaptorCall[] memory data) internal {
        for (uint256 i; i < data.length; ++i) {
            address adaptor = data[i].adaptor;
            // Revert if adaptor not in catalogue, or adaptor is paused.
            if (!adaptorCatalogue[adaptor]) revert Fund__CallToAdaptorNotAllowed(adaptor);
            for (uint256 j; j < data[i].callData.length; ++j) {
                adaptor.functionDelegateCall(data[i].callData[j]);
                emit AdaptorCalled(adaptor, data[i].callData[j]);
            }
        }
    }

    /**
     * @notice Allows owner or Automation Actions to manage the Fund using arbitrary logic calls to trusted adaptors.
     * @dev There are several safety checks in this function to prevent rebalancers from abusing it.
     *      - `blockExternalReceiver`
     *      - `totalAssets` must not change by much
     *      - `totalShares` must remain constant
     *      - adaptors must be set up to be used with this fund
     * @dev Since `totalAssets` is allowed to deviate slightly, rebalancers could abuse this by sending
     *      multiple `callOnAdaptor` calls rapidly, to gradually change the share price (for example when swapping unfairly).
     *      To mitigate this, a Fund can be limited in the total volume that can be done in a period of time by the Registry.
     * @dev Callable by the Fund's owner, and Automation Actions address.
     */
    function callOnAdaptor(AdaptorCall[] calldata data) external virtual nonReentrant {
        if (msg.sender != owner() && msg.sender != automationActions) revert Fund__CallerNotApprovedToRebalance();
        _whenNotShutdown();
        _whenNotPaused();
        blockExternalReceiver = true;

        // Record `totalAssets` and `totalShares` before making any external calls.
        uint256 minimumAllowedAssets;
        uint256 maximumAllowedAssets;
        uint256 totalShares;
        {
            uint256 assetsBeforeAdaptorCall = _calculateTotalAssets();
            minimumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 - allowedRebalanceDeviation), 1e18);
            maximumAllowedAssets = assetsBeforeAdaptorCall.mulDivUp((1e18 + allowedRebalanceDeviation), 1e18);
            totalShares = totalSupply;
        }

        // Run all adaptor calls.
        _makeAdaptorCalls(data);

        // After making every external call, check that the totalAssets has not deviated significantly, and that totalShares is the same.
        uint256 assets = _calculateTotalAssets();
        if (assets < minimumAllowedAssets || assets > maximumAllowedAssets) {
            revert Fund__TotalAssetDeviatedOutsideRange(assets, minimumAllowedAssets, maximumAllowedAssets);
        }
        if (totalShares != totalSupply) revert Fund__TotalSharesMustRemainConstant(totalSupply, totalShares);

        blockExternalReceiver = false;
    }

    // ============================================ LIMITS LOGIC ============================================

    /**
     * @notice Attempted entry would raise totalSupply above Share Supply Cap.
     */
    error Fund__ShareSupplyCapExceeded();

    event ShareSupplyCapChanged(uint192 newShareSupplyCap);

    /**
     * @notice Increases the share supply cap.
     * @dev Callable by the Fund's owner.
     */
    function setShareSupplyCap(uint192 _newShareSupplyCap) public onlyOwner {
        shareSupplyCap = _newShareSupplyCap;
        emit ShareSupplyCapChanged(_newShareSupplyCap);
    }

    /**
     * @notice Total amount of assets that can be deposited for a user.
     * @return assets maximum amount of assets that can be deposited
     */
    function maxDeposit(address) public view override returns (uint256) {
        if (isShutdown) return 0;

        uint192 _cap = shareSupplyCap;

        (uint256 _totalAssets, uint256 _totalSupply) = _previewTotalAssetsAndTotalSupplyAfterFees(true);

        if (_totalSupply >= _cap) return 0;
        else {
            uint256 shareDelta = _cap - _totalSupply;
            return _convertToAssets(shareDelta, _totalAssets, _totalSupply);
        }
    }

    /**
     * @notice Total amount of shares that can be minted for a user.
     * @return shares maximum amount of shares that can be minted
     */
    function maxMint(address) public view override returns (uint256) {
        if (isShutdown) return 0;

        uint192 _cap = shareSupplyCap;
        uint256 _totalSupply = totalSupply;

        return _totalSupply >= _cap ? 0 : _cap - _totalSupply;
    }

    // ========================================== HELPER FUNCTIONS ==========================================

    /**
     * @dev Deposit into a position according to its position type and update related state.
     * @param position address to deposit funds into
     * @param assets the amount of assets to deposit into the position
     */
    function _depositTo(uint32 position, uint256 assets) internal {
        address adaptor = getPositionData[position].adaptor;
        adaptor.functionDelegateCall(
            abi.encodeWithSelector(
                BaseAdaptor.deposit.selector,
                assets,
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            )
        );
    }

    /**
     * @dev Withdraw from a position according to its position type and update related state.
     * @param position address to withdraw funds from
     * @param assets the amount of assets to withdraw from the position
     * @param receiver the address to sent withdrawn assets to
     */
    function _withdrawFrom(uint32 position, uint256 assets, address receiver) internal {
        address adaptor = getPositionData[position].adaptor;
        adaptor.functionDelegateCall(
            abi.encodeWithSelector(
                BaseAdaptor.withdraw.selector,
                assets,
                receiver,
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            )
        );
    }

    /**
     * @dev Get the withdrawable balance of a position according to its position type.
     * @param position position to get the withdrawable balance of
     */
    function _withdrawableFrom(uint32 position) internal view returns (uint256) {
        // Debt positions always return 0 for their withdrawable.
        if (getPositionData[position].isDebt) return 0;
        return
            BaseAdaptor(getPositionData[position].adaptor).withdrawableFrom(
                getPositionData[position].adaptorData,
                getPositionData[position].configurationData
            );
    }

    /**
     * @dev Get the balance of a position according to its position type.
     * @dev For ERC4626 position balances, this uses `previewRedeem` as opposed
     *      to `convertToAssets` so that balanceOf ERC4626 positions includes fees taken on withdraw.
     * @param position position to get the balance of
     */
    function _balanceOf(uint32 position) internal view returns (uint256) {
        address adaptor = getPositionData[position].adaptor;
        return BaseAdaptor(adaptor).balanceOf(getPositionData[position].adaptorData);
    }

    /**
     * @dev Get the asset of a position according to its position type.
     * @param position to get the asset of
     */
    function _assetOf(uint32 position) internal view returns (ERC20) {
        address adaptor = getPositionData[position].adaptor;
        return BaseAdaptor(adaptor).assetOf(getPositionData[position].adaptorData);
    }

    /**
     * @notice Attempted to use an address from the registry, but address was not expected.
     */
    error Fund__ExpectedAddressDoesNotMatchActual();

    /**
     * @notice Attempted to set an address to registry Id 0.
     */
    error Fund__SettingValueToRegistryIdZeroIsProhibited();

    /**
     * @notice Verify that `_registryId` in registry corresponds to expected address.
     */
    function _checkRegistryAddressAgainstExpected(uint256 _registryId, address _expected) internal view {
        if (_registryId == 0) revert Fund__SettingValueToRegistryIdZeroIsProhibited();
        if (registry.getAddress(_registryId) != _expected) revert Fund__ExpectedAddressDoesNotMatchActual();
    }

    /**
     * @notice View the amount of assets in each Fund Position.
     */
    function viewPositionBalances()
        external
        view
        returns (ERC20[] memory assets, uint256[] memory balances, bool[] memory isDebt)
    {
        uint256 creditLen = creditPositions.length;
        uint256 debtLen = debtPositions.length;
        uint256 totalLen = creditLen + debtLen;
        assets = new ERC20[](totalLen);
        balances = new uint256[](totalLen);
        isDebt = new bool[](totalLen);
        for (uint256 i; i < creditLen; ++i) {
            assets[i] = _assetOf(creditPositions[i]);
            balances[i] = _balanceOf(creditPositions[i]);
            isDebt[i] = false;
        }

        for (uint256 i; i < debtLen; ++i) {
            // uint256 index;
            uint256 index = i + creditLen;
            assets[index] = _assetOf(debtPositions[i]);
            balances[index] = _balanceOf(debtPositions[i]);
            isDebt[index] = true;
        }
    }
}

File 3 of 44 : IFlashLoanRecipient.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

// Inspired by Aave Protocol's IFlashLoanReceiver.

import "../solidity-utils/openzeppelin/IERC20.sol";

interface IFlashLoanRecipient {
    /**
     * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
     *
     * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
     * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
     * Vault, or else the entire flash loan will revert.
     *
     * `userData` is the same value passed in the `IVault.flashLoan` call.
     */
    function receiveFlashLoan(
        IERC20[] memory tokens,
        uint256[] memory amounts,
        uint256[] memory feeAmounts,
        bytes memory userData
    ) external;
}

File 4 of 44 : FundWithShareLockPeriod.sol
// SPDX-License-Identifier: Apache-2.0

/*
                                      sβ–ˆβ–ˆβ–ˆ
                                    β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                              ,sβ–ˆβ–ˆβ–ˆ`
                           ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                          β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ^@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_ 7@β–ˆβ–ˆβ–ˆ_            "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆM
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_     `_              "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                        ^^^^^^^^^^"                         ^"`
                         
                        β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆp   _β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆWT@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                         @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                          @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                           "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                             @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                               %β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ`
                                 ^%β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
                                     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆW"`
                                     1β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                      "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                         7W@β–ˆ
*/

pragma solidity 0.8.21;

import { Fund, Registry, ERC20, Math } from "src/base/Fund.sol";

/**
 * @title Fund With Share Lock Period
 * @notice Extends Fund to add a share lock period.*
 * @dev Forked from https://github.com/PeggyJV/cellar-contracts
 */
contract FundWithShareLockPeriod is Fund {
    using Math for uint256;

    constructor(
        address _owner,
        Registry _registry,
        ERC20 _asset,
        string memory _name,
        string memory _symbol,
        uint32 _holdingPosition,
        bytes memory _holdingPositionConfig,
        uint256 _initialDeposit,
        uint192 _shareSupplyCap
    )
        Fund(
            _owner,
            _registry,
            _asset,
            _name,
            _symbol,
            _holdingPosition,
            _holdingPositionConfig,
            _initialDeposit,
            _shareSupplyCap
        )
    {}

    /**
     * @notice Emitted when share locking period is changed.
     * @param oldPeriod the old locking period
     * @param newPeriod the new locking period
     */
    event ShareLockingPeriodChanged(uint256 oldPeriod, uint256 newPeriod);

    /**
     * @notice Attempted to set `shareLockPeriod` to an invalid number.
     */
    error Fund__InvalidShareLockPeriod();

    /**
     * @notice Attempted to burn shares when they are locked.
     * @param timeSharesAreUnlocked time when caller can transfer/redeem shares
     * @param currentBlock the current block number.
     */
    error Fund__SharesAreLocked(uint256 timeSharesAreUnlocked, uint256 currentBlock);

    /**
     * @notice Attempted deposit on behalf of a user without being approved.
     */
    error Fund__NotApprovedToDepositOnBehalf(address depositor);

    /**
     * @notice Shares must be locked for at least 5 minutes after minting.
     */
    uint256 public constant MINIMUM_SHARE_LOCK_PERIOD = 5 * 60;

    /**
     * @notice Shares can be locked for at most 2 days after minting.
     */
    uint256 public constant MAXIMUM_SHARE_LOCK_PERIOD = 2 days;

    /**
     * @notice After deposits users must wait `shareLockPeriod` time before being able to transfer or withdraw their shares.
     */
    uint256 public shareLockPeriod = MAXIMUM_SHARE_LOCK_PERIOD;

    /**
     * @notice mapping that stores every users last time stamp they minted shares.
     */
    mapping(address => uint256) public userShareLockStartTime;

    /**
     * @notice Allows share lock period to be updated.
     * @param newLock the new lock period
     * @dev Callable by Fund's owner.
     */
    function setShareLockPeriod(uint256 newLock) external onlyOwner {
        if (newLock < MINIMUM_SHARE_LOCK_PERIOD || newLock > MAXIMUM_SHARE_LOCK_PERIOD)
            revert Fund__InvalidShareLockPeriod();
        uint256 oldLockingPeriod = shareLockPeriod;
        shareLockPeriod = newLock;
        emit ShareLockingPeriodChanged(oldLockingPeriod, newLock);
    }

    /**
     * @notice helper function that checks enough time has passed to unlock shares.
     * @param owner the address of the user to check
     */
    function _checkIfSharesLocked(address owner) internal view {
        uint256 lockTime = userShareLockStartTime[owner];
        if (lockTime != 0) {
            uint256 timeSharesAreUnlocked = lockTime + shareLockPeriod;
            if (timeSharesAreUnlocked > block.timestamp)
                revert Fund__SharesAreLocked(timeSharesAreUnlocked, block.timestamp);
        }
    }

    /**
     * @notice Override `transfer` to add share lock check.
     */
    function transfer(address to, uint256 amount) public override returns (bool) {
        _checkIfSharesLocked(msg.sender);
        return super.transfer(to, amount);
    }

    /**
     * @notice Override `transferFrom` to add share lock check.
     */
    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        _checkIfSharesLocked(from);
        return super.transferFrom(from, to, amount);
    }

    /**
     * @notice called at the beginning of deposit.
     * @param assets amount of assets deposited by user.
     * @param receiver address receiving the shares.
     */
    function beforeDeposit(uint256 assets, uint256 shares, address receiver) internal view override {
        super.beforeDeposit(assets, shares, receiver);
        if (msg.sender != receiver) {
            if (!registry.approvedForDepositOnBehalf(msg.sender)) revert Fund__NotApprovedToDepositOnBehalf(msg.sender);
        }
    }

    /**
     * @notice called at the end of deposit.
     * @param assets amount of assets deposited by user.
     */
    function afterDeposit(uint256 assets, uint256 shares, address receiver) internal override {
        userShareLockStartTime[receiver] = block.timestamp;
        super.afterDeposit(assets, shares, receiver);
    }

    /**
     * @notice called at the beginning of withdraw.
     */
    function beforeWithdraw(uint256 assets, uint256 shares, address receiver, address owner) internal view override {
        _checkIfSharesLocked(owner);
        super.beforeWithdraw(assets, shares, receiver, owner);
    }

    /**
     * @notice Finds the max amount of value an `owner` can remove from the fund.
     * @param owner address of the user to find max value.
     * @param inShares if false, then returns value in terms of assets
     *                 if true then returns value in terms of shares
     */
    function _findMax(address owner, bool inShares) internal view override returns (uint256) {
        uint256 lockTime = userShareLockStartTime[owner];
        if (lockTime != 0) {
            uint256 timeSharesAreUnlocked = lockTime + shareLockPeriod;
            if (timeSharesAreUnlocked > block.timestamp) return 0;
        }
        return super._findMax(owner, inShares);
    }
}

File 5 of 44 : EIP712.sol
// SPDX-License-Identifier: MIT

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 6 of 44 : Math.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

library Math {
    /**
     * @notice Substract with a floor of 0 for the result.
     */
    function subMinZero(uint256 x, uint256 y) internal pure returns (uint256) {
        return x > y ? x - y : 0;
    }

    /**
     * @notice Used to change the decimals of precision used for an amount.
     */
    function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * 10 ** (toDecimals - fromDecimals);
        } else {
            return amount / 10 ** (fromDecimals - toDecimals);
        }
    }

    // ===================================== OPENZEPPELIN'S MATH =====================================

    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    // ================================= SOLMATE's FIXEDPOINTMATHLIB =================================

    uint256 public constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // Divide z by the denominator.
            z := div(z, denominator)
        }
    }

    function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // First, divide z - 1 by the denominator and add 1.
            // We allow z - 1 to underflow if z is 0, because we multiply the
            // end result by 0 if z is zero, ensuring we return 0 if z is zero.
            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
        }
    }
}

File 7 of 44 : ERC4626.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import { ERC20 } from "@solmate/tokens/ERC20.sol";

/**
 * @title ERC4626
 * @notice An interface for a contract that represents a pool of assets and shares.
 */
abstract contract ERC4626 is ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed caller,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /*//////////////////////////////////////////////////////////////
                               IMMUTABLES
    //////////////////////////////////////////////////////////////*/

    ERC20 public immutable asset;

    constructor(ERC20 _asset) {
        asset = _asset;
    }

    /*//////////////////////////////////////////////////////////////
                        DEPOSIT/WITHDRAWAL LOGIC
    //////////////////////////////////////////////////////////////*/

    function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares);

    function mint(uint256 shares, address receiver) public virtual returns (uint256 assets);

    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256 shares);

    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256 assets);

    /*//////////////////////////////////////////////////////////////
                            ACCOUNTING LOGIC
    //////////////////////////////////////////////////////////////*/

    function totalAssets() public view virtual returns (uint256);

    function convertToShares(uint256 assets) public view virtual returns (uint256);

    function convertToAssets(uint256 shares) public view virtual returns (uint256);

    function previewDeposit(uint256 assets) public view virtual returns (uint256);

    function previewMint(uint256 shares) public view virtual returns (uint256);

    function previewWithdraw(uint256 assets) public view virtual returns (uint256);

    function previewRedeem(uint256 shares) public view virtual returns (uint256);

    /*//////////////////////////////////////////////////////////////
                     DEPOSIT/WITHDRAWAL LIMIT LOGIC
    //////////////////////////////////////////////////////////////*/

    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return convertToAssets(balanceOf[owner]);
    }

    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf[owner];
    }
}

File 8 of 44 : SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

File 9 of 44 : Registry.sol
// SPDX-License-Identifier: Apache-2.0

/*
                                      sβ–ˆβ–ˆβ–ˆ
                                    β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                              ,sβ–ˆβ–ˆβ–ˆ`
                           ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                          β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ^@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_ 7@β–ˆβ–ˆβ–ˆ_            "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆM
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_     `_              "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                        ^^^^^^^^^^"                         ^"`
                         
                        β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆp   _β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆWT@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                         @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                          @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                           "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                             @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                               %β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ`
                                 ^%β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
                                     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆW"`
                                     1β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                      "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                         7W@β–ˆ
*/

pragma solidity 0.8.21;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Fund } from "src/base/Fund.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { BaseAdaptor } from "src/modules/adaptors/BaseAdaptor.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { FeesManager } from "src/modules/fees/FeesManager.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";

contract Registry is Ownable {
    using Address for address;
    // ============================================= ADDRESS CONFIG =============================================

    /**
     * @notice Emitted when the address of a contract is changed.
     * @param id value representing the unique ID tied to the changed contract
     * @param oldAddress address of the contract before the change
     * @param newAddress address of the contract after the contract
     */
    event AddressChanged(uint256 indexed id, address oldAddress, address newAddress);

    /**
     * @notice Attempted to set the address of a contract that is not registered.
     * @param id id of the contract that is not registered
     */
    error Registry__ContractNotRegistered(uint256 id);

    /**
     * @notice Emitted when depositor privilege changes.
     * @param depositor depositor address
     * @param state the new state of the depositor privilege
     */
    event DepositorOnBehalfChanged(address indexed depositor, bool state);

    /**
     * @notice The unique ID that the next registered contract will have.
     */
    uint256 public nextId;

    /**
     * @notice Get the address associated with an id.
     */
    mapping(uint256 => address) public getAddress;

    /**
     * @notice In order for an address to make deposits on behalf of users they must be approved.
     */
    mapping(address => bool) public approvedForDepositOnBehalf;

    /**
     * @notice In order to receive a flash loan from a source, it must be approved first.
     */
    mapping(address => bool) public approvedFlashLoanSource;

    /**
     * @notice Defines spender address of an aggregator
     * @dev if spender address is 0, the aggregator was not approved
     */
    mapping(address => address) public aggregatorSpender;

    /**
     * @notice The FeesManager contract.
     */
    FeesManager public immutable FEES_MANAGER;

    /**
     * @notice Allows caller to call multiple functions in a single TX.
     * @dev Does NOT return the function return values.
     */
    function multicall(bytes[] calldata data) external {
        for (uint256 i; i < data.length; ++i) address(this).functionDelegateCall(data[i]);
    }

    /**
     * @notice toggles a depositors  ability to deposit into funds on behalf of users.
     */
    function setApprovedForDepositOnBehalf(address depositor, bool state) external onlyOwner {
        approvedForDepositOnBehalf[depositor] = state;
        emit DepositorOnBehalfChanged(depositor, state);
    }

    /**
     * @notice Set the address of the contract at a given id.
     */
    function setAddress(uint256 id, address newAddress) external {
        if (id > 0) {
            _checkOwner();
            if (id >= nextId) revert Registry__ContractNotRegistered(id);
        } else {
            if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        }

        emit AddressChanged(id, getAddress[id], newAddress);

        getAddress[id] = newAddress;
    }

    // ============================================= INITIALIZATION =============================================

    /**
     * @param protocolDAO address of ProtocolDAO contract
     * @param swapRouter address of SwapRouter contract
     * @param priceRouter address of PriceRouter contract
     */
    constructor(address newOwner, address protocolDAO, address swapRouter, address priceRouter) Ownable() {
        _register(protocolDAO);
        _register(swapRouter);
        _register(priceRouter);
        FEES_MANAGER = new FeesManager(address(this), newOwner);
        transferOwnership(newOwner);
    }

    // ============================================ REGISTER CONFIG ============================================

    /**
     * @notice Emitted when a new contract is registered.
     * @param id value representing the unique ID tied to the new contract
     * @param newContract address of the new contract
     */
    event Registered(uint256 indexed id, address indexed newContract);

    /**
     * @notice Register the address of a new contract.
     * @param newContract address of the new contract to register
     */
    function register(address newContract) external onlyOwner {
        _register(newContract);
    }

    function _register(address newContract) internal {
        getAddress[nextId] = newContract;

        emit Registered(nextId, newContract);

        nextId++;
    }

    // ============================================= ADDRESS 0 LOGIC =============================================
    /**
     * Address 0 is the address of the ProtocolDAO, and special abilities that the owner does not have.
     * - It can change what address is stored at address 0.
     * - It can change the owner of this contract.
     */

    /**
     * @notice Emitted when an ownership transition is started.
     */
    event OwnerTransitionStarted(address indexed pendingOwner, uint256 startTime);

    /**
     * @notice Emitted when an ownership transition is cancelled.
     */
    event OwnerTransitionCancelled(address indexed pendingOwner);

    /**
     * @notice Emitted when an ownership transition is completed.
     */
    event OwnerTransitionComplete(address indexed newOwner);

    /**
     * @notice Attempted to call a function intended for Zero Id address.
     */
    error Registry__OnlyCallableByZeroId();

    /**
     * @notice Attempted to transition owner to the zero address.
     */
    error Registry__NewOwnerCanNotBeZero();

    /**
     * @notice Attempted to perform a restricted action while ownership transition is pending.
     */
    error Registry__TransitionPending();

    /**
     * @notice Attempted to cancel or complete a transition when one is not active.
     */
    error Registry__TransitionNotPending();

    /**
     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.
     */
    error Registry__OnlyCallableByPendingOwner();

    /**
     * @notice The amount of time it takes for an ownership transition to work.
     */
    uint256 public constant TRANSITION_PERIOD = 7 days;

    /**
     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.
     */
    address public pendingOwner;

    /**
     * @notice The starting time stamp of the transition.
     */
    uint256 public transitionStart;

    /**
     * @notice Allows Zero Id address to set a new owner, after the transition period is up.
     */
    function transitionOwner(address newOwner) external {
        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        if (pendingOwner != address(0)) revert Registry__TransitionPending();
        if (newOwner == address(0)) revert Registry__NewOwnerCanNotBeZero();

        emit OwnerTransitionStarted(newOwner, transitionStart);

        pendingOwner = newOwner;
        transitionStart = block.timestamp;
    }

    /**
     * @notice Allows Zero Id address to cancel an ongoing owner transition.
     */
    function cancelTransition() external {
        address _pendingOwner = pendingOwner;

        if (msg.sender != getAddress[0]) revert Registry__OnlyCallableByZeroId();
        if (_pendingOwner == address(0)) revert Registry__TransitionNotPending();

        emit OwnerTransitionCancelled(_pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Allows pending owner to complete the ownership transition.
     */
    function completeTransition() external {
        address _pendingOwner = pendingOwner;

        if (msg.sender != _pendingOwner) revert Registry__OnlyCallableByPendingOwner();
        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert Registry__TransitionPending();

        _transferOwnership(_pendingOwner);

        emit OwnerTransitionComplete(_pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.
     */
    function _checkOwner() internal view override {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        if (transitionStart != 0) revert Registry__TransitionPending();
    }

    // ============================================ Flashloan LOGIC ============================================

    /**
     * @notice Emitted when a flashloan source is added or removed
     */
    event FlashLoanSourceChanged(address indexed source, bool state);

    /**
     * @notice Allows to set or remove a flashloan source
     * @param source Address from which the flashloan can be received
     * @param state The authorization state
     */
    function setApprovedFlashLoanSource(address source, bool state) external onlyOwner {
        approvedFlashLoanSource[source] = state;
        emit FlashLoanSourceChanged(source, state);
    }

    // ============================================ PAUSE LOGIC ============================================

    /**
     * @notice Emitted when a target is paused.
     */
    event TargetPaused(address indexed target);

    /**
     * @notice Emitted when a target is unpaused.
     */
    event TargetUnpaused(address indexed target);

    /**
     * @notice Attempted to unpause a target that was not paused.
     */
    error Registry__TargetNotPaused(address target);

    /**
     * @notice Mapping stores whether or not a fund is paused.
     */
    mapping(address => bool) public isCallerPaused;

    /**
     * @notice Allows multisig to pause multiple funds in a single call.
     */
    function batchPause(address[] calldata targets) external onlyOwner {
        for (uint256 i; i < targets.length; ++i) _pauseTarget(targets[i]);
    }

    /**
     * @notice Allows multisig to unpause multiple funds in a single call.
     */
    function batchUnpause(address[] calldata targets) external onlyOwner {
        for (uint256 i; i < targets.length; ++i) _unpauseTarget(targets[i]);
    }

    /**
     * @notice Helper function to pause some target.
     */
    function _pauseTarget(address target) internal {
        isCallerPaused[target] = true;
        emit TargetPaused(target);
    }

    /**
     * @notice Helper function to unpause some target.
     */
    function _unpauseTarget(address target) internal {
        if (!isCallerPaused[target]) revert Registry__TargetNotPaused(target);
        isCallerPaused[target] = false;
        emit TargetUnpaused(target);
    }

    // ============================================ ADAPTOR LOGIC ============================================

    /**
     * @notice Emitted when an adaptor is trusted.
     * @param adaptor address of the trusted adaptor
     */
    event Registry__AdaptorTrusted(address indexed adaptor);

    /**
     * @notice Emitted when an adaptor is not trusted.
     * @param adaptor address of the distrusted adaptor
     */
    event Registry__AdaptorDistrusted(address indexed adaptor);

    /**
     * @notice Attempted to trust an adaptor with non unique identifier.
     */
    error Registry__IdentifierNotUnique();

    /**
     * @notice Attempted to use an untrusted adaptor.
     */
    error Registry__AdaptorNotTrusted(address adaptor);

    /**
     * @notice Attempted to trust an already trusted adaptor.
     */
    error Registry__AdaptorAlreadyTrusted(address adaptor);

    /**
     * @notice Maps an adaptor address to bool indicating whether it has been set up in the registry.
     */
    mapping(address => bool) public isAdaptorTrusted;

    /**
     * @notice Maps an adaptors identfier to bool, to track if the identifier is unique wrt the registry.
     */
    mapping(bytes32 => bool) public isIdentifierUsed;

    /**
     * @notice Trust an adaptor to be used by funds
     * @param adaptor address of the adaptor to trust
     */
    function trustAdaptor(address adaptor) external onlyOwner {
        if (isAdaptorTrusted[adaptor]) revert Registry__AdaptorAlreadyTrusted(adaptor);
        bytes32 identifier = BaseAdaptor(adaptor).identifier();
        if (isIdentifierUsed[identifier]) revert Registry__IdentifierNotUnique();
        isAdaptorTrusted[adaptor] = true;
        isIdentifierUsed[identifier] = true;
        emit Registry__AdaptorTrusted(adaptor);
    }

    /**
     * @notice Allows registry to distrust adaptors.
     * @dev Doing so prevents Funds from adding this adaptor to their catalogue.
     */
    function distrustAdaptor(address adaptor) external onlyOwner {
        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);
        // Set trust to false.
        isAdaptorTrusted[adaptor] = false;

        emit Registry__AdaptorDistrusted(adaptor);

        // We are NOT resetting `isIdentifierUsed` because if this adaptor is distrusted, then something needs
        // to change about the new one being re-trusted.
    }

    /**
     * @notice Reverts if `adaptor` is not trusted by the registry.
     */
    function revertIfAdaptorIsNotTrusted(address adaptor) external view {
        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);
    }

    // ============================================ POSITION LOGIC ============================================
    /**
     * @notice stores data related to Fund positions.
     * @param adaptors address of the adaptor to use for this position
     * @param isDebt bool indicating whether this position takes on debt or not
     * @param adaptorData arbitrary data needed to correclty set up a position
     * @param configurationData arbitrary data settable by strategist to change fund <-> adaptor interaction
     */
    struct PositionData {
        address adaptor;
        bool isDebt;
        bytes adaptorData;
        bytes configurationData;
    }

    /**
     * @notice Emitted when a new position is added to the registry.
     * @param id the positions id
     * @param adaptor address of the adaptor this position uses
     * @param isDebt bool indicating whether this position takes on debt or not
     * @param adaptorData arbitrary bytes used to configure this position
     */
    event Registry__PositionTrusted(uint32 indexed id, address indexed adaptor, bool isDebt, bytes adaptorData);

    /**
     * @notice Emitted when a position is distrusted.
     * @param id the positions id
     */
    event Registry__PositionDistrusted(uint32 indexed id);

    /**
     * @notice Attempted to trust a position not being used.
     * @param position address of the invalid position
     */
    error Registry__PositionPricingNotSetUp(address position);

    /**
     * @notice Attempted to add a position with bad input values.
     */
    error Registry__InvalidPositionInput();

    /**
     * @notice Attempted to add a position that does not exist.
     */
    error Registry__PositionDoesNotExist();

    /**
     * @notice Attempted to add a position that is not trusted.
     */
    error Registry__PositionIsNotTrusted(uint32 position);

    /**
     * @notice Addresses of the positions currently used by the fund.
     */
    uint256 public constant PRICE_ROUTER_REGISTRY_SLOT = 2;

    /**
     * @notice Maps a position hash to a position Id.
     * @dev can be used by adaptors to verify that a certain position is open during Fund `callOnAdaptor` calls.
     */
    mapping(bytes32 => uint32) public getPositionHashToPositionId;

    /**
     * @notice Maps a position id to its position data.
     * @dev used by Funds when adding new positions.
     */
    mapping(uint32 => PositionData) public getPositionIdToPositionData;

    /**
     * @notice Maps a position to a bool indicating whether or not it is trusted.
     */
    mapping(uint32 => bool) public isPositionTrusted;

    /**
     * @notice Trust a position to be used by the fund.
     * @param positionId the position id of the newly added position
     * @param adaptor the adaptor address this position uses
     * @param adaptorData arbitrary bytes used to configure this position
     */
    function trustPosition(uint32 positionId, address adaptor, bytes memory adaptorData) external onlyOwner {
        bytes32 identifier = BaseAdaptor(adaptor).identifier();
        bool isDebt = BaseAdaptor(adaptor).isDebt();
        bytes32 positionHash = keccak256(abi.encode(identifier, isDebt, adaptorData));

        if (positionId == 0) revert Registry__InvalidPositionInput();
        // Make sure positionId is not already in use.
        PositionData storage pData = getPositionIdToPositionData[positionId];
        if (pData.adaptor != address(0)) revert Registry__InvalidPositionInput();

        // Check that...
        // `adaptor` is a non zero address
        // position has not been already set up
        if (adaptor == address(0) || getPositionHashToPositionId[positionHash] != 0)
            revert Registry__InvalidPositionInput();

        if (!isAdaptorTrusted[adaptor]) revert Registry__AdaptorNotTrusted(adaptor);

        // Set position data.
        pData.adaptor = adaptor;
        pData.isDebt = isDebt;
        pData.adaptorData = adaptorData;
        pData.configurationData = abi.encode(0);

        // Globally trust the position.
        isPositionTrusted[positionId] = true;

        getPositionHashToPositionId[positionHash] = positionId;

        // Check that assets position uses are supported for pricing operations.
        ERC20[] memory assets = BaseAdaptor(adaptor).assetsUsed(adaptorData);
        PriceRouter priceRouter = PriceRouter(getAddress[PRICE_ROUTER_REGISTRY_SLOT]);
        for (uint256 i; i < assets.length; ++i) {
            if (!priceRouter.isSupported(assets[i])) revert Registry__PositionPricingNotSetUp(address(assets[i]));
        }

        emit Registry__PositionTrusted(positionId, adaptor, isDebt, adaptorData);
    }

    /**
     * @notice Allows registry to distrust positions.
     * @dev Doing so prevents Funds from adding this position to their catalogue,
     *      and adding the position to their tracked arrays.
     */
    function distrustPosition(uint32 positionId) external onlyOwner {
        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);
        isPositionTrusted[positionId] = false;
        emit Registry__PositionDistrusted(positionId);
    }

    /**
     * @notice Called by Funds to add a new position to themselves.
     * @param positionId the id of the position the fund wants to add
     * @return adaptor the address of the adaptor, isDebt bool indicating whether position is
     *         debt or not, and adaptorData needed to interact with position
     */
    function addPositionToFund(
        uint32 positionId
    ) external view returns (address adaptor, bool isDebt, bytes memory adaptorData) {
        if (positionId == 0) revert Registry__PositionDoesNotExist();
        PositionData memory positionData = getPositionIdToPositionData[positionId];
        if (positionData.adaptor == address(0)) revert Registry__PositionDoesNotExist();

        revertIfPositionIsNotTrusted(positionId);

        return (positionData.adaptor, positionData.isDebt, positionData.adaptorData);
    }

    /**
     * @notice Reverts if `positionId` is not trusted by the registry.
     */
    function revertIfPositionIsNotTrusted(uint32 positionId) public view {
        if (!isPositionTrusted[positionId]) revert Registry__PositionIsNotTrusted(positionId);
    }

    // ========================================= APPROVED AGGREGATOR SPENDER LOGIC =========================================

    /**
     * @notice Emitted when an aggregator spender is changed or removed
     */
    event AggregatorSpenderChanged(address indexed aggregator, address indexed spender);

    /**
     * @notice Trust aggregator and add the corresponding spender
     */
    function changeAggregatorSpender(address aggregator, address spender) external {
        aggregatorSpender[aggregator] = spender;
        emit AggregatorSpenderChanged(aggregator, spender);
    }

    /**
     * @notice Untrust aggregator and remove spender
     */
    function removeAggregatorSpender(address aggregator) external {
        delete aggregatorSpender[aggregator];
        emit AggregatorSpenderChanged(aggregator, address(0));
    }

    // ========================================== LIMIT ADAPTOR SWAP VOLUME LOGIC ==========================================

    event FundTradeVolumeDataUpdated(
        address indexed fund,
        uint48 lastUpdate,
        uint48 periodLength,
        uint80 volumeInUSD,
        uint80 maxVolumeInUSD
    );

    error Registry__FundTradingVolumeExceeded(address fund);
    error Registry__InvalidVolumeInput();

    struct FundVolumeData {
        uint48 lastUpdate;
        uint48 periodLength;
        uint80 volumeInUSD; // volume per period in USD and 8 decimals (80 bits are largely sufficient)
        uint80 maxVolumeInUSD; // volume per period in USD and 8 decimals (80 bits are largely sufficient)
    }

    mapping(address => FundVolumeData) public fundsAdaptorVolumeData;

    /**
     * @notice Updates and checks if the fund's traded volume is violated.
     * @param volumeInUSD the volume in USD to add to the fund's traded volume.
     * @dev If the fund volume parameters were not set, the fund won't be able to trade on reblances.
     */
    function checkAndUpdateFundTradeVolume(uint256 volumeInUSD) external {
        // caller should be the fund through the swap adapters
        FundVolumeData storage fundVolumeData = fundsAdaptorVolumeData[msg.sender];

        if (fundVolumeData.maxVolumeInUSD == type(uint80).max) return;

        // input sanity check
        if (volumeInUSD > type(uint80).max) revert Registry__InvalidVolumeInput();

        uint256 endPeriod;
        unchecked {
            endPeriod = uint256(fundVolumeData.lastUpdate) + uint256(fundVolumeData.periodLength);
        }

        if (block.timestamp > endPeriod) {
            fundVolumeData.lastUpdate = uint48(block.timestamp);
            fundVolumeData.volumeInUSD = uint80(volumeInUSD);
        } else {
            fundVolumeData.volumeInUSD += uint80(volumeInUSD);
        }

        if (fundVolumeData.volumeInUSD > fundVolumeData.maxVolumeInUSD)
            revert Registry__FundTradingVolumeExceeded(msg.sender);

        emit FundTradeVolumeDataUpdated(
            msg.sender,
            fundVolumeData.lastUpdate,
            fundVolumeData.periodLength,
            fundVolumeData.volumeInUSD,
            fundVolumeData.maxVolumeInUSD
        );
    }

    /**
     * @notice Set the max allowed volume for an adaptor to trade in a period.
     * @param fund the address of the fund
     * @param periodLength the length of the period in seconds
     * @param maxVolumeInUSD the max volume an adaptor can trade in a period
     * @param resetVolume reset or not the current volume an adaptor has traded
     */
    function setMaxAllowedAdaptorVolumeParams(
        address fund,
        uint48 periodLength,
        uint80 maxVolumeInUSD,
        bool resetVolume
    ) external onlyOwner {
        // there is no explicit limit on volume since it can depend on the size of the fund,
        // as well as the strategies involved
        FundVolumeData storage fundVolumeData = fundsAdaptorVolumeData[fund];
        fundVolumeData.periodLength = periodLength;
        fundVolumeData.maxVolumeInUSD = maxVolumeInUSD;

        if (resetVolume) {
            fundVolumeData.lastUpdate = uint48(block.timestamp);
            fundVolumeData.volumeInUSD = 0;
        }

        emit FundTradeVolumeDataUpdated(
            fund,
            fundVolumeData.lastUpdate,
            periodLength,
            fundVolumeData.volumeInUSD,
            maxVolumeInUSD
        );
    }
}

File 10 of 44 : PriceRouter.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol";
import { IChainlinkAggregatorProxy } from "src/interfaces/external/IChainlinkAggregatorProxy.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Math } from "src/utils/Math.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Extension } from "src/modules/price-router/Extensions/Extension.sol";
import { Registry } from "src/Registry.sol";

import { UniswapV3Pool } from "src/interfaces/external/UniswapV3Pool.sol";
import { OracleLibrary } from "@uniswapV3P/libraries/OracleLibrary.sol";

/**
 * @title Swaap Price Router
 * @notice Provides a universal interface allowing Swaap contracts to retrieve secure pricing
 *         data from Chainlink.
 * @author crispymangoes
 */
contract PriceRouter is Ownable {
    using SafeTransferLib for ERC20;
    using SafeCast for int256;
    using Math for uint256;
    using Address for address;

    event AddAsset(address indexed asset);

    event IntentToEditAsset(
        address indexed asset,
        AssetSettings _settings,
        bytes _storage,
        bytes32 editHash,
        uint256 assetEditableAt
    );

    event EditAssetCancelled(address indexed asset, bytes32 editHash);

    event EditAssetComplete(address indexed asset, bytes32 editHash);

    Registry public immutable registry;
    ERC20 public immutable WETH;

    constructor(address newOwner, Registry _registry, ERC20 _weth) {
        registry = _registry;
        WETH = _weth;
        transferOwnership(newOwner);
    }

    // =========================================== ASSETS CONFIG ===========================================
    /**
     * @notice Bare minimum settings all derivatives support.
     * @param derivative the derivative used to price the asset
     * @param source the address used to price the asset
     */
    struct AssetSettings {
        uint8 derivative;
        address source;
    }

    /**
     * @notice Mapping between an asset to price and its `AssetSettings`.
     */
    mapping(ERC20 => AssetSettings) public getAssetSettings;

    // ======================================= OWNERSHIP TRANSISITION =======================================

    /**
     * @notice Emitted when an ownership transition is started.
     */
    event OwnerTransitionStarted(address indexed pendingOwner, uint256 startTime);

    /**
     * @notice Emitted when an ownership transition is cancelled.
     */
    event OwnerTransitionCancelled(address indexed pendingOwner);

    /**
     * @notice Emitted when an ownership transition is completed.
     */
    event OwnerTransitionComplete(address indexed newOwner);

    /**
     * @notice Attempted to call a function intended for Zero Id address.
     */
    error PriceRouter__OnlyCallableByZeroId();

    /**
     * @notice Attempted to transition owner to the zero address.
     */
    error PriceRouter__NewOwnerCanNotBeZero();

    /**
     * @notice Attempted to perform a restricted action while ownership transition is pending.
     */
    error PriceRouter__TransitionPending();

    /**
     * @notice Attempted to cancel or complete a transition when one is not active.
     */
    error PriceRouter__TransitionNotPending();

    /**
     * @notice Attempted to call `completeTransition` from an address that is not the pending owner.
     */
    error PriceRouter__OnlyCallableByPendingOwner();

    /**
     * @notice The amount of time it takes for an ownership transition to work.
     */
    uint256 public constant TRANSITION_PERIOD = 7 days;

    /**
     * @notice The Pending Owner, that becomes the owner after the transition period, and they call `completeTransition`.
     */
    address public pendingOwner;

    /**
     * @notice The starting time stamp of the transition.
     */
    uint256 public transitionStart;

    /**
     * @notice Allows Zero Id address to set a new owner, after the transition period is up.
     */
    function transitionOwner(address newOwner) external {
        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();
        if (pendingOwner != address(0)) revert PriceRouter__TransitionPending();
        if (newOwner == address(0)) revert PriceRouter__NewOwnerCanNotBeZero();

        emit OwnerTransitionStarted(newOwner, transitionStart);

        pendingOwner = newOwner;
        transitionStart = block.timestamp;
    }

    /**
     * @notice Allows Zero Id address to cancel an ongoing owner transition.
     */
    function cancelTransition() external {
        address _pendingOwner = pendingOwner;

        if (msg.sender != registry.getAddress(0)) revert PriceRouter__OnlyCallableByZeroId();
        if (_pendingOwner == address(0)) revert PriceRouter__TransitionNotPending();

        emit OwnerTransitionCancelled(_pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Allows pending owner to complete the ownership transition.
     */
    function completeTransition() external {
        address _pendingOwner = pendingOwner;

        if (msg.sender != _pendingOwner) revert PriceRouter__OnlyCallableByPendingOwner();
        if (block.timestamp < transitionStart + TRANSITION_PERIOD) revert PriceRouter__TransitionPending();

        _transferOwnership(_pendingOwner);

        emit OwnerTransitionComplete(_pendingOwner);

        pendingOwner = address(0);
        transitionStart = 0;
    }

    /**
     * @notice Extends OZ Ownable `_checkOwner` function to block owner calls, if there is an ongoing transition.
     */
    function _checkOwner() internal view override {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        if (transitionStart != 0) revert PriceRouter__TransitionPending();
    }

    // ======================================= ASSET OPERATIONS =======================================

    /**
     * @notice Attempted to set a minimum price below the Chainlink minimum price (with buffer).
     * @param minPrice minimum price attempted to set
     * @param bufferedMinPrice minimum price that can be set including buffer
     */
    error PriceRouter__InvalidMinPrice(uint256 minPrice, uint256 bufferedMinPrice);

    /**
     * @notice Attempted to set a maximum price above the Chainlink maximum price (with buffer).
     * @param maxPrice maximum price attempted to set
     * @param bufferedMaxPrice maximum price that can be set including buffer
     */
    error PriceRouter__InvalidMaxPrice(uint256 maxPrice, uint256 bufferedMaxPrice);

    /**
     * @notice Attempted to add an invalid asset.
     * @param asset address of the invalid asset
     */
    error PriceRouter__InvalidAsset(address asset);

    /**
     * @notice Attempted to add an asset that is already supported.
     */
    error PriceRouter__AssetAlreadyAdded(address asset);

    /**
     * @notice Attempted to edit an asset that is not supported.
     */
    error PriceRouter__AssetNotAdded(address asset);

    /**
     * @notice Attempted to edit an asset that is not editable.
     */
    error PriceRouter__AssetNotEditable(address asset);

    /**
     * @notice Attempted to edit an asset that is pending edit.
     */
    error PriceRouter__AssetPendingEdit(address asset);

    /**
     * @notice Attempted to cancel the editing of an asset that is not pending edit.
     */
    error PriceRouter__AssetNotPendingEdit(address asset);

    /**
     * @notice Attempted to add an asset, but actual answer was outside range of expectedAnswer.
     */
    error PriceRouter__BadAnswer(uint256 answer, uint256 expectedAnswer);

    /**
     * @notice Attempted to perform an operation using an unknown derivative.
     */
    error PriceRouter__UnknownDerivative(uint8 unknownDerivative);

    /**
     * @notice Attempted to add an asset with invalid min/max prices.
     * @param min price
     * @param max price
     */
    error PriceRouter__MinPriceGreaterThanMaxPrice(uint256 min, uint256 max);

    /// @dev The price buffer for Chainlink aggregator minimum price.
    uint256 internal constant _CHAINLINK_MIN_PRICE_BUFFER = 1.1e18; // 10%

    /// @dev The price buffer for Chainlink aggregator maximum price.
    uint256 internal constant _CHAINLINK_MAX_PRICE_BUFFER = 0.9e18; // 10%

    /**
     * @notice The allowed deviation between the expected answer vs the actual answer.
     */
    uint256 public constant EXPECTED_ANSWER_DEVIATION = 0.02e18;

    /**
     * @notice The amount of time that must pass between owner calling `startEditAsset`, and `completeEditAsset`.
     */
    uint64 public constant EDIT_ASSET_DELAY = 7 days;

    /**
     * @notice Stores the info that an asset can be editted to.
     */
    mapping(ERC20 => bytes32) public assetEditableHash;

    /**
     * @notice Allows caller to call multiple functions in a single TX.
     * @dev Does NOT return the function return values.
     */
    function multicall(bytes[] calldata data) external {
        for (uint256 i; i < data.length; ++i) address(this).functionDelegateCall(data[i]);
    }

    /**
     * @notice Allows owner to add assets to the price router.
     * @dev Performs a sanity check by comparing the price router computed price to
     * a user input `_expectedAnswer`.
     * @param _asset the asset to add to the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     * @param _expectedAnswer the expected answer for the asset from  `_getPriceInUSD`
     */
    function addAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 _expectedAnswer
    ) external onlyOwner {
        // Check that asset is not already added.
        if (getAssetSettings[_asset].derivative > 0) revert PriceRouter__AssetAlreadyAdded(address(_asset));

        _updateAsset(_asset, _settings, _storage, _expectedAnswer);

        emit AddAsset(address(_asset));
    }

    /**
     * @notice Allows owner to start the edit asset process.
     * @dev Saves a hash of the inputs, and maps it to the timestamp when `_asset` is editable.
     * @param _asset the asset to edit in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     */
    function startEditAsset(ERC20 _asset, AssetSettings memory _settings, bytes memory _storage) external onlyOwner {
        // Make sure the asset does not have a pending edit.
        if (assetEditableHash[_asset] != bytes32(0)) revert PriceRouter__AssetPendingEdit(address(_asset));

        // Make sure the asset has been added.
        if (getAssetSettings[_asset].derivative == 0) revert PriceRouter__AssetNotAdded(address(_asset));

        uint256 assetEditableAt = block.timestamp + EDIT_ASSET_DELAY;
        bytes32 editHash = keccak256(abi.encode(_asset, _settings, _storage, assetEditableAt));

        assetEditableHash[_asset] = editHash;

        emit IntentToEditAsset(address(_asset), _settings, _storage, editHash, assetEditableAt);
    }

    /**
     * @notice Once `EDIT_ASSET_DELAY` has passed, `_asset` is now editable using the
     *         same inputs given to `startEditAsset`.
     * @param _asset the asset to finish editing in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     * @param assetEditableAt the timestamp after which `_asset` is editable
     * @param _expectedAnswer the expected answer for the asset from  `_getPriceInUSD`
     */
    function completeEditAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 assetEditableAt,
        uint256 _expectedAnswer
    ) external onlyOwner {
        bytes32 expectedEditHash = keccak256(abi.encode(_asset, _settings, _storage, assetEditableAt));

        // Make sure asset can be edited.
        bytes32 editHash = assetEditableHash[_asset];
        if (editHash == bytes32(0) || editHash != expectedEditHash || block.timestamp < assetEditableAt)
            revert PriceRouter__AssetNotEditable(address(_asset));

        // Reset asset editable inputs.
        delete assetEditableHash[_asset];

        // Edit the asset.
        _updateAsset(_asset, _settings, _storage, _expectedAnswer);

        emit EditAssetComplete(address(_asset), editHash);
    }

    /**
     * @notice Cancel a pending edit for `_asset`.
     * @param _asset the asset to cancel editing of in the pricing router
     */
    function cancelEditAsset(ERC20 _asset) external onlyOwner {
        bytes32 editHash = assetEditableHash[_asset];

        // make sure the asset was pending to edit.
        if (editHash == bytes32(0)) revert PriceRouter__AssetNotPendingEdit(address(_asset));

        delete assetEditableHash[_asset];

        emit EditAssetCancelled(address(_asset), editHash);
    }

    /**
     * @notice Helper function to update an `_asset`s configuration.
     * @param _asset the asset to update in the pricing router
     * @param _settings the settings for `_asset`
     *        @dev The `derivative` value in settings MUST be non zero.
     * @param _storage arbitrary bytes data used to configure `_asset` pricing
     * @param _expectedAnswer the expected answer for the asset from  `_getPriceInUSD`
     */
    function _updateAsset(
        ERC20 _asset,
        AssetSettings memory _settings,
        bytes memory _storage,
        uint256 _expectedAnswer
    ) internal {
        if (address(_asset) == address(0)) revert PriceRouter__InvalidAsset(address(_asset));

        // Zero is an invalid derivative.
        if (_settings.derivative == 0) revert PriceRouter__UnknownDerivative(_settings.derivative);

        // Call setup function for appropriate derivative.
        if (_settings.derivative == 1) {
            _setupPriceForChainlinkDerivative(_asset, _settings.source, _storage);
        } else if (_settings.derivative == 2) {
            _setupPriceForTwapDerivative(_asset, _settings.source, _storage);
        } else if (_settings.derivative == 3) {
            Extension(_settings.source).setupSource(_asset, _storage);
        } else revert PriceRouter__UnknownDerivative(_settings.derivative);

        // Check `_getPriceInUSD` against `_expectedAnswer`.
        uint256 minAnswer = _expectedAnswer.mulWadDown((Math.WAD - EXPECTED_ANSWER_DEVIATION));
        uint256 maxAnswer = _expectedAnswer.mulWadDown((Math.WAD + EXPECTED_ANSWER_DEVIATION));

        getAssetSettings[_asset] = _settings;
        uint256 answer = _getPriceInUSD(_asset, _settings);
        if (answer < minAnswer || answer > maxAnswer) revert PriceRouter__BadAnswer(answer, _expectedAnswer);
    }

    /**
     * @notice return bool indicating whether or not an asset has been set up.
     * @dev Since `addAsset` enforces the derivative is non zero, checking if the stored setting
     *      is nonzero is sufficient to see if the asset is set up.
     */
    function isSupported(ERC20 asset) external view returns (bool) {
        return getAssetSettings[asset].derivative > 0;
    }

    // ======================================= PRICING OPERATIONS =======================================

    /**
     * @notice Get `asset` price in USD.
     * @dev Returns price in USD with 8 decimals.
     */
    function getPriceInUSD(ERC20 asset) external view returns (uint256) {
        AssetSettings memory assetSettings = getAssetSettings[asset];
        return _getPriceInUSD(asset, assetSettings);
    }

    /**
     * @notice Get multiple `asset` prices in USD.
     * @dev Returns array of prices in USD with 8 decimals.
     */
    function getPricesInUSD(ERC20[] calldata assets) external view returns (uint256[] memory prices) {
        prices = new uint256[](assets.length);
        for (uint256 i; i < assets.length; ++i) {
            AssetSettings memory assetSettings = getAssetSettings[assets[i]];
            prices[i] = _getPriceInUSD(assets[i], assetSettings);
        }
    }

    /**
     * @notice Get the value of an asset in terms of another asset.
     * @param baseAsset address of the asset to get the price of in terms of the quote asset
     * @param amount amount of the base asset to price
     * @param quoteAsset address of the asset that the base asset is priced in terms of
     * @return value value of the amount of base assets specified in terms of the quote asset
     */
    function getValue(ERC20 baseAsset, uint256 amount, ERC20 quoteAsset) external view returns (uint256 value) {
        AssetSettings memory baseSettings = getAssetSettings[baseAsset];
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
        uint256 priceBaseUSD = _getPriceInUSD(baseAsset, baseSettings);
        uint256 priceQuoteUSD = _getPriceInUSD(quoteAsset, quoteSettings);
        value = _getValueInQuote(priceBaseUSD, priceQuoteUSD, baseAsset.decimals(), quoteAsset.decimals(), amount);
    }

    /**
     * @notice Helper function that compares `_getValues` between input 0 and input 1.
     */
    function getValuesDelta(
        ERC20[] calldata baseAssets0,
        uint256[] calldata amounts0,
        ERC20[] calldata baseAssets1,
        uint256[] calldata amounts1,
        ERC20 quoteAsset
    ) external view returns (uint256) {
        uint256 value0 = _getValues(baseAssets0, amounts0, quoteAsset);
        uint256 value1 = _getValues(baseAssets1, amounts1, quoteAsset);
        return value0 - value1;
    }

    /**
     * @notice Helper function that determines the value of assets using `_getValues`.
     */
    function getValues(
        ERC20[] calldata baseAssets,
        uint256[] calldata amounts,
        ERC20 quoteAsset
    ) external view returns (uint256) {
        return _getValues(baseAssets, amounts, quoteAsset);
    }

    /**
     * @notice Get the exchange rate between two assets.
     * @param baseAsset address of the asset to get the exchange rate of in terms of the quote asset
     * @param quoteAsset address of the asset that the base asset is exchanged for
     * @return exchangeRate rate of exchange between the base asset and the quote asset
     */
    function getExchangeRate(ERC20 baseAsset, ERC20 quoteAsset) public view returns (uint256 exchangeRate) {
        AssetSettings memory baseSettings = getAssetSettings[baseAsset];
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];

        exchangeRate = _getExchangeRate(baseAsset, baseSettings, quoteAsset, quoteSettings, quoteAsset.decimals());
    }

    /**
     * @notice Get the exchange rates between multiple assets and another asset.
     * @param baseAssets addresses of the assets to get the exchange rates of in terms of the quote asset
     * @param quoteAsset address of the asset that the base assets are exchanged for
     * @return exchangeRates rate of exchange between the base assets and the quote asset
     */
    function getExchangeRates(
        ERC20[] memory baseAssets,
        ERC20 quoteAsset
    ) external view returns (uint256[] memory exchangeRates) {
        uint8 quoteAssetDecimals = quoteAsset.decimals();
        AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];

        uint256 numOfAssets = baseAssets.length;
        exchangeRates = new uint256[](numOfAssets);
        for (uint256 i; i < numOfAssets; ++i) {
            AssetSettings memory baseSettings = getAssetSettings[baseAssets[i]];
            exchangeRates[i] = _getExchangeRate(
                baseAssets[i],
                baseSettings,
                quoteAsset,
                quoteSettings,
                quoteAssetDecimals
            );
        }
    }

    // =========================================== HELPER FUNCTIONS ===========================================

    /**
     * @notice Attempted to update the asset to one that is not supported by the platform.
     * @param asset address of the unsupported asset
     */
    error PriceRouter__UnsupportedAsset(address asset);

    /**
     * @notice Gets the exchange rate between a base and a quote asset
     * @param baseAsset the asset to convert into quoteAsset
     * @param quoteAsset the asset base asset is converted into
     * @return exchangeRate value of base asset in terms of quote asset
     */
    function _getExchangeRate(
        ERC20 baseAsset,
        AssetSettings memory baseSettings,
        ERC20 quoteAsset,
        AssetSettings memory quoteSettings,
        uint8 quoteAssetDecimals
    ) internal view returns (uint256) {
        uint256 basePrice = _getPriceInUSD(baseAsset, baseSettings);
        uint256 quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);
        uint256 exchangeRate = basePrice.mulDivDown(10 ** quoteAssetDecimals, quotePrice);
        return exchangeRate;
    }

    /**
     * @notice Helper function to get an assets price in USD.
     * @dev Returns price in USD with 8 decimals.
     */
    function _getPriceInUSD(ERC20 asset, AssetSettings memory settings) internal view returns (uint256) {
        _runPreFlightCheck();
        // Call get price function using appropriate derivative.
        uint256 price;
        if (settings.derivative == 1) {
            price = _getPriceForChainlinkDerivative(asset, settings.source);
        } else if (settings.derivative == 2) {
            price = _getPriceForTwapDerivative(asset, settings.source);
        } else if (settings.derivative == 3) {
            price = Extension(settings.source).getPriceInUSD(asset);
        } else if (settings.derivative == 0) {
            revert PriceRouter__UnsupportedAsset(address(asset));
        } else revert PriceRouter__UnknownDerivative(settings.derivative);

        return price;
    }

    /**
     * @notice If any safety checks needs to be run before pricing operations, they should be added here.
     */
    function _runPreFlightCheck() internal view virtual {}

    /**
     * @notice math function that preserves precision by multiplying the amountBase before dividing.
     * @param priceBaseUSD the base asset price in USD
     * @param priceQuoteUSD the quote asset price in USD
     * @param baseDecimals the base asset decimals
     * @param quoteDecimals the quote asset decimals
     * @param amountBase the amount of base asset
     */
    function _getValueInQuote(
        uint256 priceBaseUSD,
        uint256 priceQuoteUSD,
        uint8 baseDecimals,
        uint8 quoteDecimals,
        uint256 amountBase
    ) internal pure returns (uint256 valueInQuote) {
        // Get value in quote asset, but maintain as much precision as possible.
        // Cleaner equations below.
        // baseToUSD = amountBase * priceBaseUSD / 10**baseDecimals.
        // valueInQuote = baseToUSD * 10**quoteDecimals / priceQuoteUSD
        valueInQuote = amountBase.mulDivDown(
            (priceBaseUSD * 10 ** quoteDecimals),
            (10 ** baseDecimals * priceQuoteUSD)
        );
    }

    /**
     * @notice Attempted an operation with arrays of unequal lengths that were expected to be equal length.
     */
    error PriceRouter__LengthMismatch();

    /**
     * @notice Get the total value of multiple assets in terms of another asset.
     * @param baseAssets addresses of the assets to get the price of in terms of the quote asset
     * @param amounts amounts of each base asset to price
     * @param quoteAsset address of the assets that the base asset is priced in terms of
     * @return value total value of the amounts of each base assets specified in terms of the quote asset
     */
    function _getValues(
        ERC20[] calldata baseAssets,
        uint256[] calldata amounts,
        ERC20 quoteAsset
    ) internal view returns (uint256) {
        if (baseAssets.length != amounts.length) revert PriceRouter__LengthMismatch();
        uint256 quotePrice;
        {
            AssetSettings memory quoteSettings = getAssetSettings[quoteAsset];
            quotePrice = _getPriceInUSD(quoteAsset, quoteSettings);
        }
        uint256 valueInQuote;
        uint8 quoteDecimals = quoteAsset.decimals();

        for (uint256 i; i < baseAssets.length; ++i) {
            // Skip zero amount values.
            if (amounts[i] == 0) continue;
            ERC20 baseAsset = baseAssets[i];
            if (baseAsset == quoteAsset) valueInQuote += amounts[i];
            else {
                uint256 basePrice;
                {
                    AssetSettings memory baseSettings = getAssetSettings[baseAsset];
                    basePrice = _getPriceInUSD(baseAsset, baseSettings);
                }
                valueInQuote += _getValueInQuote(
                    basePrice,
                    quotePrice,
                    baseAsset.decimals(),
                    quoteDecimals,
                    amounts[i]
                );
            }
        }
        return valueInQuote;
    }

    // =========================================== CHAINLINK PRICE DERIVATIVE ===========================================\
    /**
     * @notice Stores data for Chainlink derivative assets.
     * @param max the max valid price of the asset
     * @param min the min valid price of the asset
     * @param heartbeat the max amount of time between price updates
     * @param inETH bool indicating whether the price feed is
     *        denominated in ETH(true) or USD(false)
     */
    struct ChainlinkDerivativeStorage {
        uint144 max;
        uint80 min;
        uint24 heartbeat;
        bool inETH;
    }

    /**
     * @notice Buffered min price exceedes 80 bits of data.
     */
    error PriceRouter__BufferedMinOverflow();

    /**
     * @notice Aggregator price feed is not in the expected decimals. (8 when in USD or 18 when in ETH)
     */
    error PriceRouter__InvalidPriceDecimals();

    /**
     * @notice Returns Chainlink Derivative Storage
     */
    mapping(ERC20 => ChainlinkDerivativeStorage) public getChainlinkDerivativeStorage;

    /**
     * @notice If zero is specified for a Chainlink asset heartbeat, this value is used instead.
     */
    uint24 public constant DEFAULT_HEART_BEAT = 1 days;

    /**
     * @notice Setup function for pricing Chainlink derivative assets.
     * @dev _source The address of the Chainlink Data feed.
     * @dev _storage A ChainlinkDerivativeStorage value defining valid prices.
     */
    function _setupPriceForChainlinkDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {
        ChainlinkDerivativeStorage memory parameters = abi.decode(_storage, (ChainlinkDerivativeStorage));

        // Use Chainlink to get the min and max of the asset.
        IChainlinkAggregator aggregator = IChainlinkAggregator(IChainlinkAggregatorProxy(_source).aggregator());
        uint256 minFromChainklink = uint256(uint192(aggregator.minAnswer()));
        uint256 maxFromChainlink = uint256(uint192(aggregator.maxAnswer()));

        // Add a ~10% buffer to minimum and maximum price from Chainlink because Chainlink can stop updating
        // its price before/above the min/max price.
        uint256 bufferedMinPrice = (minFromChainklink * _CHAINLINK_MIN_PRICE_BUFFER) / Math.WAD;
        uint256 bufferedMaxPrice = (maxFromChainlink * _CHAINLINK_MAX_PRICE_BUFFER) / Math.WAD;

        if (parameters.min == 0) {
            // Revert if bufferedMinPrice overflows because uint80 is too small to hold the minimum price,
            // and lowering it to uint80 is not safe because the price feed can stop being updated before
            // it actually gets to that lower price.
            if (bufferedMinPrice > type(uint80).max) revert PriceRouter__BufferedMinOverflow();
            parameters.min = uint80(bufferedMinPrice);
        } else {
            if (parameters.min < bufferedMinPrice)
                revert PriceRouter__InvalidMinPrice(parameters.min, bufferedMinPrice);
        }

        if (parameters.max == 0) {
            //Do not revert even if bufferedMaxPrice is greater than uint144, because lowering it to uint144 max is more conservative.
            parameters.max = bufferedMaxPrice > type(uint144).max ? type(uint144).max : uint144(bufferedMaxPrice);
        } else {
            if (parameters.max > bufferedMaxPrice)
                revert PriceRouter__InvalidMaxPrice(parameters.max, bufferedMaxPrice);
        }

        if (parameters.min >= parameters.max)
            revert PriceRouter__MinPriceGreaterThanMaxPrice(parameters.min, parameters.max);

        if (parameters.inETH) {
            if (aggregator.decimals() != 18) revert PriceRouter__InvalidPriceDecimals();
        } else {
            if (aggregator.decimals() != 8) revert PriceRouter__InvalidPriceDecimals();
        }

        parameters.heartbeat = parameters.heartbeat != 0 ? parameters.heartbeat : DEFAULT_HEART_BEAT;

        getChainlinkDerivativeStorage[_asset] = parameters;
    }

    /**
     * @notice Get the price of a Chainlink derivative in terms of USD.
     */
    function _getPriceForChainlinkDerivative(ERC20 _asset, address _source) internal view returns (uint256) {
        ChainlinkDerivativeStorage memory parameters = getChainlinkDerivativeStorage[_asset];
        IChainlinkAggregator aggregator = IChainlinkAggregator(_source);
        (, int256 _price, , uint256 _timestamp, ) = aggregator.latestRoundData();
        uint256 price = _price.toUint256();
        _checkPriceFeed(address(_asset), price, _timestamp, parameters.max, parameters.min, parameters.heartbeat);
        // If price is in ETH, then convert price into USD.
        if (parameters.inETH) {
            uint256 _ethToUsd = _getPriceInUSD(WETH, getAssetSettings[WETH]);
            price = price.mulWadDown(_ethToUsd);
        }
        return price;
    }

    /**
     * @notice Attempted an operation to price an asset that under its minimum valid price.
     * @param asset address of the asset that is under its minimum valid price
     * @param price price of the asset
     * @param minPrice minimum valid price of the asset
     */
    error PriceRouter__AssetBelowMinPrice(address asset, uint256 price, uint256 minPrice);

    /**
     * @notice Attempted an operation to price an asset that under its maximum valid price.
     * @param asset address of the asset that is under its maximum valid price
     * @param price price of the asset
     * @param maxPrice maximum valid price of the asset
     */
    error PriceRouter__AssetAboveMaxPrice(address asset, uint256 price, uint256 maxPrice);

    /**
     * @notice Attempted to fetch a price for an asset that has not been updated in too long.
     * @param asset address of the asset thats price is stale
     * @param timeSinceLastUpdate seconds since the last price update
     * @param heartbeat maximum allowed time between price updates
     */
    error PriceRouter__StalePrice(address asset, uint256 timeSinceLastUpdate, uint256 heartbeat);

    /**
     * @notice helper function to validate a price feed is safe to use.
     * @param asset ERC20 asset price feed data is for.
     * @param value the price value the price feed gave.
     * @param timestamp the last timestamp the price feed was updated.
     * @param max the upper price bound
     * @param min the lower price bound
     * @param heartbeat the max amount of time between price updates
     */
    function _checkPriceFeed(
        address asset,
        uint256 value,
        uint256 timestamp,
        uint144 max,
        uint88 min,
        uint24 heartbeat
    ) internal view {
        if (value < min) revert PriceRouter__AssetBelowMinPrice(address(asset), value, min);

        if (value > max) revert PriceRouter__AssetAboveMaxPrice(address(asset), value, max);

        uint256 timeSinceLastUpdate = block.timestamp - timestamp;
        if (timeSinceLastUpdate > heartbeat)
            revert PriceRouter__StalePrice(address(asset), timeSinceLastUpdate, heartbeat);
    }

    // =========================================== TWAP PRICE DERIVATIVE ===========================================

    /**
     * @notice Stores data for Twap derivative assets.
     * @param secondsAgo the twap duration
     * @param baseDecimals the base assets decimals
     * @param quoteDecimals the quote assets decimals
     * @param quoteToken the asset the twap quotes in
     */
    struct TwapDerivativeStorage {
        uint32 secondsAgo;
        uint8 baseDecimals;
        uint8 quoteDecimals;
        ERC20 quoteToken;
    }

    /**
     * @notice Tried setting up a Twap for an asset where the underlying pools does not use the asset.
     */
    error PriceRouter__TwapAssetNotInPool();

    /**
     * @notice Provided secondsAgo does not meet minimum,
     */
    error PriceRouter__SecondsAgoDoesNotMeetMinimum();

    /**
     * @notice Returns Twap Derivative Storage
     */
    mapping(ERC20 => TwapDerivativeStorage) public getTwapDerivativeStorage;

    /**
     * @notice The smallest possible TWAP that can be used.
     */
    uint32 public constant MINIMUM_SECONDS_AGO = 900;

    /**
     * @notice Setup function for pricing Twap derivative assets.
     * @dev Make sure that TWAP assets have sufficient observations, and increase them if not before adding.
     * @dev _source The address of the Uniswap V3 pool.
     * @dev _storage A TwapDerivativeStorage value defining valid prices.
     */
    function _setupPriceForTwapDerivative(ERC20 _asset, address _source, bytes memory _storage) internal {
        TwapDerivativeStorage memory parameters = abi.decode(_storage, (TwapDerivativeStorage));

        // Verify seconds ago is reasonable.
        if (parameters.secondsAgo < MINIMUM_SECONDS_AGO) revert PriceRouter__SecondsAgoDoesNotMeetMinimum();

        UniswapV3Pool pool = UniswapV3Pool(_source);

        ERC20 token0 = ERC20(pool.token0());
        ERC20 token1 = ERC20(pool.token1());
        if (token0 == _asset) {
            parameters.baseDecimals = _asset.decimals();
            parameters.quoteDecimals = token1.decimals();
            parameters.quoteToken = token1;
        } else if (token1 == _asset) {
            parameters.baseDecimals = _asset.decimals();
            parameters.quoteDecimals = token0.decimals();
            parameters.quoteToken = token0;
        } else revert PriceRouter__TwapAssetNotInPool();

        getTwapDerivativeStorage[_asset] = parameters;
    }

    /**
     * @notice Get the price of a Twap derivative in terms of USD.
     */
    function _getPriceForTwapDerivative(ERC20 asset, address _source) internal view returns (uint256) {
        TwapDerivativeStorage memory parameters = getTwapDerivativeStorage[asset];
        (int24 arithmeticMeanTick, ) = OracleLibrary.consult(_source, parameters.secondsAgo);
        // Get the amount of quote token each base token is worth.
        uint256 quoteAmount = OracleLibrary.getQuoteAtTick(
            arithmeticMeanTick,
            uint128(10 ** parameters.baseDecimals),
            address(asset),
            address(parameters.quoteToken)
        );
        uint256 quotePrice = _getPriceInUSD(parameters.quoteToken, getAssetSettings[parameters.quoteToken]);
        return quoteAmount.mulDivDown(quotePrice, 10 ** parameters.quoteDecimals);
    }
}

File 11 of 44 : Uint32Array.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

/**
 * @notice A library to extend the uint32 array data type.
 */
library Uint32Array {
    // =========================================== ADDRESS STORAGE ===========================================

    /**
     * @notice Add an uint32 to the array at a given index.
     * @param array uint32 array to add the uint32 to
     * @param index index to add the uint32 at
     * @param value uint32 to add to the array
     */
    function add(uint32[] storage array, uint32 index, uint32 value) internal {
        uint256 len = array.length;

        if (len > 0) {
            array.push(array[len - 1]);

            for (uint256 i = len - 1; i > index; i--) array[i] = array[i - 1];

            array[index] = value;
        } else {
            array.push(value);
        }
    }

    /**
     * @notice Remove a uint32 from the array at a given index.
     * @param array uint32 array to remove the uint32 from
     * @param index index to remove the uint32 at
     */
    function remove(uint32[] storage array, uint32 index) internal {
        uint256 len = array.length;

        require(index < len, "Index out of bounds");

        for (uint256 i = index; i < len - 1; i++) array[i] = array[i + 1];

        array.pop();
    }

    /**
     * @notice Check whether an array contains an uint32.
     * @param array uint32 array to check
     * @param value uint32 to check for
     */
    function contains(uint32[] storage array, uint32 value) internal view returns (bool) {
        for (uint256 i; i < array.length; i++) if (value == array[i]) return true;

        return false;
    }
}

File 12 of 44 : BaseAdaptor.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Math } from "src/utils/Math.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { Registry } from "src/Registry.sol";
import { Fund } from "src/base/Fund.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";

/**
 * @title Base Adaptor
 * @notice Base contract all adaptors must inherit from.
 * @dev Allows Funds to interact with arbritrary DeFi assets and protocols.
 * @author crispymangoes
 */
abstract contract BaseAdaptor {
    using SafeTransferLib for ERC20;
    using Math for uint256;

    /**
     * @notice Attempted to specify an external receiver during a Fund `callOnAdaptor` call.
     */
    error BaseAdaptor__ExternalReceiverBlocked();

    /**
     * @notice Attempted to deposit to a position where user deposits were not allowed.
     */
    error BaseAdaptor__UserDepositsNotAllowed();

    /**
     * @notice Attempted to withdraw from a position where user withdraws were not allowed.
     */
    error BaseAdaptor__UserWithdrawsNotAllowed();

    /**
     * @notice Attempted swap has bad slippage.
     */
    error BaseAdaptor__Slippage();

    /**
     * @notice Attempted swap used unsupported output asset.
     */
    error BaseAdaptor__PricingNotSupported(address asset);

    /**
     * @notice Attempted to set a constructor minimum health factor to a value
     *         below `MINIMUM_CONSTRUCTOR_HEALTH_FACTOR()`.
     */
    error BaseAdaptor__ConstructorHealthFactorTooLow();

    /**
     * @notice Attempted to interact with a position that is not used in the calling fund.
     */
    error BaseAdaptor__PositionNotUsed(bytes adaptorData);

    //============================================ Global Functions ===========================================
    /**
     * @dev Identifier unique to this adaptor for a shared registry.
     * Normally the identifier would just be the address of this contract, but this
     * Identifier is needed during Fund Delegate Call Operations, so getting the address
     * of the adaptor is more difficult.
     */
    function identifier() public pure virtual returns (bytes32) {
        return keccak256(abi.encode("Base Adaptor V 0.0"));
    }

    function SWAP_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {
        return 1;
    }

    function PRICE_ROUTER_REGISTRY_SLOT() internal pure returns (uint256) {
        return 2;
    }

    /**
     * @notice Max possible slippage when making a swap router swap.
     */
    function slippage() public pure virtual returns (uint32) {
        return 0.9e4;
    }

    /**
     * @notice The default minimum constructor health factor.
     * @dev Adaptors can choose to override this if they need a different value.
     */
    function MINIMUM_CONSTRUCTOR_HEALTH_FACTOR() internal pure virtual returns (uint256) {
        return 1.02e18;
    }

    //============================================ Implement Base Functions ===========================================
    //==================== Base Function Specification ====================
    // Base functions are functions designed to help the Fund interact with
    // an adaptor position, strategists are not intended to use these functions.
    // Base functions MUST be implemented in adaptor contracts, even if that is just
    // adding a revert statement to make them uncallable by normal user operations.
    //
    // All view Base functions will be called used normal staticcall.
    // All mutative Base functions will be called using delegatecall.
    //=====================================================================
    /**
     * @notice Function Funds call to deposit users funds into holding position.
     * @param assets the amount of assets to deposit
     * @param adaptorData data needed to deposit into a position
     * @param configurationData data settable when strategists add positions to their Fund
     *                          Allows strategist to control how the adaptor interacts with the position
     */
    function deposit(uint256 assets, bytes memory adaptorData, bytes memory configurationData) public virtual;

    /**
     * @notice Function Funds call to withdraw funds from positions to send to users.
     * @param receiver the address that should receive withdrawn funds
     * @param adaptorData data needed to withdraw from a position
     * @param configurationData data settable when strategists add positions to their Fund
     *                          Allows strategist to control how the adaptor interacts with the position
     */
    function withdraw(
        uint256 assets,
        address receiver,
        bytes memory adaptorData,
        bytes memory configurationData
    ) public virtual;

    /**
     * @notice Function Funds use to determine `assetOf` balance of an adaptor position.
     * @param adaptorData data needed to interact with the position
     * @return balance of the position in terms of `assetOf`
     */
    function balanceOf(bytes memory adaptorData) public view virtual returns (uint256);

    /**
     * @notice Functions Funds use to determine the withdrawable balance from an adaptor position.
     * @dev Debt positions MUST return 0 for their `withdrawableFrom`
     * @notice accepts adaptorData and configurationData
     * @return withdrawable balance of the position in terms of `assetOf`
     */
    function withdrawableFrom(bytes memory, bytes memory) public view virtual returns (uint256);

    /**
     * @notice Function Funds use to determine the underlying ERC20 asset of a position.
     * @param adaptorData data needed to withdraw from a position
     * @return the underlying ERC20 asset of a position
     */
    function assetOf(bytes memory adaptorData) public view virtual returns (ERC20);

    /**
     * @notice When positions are added to the Registry, this function can be used in order to figure out
     *         what assets this adaptor needs to price, and confirm pricing is properly setup.
     */
    function assetsUsed(bytes memory adaptorData) public view virtual returns (ERC20[] memory assets) {
        assets = new ERC20[](1);
        assets[0] = assetOf(adaptorData);
    }

    /**
     * @notice Functions Registry/Funds use to determine if this adaptor reports debt values.
     * @dev returns true if this adaptor reports debt values.
     */
    function isDebt() public view virtual returns (bool);

    //============================================ Strategist Functions ===========================================
    //==================== Strategist Function Specification ====================
    // Strategist functions are only callable by strategists through the Funds
    // `callOnAdaptor` function. A fund will never call any of these functions,
    // when a normal user interacts with a fund(depositing/withdrawing)
    //
    // All strategist functions will be called using delegatecall.
    // Strategist functions are intentionally "blind" to what positions the fund
    // is currently holding. This allows strategists to enter temporary positions
    // while rebalancing.
    // To mitigate strategist from abusing this and moving funds in untracked
    // positions, the fund will enforce a Total Value Locked check that
    // insures TVL has not deviated too much from `callOnAdaptor`.
    //===========================================================================

    //============================================ Helper Functions ===========================================
    /**
     * @notice Helper function that allows adaptor calls to use the max available of an ERC20 asset
     * by passing in type(uint256).max
     * @param token the ERC20 asset to work with
     * @param amount when `type(uint256).max` is used, this function returns `token`s `balanceOf`
     * otherwise this function returns amount.
     */
    function _maxAvailable(ERC20 token, uint256 amount) internal view virtual returns (uint256) {
        if (amount == type(uint256).max) return token.balanceOf(address(this));
        else return amount;
    }

    /**
     * @notice Helper function that checks if `spender` has any more approval for `asset`, and if so revokes it.
     */
    function _revokeExternalApproval(ERC20 asset, address spender) internal {
        if (asset.allowance(address(this), spender) > 0) asset.safeApprove(spender, 0);
    }

    /**
     * @notice Helper function that validates external receivers are allowed.
     */
    function _externalReceiverCheck(address receiver) internal view {
        if (receiver != address(this) && Fund(address(this)).blockExternalReceiver())
            revert BaseAdaptor__ExternalReceiverBlocked();
    }

    /**
     * @notice Verifies if the configured minimum health factor is in the allowed range.
     * @param minimumHealthFactor the configured minimum health factor to verify.
     */
    function _verifyConstructorMinimumHealthFactor(uint256 minimumHealthFactor) internal pure {
        if (minimumHealthFactor < MINIMUM_CONSTRUCTOR_HEALTH_FACTOR())
            revert BaseAdaptor__ConstructorHealthFactorTooLow();
    }

    /**
     * @notice Allows strategists to zero out an approval for a given `asset`.
     * @param asset the ERC20 asset to revoke `spender`s approval for
     * @param spender the address to revoke approval for
     */
    function revokeApproval(ERC20 asset, address spender) public {
        asset.safeApprove(spender, 0);
    }

    /**
     * @notice Allows fund to validate if a position is used in the calling fund.
     * If the fund is deployed (code size > 0), this function will check if the position is used.
     * If not deployed, this function will not check if the position is being used as it is assumed that it is
     * being used by the initial deposit function in the constructor which already adds the position to the fund.
     */
    function _verifyUsedPositionIfDeployed(bytes memory adaptorData) internal view {
        uint256 fundCodeSize;
        address fundAddress = address(this);

        /// @solidity memory-safe-assembly
        assembly {
            fundCodeSize := extcodesize(fundAddress)
        }

        if (fundCodeSize > 0) {
            _verifyUsedPosition(adaptorData);
        }
    }

    /**
     * @notice Allows fund to validate if a position is used in the calling fund.
     */
    function _verifyUsedPosition(bytes memory adaptorData) internal view {
        // Check that erc4626Vault position is setup to be used in the calling fund.
        bytes32 positionHash = keccak256(abi.encode(identifier(), isDebt(), adaptorData));
        uint32 positionId = Fund(address(this)).registry().getPositionHashToPositionId(positionHash);
        if (!Fund(address(this)).isPositionUsed(positionId)) revert BaseAdaptor__PositionNotUsed(adaptorData);
    }
}

File 13 of 44 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

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

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

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

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

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

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

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

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

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

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

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

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

File 14 of 44 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 15 of 44 : Owned.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

    function transferOwnership(address newOwner) public virtual onlyOwner {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

File 16 of 44 : FeesManager.sol
// SPDX-License-Identifier: Apache-2.0

/*
                                      sβ–ˆβ–ˆβ–ˆ
                                    β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                              ,sβ–ˆβ–ˆβ–ˆ`
                           ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                          β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ^@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_ 7@β–ˆβ–ˆβ–ˆ_            "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆM
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ_     `_              "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                        ^^^^^^^^^^"                         ^"`
                         
                        β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆp   _β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                        @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆWT@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                         β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ  ,β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                         @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                          @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                           "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆb
                             @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                               %β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ`
                                 ^%β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
                                     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   @β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆW"`
                                     1β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                      "@β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ
                                         7W@β–ˆ
*/

pragma solidity 0.8.21;

import { ManagementFeesLib } from "src/modules/fees/ManagementFeesLib.sol";
import { PerformanceFeesLib } from "src/modules/fees/PerformanceFeesLib.sol";
import { Fund } from "src/base/Fund.sol";
import { Registry } from "src/Registry.sol";
import { Math } from "src/utils/Math.sol";
import { SafeTransferLib, ERC20 } from "@solmate/utils/SafeTransferLib.sol";

/**
 * @title Handles Fees collection and distribution for Funds
 */
contract FeesManager {
    using Math for uint256;
    using SafeTransferLib for ERC20;

    // =============================================== EVENTS ===============================================
    /**
     * @notice Emitted when strategist platform fee cut is changed.
     * @param fund the fund that had the strategist platform fee cut changed
     * @param newPlatformCut value strategist platform fee cut was changed to
     */
    event StrategistPlatformCutChanged(address indexed fund, uint64 newPlatformCut);

    /**
     * @notice Emitted when strategists payout address is changed.
     * @param fund the fund that had the strategist payout address changed
     * @param newPayoutAddress value strategists payout address was changed to
     */
    event StrategistPayoutAddressChanged(address indexed fund, address indexed newPayoutAddress);

    /**
     * @notice Emitted when protocol payout address is changed.
     * @param newPayoutAddress value protocol payout address was changed to
     */
    event ProtocolPayoutAddressChanged(address indexed newPayoutAddress);

    /**
     * @notice Emitted when a fund's fees are paid out.
     * @param fund the fund that had fees paid out
     * @param strategistPayoutAddress the address that the strategist's fees were paid to
     * @param protocolPayoutAddress the address that the protocol's fees were paid to
     * @param strategistPayout the amount of fees paid to the strategist
     * @param protocolPayout the amount of fees paid to the protocol
     */
    event Payout(
        address indexed fund,
        address indexed strategistPayoutAddress,
        uint256 strategistPayout,
        address indexed protocolPayoutAddress,
        uint256 protocolPayout
    );

    /**
     * @notice Emitted when management fees are claimed.
     * @param fund the fund that had management fees claimed
     * @param fees the amount of management fees claimed
     */
    event ManagementFeesClaimed(address indexed fund, uint256 fees);

    /**
     * @notice Emitted when management fees rate is updated.
     * @param fund the fund that had management fees rate updated
     * @param managementFeesPerYear the new management fees yearly fees (1e18 = 100% per year)
     * @param managementFeesRate the new management fees rate
     */
    event ManagementFeesRateUpdated(address indexed fund, uint256 managementFeesPerYear, uint256 managementFeesRate);

    /**
     * @notice Emitted when performance fees are claimed.
     * @param fund the fund that had performance fees claimed
     * @param fees the amount of performance fees claimed
     */
    event PerformanceFeesClaimed(address indexed fund, uint256 fees, uint256 highWaterMarkPrice);

    /**
     * @notice Emitted when performance fees rate is updated.
     * @param fund the fund that had performance fees rate updated
     * @param performanceFeesRate the new performance fees rate
     * @param highWaterMarkPrice the high-water mark price at the time of the update
     */
    event PerformanceFeesRateUpdated(address indexed fund, uint256 performanceFeesRate, uint256 highWaterMarkPrice);

    /**
     * @notice Emitted when enter fees are updated.
     * @param fund the fund that had enter fees updated
     * @param enterFeesRate the new enter fees rate
     */
    event EnterFeesUpdated(address indexed fund, uint16 enterFeesRate);

    /**
     * @notice Emitted when exit fees are updated.
     * @param fund the fund that had exit fees updated
     * @param exitFeesRate the new exit fees rate
     */
    event ExitFeesUpdated(address indexed fund, uint16 exitFeesRate);

    // =============================================== ERRORS ===============================================

    /// @notice Throws when the caller is not the fund owner.
    error FeesManager__OnlyFundOwner();

    /// @notice Throws when the caller is not the registry owner.
    error FeesManager__OnlyRegistryOwner();

    /// @notice Throws when the fee cut is above the authorized limit.
    error FeesManager__InvalidFeesCut();

    /// @notice Throws when the fees are above authorized limit.
    error FeesManager__InvalidFeesRate();

    /// @notice Throws when the protocol payout address is invalid.
    error FeesManager__InvalidProtocolPayoutAddress();

    /// @notice Throws when the high-water mark has not yet expired.
    error FeesManager__HighWaterMarkNotYetExpired();

    /// @notice Throws when the high-water mark price overflows. (unlikely scenario)
    error FeesManager__WaterMarkPriceOverflow();

    // =============================================== CONSTANTS ===============================================

    /// @notice Sets the max possible fee cut for funds.
    uint256 public constant MAX_FEE_CUT = 1e18;

    /// @notice Sets the max possible management fees for funds.
    uint256 public constant MAX_MANAGEMENT_FEES = 50e16; // 50%

    /// @notice Sets the max possible performance fees for funds.
    uint256 public constant MAX_PERFORMANCE_FEES = 50e16; // 50%

    // Enter and exit fees are expressed in basis points (1e4 = 100%)
    uint256 internal constant _BPS_ONE_HUNDRED_PER_CENT = 1e4;

    /// @notice Sets the max possible enter fees for funds.
    uint256 public constant MAX_ENTER_FEES = _BPS_ONE_HUNDRED_PER_CENT / 10; // 10%

    /// @notice Sets the max possible exit fees for funds.
    uint256 public constant MAX_EXIT_FEES = _BPS_ONE_HUNDRED_PER_CENT / 10; // 10%

    /// @notice Sets the high-water mark reset interval for funds.
    uint256 public constant HIGH_WATERMARK_RESET_INTERVAL = 3 * 30 days; // 3 months

    /// @notice Sets the high-water mark reset interval for funds.
    uint256 public constant HIGH_WATERMARK_RESET_ASSET_THRESHOLD = Math.WAD + Math.WAD / 2; // 50%

    // =============================================== MODIFIERS ===============================================

    modifier onlyFundOwner(address fund) {
        if (msg.sender != Fund(fund).owner()) {
            revert FeesManager__OnlyFundOwner();
        }
        _;
    }

    modifier onlyRegistryOwner() {
        if (msg.sender != registry.owner()) {
            revert FeesManager__OnlyRegistryOwner();
        }
        _;
    }

    // =============================================== STATE VARIABLES ===============================================

    /**
     * @notice Address of the platform's protocol payout address. Used to send protocol fees.
     */
    address public protocolPayoutAddress;

    /**
     * @notice Address of the platform's registry contract. Used to get the latest address of modules.
     */
    Registry public immutable registry;

    constructor(address _registry, address _protocolPayoutAddress) {
        registry = Registry(_registry);
        _setProtocolPayoutAddress(_protocolPayoutAddress);
    }

    struct FeesData {
        uint16 enterFeesRate; // in bps (max value = 10000)
        uint16 exitFeesRate; // in bps (max value = 10000)
        uint40 previousManagementFeesClaimTime; // last management fees claim time
        uint48 managementFeesRate; // in 18 decimals
        uint64 performanceFeesRate; // in 18 decimals (100% corresponds to 1e18)
        uint72 highWaterMarkPrice; // the high-water mark price
        uint40 highWaterMarkResetTime; // the owner can choose to reset the high-water mark (at most every HIGH_WATERMARK_RESET_INTERVAL)
        uint256 highWaterMarkResetAssets; // the owner can choose to reset the high-water mark (at most every HIGH_WATERMARK_RESET_ASSETS_TOLERANCE)
        uint64 strategistPlatformCut; // the platform cut for the strategist in 18 decimals
        address strategistPayoutAddress; // the address to send the strategist's fees to
    }

    mapping(address => FeesData) internal fundFeesData;

    function getFundFeesData(address fund) external view returns (FeesData memory) {
        return fundFeesData[fund];
    }

    /**
     * @notice Called by funds to compute the fees to apply before depositing assets (or minting shares).
     * @param totalAssets total assets in the fund
     * @param totalSupply total shares in the fund
     * @return enterOrExitFeesRate enter or exit fees rate
     * @return mintFeesAsShares minted shares to be used as fees
     */
    function previewApplyFeesBeforeJoinExit(
        uint256 totalAssets,
        uint256 totalSupply,
        bool isEntering
    ) external view returns (uint16, uint256) {
        (
            uint16 enterOrExitFeesRate,
            uint256 performanceFees,
            uint256 managementFees,
            ,

        ) = _previewApplyFeesBeforeJoinExit(totalAssets, totalSupply, isEntering);
        return (enterOrExitFeesRate, performanceFees + managementFees);
    }

    function _previewApplyFeesBeforeJoinExit(
        uint256 totalAssets,
        uint256 totalSupply,
        bool isEntering
    ) internal view returns (uint16, uint256, uint256, uint256, FeesData storage) {
        FeesData storage feeData = fundFeesData[msg.sender];

        (uint256 managementFees, uint256 performanceFees, uint256 highWaterMarkPrice) = _getUnclaimedFees(
            feeData,
            totalAssets,
            totalSupply
        );

        uint16 enterOrExitFeesRate = isEntering ? feeData.enterFeesRate : feeData.exitFeesRate;

        return (enterOrExitFeesRate, performanceFees, managementFees, highWaterMarkPrice, feeData);
    }

    /**
     * @notice Called by funds to compute the fees to apply before depositing assets (or minting shares).
     * @param totalAssets total assets in the fund
     * @param totalSupply total shares in the fund
     * @return enterOrExitFeesRate enter or exit fees rate
     * @return mintFeesAsShares minted shares to be used as fees
     */
    function applyFeesBeforeJoinExit(
        uint256 totalAssets,
        uint256 totalSupply,
        bool isEntering
    ) external returns (uint16, uint256) {
        (
            uint16 enterOrExitFeesRate,
            uint256 performanceFees,
            uint256 managementFees,
            uint256 highWaterMarkPrice,
            FeesData storage feeData
        ) = _previewApplyFeesBeforeJoinExit(totalAssets, totalSupply, isEntering);

        if (managementFees > 0) {
            feeData.previousManagementFeesClaimTime = uint40(block.timestamp);
            emit ManagementFeesClaimed(msg.sender, managementFees);
        }

        if (performanceFees > 0) {
            if (highWaterMarkPrice > type(uint72).max) revert FeesManager__WaterMarkPriceOverflow();

            feeData.highWaterMarkPrice = uint72(highWaterMarkPrice);
            emit PerformanceFeesClaimed(msg.sender, performanceFees, highWaterMarkPrice);
        }

        return (enterOrExitFeesRate, performanceFees + managementFees);
    }

    /**
     * @notice Get total supply after applying unclaimed fees.
     */
    function getTotalSupplyAfterFees(
        address fund,
        uint256 totalAssets,
        uint256 totalSupply
    ) external view returns (uint256) {
        FeesData storage feeData = fundFeesData[fund];

        (uint256 managementFees, uint256 performanceFees, ) = _getUnclaimedFees(feeData, totalAssets, totalSupply);

        return (totalSupply + managementFees + performanceFees);
    }

    function _getUnclaimedFees(
        FeesData storage feeData,
        uint256 totalAssets,
        uint256 totalSupply
    ) internal view returns (uint256, uint256, uint256) {
        // management fees
        uint256 managementFees = ManagementFeesLib._calcAccumulatedManagementFees(
            block.timestamp,
            feeData.previousManagementFeesClaimTime,
            feeData.managementFeesRate,
            totalSupply
        );

        // performance fees
        (uint256 performanceFees, uint256 highWaterMarkPrice) = PerformanceFeesLib._calcPerformanceFees(
            totalAssets,
            totalSupply + managementFees,
            feeData.highWaterMarkPrice,
            feeData.performanceFeesRate // performanceFees
        );

        return (managementFees, performanceFees, highWaterMarkPrice);
    }

    // =============================================== PAYOUT FUNCTIONS ===============================================

    /**
     * @notice Payout the fees to the protocol and the strategist (permissionless, anyone can call it)
     * @param fund the fund to payout the fees for
     */
    function payoutFees(address fund) public {
        Fund(fund).collectFees();
        uint256 totalFees = ERC20(fund).balanceOf(address(this));

        if (totalFees == 0) {
            return;
        }

        FeesData storage feeData = fundFeesData[fund];

        // if the strategist payout address is not set, the strategist doesn't get any fees
        address strategistPayoutAddress = feeData.strategistPayoutAddress;
        uint256 strategistPayout = strategistPayoutAddress == address(0)
            ? 0
            : (totalFees.mulDivUp(feeData.strategistPlatformCut, Math.WAD));

        strategistPayout = strategistPayout > totalFees ? totalFees : strategistPayout;

        // Send the strategist's cut
        if (strategistPayout > 0) {
            ERC20(fund).safeTransfer(strategistPayoutAddress, strategistPayout);
        }

        // Send the protocol's cut
        uint256 protocolPayout = totalFees - strategistPayout;
        if (protocolPayout > 0) {
            ERC20(fund).safeTransfer(protocolPayoutAddress, protocolPayout);
        }

        emit Payout(fund, strategistPayoutAddress, strategistPayout, protocolPayoutAddress, protocolPayout);
    }

    /**
     * @notice Sets the protocol payout address
     * @param newPayoutAddress the new protocol payout address
     */
    function setProtocolPayoutAddress(address newPayoutAddress) external onlyRegistryOwner {
        _setProtocolPayoutAddress(newPayoutAddress);
    }

    function _setProtocolPayoutAddress(address newPayoutAddress) internal {
        if (newPayoutAddress == address(0)) revert FeesManager__InvalidProtocolPayoutAddress();
        emit ProtocolPayoutAddressChanged(newPayoutAddress);
        protocolPayoutAddress = newPayoutAddress;
    }

    /**
     * @notice Sets the Strategists payout address
     * @param newPayoutAddress the new strategist payout address
     * @dev Callable by the Fund's owner.
     */
    function setStrategistPayoutAddress(address fund, address newPayoutAddress) external onlyFundOwner(fund) {
        FeesData storage feeData = fundFeesData[fund];

        // collect fees and payout the old strategist (if any) before changing the address
        payoutFees(fund);

        emit StrategistPayoutAddressChanged(fund, newPayoutAddress);
        // no need to check if the address is not valid, the owner can set it to any address
        feeData.strategistPayoutAddress = newPayoutAddress;
    }

    // =============================================== FEES CONFIG ===============================================

    /**
     * @notice Sets the Strategists cut of platform fees
     * @param cut the platform cut for the strategist
     * @dev Callable by Registry owner.
     */
    function setStrategistPlatformCut(address fund, uint64 cut) external onlyRegistryOwner {
        if (cut > MAX_FEE_CUT) revert FeesManager__InvalidFeesCut();

        payoutFees(fund);

        FeesData storage feeData = fundFeesData[fund];

        emit StrategistPlatformCutChanged(fund, cut);
        feeData.strategistPlatformCut = cut;
    }

    /**
     * @notice Sets the management fees per year for this fund.
     * @param fund the fund to set the management fees for
     * @param managementFeesPerYear the management fees per year (1e18 = 100% per year)
     */
    function setManagementFeesPerYear(address fund, uint256 managementFeesPerYear) external onlyFundOwner(fund) {
        if (managementFeesPerYear > MAX_MANAGEMENT_FEES) revert FeesManager__InvalidFeesRate();

        Fund(fund).collectFees(); // collectFees is nonReetrant, which makes setManagementFeesPerYear nonReetrant

        FeesData storage feeData = fundFeesData[fund];
        uint256 managementFeesRate = ManagementFeesLib._calcYearlyRate(managementFeesPerYear);
        feeData.managementFeesRate = uint48(managementFeesRate);

        // the management fees time is not guaranteed to be updated when collecting fees if the fees are 0
        // so we update it here to make sure it's always up to date when changing the rate
        feeData.previousManagementFeesClaimTime = uint40(block.timestamp);

        emit ManagementFeesRateUpdated(fund, managementFeesPerYear, managementFeesRate);
    }

    /**
     * @notice Sets the performance fees for this fund.
     * @param fund the fund to set the performance fees for
     * @param performanceFeesRate the performance fees (1e18 = 100%)
     */
    function setPerformanceFees(address fund, uint256 performanceFeesRate) external onlyFundOwner(fund) {
        if (performanceFeesRate > MAX_PERFORMANCE_FEES) revert FeesManager__InvalidFeesRate();

        FeesData storage feeData = fundFeesData[fund];

        // if the high-water mark is not set, set it and do not collect fees potential pending management fees
        // as the function is most likely called during the setup of the fund.
        if (feeData.highWaterMarkPrice == 0) {
            feeData.performanceFeesRate = uint64(performanceFeesRate);
            // initialize the high-water mark
            // note that the fund will revert if we are calling totalAssets() when it's locked (nonReentrantView)
            uint256 totalAssets = Fund(fund).totalAssets();
            uint256 highWaterMarkPrice = PerformanceFeesLib._calcSharePrice(totalAssets, Fund(fund).totalSupply());
            if (highWaterMarkPrice > type(uint72).max) revert FeesManager__WaterMarkPriceOverflow();

            fundFeesData[fund].highWaterMarkPrice = uint72(highWaterMarkPrice);
            fundFeesData[fund].highWaterMarkResetTime = uint40(block.timestamp);
            fundFeesData[fund].highWaterMarkResetAssets = uint256(totalAssets);

            emit PerformanceFeesRateUpdated(fund, performanceFeesRate, highWaterMarkPrice);
            return;
        }

        // collect fees before updating the rate
        Fund(fund).collectFees(); // collectFees is nonReetrant, which makes setPerformanceFees nonReetrant

        emit PerformanceFeesRateUpdated(fund, performanceFeesRate, feeData.highWaterMarkPrice);
        feeData.performanceFeesRate = uint64(performanceFeesRate);
    }

    /**
     * @notice Sets the enter fees for this fund.
     * @param fund the fund to set the performance fees for
     * @param enterFeesRate the enter fees (10000 = 100%)
     */
    function setEnterFees(address fund, uint16 enterFeesRate) external onlyFundOwner(fund) {
        if (enterFeesRate > MAX_ENTER_FEES) {
            revert FeesManager__InvalidFeesRate();
        }

        emit EnterFeesUpdated(fund, enterFeesRate);
        fundFeesData[fund].enterFeesRate = enterFeesRate;
    }

    /**
     * @notice Sets the exit fees for this fund.
     * @param fund the fund to set the performance fees for
     * @param exitFeesRate the exit fees (10000 = 100%)
     */
    function setExitFees(address fund, uint16 exitFeesRate) external onlyFundOwner(fund) {
        if (exitFeesRate > MAX_EXIT_FEES) {
            revert FeesManager__InvalidFeesRate();
        }

        emit ExitFeesUpdated(fund, exitFeesRate);
        fundFeesData[fund].exitFeesRate = exitFeesRate;
    }

    /**
     * @notice Resets the high-water mark for this fund.
     * @param fund the fund to reset the high-water mark state for
     */
    function resetHighWaterMark(address fund) external onlyRegistryOwner {
        Fund c = Fund(fund);
        c.collectFees();

        FeesData storage feeData = fundFeesData[fund];

        uint256 totalAssets = c.totalAssets();

        // checks high-water mark reset conditions
        if (
            (feeData.highWaterMarkPrice > 0) && // unset condition
            (block.timestamp < feeData.highWaterMarkResetTime + HIGH_WATERMARK_RESET_INTERVAL) && // time condition
            (totalAssets < (feeData.highWaterMarkResetAssets * HIGH_WATERMARK_RESET_ASSET_THRESHOLD) / Math.WAD) // assets condition
        ) {
            revert FeesManager__HighWaterMarkNotYetExpired();
        }

        // calculates the new high-water mark
        uint256 highWaterMarkPrice = PerformanceFeesLib._calcSharePrice(totalAssets, c.totalSupply());
        if (highWaterMarkPrice > type(uint72).max) revert FeesManager__WaterMarkPriceOverflow();

        // updates the high-water mark state
        feeData.highWaterMarkPrice = uint72(highWaterMarkPrice);
        feeData.highWaterMarkResetTime = uint40(block.timestamp);
        feeData.highWaterMarkResetAssets = uint256(totalAssets);
    }
}

File 17 of 44 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

File 18 of 44 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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 // Deprecated in v4.8
    }

    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");
        }
    }

    /**
     * @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) {
        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.
            /// @solidity memory-safe-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 {
            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 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 19 of 44 : ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

File 20 of 44 : IChainlinkAggregator.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";

interface IChainlinkAggregator is AggregatorV2V3Interface {
    function maxAnswer() external view returns (int192);

    function minAnswer() external view returns (int192);
}

File 21 of 44 : IChainlinkAggregatorProxy.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";

interface IChainlinkAggregatorProxy is AggregatorV2V3Interface {
    function aggregator() external view returns (address);
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 23 of 44 : Extension.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { Math } from "src/utils/Math.sol";

/**
 * @title Swaap Price Router Extension abstract contract.
 * @notice Provides shared logic between Extensions.
 * @author crispymangoes
 */
abstract contract Extension {
    /**
     * @notice Attempted to call a function only callable by the price router.
     */
    error Extension__OnlyPriceRouter();

    /**
     * @notice Prevents non price router contracts from calling a function.
     */
    modifier onlyPriceRouter() {
        if (msg.sender != address(priceRouter)) revert Extension__OnlyPriceRouter();
        _;
    }

    /**
     * @notice The Swaap PriceRouter contract.
     */
    PriceRouter public immutable priceRouter;

    constructor(PriceRouter _priceRouter) {
        priceRouter = _priceRouter;
    }

    /**
     * @notice Setup function is called when an asset is added/edited.
     */
    function setupSource(ERC20 asset, bytes memory sourceData) external virtual;

    /**
     * @notice Returns the price of an asset in USD.
     */
    function getPriceInUSD(ERC20 asset) external view virtual returns (uint256);
}

File 24 of 44 : UniswapV3Pool.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.10;

interface UniswapV3Pool {
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );
    event Initialize(uint160 sqrtPriceX96, int24 tick);
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);

    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    function factory() external view returns (address);

    function fee() external view returns (uint24);

    function feeGrowthGlobal0X128() external view returns (uint256);

    function feeGrowthGlobal1X128() external view returns (uint256);

    function flash(address recipient, uint256 amount0, uint256 amount1, bytes memory data) external;

    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;

    function initialize(uint160 sqrtPriceX96) external;

    function liquidity() external view returns (uint128);

    function maxLiquidityPerTick() external view returns (uint128);

    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes memory data
    ) external returns (uint256 amount0, uint256 amount1);

    function observations(
        uint256
    )
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );

    function observe(
        uint32[] memory secondsAgos
    ) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    function positions(
        bytes32
    )
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    function protocolFees() external view returns (uint128 token0, uint128 token1);

    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    function snapshotCumulativesInside(
        int24 tickLower,
        int24 tickUpper
    ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes memory data
    ) external returns (int256 amount0, int256 amount1);

    function tickBitmap(int16) external view returns (uint256);

    function tickSpacing() external view returns (int24);

    function ticks(
        int24
    )
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    function token0() external view returns (address);

    function token1() external view returns (address);
}

File 25 of 44 : OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
    /// @param pool Address of the pool that we want to observe
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, 'BP');

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool)
            .observe(secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -
            secondsPerLiquidityCumulativeX128s[0];

        arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;

        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
    /// @param pool Address of Uniswap V3 pool that we want to observe
    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
        require(observationCardinality > 0, 'NI');

        (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations(
            (observationIndex + 1) % observationCardinality
        );

        // The next index might not be initialized if the cardinality is in the process of increasing
        // In this case the oldest observation is always in index 0
        if (!initialized) {
            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
        }

        unchecked {
            secondsAgo = uint32(block.timestamp) - observationTimestamp;
        }
    }

    /// @notice Given a pool, it returns the tick value as of the start of the current block
    /// @param pool Address of Uniswap V3 pool
    /// @return The tick that the pool was in at the start of the current block
    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();

        // 2 observations are needed to reliably calculate the block starting tick
        require(observationCardinality > 1, 'NEO');

        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block
        // therefore the tick in `slot0` is the same as at the beginning of the current block.
        // We don't need to check if this observation is initialized - it is guaranteed to be.
        (
            uint32 observationTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,

        ) = IUniswapV3Pool(pool).observations(observationIndex);
        if (observationTimestamp != uint32(block.timestamp)) {
            return (tick, IUniswapV3Pool(pool).liquidity());
        }

        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
        (
            uint32 prevObservationTimestamp,
            int56 prevTickCumulative,
            uint160 prevSecondsPerLiquidityCumulativeX128,
            bool prevInitialized
        ) = IUniswapV3Pool(pool).observations(prevIndex);

        require(prevInitialized, 'ONI');

        uint32 delta = observationTimestamp - prevObservationTimestamp;
        tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta)));
        uint128 liquidity = uint128(
            (uint192(delta) * type(uint160).max) /
                (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
        );
        return (tick, liquidity);
    }

    /// @notice Information for calculating a weighted arithmetic mean tick
    struct WeightedTickData {
        int24 tick;
        uint128 weight;
    }

    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
    /// @param weightedTickData An array of ticks and weights
    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
        internal
        pure
        returns (int24 weightedArithmeticMeanTick)
    {
        // Accumulates the sum of products between each tick and its weight
        int256 numerator;

        // Accumulates the sum of the weights
        uint256 denominator;

        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
        for (uint256 i; i < weightedTickData.length; i++) {
            numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));
            denominator += weightedTickData[i].weight;
        }

        weightedArithmeticMeanTick = int24(numerator / int256(denominator));
        // Always round to negative infinity
        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
    }

    /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
    /// @dev Useful for calculating relative prices along routes.
    /// @dev There must be one tick for each pairwise set of tokens.
    /// @param tokens The token contract addresses
    /// @param ticks The ticks, representing the price of each token pair in `tokens`
    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
    function getChainedPrice(address[] memory tokens, int24[] memory ticks)
        internal
        pure
        returns (int256 syntheticTick)
    {
        require(tokens.length - 1 == ticks.length, 'DL');
        for (uint256 i = 1; i <= ticks.length; i++) {
            // check the tokens for address sort order, then accumulate the
            // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
        }
    }
}

File 26 of 44 : 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 27 of 44 : ManagementFeesLib.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import "src/utils/LogExpMathv08.sol";
import "src/utils/Math.sol";

library ManagementFeesLib {
    using Math for uint256;

    uint256 internal constant _ONE_YEAR = 365 days;

    error ManagementFees__ExponentInputInvalid();

    /**********************************************************************************************
    // f = yearly management fees percentage          /  ln(1 - f) \                             //
    // 1y = 1 year                             a = - | ------------ |                            //
    // a = yearly rate constant                       \     1y     /                             //
    **********************************************************************************************/
    function _calcYearlyRate(uint256 yearlyFees) internal pure returns (uint256) {
        uint256 logInput = Math.WAD - yearlyFees;
        // Since 0 < logInput <= 1 => logResult <= 0
        int256 logResult = LogExpMathv08.ln(int256(logInput));
        return (uint256(-logResult) / _ONE_YEAR);
    }

    /**********************************************************************************************
    // SF = shares to be minted as fees                                                          //
    // TS = total supply                                   SF = TS * (e^(a*dT) -1)               //
    // a = fees rate                                                                             //
    // dT = elapsed time between the previous and current claim                                  //
    **********************************************************************************************/
    function _calcAccumulatedManagementFees(
        uint256 currentTime,
        uint256 lastClaim,
        uint256 feesRate,
        uint256 currentSupply
    ) internal pure returns (uint256) {
        if (feesRate == 0) {
            return 0;
        }

        if (currentTime == lastClaim) {
            return 0;
        }

        uint256 elapsedTime = currentTime - lastClaim;

        uint256 expInput = feesRate * elapsedTime;

        if (expInput > uint256(type(int256).max)) {
            // it should never happen but just in case
            revert ManagementFees__ExponentInputInvalid();
        }

        uint256 expResult = uint256(LogExpMathv08.exp(int256(expInput)));
        return currentSupply.mulDivDown(expResult - Math.WAD, Math.WAD);
    }
}

File 28 of 44 : PerformanceFeesLib.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import { Math } from "src/utils/Math.sol";

library PerformanceFeesLib {
    using Math for uint256;

    function _calcSharePrice(uint256 totalAssets, uint256 totalSupply) internal pure returns (uint256) {
        return totalAssets.mulDivDown(Math.WAD, totalSupply);
    }

    /**
     * @param totalAssets The current total assets
     * @param totalSupply The total supply of shares
     * @param highWatermarkPrice The high-water mark share price (in 18 decimals)
     * @param performanceFeesRate The performance fees rate (in 18 decimals)
     * @return feesAsShares The shares that should be minted as fees
     * @return highWatermarkPrice The up-to-date high-water mark price
     */
    function _calcPerformanceFees(
        uint256 totalAssets,
        uint256 totalSupply,
        uint256 highWatermarkPrice,
        uint256 performanceFeesRate
    ) internal pure returns (uint256, uint256) {
        uint256 currentSharePrice = _calcSharePrice(totalAssets, totalSupply);

        if (highWatermarkPrice == 0) {
            // the first time the high-water mark is set
            return (0, currentSharePrice);
        }

        if (performanceFeesRate == 0) {
            return (0, currentSharePrice);
        }

        // Calculate the high-water mark total assets (in asset decimals)
        uint256 highWatermarkTotalAssets = totalSupply.mulDivDown(highWatermarkPrice, Math.WAD);

        if (totalAssets <= highWatermarkTotalAssets) {
            // no positive performance
            return (0, highWatermarkPrice);
        }

        // Calculate the increase in totalAssets (in asset decimals)
        uint256 assetsIncrease;
        unchecked {
            assetsIncrease = totalAssets - highWatermarkTotalAssets;
        }

        // NB: performanceFeesRate * assetsIncrease = feesAsShares / (totalSupply + feesAsShares) * totalAssets
        uint256 foo = performanceFeesRate * assetsIncrease;
        uint256 feesAsShares = foo.mulDivDown(totalSupply, totalAssets * Math.WAD - foo);

        // it can return feesAsShares = 0 if the price increase is too small
        return (feesAsShares, currentSharePrice);
    }
}

File 29 of 44 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

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

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

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

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

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

File 30 of 44 : AggregatorV2V3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";

interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}

File 31 of 44 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}

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

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

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

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

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

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

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

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

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

            uint256 r = ratio;
            uint256 msb = 0;

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

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

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

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

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

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

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

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

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

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

}

File 34 of 44 : LogExpMathv08.sol
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the β€œSoftware”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.

// THE SOFTWARE IS PROVIDED β€œAS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pragma solidity ^0.8.0;

/* solhint-disable */

/**
 * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
 *
 * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
 * exponentiation and logarithm (where the base is Euler's number).
 *
 * @dev This library was forked from the LogExpMath.sol by Balancer in enable its use with solidity ^0.8.0.
 * https://github.com/balancer/balancer-v2-monorepo/blob/master/pkg/solidity-utils/contracts/math/LogExpMath.sol
 */
library LogExpMathv08 {
    // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
    // two numbers, and multiply by ONE when dividing them.

    error X_OUT_OF_BOUNDS();
    error Y_OUT_OF_BOUNDS();
    error PRODUCT_OUT_OF_BOUNDS();
    error INVALID_EXPONENT();
    error OUT_OF_BOUNDS();

    // All arguments and return values are 18 decimal fixed point numbers.
    int256 constant ONE_18 = 1e18;

    // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
    // case of ln36, 36 decimals.
    int256 constant ONE_20 = 1e20;
    int256 constant ONE_36 = 1e36;

    // The domain of natural exponentiation is bound by the word size and number of decimals used.
    //
    // Because internally the result will be stored using 20 decimals, the largest possible result is
    // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
    // The smallest possible result is 10^(-18), which makes largest negative argument
    // ln(10^(-18)) = -41.446531673892822312.
    // We use 130.0 and -41.0 to have some safety margin.
    int256 constant MAX_NATURAL_EXPONENT = 130e18;
    int256 constant MIN_NATURAL_EXPONENT = -41e18;

    // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
    // 256 bit integer.
    int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
    int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;

    uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20);

    // 18 decimal constants
    int256 constant x0 = 128000000000000000000; // 2Λ†7
    int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
    int256 constant x1 = 64000000000000000000; // 2Λ†6
    int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)

    // 20 decimal constants
    int256 constant x2 = 3200000000000000000000; // 2Λ†5
    int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
    int256 constant x3 = 1600000000000000000000; // 2Λ†4
    int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
    int256 constant x4 = 800000000000000000000; // 2Λ†3
    int256 constant a4 = 298095798704172827474000; // eˆ(x4)
    int256 constant x5 = 400000000000000000000; // 2Λ†2
    int256 constant a5 = 5459815003314423907810; // eˆ(x5)
    int256 constant x6 = 200000000000000000000; // 2Λ†1
    int256 constant a6 = 738905609893065022723; // eˆ(x6)
    int256 constant x7 = 100000000000000000000; // 2Λ†0
    int256 constant a7 = 271828182845904523536; // eˆ(x7)
    int256 constant x8 = 50000000000000000000; // 2Λ†-1
    int256 constant a8 = 164872127070012814685; // eˆ(x8)
    int256 constant x9 = 25000000000000000000; // 2Λ†-2
    int256 constant a9 = 128402541668774148407; // eˆ(x9)
    int256 constant x10 = 12500000000000000000; // 2Λ†-3
    int256 constant a10 = 113314845306682631683; // eˆ(x10)
    int256 constant x11 = 6250000000000000000; // 2Λ†-4
    int256 constant a11 = 106449445891785942956; // eˆ(x11)

    /**
     * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
     *
     * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function pow(uint256 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            if (y == 0) {
                // We solve the 0^0 indetermination by making it equal one.
                return uint256(ONE_18);
            }

            if (x == 0) {
                return 0;
            }

            // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
            // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
            // x^y = exp(y * ln(x)).

            // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
            if (x >> 255 != 0) revert X_OUT_OF_BOUNDS();
            int256 x_int256 = int256(x);

            // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
            // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.

            // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
            if (y >= MILD_EXPONENT_BOUND) revert Y_OUT_OF_BOUNDS();
            int256 y_int256 = int256(y);

            int256 logx_times_y;
            if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
                int256 ln_36_x = _ln_36(x_int256);

                // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
                // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
                // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
                // (downscaled) last 18 decimals.
                logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
            } else {
                logx_times_y = _ln(x_int256) * y_int256;
            }
            logx_times_y /= ONE_18;

            // Finally, we compute exp(y * ln(x)) to arrive at x^y
            if (MIN_NATURAL_EXPONENT > logx_times_y || logx_times_y > MAX_NATURAL_EXPONENT)
                revert PRODUCT_OUT_OF_BOUNDS();

            return uint256(exp(logx_times_y));
        }
    }

    /**
     * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
     *
     * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function exp(int256 x) internal pure returns (int256) {
        unchecked {
            if (x < MIN_NATURAL_EXPONENT || x > MAX_NATURAL_EXPONENT) revert INVALID_EXPONENT();

            if (x < 0) {
                // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
                // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
                // Fixed point division requires multiplying by ONE_18.
                return ((ONE_18 * ONE_18) / exp(-x));
            }

            // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
            // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
            // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
            // decomposition.
            // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
            // decomposition, which will be lower than the smallest x_n.
            // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
            // We mutate x by subtracting x_n, making it the remainder of the decomposition.

            // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
            // intermediate overflows. Instead we store them as plain integers, with 0 decimals.
            // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
            // decomposition.

            // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
            // it and compute the accumulated product.

            int256 firstAN;
            if (x >= x0) {
                x -= x0;
                firstAN = a0;
            } else if (x >= x1) {
                x -= x1;
                firstAN = a1;
            } else {
                firstAN = 1; // One with no decimal places
            }

            // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
            // smaller terms.
            x *= 100;

            // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
            // one. Recall that fixed point multiplication requires dividing by ONE_20.
            int256 product = ONE_20;

            if (x >= x2) {
                x -= x2;
                product = (product * a2) / ONE_20;
            }
            if (x >= x3) {
                x -= x3;
                product = (product * a3) / ONE_20;
            }
            if (x >= x4) {
                x -= x4;
                product = (product * a4) / ONE_20;
            }
            if (x >= x5) {
                x -= x5;
                product = (product * a5) / ONE_20;
            }
            if (x >= x6) {
                x -= x6;
                product = (product * a6) / ONE_20;
            }
            if (x >= x7) {
                x -= x7;
                product = (product * a7) / ONE_20;
            }
            if (x >= x8) {
                x -= x8;
                product = (product * a8) / ONE_20;
            }
            if (x >= x9) {
                x -= x9;
                product = (product * a9) / ONE_20;
            }

            // x10 and x11 are unnecessary here since we have high enough precision already.

            // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
            // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).

            int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
            int256 term; // Each term in the sum, where the nth term is (x^n / n!).

            // The first term is simply x.
            term = x;
            seriesSum += term;

            // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
            // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.

            term = ((term * x) / ONE_20) / 2;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 3;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 4;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 5;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 6;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 7;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 8;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 9;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 10;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 11;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 12;
            seriesSum += term;

            // 12 Taylor terms are sufficient for 18 decimal precision.

            // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
            // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
            // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
            // and then drop two digits to return an 18 decimal value.

            return (((product * seriesSum) / ONE_20) * firstAN) / 100;
        }
    }

    /**
     * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
     */
    function log(int256 arg, int256 base) internal pure returns (int256) {
        unchecked {
            // This performs a simple base change: log(arg, base) = ln(arg) / ln(base).

            // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
            // upscaling.

            int256 logBase;
            if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
                logBase = _ln_36(base);
            } else {
                logBase = _ln(base) * ONE_18;
            }

            int256 logArg;
            if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
                logArg = _ln_36(arg);
            } else {
                logArg = _ln(arg) * ONE_18;
            }

            // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
            return (logArg * ONE_18) / logBase;
        }
    }

    /**
     * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function ln(int256 a) internal pure returns (int256) {
        unchecked {
            // The real natural logarithm is not defined for negative numbers or zero.
            if (a <= 0) revert OUT_OF_BOUNDS();
            if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
                return _ln_36(a) / ONE_18;
            } else {
                return _ln(a);
            }
        }
    }

    /**
     * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function _ln(int256 a) private pure returns (int256) {
        unchecked {
            if (a < ONE_18) {
                // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
                // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
                // Fixed point division requires multiplying by ONE_18.
                return (-_ln((ONE_18 * ONE_18) / a));
            }

            // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
            // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
            // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
            // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
            // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
            // decomposition, which will be lower than the smallest a_n.
            // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
            // We mutate a by subtracting a_n, making it the remainder of the decomposition.

            // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
            // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
            // ONE_18 to convert them to fixed point.
            // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
            // by it and compute the accumulated sum.

            int256 sum = 0;
            if (a >= a0 * ONE_18) {
                a /= a0; // Integer, not fixed point division
                sum += x0;
            }

            if (a >= a1 * ONE_18) {
                a /= a1; // Integer, not fixed point division
                sum += x1;
            }

            // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
            sum *= 100;
            a *= 100;

            // Because further a_n are  20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.

            if (a >= a2) {
                a = (a * ONE_20) / a2;
                sum += x2;
            }

            if (a >= a3) {
                a = (a * ONE_20) / a3;
                sum += x3;
            }

            if (a >= a4) {
                a = (a * ONE_20) / a4;
                sum += x4;
            }

            if (a >= a5) {
                a = (a * ONE_20) / a5;
                sum += x5;
            }

            if (a >= a6) {
                a = (a * ONE_20) / a6;
                sum += x6;
            }

            if (a >= a7) {
                a = (a * ONE_20) / a7;
                sum += x7;
            }

            if (a >= a8) {
                a = (a * ONE_20) / a8;
                sum += x8;
            }

            if (a >= a9) {
                a = (a * ONE_20) / a9;
                sum += x9;
            }

            if (a >= a10) {
                a = (a * ONE_20) / a10;
                sum += x10;
            }

            if (a >= a11) {
                a = (a * ONE_20) / a11;
                sum += x11;
            }

            // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
            // that converges rapidly for values of `a` close to one - the same one used in ln_36.
            // Let z = (a - 1) / (a + 1).
            // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

            // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
            // division by ONE_20.
            int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
            int256 z_squared = (z * z) / ONE_20;

            // num is the numerator of the series: the z^(2 * n + 1) term
            int256 num = z;

            // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
            int256 seriesSum = num;

            // In each step, the numerator is multiplied by z^2
            num = (num * z_squared) / ONE_20;
            seriesSum += num / 3;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 5;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 7;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 9;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 11;

            // 6 Taylor terms are sufficient for 36 decimal precision.

            // Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
            seriesSum *= 2;

            // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
            // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
            // value.

            return (sum + seriesSum) / 100;
        }
    }

    /**
     * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
     * for x close to one.
     *
     * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
     */
    function _ln_36(int256 x) private pure returns (int256) {
        unchecked {
            // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
            // worthwhile.

            // First, we transform x to a 36 digit fixed point value.
            x *= ONE_18;

            // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
            // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

            // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
            // division by ONE_36.
            int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
            int256 z_squared = (z * z) / ONE_36;

            // num is the numerator of the series: the z^(2 * n + 1) term
            int256 num = z;

            // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
            int256 seriesSum = num;

            // In each step, the numerator is multiplied by z^2
            num = (num * z_squared) / ONE_36;
            seriesSum += num / 3;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 5;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 7;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 9;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 11;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 13;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 15;

            // 8 Taylor terms are sufficient for 36 decimal precision.

            // All that remains is multiplying by 2 (non fixed point).
            return seriesSum * 2;
        }
    }
}

File 35 of 44 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 36 of 44 : AggregatorInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorInterface {
  function latestAnswer() external view returns (int256);

  function latestTimestamp() external view returns (uint256);

  function latestRound() external view returns (uint256);

  function getAnswer(uint256 roundId) external view returns (int256);

  function getTimestamp(uint256 roundId) external view returns (uint256);

  event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);

  event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}

File 37 of 44 : AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

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

  function version() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "remappings": [
    "@solmate/=lib/solmate/src/",
    "@forge-std/=lib/forge-std/src/",
    "@ds-test/=lib/forge-std/lib/ds-test/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@chainlink/=lib/chainlink/",
    "@uniswapV3P/=lib/v3-periphery/contracts/",
    "@uniswapV3C/=lib/v3-core/contracts/",
    "@balancer/=lib/balancer-v2-monorepo/pkg/",
    "@swaap-v2/=lib/swaap-v2-monorepo/pkg/",
    "script/=script/",
    "@balancer-labs/=lib/swaap-v2-monorepo/../../node_modules/@balancer-labs/",
    "@balancer-labs/v2-vault/=lib/swaap-v2-monorepo/./pkg/vault/",
    "balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
    "chainlink/=lib/chainlink/integration-tests/contracts/ethereum/src/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",
    "solmate/=lib/solmate/src/",
    "swaap-v2-monorepo/=lib/swaap-v2-monorepo/",
    "v3-core/=lib/v3-core/contracts/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract Registry","name":"_registry","type":"address"},{"internalType":"contract ERC20","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint32","name":"_holdingPosition","type":"uint32"},{"internalType":"bytes","name":"_holdingPositionConfig","type":"bytes"},{"internalType":"uint256","name":"_initialDeposit","type":"uint256"},{"internalType":"uint192","name":"_shareSupplyCap","type":"uint192"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"expectedAsset","type":"address"}],"name":"Fund__AssetMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"Fund__CallToAdaptorNotAllowed","type":"error"},{"inputs":[],"name":"Fund__CallerNotApprovedToRebalance","type":"error"},{"inputs":[],"name":"Fund__CallerNotAuthorizedForFlashLoan","type":"error"},{"inputs":[],"name":"Fund__ContractNotShutdown","type":"error"},{"inputs":[],"name":"Fund__ContractShutdown","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Fund__DebtMismatch","type":"error"},{"inputs":[],"name":"Fund__ExpectedAddressDoesNotMatchActual","type":"error"},{"inputs":[],"name":"Fund__ExternalInitiator","type":"error"},{"inputs":[],"name":"Fund__FailedToForceOutPosition","type":"error"},{"inputs":[{"internalType":"uint256","name":"assetsOwed","type":"uint256"}],"name":"Fund__IncompleteWithdraw","type":"error"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"Fund__InvalidHoldingPosition","type":"error"},{"inputs":[{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Fund__InvalidRebalanceDeviation","type":"error"},{"inputs":[],"name":"Fund__InvalidShareLockPeriod","type":"error"},{"inputs":[],"name":"Fund__InvalidSignature","type":"error"},{"inputs":[],"name":"Fund__InvalidSignatureDeadline","type":"error"},{"inputs":[],"name":"Fund__MinimumConstructorMintNotMet","type":"error"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"}],"name":"Fund__NotApprovedToDepositOnBehalf","type":"error"},{"inputs":[],"name":"Fund__Paused","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Fund__PositionAlreadyUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"maxPositions","type":"uint256"}],"name":"Fund__PositionArrayFull","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"},{"internalType":"uint256","name":"sharesRemaining","type":"uint256"}],"name":"Fund__PositionNotEmpty","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Fund__PositionNotInCatalogue","type":"error"},{"inputs":[{"internalType":"uint32","name":"position","type":"uint32"}],"name":"Fund__PositionNotUsed","type":"error"},{"inputs":[],"name":"Fund__Reentrancy","type":"error"},{"inputs":[],"name":"Fund__RemovingHoldingPosition","type":"error"},{"inputs":[],"name":"Fund__SettingValueToRegistryIdZeroIsProhibited","type":"error"},{"inputs":[],"name":"Fund__ShareSupplyCapExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"timeSharesAreUnlocked","type":"uint256"},{"internalType":"uint256","name":"currentBlock","type":"uint256"}],"name":"Fund__SharesAreLocked","type":"error"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"Fund__TotalAssetDeviatedOutsideRange","type":"error"},{"inputs":[{"internalType":"uint256","name":"current","type":"uint256"},{"internalType":"uint256","name":"expected","type":"uint256"}],"name":"Fund__TotalSharesMustRemainConstant","type":"error"},{"inputs":[],"name":"Fund__WhitelistEnabled","type":"error"},{"inputs":[],"name":"Fund__WrongPositionId","type":"error"},{"inputs":[],"name":"Fund__ZeroAssets","type":"error"},{"inputs":[],"name":"Fund__ZeroShares","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"AdaptorCalled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"adaptor","type":"address"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"AdaptorCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newAutomationActions","type":"address"}],"name":"Fund__AutomationActionsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"positionId","type":"uint32"},{"indexed":false,"internalType":"bool","name":"inCatalogue","type":"bool"}],"name":"PositionCatalogueAltered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"position","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"PositionRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"newPosition1","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"newPosition2","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"index1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"index2","type":"uint256"}],"name":"PositionSwapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldDeviation","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"RebalanceDeviationChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newPeriod","type":"uint256"}],"name":"ShareLockingPeriodChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint192","name":"newShareSupplyCap","type":"uint192"}],"name":"ShareSupplyCapChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isShutdown","type":"bool"}],"name":"ShutdownChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isWhitelistEnabled","type":"bool"}],"name":"WhitelistingChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FEES_MANAGER","outputs":[{"internalType":"contract FeesManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAXIMUM_SHARE_LOCK_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_REBALANCE_DEVIATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_SHARE_LOCK_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WHITELIST_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"adaptorCatalogue","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"addAdaptorToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bytes","name":"configurationData","type":"bytes"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"addPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"addPositionToCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allowedRebalanceDeviation","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"automationActions","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"blockExternalReceiver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"checkTotalAssets","type":"bool"},{"internalType":"uint16","name":"allowableRange","type":"uint16"},{"internalType":"address","name":"expectedPriceRouter","type":"address"}],"name":"cachePriceRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"adaptor","type":"address"},{"internalType":"bytes[]","name":"callData","type":"bytes[]"}],"internalType":"struct Fund.AdaptorCall[]","name":"data","type":"tuple[]"}],"name":"callOnAdaptor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collectFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"creditPositions","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"debtPositions","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"disableWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"enableWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"endPauseTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"positionId","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"forcePositionOut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCreditPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtPositions","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"","type":"uint32"}],"name":"getPositionData","outputs":[{"internalType":"address","name":"adaptor","type":"address"},{"internalType":"bool","name":"isDebt","type":"bool"},{"internalType":"bytes","name":"adaptorData","type":"bytes"},{"internalType":"bytes","name":"configurationData","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"holdingPosition","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initiateShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"isPositionUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isShutdown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isWhitelistEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liftShutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"locked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","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":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"","type":"uint32"}],"name":"positionCatalogue","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceRouter","outputs":[{"internalType":"contract PriceRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256[]","name":"feeAmounts","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"receiveFlashLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"registry","outputs":[{"internalType":"contract Registry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"adaptor","type":"address"}],"name":"removeAdaptorFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"index","type":"uint32"},{"internalType":"uint32","name":"expectedPositionId","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"removePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"removePositionFromCatalogue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_registryId","type":"uint256"},{"internalType":"address","name":"_expectedAutomationActions","type":"address"}],"name":"setAutomationActions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"positionId","type":"uint32"}],"name":"setHoldingPosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newDeviation","type":"uint256"}],"name":"setRebalanceDeviation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newLock","type":"uint256"}],"name":"setShareLockPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint192","name":"_newShareSupplyCap","type":"uint192"}],"name":"setShareSupplyCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shareLockPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shareSupplyCap","outputs":[{"internalType":"uint192","name":"","type":"uint192"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"index1","type":"uint32"},{"internalType":"uint32","name":"index2","type":"uint32"},{"internalType":"bool","name":"inDebtArray","type":"bool"}],"name":"swapPositions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssetsWithdrawable","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userShareLockStartTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"viewPositionBalances","outputs":[{"internalType":"contract ERC20[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"balances","type":"uint256[]"},{"internalType":"bool[]","name":"isDebt","type":"bool[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"signedAt","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"whitelistDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"signedAt","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"whitelistMint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

610240604052660110d9316ec0006010556202a30060115534801562000023575f80fd5b506040516200778238038062007782833981016040819052620000469162001099565b6040805180820190915260038152620312e360ec1b602082015286908a8a8a848a8a8a8a8a88888888888888888886868660125f62000086848262001216565b50600162000095838262001216565b5060ff81166080524660a052620000ab62000394565b60c0525050506001600160a01b031660e052620000c8336200040d565b620000d8630163f50042620012f2565b610100526001600160a01b038816610120819052604051635c9fcd8560e11b81526002600482015263b93f9b0a90602401602060405180830381865afa15801562000125573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200014b919062001308565b600880546001600160a01b0319166001600160a01b039290921691909117905562000176846200045e565b620001845f85858262000524565b6200018f84620007e1565b600780546001600160c01b0319166001600160c01b038316179055612710821015620001ce576040516308b35bf560e21b815260040160405180910390fd5b620001e56001600160a01b0388168a3085620008ee565b866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000222573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000248919062001326565b60ff16610140819052620002849033906200026590601262001348565b6200027290600a6200145d565b6200027e90856200146d565b6200097f565b620002908483620009ea565b876001600160a01b0316636b1b8eb26040518163ffffffff1660e01b8152600401602060405180830381865afa158015620002cd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002f3919062001308565b6001600160a01b0316610160526200030b8962000a80565b5050505050505050505050505050505050505f828051906020012090505f828051906020012090505f5f80516020620077628339815191529050826101e08181525050816102008181525050466101a081815250506200037381848462000aff60201b60201c565b61018052306101c0526102205250620016fe9b505050505050505050505050565b5f5f80516020620077628339815191525f604051620003b4919062001487565b604051908190038120620003f292917fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6904690309060200162001501565b60405160208183030381529060405280519060200120905090565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6200046862000b3a565b610120516001600160a01b031663a2b3b0fe826040518263ffffffff1660e01b81526004016200049991906200152d565b5f6040518083038186803b158015620004b0575f80fd5b505afa158015620004c3573d5f803e3d5ffd5b5050505063ffffffff81165f818152600d6020908152604091829020805460ff191660019081179091558251938452908301527fea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f910160405180910390a150565b6200052e62000b3a565b6200053862000b98565b63ffffffff83165f908152600b602052604090205460ff16156200057c578260405163a9247d0360e01b81526004016200057391906200152d565b60405180910390fd5b63ffffffff83165f908152600d602052604090205460ff16620005b6578260405163293f683360e01b81526004016200057391906200152d565b5f805f610120516001600160a01b03166331ad24f4876040518263ffffffff1660e01b8152600401620005ea91906200152d565b5f60405180830381865afa15801562000605573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526200062e91908101906200153e565b925092509250831515821515146200065d578560405163552a75d160e11b81526004016200057391906200152d565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b031990931693169290921717815591519091906001820190620006d8908262001216565b5060608201516002820190620006ef908262001216565b5090505081156200073657600a5460201162000722576040516308fe047f60e31b81526020600482015260240162000573565b62000730600a888862000bc4565b6200076c565b6009546020116200075e576040516308fe047f60e31b81526020600482015260240162000573565b6200076c6009888862000bc4565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb90620007d09088908a9063ffffffff92831681529116602082015260400190565b60405180910390a150505050505050565b620007eb62000b3a565b63ffffffff81165f908152600b602052604090205460ff16620008255780604051630871f35760e11b81526004016200057391906200152d565b60e0516001600160a01b03166200083c8262000d99565b6001600160a01b031614620008865760e051620008598262000d99565b60405163260d15b960e01b81526001600160a01b0392831660048201529116602482015260440162000573565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff1615620008c85780604051633c925c1760e11b81526004016200057391906200152d565b6007805463ffffffff909216600160d81b0263ffffffff60d81b19909216919091179055565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080620009785760405162461bcd60e51b815260206004820152601460248201527f5452414e534645525f46524f4d5f4641494c4544000000000000000000000000604482015260640162000573565b5050505050565b8060025f828254620009929190620012f2565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b039092169162000a7a916369445c3160e01b9162000a3791869160018201916002019060240162001629565b60408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b039384161790526001600160a01b0384169162000e2b16565b50505050565b62000a8a62000b3a565b6001600160a01b03811662000af15760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840162000573565b62000afc816200040d565b50565b5f838383463060405160200162000b1b95949392919062001501565b6040516020818303038152906040528051906020012090509392505050565b6006546001600160a01b0316331462000b965760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640162000573565b565b600754600160c81b900460ff161562000b9657604051633fb0b23b60e01b815260040160405180910390fd5b8254801562000d5957838062000bdc60018462001657565b8154811062000bef5762000bef6200166d565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a909204909316021790559062000c52908362001657565b90505b8363ffffffff1681111562000d05578462000c7260018362001657565b8154811062000c855762000c856200166d565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1685828154811062000cbe5762000cbe6200166d565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808062000cfc9062001681565b91505062000c55565b5081848463ffffffff168154811062000d225762000d226200166d565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff16021790555062000a7a565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf9162000de2916001019060040162001699565b602060405180830381865afa15801562000dfe573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000e24919062001308565b9392505050565b606062000e5383836040518060600160405280602781526020016200773b6027913962000e5c565b90505b92915050565b60605f80856001600160a01b03168560405162000e7a9190620016ad565b5f60405180830381855af49150503d805f811462000eb4576040519150601f19603f3d011682016040523d82523d5f602084013e62000eb9565b606091505b50909250905062000ecd8683838762000ed7565b9695505050505050565b6060831562000f4a5782515f0362000f42576001600160a01b0385163b62000f425760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640162000573565b508162000f56565b62000f56838362000f5e565b949350505050565b81511562000f6f5781518083602001fd5b8060405162461bcd60e51b8152600401620005739190620016ca565b6001600160a01b038116811462000afc575f80fd5b805162000fad8162000f8b565b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b8381101562000fe257818101518382015260200162000fc8565b50505f910152565b5f82601f83011262000ffa575f80fd5b81516001600160401b038082111562001017576200101762000fb2565b604051601f8301601f19908116603f0116810190828211818310171562001042576200104262000fb2565b816040528381528660208588010111156200105b575f80fd5b62000ecd84602083016020890162000fc6565b805163ffffffff8116811462000fad575f80fd5b80516001600160c01b038116811462000fad575f80fd5b5f805f805f805f805f6101208a8c031215620010b3575f80fd5b620010be8a62000fa0565b9850620010ce60208b0162000fa0565b9750620010de60408b0162000fa0565b60608b01519097506001600160401b0380821115620010fb575f80fd5b620011098d838e0162000fea565b975060808c01519150808211156200111f575f80fd5b6200112d8d838e0162000fea565b96506200113d60a08d016200106e565b955060c08c015191508082111562001153575f80fd5b50620011628c828d0162000fea565b93505060e08a015191506200117b6101008b0162001082565b90509295985092959850929598565b600181811c908216806200119f57607f821691505b602082108103620011be57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111562001211575f81815260208120601f850160051c81016020861015620011ec5750805b601f850160051c820191505b818110156200120d57828155600101620011f8565b5050505b505050565b81516001600160401b0381111562001232576200123262000fb2565b6200124a816200124384546200118a565b84620011c4565b602080601f83116001811462001280575f8415620012685750858301515b5f19600386901b1c1916600185901b1785556200120d565b5f85815260208120601f198616915b82811015620012b0578886015182559484019460019091019084016200128f565b5085821015620012ce57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b5f52601160045260245ffd5b8082018082111562000e565762000e56620012de565b5f6020828403121562001319575f80fd5b815162000e248162000f8b565b5f6020828403121562001337575f80fd5b815160ff8116811462000e24575f80fd5b60ff828116828216039081111562000e565762000e56620012de565b600181815b80851115620013a457815f1904821115620013885762001388620012de565b808516156200139657918102915b93841c939080029062001369565b509250929050565b5f82620013bc5750600162000e56565b81620013ca57505f62000e56565b8160018114620013e35760028114620013ee576200140e565b600191505062000e56565b60ff841115620014025762001402620012de565b50506001821b62000e56565b5060208310610133831016604e8410600b841016171562001433575081810a62000e56565b6200143f838362001364565b805f1904821115620014555762001455620012de565b029392505050565b5f62000e5360ff841683620013ac565b808202811582820484141762000e565762000e56620012de565b5f80835462001496816200118a565b60018281168015620014b15760018114620014c757620014f5565b60ff1984168752821515830287019450620014f5565b875f526020805f205f5b85811015620014ec5781548a820152908401908201620014d1565b50505082870194505b50929695505050505050565b9485526020850193909352604084019190915260608301526001600160a01b0316608082015260a00190565b63ffffffff91909116815260200190565b5f805f6060848603121562001551575f80fd5b83516200155e8162000f8b565b6020850151909350801515811462001574575f80fd5b60408501519092506001600160401b0381111562001590575f80fd5b6200159e8682870162000fea565b9150509250925092565b5f8154620015b6816200118a565b808552602060018381168015620015d65760018114620015f1576200161e565b60ff1985168884015283151560051b8801830195506200161e565b865f52825f205f5b85811015620016165781548a8201860152908301908401620015f9565b890184019650505b505050505092915050565b838152606060208201525f620016436060830185620015a8565b828103604084015262000ecd8185620015a8565b8181038181111562000e565762000e56620012de565b634e487b7160e01b5f52603260045260245ffd5b5f81620016925762001692620012de565b505f190190565b602081525f62000e536020830184620015a8565b5f8251620016c081846020870162000fc6565b9190910192915050565b602081525f8251806020840152620016ea81604085016020870162000fc6565b601f01601f19169190910160400192915050565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e0516102005161022051615f27620018145f395f6147e401525f61482601525f61480501525f61476901525f61479301525f6147bd01525f818161066e01528181612b8901528181613877015261390201525f6142df01525f818161073301528181611070015281816113c301528181611c5a01528181611fa30152818161214c0152818161277501528181613a78015261462601525f8181610450015261210f01525f818161053101528181610b6c01528181610bad01528181612a020152818161372f01528181613e38015261426e01525f610d8a01525f610d5a01525f6104dd0152615f275ff3fe608060405234801561000f575f80fd5b50600436106103b9575f3560e01c806251a3b7146103bd57806301e1d114146103d95780630402ab63146103e157806306fdde03146103eb5780630780fd3a1461040057806307a2d13a14610415578063095ea7b3146104285780630a03d6511461044b5780630a28a477146104725780630a680e181461048557806318160ddd1461048d578063184d69ab1461049657806318d4c143146104a357806323b872dd146104c5578063313ce567146104d85780633644e51514610511578063379e0b131461051957806338d52e0f1461052c5780633d8ab1e5146105605780633e3382ba14610573578063402d267d146105885780634c4602da1461059b5780634cdad506146105af5780634e84befe146105c2578063501eb4fe146105d5578063530a3714146105e857806359d20b4e146105fb5780635e2c576e1461061b5780635f6b88a0146106235780636301dccf14610636578063687c2b501461064a5780636b1b8eb2146106695780636e553f65146106905780636ff1c02a146106a357806370a08231146106b2578063715018a6146106d157806371e99dc2146106d95780637384504f146106e157806378e0233e146107045780637ab4fec71461071b5780637b1039991461072e5780637ecebe001461075557806388c4caba146107745780638da5cb5b1461078757806393bbeac01461078f57806394bf804d146107b1578063958b51e8146107c457806395d89b41146107d75780639955a9d4146107df5780639c552ca8146107f25780639c5f00c2146108055780639fdb11b61461081c578063a07bee0b14610825578063a3f462d814610838578063a8144e481461084b578063a9059cbb14610853578063ac9650d814610866578063b187bd2614610879578063b3d7f6b914610881578063b460af9414610894578063b47e8a7d146108a7578063ba087652146108ba578063bf86d690146108cd578063c244245a146108e1578063c588d8d6146108ea578063c63d75b6146108fd578063c6e6f59214610910578063c879657214610923578063c8e819501461092b578063cbdf33d01461093e578063cdfb2b4e14610960578063ce96cb7714610968578063cf3090121461097b578063d1e884041461098f578063d446bbcc146109a2578063d505accf146109c2578063d6b0f484146109d5578063d7d4bf45146109dd578063d905777e146109f0578063dd62ed3e14610a03578063e1b1acb714610a2d578063ef8b30f714610a40578063f04f270714610a53578063f2fde38b14610a66575b5f80fd5b6103c661012c81565b6040519081526020015b60405180910390f35b6103c6610a79565b6103c66202a30081565b6103f3610a97565b6040516103d09190614d25565b61041361040e366004614d4f565b610b22565b005b6103c6610423366004614d68565b610c66565b61043b610436366004614d93565b610c76565b60405190151581526020016103d0565b6103c67f000000000000000000000000000000000000000000000000000000000000000081565b6103c6610480366004614d68565b610cce565b610413610cf1565b6103c660025481565b60135461043b9060ff1681565b61043b6104b1366004614dbd565b600e6020525f908152604090205460ff1681565b61043b6104d3366004614dd8565b610d38565b6104ff7f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016103d0565b6103c6610d57565b610413610527366004614e23565b610dac565b6105537f000000000000000000000000000000000000000000000000000000000000000081565b6040516103d09190614e67565b61041361056e366004614dbd565b611051565b61057b61111f565b6040516103d09190614e7b565b6103c6610596366004614dbd565b6111a0565b60075461043b90600160d01b900460ff1681565b6103c66105bd366004614d68565b61121c565b6104136105d0366004614f04565b611237565b6104136105e3366004614d4f565b6113a4565b6104136105f6366004614d68565b611464565b61060e610609366004614d68565b6114e7565b6040516103d09190614f42565b61041361151e565b610413610631366004614dbd565b61157a565b6103c65f80516020615deb83398151915281565b6103c6610658366004614dbd565b60126020525f908152604090205481565b6105537f000000000000000000000000000000000000000000000000000000000000000081565b6103c661069e366004614f53565b6115be565b6103c667016345785d8a000081565b6103c66106c0366004614dbd565b60036020525f908152604090205481565b6104136115ed565b61057b611600565b6106f46106ef366004614d4f565b61165c565b6040516103d09493929190614f81565b61070c6117a0565b6040516103d093929190615039565b610413610729366004614e23565b611a64565b6105537f000000000000000000000000000000000000000000000000000000000000000081565b6103c6610763366004614dbd565b60056020525f908152604090205481565b600f54610553906001600160a01b031681565b610553611b6c565b61043b61079d366004614d68565b600b6020525f908152604090205460ff1681565b6103c66107bf366004614f53565b611b7b565b6103c66107d2366004615186565b611baa565b6103f3611bc9565b6104136107ed3660046151e4565b611bd6565b610413610800366004614d68565b611e74565b60075461060e90600160d81b900463ffffffff1681565b6103c660115481565b610413610833366004614e23565b611ee6565b6103c6610846366004615186565b612046565b6103c661205c565b61043b610861366004614d93565b612075565b610413610874366004614f04565b612089565b61043b61210c565b6103c661088f366004614d68565b6121c5565b6103c66108a2366004615250565b6121e1565b6104136108b5366004615284565b61221c565b6103c66108c8366004615250565b61226f565b60075461043b90600160c81b900460ff1681565b6103c660105481565b6104136108f83660046152b9565b6122c0565b6103c661090b366004614dbd565b61237d565b6103c661091e366004614d68565b6123d3565b6104136123dd565b610413610939366004614f53565b612400565b61043b61094c366004614d4f565b600d6020525f908152604090205460ff1681565b61041361245c565b6103c6610976366004614dbd565b612491565b60075461043b90600160c01b900460ff1681565b61041361099d366004614d4f565b6124a4565b6007546109b5906001600160c01b031681565b6040516103d091906152e6565b6104136109d0366004615308565b6124e5565b6104136126f0565b600854610553906001600160a01b031681565b6103c66109fe366004614dbd565b61271f565b6103c6610a11366004615374565b600460209081525f928352604080842090915290825290205481565b61060e610a3b366004614d68565b612733565b6103c6610a4e366004614d68565b612742565b610413610a613660046153a0565b61275e565b610413610a74366004614dbd565b6128e8565b5f610a82612961565b610a8a612987565b610a926129b2565b905090565b5f8054610aa390615484565b80601f0160208091040260200160405190810160405280929190818152602001828054610acf90615484565b8015610b1a5780601f10610af157610100808354040283529160200191610b1a565b820191905f5260205f20905b815481529060010190602001808311610afd57829003601f168201915b505050505081565b610b2a612a72565b63ffffffff81165f908152600b602052604090205460ff16610b6a5780604051630871f35760e11b8152600401610b619190614f42565b60405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610b9d82612ad1565b6001600160a01b031614610c01577f0000000000000000000000000000000000000000000000000000000000000000610bd582612ad1565b60405163260d15b960e01b81526001600160a01b03928316600482015291166024820152604401610b61565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff1615610c405780604051633c925c1760e11b8152600401610b619190614f42565b6007805463ffffffff909216600160d81b0263ffffffff60d81b19909216919091179055565b5f610c708261121c565b92915050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290915f80516020615e9283398151915290610cbd9086815260200190565b60405180910390a350600192915050565b5f805f610cda5f612b57565b91509150610ce9848383612c3e565b949350505050565b610cf9612a72565b610d01612c4a565b6007805460ff60c81b1916600160c81b179055604051600181525f80516020615e32833981519152906020015b60405180910390a1565b5f610d4284612c75565b610d4d848484612cc9565b90505b9392505050565b5f7f00000000000000000000000000000000000000000000000000000000000000004614610d8757610a92612da3565b507f000000000000000000000000000000000000000000000000000000000000000090565b610db4612a72565b5f808215610edd57600a8463ffffffff1681548110610dd557610dd56154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff1681548110610e1457610e146154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff1681548110610e5557610e556154bc565b905f5260205f209060089182820401919006600402600a8863ffffffff1681548110610e8357610e836154bc565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff1602179055505050610ffa565b60098463ffffffff1681548110610ef657610ef66154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16915060098563ffffffff1681548110610f3557610f356154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169050818160098763ffffffff1681548110610f7657610f766154bc565b905f5260205f20906008918282040191900660040260098863ffffffff1681548110610fa457610fa46154bc565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b611059612a72565b604051636777140560e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063ceee280a906110a5908490600401614e67565b5f6040518083038186803b1580156110bb575f80fd5b505afa1580156110cd573d5f803e3d5ffd5b5050506001600160a01b0382165f908152600e602052604090819020805460ff1916600190811790915590515f80516020615ed283398151915292506111149184916154d0565b60405180910390a150565b6060600a80548060200260200160405190810160405280929190818152602001828054801561119657602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116111595790505b5050505050905090565b6007545f90600160c81b900460ff16156111bb57505f919050565b6007546001600160c01b03165f806111d36001612b57565b91509150826001600160c01b031681106111f157505f949350505050565b5f611205826001600160c01b0386166154ff565b9050611212818484612e2a565b9695505050505050565b5f805f6112285f612b57565b91509150610ce9848383612e2a565b61123f612e36565b611247611b6c565b6001600160a01b0316336001600160a01b0316141580156112735750600f546001600160a01b03163314155b1561129157604051633d63583960e21b815260040160405180910390fd5b611299612c4a565b6112a1612961565b6007805460ff60d01b1916600160d01b1790555f8080806112c06129b2565b90506112eb601054670de0b6b3a76400006112db91906154ff565b8290670de0b6b3a7640000612e53565b9350611306601054670de0b6b3a76400006112db9190615512565b6002549093509150611322905061131d8587615660565b612e80565b5f61132b6129b2565b90508381108061133a57508281115b1561135e57808484604051630e7f213d60e31b8152600401610b619392919061566c565b6002548214611386576002548260405163030fc92b60e11b8152600401610b61929190615682565b50506007805460ff60d01b19169055506113a09050612ffe565b5050565b6113ac612a72565b604051635159d87f60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a2b3b0fe906113f8908490600401614f42565b5f6040518083038186803b15801561140e575f80fd5b505afa158015611420573d5f803e3d5ffd5b50505063ffffffff82165f908152600d602052604090819020805460ff1916600190811790915590515f80516020615eb28339815191529250611114918491615690565b61146c612a72565b67016345785d8a00008111156114a1578067016345785d8a000060405163146f176960e21b8152600401610b61929190615682565b60108054908290556040517fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff906114db9083908590615682565b60405180910390a15050565b600981815481106114f6575f80fd5b905f5260205f209060089182820401919006600402915054906101000a900463ffffffff1681565b611526612a72565b600754600160c81b900460ff16611550576040516359f6f82160e01b815260040160405180910390fd5b6007805460ff60c81b191690556040515f81525f80516020615e3283398151915290602001610d2e565b611582612a72565b6001600160a01b0381165f908152600e6020526040808220805460ff19169055515f80516020615ed283398151915291611114918491906154d0565b6013545f9060ff16156115e35760405162cf7d6f60e81b815260040160405180910390fd5b610d50838361300d565b6115f5612a72565b6115fe5f61309d565b565b60606009805480602002602001604051908101604052809291908181526020018280548015611196575f918252602091829020805463ffffffff1684529082028301929091600491018084116111595790505050505050905090565b600c6020525f9081526040902080546001820180546001600160a01b03831693600160a01b90930460ff1692919061169390615484565b80601f01602080910402602001604051908101604052809291908181526020018280546116bf90615484565b801561170a5780601f106116e15761010080835404028352916020019161170a565b820191905f5260205f20905b8154815290600101906020018083116116ed57829003601f168201915b50505050509080600201805461171f90615484565b80601f016020809104026020016040519081016040528092919081815260200182805461174b90615484565b80156117965780601f1061176d57610100808354040283529160200191611796565b820191905f5260205f20905b81548152906001019060200180831161177957829003601f168201915b5050505050905084565b600954600a5460609182918291905f6117b98284615512565b9050806001600160401b038111156117d3576117d36150a2565b6040519080825280602002602001820160405280156117fc578160200160208202803683370190505b509550806001600160401b03811115611817576118176150a2565b604051908082528060200260200182016040528015611840578160200160208202803683370190505b509450806001600160401b0381111561185b5761185b6150a2565b604051908082528060200260200182016040528015611884578160200160208202803683370190505b5093505f5b83811015611992576118d0600982815481106118a7576118a76154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612ad1565b8782815181106118e2576118e26154bc565b60200260200101906001600160a01b031690816001600160a01b03168152505061194160098281548110611918576119186154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff166130ee565b868281518110611953576119536154bc565b6020026020010181815250505f858281518110611972576119726154bc565b9115156020928302919091019091015261198b816156a8565b9050611889565b505f5b82811015611a5b575f6119a88583615512565b90506119c0600a83815481106118a7576118a76154bc565b8882815181106119d2576119d26154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050611a08600a8381548110611918576119186154bc565b878281518110611a1a57611a1a6154bc565b6020026020010181815250506001868281518110611a3a57611a3a6154bc565b9115156020928302919091019091015250611a54816156a8565b9050611995565b50505050909192565b611a6c612a72565b5f81611ab45760098463ffffffff1681548110611a8b57611a8b6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611af2565b600a8463ffffffff1681548110611acd57611acd6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614611b2057604051637870bc1160e11b815260040160405180910390fd5b5f611b2a826130ee565b90508015611b5a57604051632b7553ad60e11b815263ffffffff8316600482015260248101829052604401610b61565b611b65858385613174565b5050505050565b6006546001600160a01b031690565b6013545f9060ff1615611ba05760405162cf7d6f60e81b815260040160405180910390fd5b610d508383613257565b5f611bb68484846132dd565b611bc0858561300d565b95945050505050565b60018054610aa390615484565b611bde612a72565b611be6612c4a565b63ffffffff83165f908152600b602052604090205460ff1615611c1e578260405163a9247d0360e01b8152600401610b619190614f42565b63ffffffff83165f908152600d602052604090205460ff16611c55578260405163293f683360e01b8152600401610b619190614f42565b5f805f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166331ad24f4876040518263ffffffff1660e01b8152600401611ca49190614f42565b5f60405180830381865afa158015611cbe573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ce591908101906156c0565b92509250925083151582151514611d11578560405163552a75d160e11b8152600401610b619190614f42565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b031990931693169290921717815591519091906001820190611d8a908261579e565b5060608201516002820190611d9f908261579e565b509050508115611de057600a54602011611dcf576040516308fe047f60e31b815260206004820152602401610b61565b611ddb600a88886133f3565b611e12565b600954602011611e06576040516308fe047f60e31b815260206004820152602401610b61565b611e12600988886133f3565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb90611e639088908a90615859565b60405180910390a150505050505050565b611e7c612a72565b61012c811080611e8e57506202a30081115b15611eac57604051632f23f36f60e21b815260040160405180910390fd5b60118054908290556040517f227ff5c6b5ffb395236b09fd1b472bb128b36eaa17556633feefe28e94411f24906114db9083908590615682565b611eee612a72565b5f81611f365760098463ffffffff1681548110611f0d57611f0d6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611f74565b600a8463ffffffff1681548110611f4f57611f4f6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614158061201757506040516321a0f75360e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906321a0f75390611fd8908690600401614f42565b602060405180830381865afa158015611ff3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120179190615870565b15612035576040516309953b5760e21b815260040160405180910390fd5b612040848484613174565b50505050565b5f6120528484846132dd565b611bc08585613257565b5f612065612961565b61206d612987565b610a926135b0565b5f61207f33612c75565b610d50838361379e565b5f5b81811015612107576120f68383838181106120a8576120a86154bc565b90506020028101906120ba919061588b565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506138019050565b50612100816156a8565b905061208b565b505050565b5f7f00000000000000000000000000000000000000000000000000000000000000004210156121c057604051630ad85dff60e41b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063ad85dff090612181903090600401614e67565b602060405180830381865afa15801561219c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a929190615870565b505f90565b5f805f6121d26001612b57565b91509150610ce9848383613826565b5f6121ea612e36565b5f806121f55f613832565b91509150612204868383612c3e565b92506122128684878761394c565b5050610d50612ffe565b612224612a72565b600780546001600160c01b0319166001600160c01b0383161790556040517f7db520ee920d1ba9b37317ccb723d0593fdbb627fdc10f325cf254043ae71368906111149083906152e6565b5f612278612e36565b5f806122835f613832565b91509150612292868383612e2a565b9250825f036122b45760405163b8018d2560e01b815260040160405180910390fd5b6122128387878761394c565b6122c8612a72565b5f80841561230d575f6122d9610a79565b90506122f86122ea866127106158cd565b829061ffff16612710613a2e565b92506123096122ea866127106158ef565b9150505b612318600284613a4c565b600880546001600160a01b0319166001600160a01b0385161790558415611b65575f612342610a79565b90508281108061235157508181115b1561237557808383604051630e7f213d60e31b8152600401610b619392919061566c565b505050505050565b6007545f90600160c81b900460ff161561239857505f919050565b6007546002546001600160c01b0390911690818110156123ca576123c5816001600160c01b0384166154ff565b610ce9565b5f949350505050565b5f610c7082612742565b6123e5612e36565b6123ed612961565b6123f65f613832565b50506115fe612ffe565b612408612a72565b6124128282613a4c565b600f80546001600160a01b0319166001600160a01b0383169081179091556040517fc0f008b5949918c64044a073e77a2e2b28044120eb984a4126b92a121ac32464905f90a25050565b612464612a72565b6013805460ff191660019081179091556040519081525f80516020615e7283398151915290602001610d2e565b5f61249a612987565b610c70825f613b2a565b6124ac612a72565b63ffffffff81165f908152600d6020526040808220805460ff19169055515f80516020615eb28339815191529161111491849190615690565b4284101561252f5760405162461bcd60e51b815260206004820152601760248201527614115493525517d11150511312539157d1561412549151604a1b6044820152606401610b61565b5f600161253a610d57565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e0830190915280519201919091206125d392916101000161590a565b604051602081830303815290604052805190602001208585856040515f81526020016040526040516126089493929190615925565b6020604051602081039080840390855afa158015612628573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b0381161580159061265e5750876001600160a01b0316816001600160a01b0316145b61269b5760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610b61565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16915f80516020615e92833981519152910160405180910390a350505050505050565b6126f8612a72565b6013805460ff191690556040515f81525f80516020615e7283398151915290602001610d2e565b5f612728612987565b610c70826001613b2a565b600a81815481106114f6575f80fd5b5f805f61274f6001612b57565b91509150610ce9848383613b77565b60405163131119fb60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063262233f6906127aa903390600401614e67565b602060405180830381865afa1580156127c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127e99190615870565b61280957604051600162cea27760e01b0319815260040160405180910390fd5b600754600160d01b900460ff166128335760405163026d802d60e01b815260040160405180910390fd5b5f61284082840184615943565b905061284b81612e80565b5f5b868110156128dc576128cc3387878481811061286b5761286b6154bc565b905060200201358a8a85818110612884576128846154bc565b905060200201356128959190615512565b8c8c858181106128a7576128a76154bc565b90506020020160208101906128bc9190614dbd565b6001600160a01b03169190613b83565b6128d5816156a8565b905061284d565b50505050505050505050565b6128f0612a72565b6001600160a01b0381166129555760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610b61565b61295e8161309d565b50565b61296961210c565b156115fe57604051633c8a755760e11b815260040160405180910390fd5b600754600160c01b900460ff16156115fe576040516332d15db560e11b815260040160405180910390fd5b5f805f6129be5f613bf7565b915091505f806129ce6001613bf7565b600854604051637563738b60e11b81529294509092506001600160a01b03169063eac6e71690612a2a9087908790879087907f000000000000000000000000000000000000000000000000000000000000000090600401615987565b602060405180830381865afa158015612a45573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a6991906159ee565b94505050505090565b33612a7b611b6c565b6001600160a01b0316146115fe5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610b61565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf91612b189160010190600401615a7e565b602060405180830381865afa158015612b33573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d509190615a90565b5f805f612b626129b2565b60025460075491925090600160c81b900460ff1615612b85579094909350915050565b5f807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633a9f46df85858a6040518463ffffffff1660e01b8152600401612bd793929190615aab565b6040805180830381865afa158015612bf1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c159190615ac3565b91509150612c24848389613dc6565b935083612c318285615512565b9550955050505050915091565b5f610d4d848385612e53565b600754600160c81b900460ff16156115fe57604051633fb0b23b60e01b815260040160405180910390fd5b6001600160a01b0381165f9081526012602052604090205480156113a0575f60115482612ca29190615512565b905042811115612107578042604051634aa58ecb60e11b8152600401610b61929190615682565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f198114612d2257612cfe83826154ff565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f9081526003602052604081208054859290612d499084906154ff565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615e5283398151915290612d909087815260200190565b60405180910390a3506001949350505050565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051612dd39190615aef565b604051908190038120612e0f92917fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc69046903090602001615b61565b60405160208183030381529060405280519060200120905090565b5f610d4d848484613a2e565b612e3e612987565b6007805460ff60c01b1916600160c01b179055565b828202811515841585830485141716612e6a575f80fd5b6001826001830304018115150290509392505050565b5f5b81518110156113a0575f828281518110612e9e57612e9e6154bc565b602090810291909101810151516001600160a01b0381165f908152600e90925260409091205490915060ff16612ee957806040516302f032c160e51b8152600401610b619190614e67565b5f5b838381518110612efd57612efd6154bc565b60200260200101516020015151811015612feb57612f63848481518110612f2657612f266154bc565b6020026020010151602001518281518110612f4357612f436154bc565b6020026020010151836001600160a01b031661380190919063ffffffff16565b50816001600160a01b03167f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf483858581518110612fa157612fa16154bc565b6020026020010151602001518381518110612fbe57612fbe6154bc565b6020026020010151604051612fd39190614d25565b60405180910390a2612fe4816156a8565b9050612eeb565b505080612ff7906156a8565b9050612e82565b6007805460ff60c01b19169055565b5f613016612e36565b5f806130226001613832565b91509150613031858383613b77565b9250825f036130535760405163328d31e360e11b815260040160405180910390fd5b6007546001600160c01b03166130698483615512565b111561308857604051630bbcb58960e41b815260040160405180910390fd5b613093858486613e20565b5050610c70612ffe565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b63ffffffff81165f908152600c602052604080822080549151637841536560e01b81526001600160a01b039092169182916378415365916131359160010190600401615a7e565b602060405180830381865afa158015613150573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d5091906159ee565b60075463ffffffff600160d81b9091048116908316036131a75760405163c5fe093960e01b815260040160405180910390fd5b80156131bd576131b8600a84613ec2565b6131c8565b6131c8600984613ec2565b63ffffffff82165f908152600b60209081526040808320805460ff19169055600c909152812080546001600160a81b03191681559061320a6001830182614c8e565b613217600283015f614c8e565b50507fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd51828460405161324a929190615859565b60405180910390a1505050565b5f613260612e36565b5f8061326c6001613832565b9150915061327b858383613826565b9250825f0361329d5760405163b8018d2560e01b815260040160405180910390fd5b6007546001600160c01b03166132b38683615512565b11156132d257604051630bbcb58960e41b815260040160405180910390fd5b613093838686613e20565b60135460ff1615612107576132f461012c83615512565b4211156133145760405163021aec4f60e41b815260040160405180910390fd5b814210156133355760405163021aec4f60e41b815260040160405180910390fd5b604080515f80516020615deb833981519152602082015233918101919091526001600160a01b0384166060820152608081018390525f9061338e9060a00160405160208183030381529060405280519060200120614001565b90505f61339b8284614013565b600f549091506001600160a01b038083169116148015906133d557506133bf611b6c565b6001600160a01b0316816001600160a01b031614155b15611b6557604051633567d76d60e11b815260040160405180910390fd5b825480156135705783806134086001846154ff565b81548110613418576134186154bc565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a909204909316021790559061347990836154ff565b90505b8363ffffffff1681111561352057846134966001836154ff565b815481106134a6576134a66154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff168582815481106134dc576134dc6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061351890615b8d565b91505061347c565b5081848463ffffffff168154811061353a5761353a6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550612040565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b6009545f9081816001600160401b038111156135ce576135ce6150a2565b6040519080825280602002602001820160405280156135f7578160200160208202803683370190505b5090505f826001600160401b03811115613613576136136150a2565b60405190808252806020026020018201604052801561363c578160200160208202803683370190505b5090505f5b83811015613702575f6009828154811061365d5761365d6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061368c81614035565b83838151811061369e5761369e6154bc565b60200260200101818152505f036136b557506136f2565b6136be81612ad1565b8483815181106136d0576136d06154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6136fb816156a8565b9050613641565b5060085460405163b333a17560e01b81526001600160a01b039091169063b333a1759061375790859085907f000000000000000000000000000000000000000000000000000000000000000090600401615ba2565b602060405180830381865afa158015613772573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061379691906159ee565b935050505090565b335f908152600360205260408120805483919083906137be9084906154ff565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615e5283398151915290610cbd9086815260200190565b6060610d508383604051806060016040528060278152602001615e0b602791396140ea565b5f610d4d848484612e53565b5f805f61383d6129b2565b60025460075491925090600160c81b900460ff1615613860579094909350915050565b6040516312325b5d60e21b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906348c96d74906138b090859085908a90600401615aab565b60408051808303815f875af19250505080156138e9575060408051601f3d908101601f191682019092526138e691810190615ac3565b60015b6138f7579094909350915050565b8015613934576139277f000000000000000000000000000000000000000000000000000000000000000082614154565b6139318184615512565b92505b61393f848389613dc6565b9792965091945050505050565b613958848484846141ab565b336001600160a01b038216146139c3576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146139c15761399d84826154ff565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b6139cd81846141c0565b806001600160a01b0316826001600160a01b0316336001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8787604051613a1c929190615682565b60405180910390a4612040848361421f565b828202811515841585830485141716613a45575f80fd5b0492915050565b815f03613a6c57604051631218237b60e31b815260040160405180910390fd5b806001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663b93f9b0a846040518263ffffffff1660e01b8152600401613ac491815260200190565b602060405180830381865afa158015613adf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b039190615a90565b6001600160a01b0316146113a057604051632105ff5560e11b815260040160405180910390fd5b6001600160a01b0382165f908152601260205260408120548015613b6d575f60115482613b579190615512565b905042811115613b6b575f92505050610c70565b505b610ce98484614579565b5f610d4d848385613a2e565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806120405760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610b61565b6060805f83613c07576009613c0a565b600a5b805480602002602001604051908101604052809291908181526020018280548015613c7d57602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff1681526020019060040190602082600301049283019260010382029150808411613c405790505b505050505090505f815190505f816001600160401b03811115613ca257613ca26150a2565b604051908082528060200260200182016040528015613ccb578160200160208202803683370190505b5090505f826001600160401b03811115613ce757613ce76150a2565b604051908082528060200260200182016040528015613d10578160200160208202803683370190505b5090505f5b83811015613db9575f858281518110613d3057613d306154bc565b60200260200101519050613d43816130ee565b838381518110613d5557613d556154bc565b60200260200101818152505f03613d6c5750613da9565b613d7581612ad1565b848381518110613d8757613d876154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050505b613db2816156a8565b9050613d15565b5090969095509350505050565b5f8261ffff165f03613dd9575082610d50565b8115613e0357613dfc613dee846127106158ef565b859061ffff16612710612e53565b9050610d50565b610d4d613e12846127106158cd565b859061ffff16612710613a2e565b613e2b8383836145f4565b613e606001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163330866146b9565b613e6a8183614154565b806001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d78585604051613eaf929190615682565b60405180910390a3612107838383614738565b815463ffffffff82168111613f0f5760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610b61565b63ffffffff82165b613f226001836154ff565b811015613fbf5783613f35826001615512565b81548110613f4557613f456154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16848281548110613f7b57613f7b6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff1602179055508080613fb7906156a8565b915050613f17565b5082805480613fd057613fd0615bdf565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b5f610c7061400d61475d565b8361484a565b5f805f614020858561487c565b9150915061402d816148be565b509392505050565b63ffffffff81165f908152600c6020526040812054600160a01b900460ff161561406057505f919050565b63ffffffff82165f908152600c60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d2916140ab91600182019160020190600401615bf3565b602060405180830381865afa1580156140c6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c7091906159ee565b60605f80856001600160a01b0316856040516141069190615c17565b5f60405180830381855af49150503d805f811461413e576040519150601f19603f3d011682016040523d82523d5f602084013e614143565b606091505b509150915061121286838387614a02565b8060025f8282546141659190615512565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615e5283398151915291015b60405180910390a35050565b6141b481612c75565b61204084848484614a7a565b6001600160a01b0382165f90815260036020526040812080548392906141e79084906154ff565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615e528339815191529060200161419f565b61424660405180608001604052805f81526020015f81526020015f81526020015f81525090565b600854604051630226614760e01b81526001600160a01b0390911690630226614790614296907f000000000000000000000000000000000000000000000000000000000000000090600401614e67565b602060405180830381865afa1580156142b1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142d591906159ee565b60408201526143057f0000000000000000000000000000000000000000000000000000000000000000600a615d12565b60608201526009545f5b81811015614556575f6009828154811061432b5761432b6154bc565b5f9182526020822060088204015460079091166004026101000a900463ffffffff16915061435882614035565b9050805f03614368575050614546565b5f61437283612ad1565b600854604051630226614760e01b81529192506001600160a01b0316906302266147906143a3908490600401614e67565b602060405180830381865afa1580156143be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143e291906159ee565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614426573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061444a9190615d20565b61445590600a615d12565b6020870181905286515f91829161447f9161447887670de0b6b3a7640000615d3b565b9190613a2e565b905061449e8860600151896040015183613a2e9092919063ffffffff16565b91506144b2670de0b6b3a764000083615d52565b9150505f89821115614515575f6144e089604001518a606001518d670de0b6b3a76400006144789190615d3b565b60208a01518a519192506144f691839190613a2e565b915061450a670de0b6b3a764000083615d52565b91505f9a5050614524565b5082614521828b6154ff565b99505b61452f85828b614a82565b895f03614540575050505050614556565b50505050505b61454f816156a8565b905061430f565b5083156120405760405163089d698560e41b815260048101859052602401610b61565b5f614582612961565b5f8061458d5f612b57565b6001600160a01b0387165f90815260036020526040812054929450909250906145b7908484612e2a565b90505f6145c26135b0565b9050808211156145d257806145d4565b815b945085156145ea576145e7858585613b77565b94505b5050505092915050565b6145ff838383614b12565b336001600160a01b0382161461210757604051635551e1b560e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690635551e1b59061465b903390600401614e67565b602060405180830381865afa158015614676573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061469a9190615870565b6121075733604051634d1b6c4d60e01b8152600401610b619190614e67565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080611b655760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610b61565b6001600160a01b0381165f908152601260205260409020429055612107838383614b22565b5f306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480156147b557507f000000000000000000000000000000000000000000000000000000000000000046145b156147df57507f000000000000000000000000000000000000000000000000000000000000000090565b610a927f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000614b3c565b5f828260405160200161485e92919061590a565b60405160208183030381529060405280519060200120905092915050565b5f8082516041036148b0576020830151604084015160608501515f1a6148a487828585614b75565b945094505050506148b7565b505f905060025b9250929050565b5f8160048111156148d1576148d1615d71565b036148d95750565b60018160048111156148ed576148ed615d71565b036149355760405162461bcd60e51b815260206004820152601860248201527745434453413a20696e76616c6964207369676e617475726560401b6044820152606401610b61565b600281600481111561494957614949615d71565b036149965760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610b61565b60038160048111156149aa576149aa615d71565b0361295e5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610b61565b60608315614a705782515f03614a69576001600160a01b0385163b614a695760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610b61565b5081610ce9565b610ce98383614c1a565b612040612961565b63ffffffff83165f908152600c602052604090819020805491516001600160a01b0390921691611b659163c9111bd760e01b91614ad091879187916001810191600290910190602401615d85565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b03831690613801565b614b1a612c4a565b612107612961565b60075461210790600160d81b900463ffffffff1684614c44565b5f8383834630604051602001614b56959493929190615b61565b6040516020818303038152906040528051906020012090509392505050565b5f806fa2a8918ca85bafe22016d0b997e4df60600160ff1b03831115614ba057505f90506003614c11565b5f6001878787876040515f8152602001604052604051614bc39493929190615925565b6020604051602081039080840390855afa158015614be3573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614c0b575f60019250925050614c11565b91505f90505b94509492505050565b815115614c2a5781518083602001fd5b8060405162461bcd60e51b8152600401610b619190614d25565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b0390921691612040916369445c3160e01b91614ad0918691600182019160020190602401615dc0565b508054614c9a90615484565b5f825580601f10614ca9575050565b601f0160209004905f5260205f209081019061295e91905b80821115614cd4575f8155600101614cc1565b5090565b5f5b83811015614cf2578181015183820152602001614cda565b50505f910152565b5f8151808452614d11816020860160208601614cd8565b601f01601f19169290920160200192915050565b602081525f610d506020830184614cfa565b803563ffffffff81168114614d4a575f80fd5b919050565b5f60208284031215614d5f575f80fd5b610d5082614d37565b5f60208284031215614d78575f80fd5b5035919050565b6001600160a01b038116811461295e575f80fd5b5f8060408385031215614da4575f80fd5b8235614daf81614d7f565b946020939093013593505050565b5f60208284031215614dcd575f80fd5b8135610d5081614d7f565b5f805f60608486031215614dea575f80fd5b8335614df581614d7f565b92506020840135614e0581614d7f565b929592945050506040919091013590565b801515811461295e575f80fd5b5f805f60608486031215614e35575f80fd5b614e3e84614d37565b9250614e4c60208501614d37565b91506040840135614e5c81614e16565b809150509250925092565b6001600160a01b0391909116815260200190565b602080825282518282018190525f9190848201906040850190845b81811015614eb857835163ffffffff1683529284019291840191600101614e96565b50909695505050505050565b5f8083601f840112614ed4575f80fd5b5081356001600160401b03811115614eea575f80fd5b6020830191508360208260051b85010111156148b7575f80fd5b5f8060208385031215614f15575f80fd5b82356001600160401b03811115614f2a575f80fd5b614f3685828601614ec4565b90969095509350505050565b63ffffffff91909116815260200190565b5f8060408385031215614f64575f80fd5b823591506020830135614f7681614d7f565b809150509250929050565b6001600160a01b038516815283151560208201526080604082018190525f90614fac90830185614cfa565b8281036060840152614fbe8185614cfa565b979650505050505050565b5f8151808452602080850194508084015f5b838110156150005781516001600160a01b031687529582019590820190600101614fdb565b509495945050505050565b5f8151808452602080850194508084015f5b838110156150005781518752958201959082019060010161501d565b606081525f61504b6060830186614fc9565b60208382038185015261505e828761500b565b848103604086015285518082528287019350908201905f5b81811015615094578451151583529383019391830191600101615076565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b03811182821017156150d8576150d86150a2565b60405290565b604051601f8201601f191681016001600160401b0381118282101715615106576151066150a2565b604052919050565b5f6001600160401b03821115615126576151266150a2565b50601f01601f191660200190565b5f82601f830112615143575f80fd5b81356151566151518261510e565b6150de565b81815284602083860101111561516a575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215615199575f80fd5b8435935060208501356151ab81614d7f565b92506040850135915060608501356001600160401b038111156151cc575f80fd5b6151d887828801615134565b91505092959194509250565b5f805f80608085870312156151f7575f80fd5b61520085614d37565b935061520e60208601614d37565b925060408501356001600160401b03811115615228575f80fd5b61523487828801615134565b925050606085013561524581614e16565b939692955090935050565b5f805f60608486031215615262575f80fd5b83359250602084013561527481614d7f565b91506040840135614e5c81614d7f565b5f60208284031215615294575f80fd5b81356001600160c01b0381168114610d50575f80fd5b61ffff8116811461295e575f80fd5b5f805f606084860312156152cb575f80fd5b83356152d681614e16565b92506020840135615274816152aa565b6001600160c01b0391909116815260200190565b60ff8116811461295e575f80fd5b5f805f805f805f60e0888a03121561531e575f80fd5b873561532981614d7f565b9650602088013561533981614d7f565b955060408801359450606088013593506080880135615357816152fa565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615385575f80fd5b823561539081614d7f565b91506020830135614f7681614d7f565b5f805f805f805f806080898b0312156153b7575f80fd5b88356001600160401b03808211156153cd575f80fd5b6153d98c838d01614ec4565b909a50985060208b01359150808211156153f1575f80fd5b6153fd8c838d01614ec4565b909850965060408b0135915080821115615415575f80fd5b6154218c838d01614ec4565b909650945060608b0135915080821115615439575f80fd5b818b0191508b601f83011261544c575f80fd5b81358181111561545a575f80fd5b8c602082850101111561546b575f80fd5b6020830194508093505050509295985092959890939650565b600181811c9082168061549857607f821691505b6020821081036154b657634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b6001600160a01b039290921682521515602082015260400190565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610c7057610c706154eb565b80820180821115610c7057610c706154eb565b5f6001600160401b0382111561553d5761553d6150a2565b5060051b60200190565b5f61555461515184615525565b8381529050602080820190600585901b840186811115615572575f80fd5b845b81811015615655576001600160401b038135811015615591575f80fd5b813587016040818b0312156155a4575f80fd5b6155ac6150b6565b6155b68235614d7f565b8135815285820135838111156155ca575f80fd5b8083019250508a601f8301126155de575f80fd5b81356155ec61515182615525565b81815260059190911b8301870190878101908d83111561560a575f80fd5b8885015b8381101561563f578681351115615623575f80fd5b6156328f8b8335890101615134565b835291890191890161560e565b5083890152505086525050928201928201615574565b505050509392505050565b5f610d50368484615547565b9283526020830191909152604082015260600190565b918252602082015260400190565b63ffffffff9290921682521515602082015260400190565b5f600182016156b9576156b96154eb565b5060010190565b5f805f606084860312156156d2575f80fd5b83516156dd81614d7f565b60208501519093506156ee81614e16565b60408501519092506001600160401b03811115615709575f80fd5b8401601f81018613615719575f80fd5b80516157276151518261510e565b81815287602083850101111561573b575f80fd5b61574c826020830160208601614cd8565b8093505050509250925092565b601f821115612107575f81815260208120601f850160051c8101602086101561577f5750805b601f850160051c820191505b818110156123755782815560010161578b565b81516001600160401b038111156157b7576157b76150a2565b6157cb816157c58454615484565b84615759565b602080601f8311600181146157fe575f84156157e75750858301515b5f19600386901b1c1916600185901b178555612375565b5f85815260208120601f198616915b8281101561582c5788860151825594840194600190910190840161580d565b508582101561584957878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b63ffffffff92831681529116602082015260400190565b5f60208284031215615880575f80fd5b8151610d5081614e16565b5f808335601e198436030181126158a0575f80fd5b8301803591506001600160401b038211156158b9575f80fd5b6020019150368190038213156148b7575f80fd5b61ffff8281168282160390808211156158e8576158e86154eb565b5092915050565b61ffff8181168382160190808211156158e8576158e86154eb565b61190160f01b81526002810192909252602282015260420190565b93845260ff9290921660208401526040830152606082015260800190565b5f60208284031215615953575f80fd5b81356001600160401b03811115615968575f80fd5b8201601f81018413615978575f80fd5b610ce984823560208401615547565b60a081525f61599960a0830188614fc9565b82810360208401526159ab818861500b565b905082810360408401526159bf8187614fc9565b905082810360608401526159d3818661500b565b91505060018060a01b03831660808301529695505050505050565b5f602082840312156159fe575f80fd5b5051919050565b5f8154615a1181615484565b808552602060018381168015615a2e5760018114615a4857615a73565b60ff1985168884015283151560051b880183019550615a73565b865f52825f205f5b85811015615a6b5781548a8201860152908301908401615a50565b890184019650505b505050505092915050565b602081525f610d506020830184615a05565b5f60208284031215615aa0575f80fd5b8151610d5081614d7f565b92835260208301919091521515604082015260600190565b5f8060408385031215615ad4575f80fd5b8251615adf816152aa565b6020939093015192949293505050565b5f808354615afc81615484565b60018281168015615b145760018114615b2957615b55565b60ff1984168752821515830287019450615b55565b875f526020805f205f5b85811015615b4c5781548a820152908401908201615b33565b50505082870194505b50929695505050505050565b9485526020850193909352604084019190915260608301526001600160a01b0316608082015260a00190565b5f81615b9b57615b9b6154eb565b505f190190565b606081525f615bb46060830186614fc9565b8281036020840152615bc6818661500b565b91505060018060a01b0383166040830152949350505050565b634e487b7160e01b5f52603160045260245ffd5b604081525f615c056040830185615a05565b8281036020840152611bc08185615a05565b5f8251615c28818460208701614cd8565b9190910192915050565b600181815b80851115615c6c57815f1904821115615c5257615c526154eb565b80851615615c5f57918102915b93841c9390800290615c37565b509250929050565b5f82615c8257506001610c70565b81615c8e57505f610c70565b8160018114615ca45760028114615cae57615cca565b6001915050610c70565b60ff841115615cbf57615cbf6154eb565b50506001821b610c70565b5060208310610133831016604e8410600b8410161715615ced575081810a610c70565b615cf78383615c32565b805f1904821115615d0a57615d0a6154eb565b029392505050565b5f610d5060ff841683615c74565b5f60208284031215615d30575f80fd5b8151610d50816152fa565b8082028115828204841417610c7057610c706154eb565b5f82615d6c57634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52602160045260245ffd5b8481526001600160a01b03841660208201526080604082018190525f90615dae90830185615a05565b8281036060840152614fbe8185615a05565b838152606060208201525f615dd86060830185615a05565b82810360408401526112128185615a0556feb3e99edbe0a6168c4e5e3779981b987a4957b59c9d41c08b56a5fd1e774fbe13416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564b8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3cddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efc6dc7171957873ef39aa9e363c5872095067708a59f84b8e467223fb726e49ea8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925ea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7aa2646970667358221220d1d96c33fbdcbe143392b9b1527360ff9557035615a71d8aa9c8b591e6e1c4f264736f6c63430008150033416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c65648b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f0000000000000000000000000269aaa07af2793ebb713ba787316ef579a5299a0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc200000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000038d7ea4c680000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000f537761617020574554482046756e6400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007737770574554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106103b9575f3560e01c806251a3b7146103bd57806301e1d114146103d95780630402ab63146103e157806306fdde03146103eb5780630780fd3a1461040057806307a2d13a14610415578063095ea7b3146104285780630a03d6511461044b5780630a28a477146104725780630a680e181461048557806318160ddd1461048d578063184d69ab1461049657806318d4c143146104a357806323b872dd146104c5578063313ce567146104d85780633644e51514610511578063379e0b131461051957806338d52e0f1461052c5780633d8ab1e5146105605780633e3382ba14610573578063402d267d146105885780634c4602da1461059b5780634cdad506146105af5780634e84befe146105c2578063501eb4fe146105d5578063530a3714146105e857806359d20b4e146105fb5780635e2c576e1461061b5780635f6b88a0146106235780636301dccf14610636578063687c2b501461064a5780636b1b8eb2146106695780636e553f65146106905780636ff1c02a146106a357806370a08231146106b2578063715018a6146106d157806371e99dc2146106d95780637384504f146106e157806378e0233e146107045780637ab4fec71461071b5780637b1039991461072e5780637ecebe001461075557806388c4caba146107745780638da5cb5b1461078757806393bbeac01461078f57806394bf804d146107b1578063958b51e8146107c457806395d89b41146107d75780639955a9d4146107df5780639c552ca8146107f25780639c5f00c2146108055780639fdb11b61461081c578063a07bee0b14610825578063a3f462d814610838578063a8144e481461084b578063a9059cbb14610853578063ac9650d814610866578063b187bd2614610879578063b3d7f6b914610881578063b460af9414610894578063b47e8a7d146108a7578063ba087652146108ba578063bf86d690146108cd578063c244245a146108e1578063c588d8d6146108ea578063c63d75b6146108fd578063c6e6f59214610910578063c879657214610923578063c8e819501461092b578063cbdf33d01461093e578063cdfb2b4e14610960578063ce96cb7714610968578063cf3090121461097b578063d1e884041461098f578063d446bbcc146109a2578063d505accf146109c2578063d6b0f484146109d5578063d7d4bf45146109dd578063d905777e146109f0578063dd62ed3e14610a03578063e1b1acb714610a2d578063ef8b30f714610a40578063f04f270714610a53578063f2fde38b14610a66575b5f80fd5b6103c661012c81565b6040519081526020015b60405180910390f35b6103c6610a79565b6103c66202a30081565b6103f3610a97565b6040516103d09190614d25565b61041361040e366004614d4f565b610b22565b005b6103c6610423366004614d68565b610c66565b61043b610436366004614d93565b610c76565b60405190151581526020016103d0565b6103c67f0000000000000000000000000000000000000000000000000000000067be4dd381565b6103c6610480366004614d68565b610cce565b610413610cf1565b6103c660025481565b60135461043b9060ff1681565b61043b6104b1366004614dbd565b600e6020525f908152604090205460ff1681565b61043b6104d3366004614dd8565b610d38565b6104ff7f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff90911681526020016103d0565b6103c6610d57565b610413610527366004614e23565b610dac565b6105537f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b6040516103d09190614e67565b61041361056e366004614dbd565b611051565b61057b61111f565b6040516103d09190614e7b565b6103c6610596366004614dbd565b6111a0565b60075461043b90600160d01b900460ff1681565b6103c66105bd366004614d68565b61121c565b6104136105d0366004614f04565b611237565b6104136105e3366004614d4f565b6113a4565b6104136105f6366004614d68565b611464565b61060e610609366004614d68565b6114e7565b6040516103d09190614f42565b61041361151e565b610413610631366004614dbd565b61157a565b6103c65f80516020615deb83398151915281565b6103c6610658366004614dbd565b60126020525f908152604090205481565b6105537f000000000000000000000000e52b0cce837f5de2d4d984a667a8117af47d4fb781565b6103c661069e366004614f53565b6115be565b6103c667016345785d8a000081565b6103c66106c0366004614dbd565b60036020525f908152604090205481565b6104136115ed565b61057b611600565b6106f46106ef366004614d4f565b61165c565b6040516103d09493929190614f81565b61070c6117a0565b6040516103d093929190615039565b610413610729366004614e23565b611a64565b6105537f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af34581565b6103c6610763366004614dbd565b60056020525f908152604090205481565b600f54610553906001600160a01b031681565b610553611b6c565b61043b61079d366004614d68565b600b6020525f908152604090205460ff1681565b6103c66107bf366004614f53565b611b7b565b6103c66107d2366004615186565b611baa565b6103f3611bc9565b6104136107ed3660046151e4565b611bd6565b610413610800366004614d68565b611e74565b60075461060e90600160d81b900463ffffffff1681565b6103c660115481565b610413610833366004614e23565b611ee6565b6103c6610846366004615186565b612046565b6103c661205c565b61043b610861366004614d93565b612075565b610413610874366004614f04565b612089565b61043b61210c565b6103c661088f366004614d68565b6121c5565b6103c66108a2366004615250565b6121e1565b6104136108b5366004615284565b61221c565b6103c66108c8366004615250565b61226f565b60075461043b90600160c81b900460ff1681565b6103c660105481565b6104136108f83660046152b9565b6122c0565b6103c661090b366004614dbd565b61237d565b6103c661091e366004614d68565b6123d3565b6104136123dd565b610413610939366004614f53565b612400565b61043b61094c366004614d4f565b600d6020525f908152604090205460ff1681565b61041361245c565b6103c6610976366004614dbd565b612491565b60075461043b90600160c01b900460ff1681565b61041361099d366004614d4f565b6124a4565b6007546109b5906001600160c01b031681565b6040516103d091906152e6565b6104136109d0366004615308565b6124e5565b6104136126f0565b600854610553906001600160a01b031681565b6103c66109fe366004614dbd565b61271f565b6103c6610a11366004615374565b600460209081525f928352604080842090915290825290205481565b61060e610a3b366004614d68565b612733565b6103c6610a4e366004614d68565b612742565b610413610a613660046153a0565b61275e565b610413610a74366004614dbd565b6128e8565b5f610a82612961565b610a8a612987565b610a926129b2565b905090565b5f8054610aa390615484565b80601f0160208091040260200160405190810160405280929190818152602001828054610acf90615484565b8015610b1a5780601f10610af157610100808354040283529160200191610b1a565b820191905f5260205f20905b815481529060010190602001808311610afd57829003601f168201915b505050505081565b610b2a612a72565b63ffffffff81165f908152600b602052604090205460ff16610b6a5780604051630871f35760e11b8152600401610b619190614f42565b60405180910390fd5b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316610b9d82612ad1565b6001600160a01b031614610c01577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610bd582612ad1565b60405163260d15b960e01b81526001600160a01b03928316600482015291166024820152604401610b61565b63ffffffff81165f908152600c6020526040902054600160a01b900460ff1615610c405780604051633c925c1760e11b8152600401610b619190614f42565b6007805463ffffffff909216600160d81b0263ffffffff60d81b19909216919091179055565b5f610c708261121c565b92915050565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290915f80516020615e9283398151915290610cbd9086815260200190565b60405180910390a350600192915050565b5f805f610cda5f612b57565b91509150610ce9848383612c3e565b949350505050565b610cf9612a72565b610d01612c4a565b6007805460ff60c81b1916600160c81b179055604051600181525f80516020615e32833981519152906020015b60405180910390a1565b5f610d4284612c75565b610d4d848484612cc9565b90505b9392505050565b5f7f00000000000000000000000000000000000000000000000000000000000000014614610d8757610a92612da3565b507fa9eb49ce53f8582b91ca3a7606a03df851bfe98a0bbd1cb53b83e5b96f8a249590565b610db4612a72565b5f808215610edd57600a8463ffffffff1681548110610dd557610dd56154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169150600a8563ffffffff1681548110610e1457610e146154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff1690508181600a8763ffffffff1681548110610e5557610e556154bc565b905f5260205f209060089182820401919006600402600a8863ffffffff1681548110610e8357610e836154bc565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff1602179055505050610ffa565b60098463ffffffff1681548110610ef657610ef66154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16915060098563ffffffff1681548110610f3557610f356154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff169050818160098763ffffffff1681548110610f7657610f766154bc565b905f5260205f20906008918282040191900660040260098863ffffffff1681548110610fa457610fa46154bc565b905f5260205f2090600891828204019190066004028491906101000a81548163ffffffff021916908363ffffffff1602179055508391906101000a81548163ffffffff021916908363ffffffff16021790555050505b6040805163ffffffff84811682528381166020830152878116828401528616606082015290517fb7c5df04749a3a06a9a7bf1a8142ccf2a4ee6cbf4709489e876a6e4eb3301e8a9181900360800190a15050505050565b611059612a72565b604051636777140560e11b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345169063ceee280a906110a5908490600401614e67565b5f6040518083038186803b1580156110bb575f80fd5b505afa1580156110cd573d5f803e3d5ffd5b5050506001600160a01b0382165f908152600e602052604090819020805460ff1916600190811790915590515f80516020615ed283398151915292506111149184916154d0565b60405180910390a150565b6060600a80548060200260200160405190810160405280929190818152602001828054801561119657602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff16815260200190600401906020826003010492830192600103820291508084116111595790505b5050505050905090565b6007545f90600160c81b900460ff16156111bb57505f919050565b6007546001600160c01b03165f806111d36001612b57565b91509150826001600160c01b031681106111f157505f949350505050565b5f611205826001600160c01b0386166154ff565b9050611212818484612e2a565b9695505050505050565b5f805f6112285f612b57565b91509150610ce9848383612e2a565b61123f612e36565b611247611b6c565b6001600160a01b0316336001600160a01b0316141580156112735750600f546001600160a01b03163314155b1561129157604051633d63583960e21b815260040160405180910390fd5b611299612c4a565b6112a1612961565b6007805460ff60d01b1916600160d01b1790555f8080806112c06129b2565b90506112eb601054670de0b6b3a76400006112db91906154ff565b8290670de0b6b3a7640000612e53565b9350611306601054670de0b6b3a76400006112db9190615512565b6002549093509150611322905061131d8587615660565b612e80565b5f61132b6129b2565b90508381108061133a57508281115b1561135e57808484604051630e7f213d60e31b8152600401610b619392919061566c565b6002548214611386576002548260405163030fc92b60e11b8152600401610b61929190615682565b50506007805460ff60d01b19169055506113a09050612ffe565b5050565b6113ac612a72565b604051635159d87f60e11b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345169063a2b3b0fe906113f8908490600401614f42565b5f6040518083038186803b15801561140e575f80fd5b505afa158015611420573d5f803e3d5ffd5b50505063ffffffff82165f908152600d602052604090819020805460ff1916600190811790915590515f80516020615eb28339815191529250611114918491615690565b61146c612a72565b67016345785d8a00008111156114a1578067016345785d8a000060405163146f176960e21b8152600401610b61929190615682565b60108054908290556040517fdf4be33b2e9e3dd4d9e0e85645aea428494a0644a72c51d6a15aedae6b66a3ff906114db9083908590615682565b60405180910390a15050565b600981815481106114f6575f80fd5b905f5260205f209060089182820401919006600402915054906101000a900463ffffffff1681565b611526612a72565b600754600160c81b900460ff16611550576040516359f6f82160e01b815260040160405180910390fd5b6007805460ff60c81b191690556040515f81525f80516020615e3283398151915290602001610d2e565b611582612a72565b6001600160a01b0381165f908152600e6020526040808220805460ff19169055515f80516020615ed283398151915291611114918491906154d0565b6013545f9060ff16156115e35760405162cf7d6f60e81b815260040160405180910390fd5b610d50838361300d565b6115f5612a72565b6115fe5f61309d565b565b60606009805480602002602001604051908101604052809291908181526020018280548015611196575f918252602091829020805463ffffffff1684529082028301929091600491018084116111595790505050505050905090565b600c6020525f9081526040902080546001820180546001600160a01b03831693600160a01b90930460ff1692919061169390615484565b80601f01602080910402602001604051908101604052809291908181526020018280546116bf90615484565b801561170a5780601f106116e15761010080835404028352916020019161170a565b820191905f5260205f20905b8154815290600101906020018083116116ed57829003601f168201915b50505050509080600201805461171f90615484565b80601f016020809104026020016040519081016040528092919081815260200182805461174b90615484565b80156117965780601f1061176d57610100808354040283529160200191611796565b820191905f5260205f20905b81548152906001019060200180831161177957829003601f168201915b5050505050905084565b600954600a5460609182918291905f6117b98284615512565b9050806001600160401b038111156117d3576117d36150a2565b6040519080825280602002602001820160405280156117fc578160200160208202803683370190505b509550806001600160401b03811115611817576118176150a2565b604051908082528060200260200182016040528015611840578160200160208202803683370190505b509450806001600160401b0381111561185b5761185b6150a2565b604051908082528060200260200182016040528015611884578160200160208202803683370190505b5093505f5b83811015611992576118d0600982815481106118a7576118a76154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16612ad1565b8782815181106118e2576118e26154bc565b60200260200101906001600160a01b031690816001600160a01b03168152505061194160098281548110611918576119186154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff166130ee565b868281518110611953576119536154bc565b6020026020010181815250505f858281518110611972576119726154bc565b9115156020928302919091019091015261198b816156a8565b9050611889565b505f5b82811015611a5b575f6119a88583615512565b90506119c0600a83815481106118a7576118a76154bc565b8882815181106119d2576119d26154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050611a08600a8381548110611918576119186154bc565b878281518110611a1a57611a1a6154bc565b6020026020010181815250506001868281518110611a3a57611a3a6154bc565b9115156020928302919091019091015250611a54816156a8565b9050611995565b50505050909192565b611a6c612a72565b5f81611ab45760098463ffffffff1681548110611a8b57611a8b6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611af2565b600a8463ffffffff1681548110611acd57611acd6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614611b2057604051637870bc1160e11b815260040160405180910390fd5b5f611b2a826130ee565b90508015611b5a57604051632b7553ad60e11b815263ffffffff8316600482015260248101829052604401610b61565b611b65858385613174565b5050505050565b6006546001600160a01b031690565b6013545f9060ff1615611ba05760405162cf7d6f60e81b815260040160405180910390fd5b610d508383613257565b5f611bb68484846132dd565b611bc0858561300d565b95945050505050565b60018054610aa390615484565b611bde612a72565b611be6612c4a565b63ffffffff83165f908152600b602052604090205460ff1615611c1e578260405163a9247d0360e01b8152600401610b619190614f42565b63ffffffff83165f908152600d602052604090205460ff16611c55578260405163293f683360e01b8152600401610b619190614f42565b5f805f7f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af3456001600160a01b03166331ad24f4876040518263ffffffff1660e01b8152600401611ca49190614f42565b5f60405180830381865afa158015611cbe573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611ce591908101906156c0565b92509250925083151582151514611d11578560405163552a75d160e11b8152600401610b619190614f42565b604080516080810182526001600160a01b0380861682528415156020808401918252838501868152606085018b905263ffffffff8c165f908152600c9092529490208351815492511515600160a01b026001600160a81b031990931693169290921717815591519091906001820190611d8a908261579e565b5060608201516002820190611d9f908261579e565b509050508115611de057600a54602011611dcf576040516308fe047f60e31b815260206004820152602401610b61565b611ddb600a88886133f3565b611e12565b600954602011611e06576040516308fe047f60e31b815260206004820152602401610b61565b611e12600988886133f3565b63ffffffff86165f908152600b602052604090819020805460ff19166001179055517fc4f8cb57c016f0b294fff2666f86fa6cfee9b03aed19f816ae4bf44b7e837bbb90611e639088908a90615859565b60405180910390a150505050505050565b611e7c612a72565b61012c811080611e8e57506202a30081115b15611eac57604051632f23f36f60e21b815260040160405180910390fd5b60118054908290556040517f227ff5c6b5ffb395236b09fd1b472bb128b36eaa17556633feefe28e94411f24906114db9083908590615682565b611eee612a72565b5f81611f365760098463ffffffff1681548110611f0d57611f0d6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16611f74565b600a8463ffffffff1681548110611f4f57611f4f6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff165b90508063ffffffff168363ffffffff1614158061201757506040516321a0f75360e01b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af34516906321a0f75390611fd8908690600401614f42565b602060405180830381865afa158015611ff3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120179190615870565b15612035576040516309953b5760e21b815260040160405180910390fd5b612040848484613174565b50505050565b5f6120528484846132dd565b611bc08585613257565b5f612065612961565b61206d612987565b610a926135b0565b5f61207f33612c75565b610d50838361379e565b5f5b81811015612107576120f68383838181106120a8576120a86154bc565b90506020028101906120ba919061588b565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525030939250506138019050565b50612100816156a8565b905061208b565b505050565b5f7f0000000000000000000000000000000000000000000000000000000067be4dd34210156121c057604051630ad85dff60e41b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345169063ad85dff090612181903090600401614e67565b602060405180830381865afa15801561219c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a929190615870565b505f90565b5f805f6121d26001612b57565b91509150610ce9848383613826565b5f6121ea612e36565b5f806121f55f613832565b91509150612204868383612c3e565b92506122128684878761394c565b5050610d50612ffe565b612224612a72565b600780546001600160c01b0319166001600160c01b0383161790556040517f7db520ee920d1ba9b37317ccb723d0593fdbb627fdc10f325cf254043ae71368906111149083906152e6565b5f612278612e36565b5f806122835f613832565b91509150612292868383612e2a565b9250825f036122b45760405163b8018d2560e01b815260040160405180910390fd5b6122128387878761394c565b6122c8612a72565b5f80841561230d575f6122d9610a79565b90506122f86122ea866127106158cd565b829061ffff16612710613a2e565b92506123096122ea866127106158ef565b9150505b612318600284613a4c565b600880546001600160a01b0319166001600160a01b0385161790558415611b65575f612342610a79565b90508281108061235157508181115b1561237557808383604051630e7f213d60e31b8152600401610b619392919061566c565b505050505050565b6007545f90600160c81b900460ff161561239857505f919050565b6007546002546001600160c01b0390911690818110156123ca576123c5816001600160c01b0384166154ff565b610ce9565b5f949350505050565b5f610c7082612742565b6123e5612e36565b6123ed612961565b6123f65f613832565b50506115fe612ffe565b612408612a72565b6124128282613a4c565b600f80546001600160a01b0319166001600160a01b0383169081179091556040517fc0f008b5949918c64044a073e77a2e2b28044120eb984a4126b92a121ac32464905f90a25050565b612464612a72565b6013805460ff191660019081179091556040519081525f80516020615e7283398151915290602001610d2e565b5f61249a612987565b610c70825f613b2a565b6124ac612a72565b63ffffffff81165f908152600d6020526040808220805460ff19169055515f80516020615eb28339815191529161111491849190615690565b4284101561252f5760405162461bcd60e51b815260206004820152601760248201527614115493525517d11150511312539157d1561412549151604a1b6044820152606401610b61565b5f600161253a610d57565b6001600160a01b038a81165f8181526005602090815260409182902080546001810190915582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98184015280840194909452938d166060840152608083018c905260a083019390935260c08083018b90528151808403909101815260e0830190915280519201919091206125d392916101000161590a565b604051602081830303815290604052805190602001208585856040515f81526020016040526040516126089493929190615925565b6020604051602081039080840390855afa158015612628573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b0381161580159061265e5750876001600160a01b0316816001600160a01b0316145b61269b5760405162461bcd60e51b815260206004820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152606401610b61565b6001600160a01b039081165f9081526004602090815260408083208a8516808552908352928190208990555188815291928a16915f80516020615e92833981519152910160405180910390a350505050505050565b6126f8612a72565b6013805460ff191690556040515f81525f80516020615e7283398151915290602001610d2e565b5f612728612987565b610c70826001613b2a565b600a81815481106114f6575f80fd5b5f805f61274f6001612b57565b91509150610ce9848383613b77565b60405163131119fb60e11b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345169063262233f6906127aa903390600401614e67565b602060405180830381865afa1580156127c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127e99190615870565b61280957604051600162cea27760e01b0319815260040160405180910390fd5b600754600160d01b900460ff166128335760405163026d802d60e01b815260040160405180910390fd5b5f61284082840184615943565b905061284b81612e80565b5f5b868110156128dc576128cc3387878481811061286b5761286b6154bc565b905060200201358a8a85818110612884576128846154bc565b905060200201356128959190615512565b8c8c858181106128a7576128a76154bc565b90506020020160208101906128bc9190614dbd565b6001600160a01b03169190613b83565b6128d5816156a8565b905061284d565b50505050505050505050565b6128f0612a72565b6001600160a01b0381166129555760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610b61565b61295e8161309d565b50565b61296961210c565b156115fe57604051633c8a755760e11b815260040160405180910390fd5b600754600160c01b900460ff16156115fe576040516332d15db560e11b815260040160405180910390fd5b5f805f6129be5f613bf7565b915091505f806129ce6001613bf7565b600854604051637563738b60e11b81529294509092506001600160a01b03169063eac6e71690612a2a9087908790879087907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401615987565b602060405180830381865afa158015612a45573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a6991906159ee565b94505050505090565b33612a7b611b6c565b6001600160a01b0316146115fe5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610b61565b63ffffffff81165f908152600c60205260408082208054915163e170a9bf60e01b81526001600160a01b0390921691829163e170a9bf91612b189160010190600401615a7e565b602060405180830381865afa158015612b33573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d509190615a90565b5f805f612b626129b2565b60025460075491925090600160c81b900460ff1615612b85579094909350915050565b5f807f000000000000000000000000e52b0cce837f5de2d4d984a667a8117af47d4fb76001600160a01b0316633a9f46df85858a6040518463ffffffff1660e01b8152600401612bd793929190615aab565b6040805180830381865afa158015612bf1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c159190615ac3565b91509150612c24848389613dc6565b935083612c318285615512565b9550955050505050915091565b5f610d4d848385612e53565b600754600160c81b900460ff16156115fe57604051633fb0b23b60e01b815260040160405180910390fd5b6001600160a01b0381165f9081526012602052604090205480156113a0575f60115482612ca29190615512565b905042811115612107578042604051634aa58ecb60e11b8152600401610b61929190615682565b6001600160a01b0383165f9081526004602090815260408083203384529091528120545f198114612d2257612cfe83826154ff565b6001600160a01b0386165f9081526004602090815260408083203384529091529020555b6001600160a01b0385165f9081526003602052604081208054859290612d499084906154ff565b90915550506001600160a01b038085165f81815260036020526040908190208054870190555190918716905f80516020615e5283398151915290612d909087815260200190565b60405180910390a3506001949350505050565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f5f604051612dd39190615aef565b604051908190038120612e0f92917fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc69046903090602001615b61565b60405160208183030381529060405280519060200120905090565b5f610d4d848484613a2e565b612e3e612987565b6007805460ff60c01b1916600160c01b179055565b828202811515841585830485141716612e6a575f80fd5b6001826001830304018115150290509392505050565b5f5b81518110156113a0575f828281518110612e9e57612e9e6154bc565b602090810291909101810151516001600160a01b0381165f908152600e90925260409091205490915060ff16612ee957806040516302f032c160e51b8152600401610b619190614e67565b5f5b838381518110612efd57612efd6154bc565b60200260200101516020015151811015612feb57612f63848481518110612f2657612f266154bc565b6020026020010151602001518281518110612f4357612f436154bc565b6020026020010151836001600160a01b031661380190919063ffffffff16565b50816001600160a01b03167f7445c6598e1b553f076d507692eab3dceef0d608757141b53e9e56aa8bbaf483858581518110612fa157612fa16154bc565b6020026020010151602001518381518110612fbe57612fbe6154bc565b6020026020010151604051612fd39190614d25565b60405180910390a2612fe4816156a8565b9050612eeb565b505080612ff7906156a8565b9050612e82565b6007805460ff60c01b19169055565b5f613016612e36565b5f806130226001613832565b91509150613031858383613b77565b9250825f036130535760405163328d31e360e11b815260040160405180910390fd5b6007546001600160c01b03166130698483615512565b111561308857604051630bbcb58960e41b815260040160405180910390fd5b613093858486613e20565b5050610c70612ffe565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b63ffffffff81165f908152600c602052604080822080549151637841536560e01b81526001600160a01b039092169182916378415365916131359160010190600401615a7e565b602060405180830381865afa158015613150573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d5091906159ee565b60075463ffffffff600160d81b9091048116908316036131a75760405163c5fe093960e01b815260040160405180910390fd5b80156131bd576131b8600a84613ec2565b6131c8565b6131c8600984613ec2565b63ffffffff82165f908152600b60209081526040808320805460ff19169055600c909152812080546001600160a81b03191681559061320a6001830182614c8e565b613217600283015f614c8e565b50507fa5cd0099b78b279c04987aa80ffffaf8fc8c8af4e7c7bce2686e8d01e2e1bd51828460405161324a929190615859565b60405180910390a1505050565b5f613260612e36565b5f8061326c6001613832565b9150915061327b858383613826565b9250825f0361329d5760405163b8018d2560e01b815260040160405180910390fd5b6007546001600160c01b03166132b38683615512565b11156132d257604051630bbcb58960e41b815260040160405180910390fd5b613093838686613e20565b60135460ff1615612107576132f461012c83615512565b4211156133145760405163021aec4f60e41b815260040160405180910390fd5b814210156133355760405163021aec4f60e41b815260040160405180910390fd5b604080515f80516020615deb833981519152602082015233918101919091526001600160a01b0384166060820152608081018390525f9061338e9060a00160405160208183030381529060405280519060200120614001565b90505f61339b8284614013565b600f549091506001600160a01b038083169116148015906133d557506133bf611b6c565b6001600160a01b0316816001600160a01b031614155b15611b6557604051633567d76d60e11b815260040160405180910390fd5b825480156135705783806134086001846154ff565b81548110613418576134186154bc565b5f9182526020808320600880840490910154855460018082018855968652928520918304909101805463ffffffff60046007958616810261010090810a83810219909416969097160290950a909204909316021790559061347990836154ff565b90505b8363ffffffff1681111561352057846134966001836154ff565b815481106134a6576134a66154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff168582815481106134dc576134dc6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550808061351890615b8d565b91505061347c565b5081848463ffffffff168154811061353a5761353a6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550612040565b5082546001810184555f93845260209093206008840401805460079094166004026101000a63ffffffff8181021990951692909416939093021790915550565b6009545f9081816001600160401b038111156135ce576135ce6150a2565b6040519080825280602002602001820160405280156135f7578160200160208202803683370190505b5090505f826001600160401b03811115613613576136136150a2565b60405190808252806020026020018201604052801561363c578160200160208202803683370190505b5090505f5b83811015613702575f6009828154811061365d5761365d6154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16905061368c81614035565b83838151811061369e5761369e6154bc565b60200260200101818152505f036136b557506136f2565b6136be81612ad1565b8483815181106136d0576136d06154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050505b6136fb816156a8565b9050613641565b5060085460405163b333a17560e01b81526001600160a01b039091169063b333a1759061375790859085907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401615ba2565b602060405180830381865afa158015613772573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061379691906159ee565b935050505090565b335f908152600360205260408120805483919083906137be9084906154ff565b90915550506001600160a01b0383165f81815260036020526040908190208054850190555133905f80516020615e5283398151915290610cbd9086815260200190565b6060610d508383604051806060016040528060278152602001615e0b602791396140ea565b5f610d4d848484612e53565b5f805f61383d6129b2565b60025460075491925090600160c81b900460ff1615613860579094909350915050565b6040516312325b5d60e21b81526001600160a01b037f000000000000000000000000e52b0cce837f5de2d4d984a667a8117af47d4fb716906348c96d74906138b090859085908a90600401615aab565b60408051808303815f875af19250505080156138e9575060408051601f3d908101601f191682019092526138e691810190615ac3565b60015b6138f7579094909350915050565b8015613934576139277f000000000000000000000000e52b0cce837f5de2d4d984a667a8117af47d4fb782614154565b6139318184615512565b92505b61393f848389613dc6565b9792965091945050505050565b613958848484846141ab565b336001600160a01b038216146139c3576001600160a01b0381165f9081526004602090815260408083203384529091529020545f1981146139c15761399d84826154ff565b6001600160a01b0383165f9081526004602090815260408083203384529091529020555b505b6139cd81846141c0565b806001600160a01b0316826001600160a01b0316336001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8787604051613a1c929190615682565b60405180910390a4612040848361421f565b828202811515841585830485141716613a45575f80fd5b0492915050565b815f03613a6c57604051631218237b60e31b815260040160405180910390fd5b806001600160a01b03167f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af3456001600160a01b031663b93f9b0a846040518263ffffffff1660e01b8152600401613ac491815260200190565b602060405180830381865afa158015613adf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b039190615a90565b6001600160a01b0316146113a057604051632105ff5560e11b815260040160405180910390fd5b6001600160a01b0382165f908152601260205260408120548015613b6d575f60115482613b579190615512565b905042811115613b6b575f92505050610c70565b505b610ce98484614579565b5f610d4d848385613a2e565b5f60405163a9059cbb60e01b815283600482015282602482015260205f6044835f895af13d15601f3d1160015f5114161716915050806120405760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610b61565b6060805f83613c07576009613c0a565b600a5b805480602002602001604051908101604052809291908181526020018280548015613c7d57602002820191905f5260205f20905f905b82829054906101000a900463ffffffff1663ffffffff1681526020019060040190602082600301049283019260010382029150808411613c405790505b505050505090505f815190505f816001600160401b03811115613ca257613ca26150a2565b604051908082528060200260200182016040528015613ccb578160200160208202803683370190505b5090505f826001600160401b03811115613ce757613ce76150a2565b604051908082528060200260200182016040528015613d10578160200160208202803683370190505b5090505f5b83811015613db9575f858281518110613d3057613d306154bc565b60200260200101519050613d43816130ee565b838381518110613d5557613d556154bc565b60200260200101818152505f03613d6c5750613da9565b613d7581612ad1565b848381518110613d8757613d876154bc565b60200260200101906001600160a01b031690816001600160a01b031681525050505b613db2816156a8565b9050613d15565b5090969095509350505050565b5f8261ffff165f03613dd9575082610d50565b8115613e0357613dfc613dee846127106158ef565b859061ffff16612710612e53565b9050610d50565b610d4d613e12846127106158cd565b859061ffff16612710613a2e565b613e2b8383836145f4565b613e606001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2163330866146b9565b613e6a8183614154565b806001600160a01b0316336001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d78585604051613eaf929190615682565b60405180910390a3612107838383614738565b815463ffffffff82168111613f0f5760405162461bcd60e51b8152602060048201526013602482015272496e646578206f7574206f6620626f756e647360681b6044820152606401610b61565b63ffffffff82165b613f226001836154ff565b811015613fbf5783613f35826001615512565b81548110613f4557613f456154bc565b905f5260205f2090600891828204019190066004029054906101000a900463ffffffff16848281548110613f7b57613f7b6154bc565b905f5260205f2090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff1602179055508080613fb7906156a8565b915050613f17565b5082805480613fd057613fd0615bdf565b5f8281526020902060085f1990920191820401805463ffffffff600460078516026101000a02191690559055505050565b5f610c7061400d61475d565b8361484a565b5f805f614020858561487c565b9150915061402d816148be565b509392505050565b63ffffffff81165f908152600c6020526040812054600160a01b900460ff161561406057505f919050565b63ffffffff82165f908152600c60205260409081902080549151637d2872e960e11b81526001600160a01b039092169163fa50e5d2916140ab91600182019160020190600401615bf3565b602060405180830381865afa1580156140c6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c7091906159ee565b60605f80856001600160a01b0316856040516141069190615c17565b5f60405180830381855af49150503d805f811461413e576040519150601f19603f3d011682016040523d82523d5f602084013e614143565b606091505b509150915061121286838387614a02565b8060025f8282546141659190615512565b90915550506001600160a01b0382165f818152600360209081526040808320805486019055518481525f80516020615e5283398151915291015b60405180910390a35050565b6141b481612c75565b61204084848484614a7a565b6001600160a01b0382165f90815260036020526040812080548392906141e79084906154ff565b90915550506002805482900390556040518181525f906001600160a01b038416905f80516020615e528339815191529060200161419f565b61424660405180608001604052805f81526020015f81526020015f81526020015f81525090565b600854604051630226614760e01b81526001600160a01b0390911690630226614790614296907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290600401614e67565b602060405180830381865afa1580156142b1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142d591906159ee565b60408201526143057f0000000000000000000000000000000000000000000000000000000000000012600a615d12565b60608201526009545f5b81811015614556575f6009828154811061432b5761432b6154bc565b5f9182526020822060088204015460079091166004026101000a900463ffffffff16915061435882614035565b9050805f03614368575050614546565b5f61437283612ad1565b600854604051630226614760e01b81529192506001600160a01b0316906302266147906143a3908490600401614e67565b602060405180830381865afa1580156143be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143e291906159ee565b865f018181525050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015614426573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061444a9190615d20565b61445590600a615d12565b6020870181905286515f91829161447f9161447887670de0b6b3a7640000615d3b565b9190613a2e565b905061449e8860600151896040015183613a2e9092919063ffffffff16565b91506144b2670de0b6b3a764000083615d52565b9150505f89821115614515575f6144e089604001518a606001518d670de0b6b3a76400006144789190615d3b565b60208a01518a519192506144f691839190613a2e565b915061450a670de0b6b3a764000083615d52565b91505f9a5050614524565b5082614521828b6154ff565b99505b61452f85828b614a82565b895f03614540575050505050614556565b50505050505b61454f816156a8565b905061430f565b5083156120405760405163089d698560e41b815260048101859052602401610b61565b5f614582612961565b5f8061458d5f612b57565b6001600160a01b0387165f90815260036020526040812054929450909250906145b7908484612e2a565b90505f6145c26135b0565b9050808211156145d257806145d4565b815b945085156145ea576145e7858585613b77565b94505b5050505092915050565b6145ff838383614b12565b336001600160a01b0382161461210757604051635551e1b560e01b81526001600160a01b037f0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af3451690635551e1b59061465b903390600401614e67565b602060405180830381865afa158015614676573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061469a9190615870565b6121075733604051634d1b6c4d60e01b8152600401610b619190614e67565b5f6040516323b872dd60e01b815284600482015283602482015282604482015260205f6064835f8a5af13d15601f3d1160015f511416171691505080611b655760405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606401610b61565b6001600160a01b0381165f908152601260205260409020429055612107838383614b22565b5f306001600160a01b037f000000000000000000000000ede905b2732ffcb73b95f5facb2a0f241b30bd50161480156147b557507f000000000000000000000000000000000000000000000000000000000000000146145b156147df57507f8fdbebb2d14c0dd87b62136d448c8efa43960bee9f4663f0a9d78d1f0867200c90565b610a927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f7fd7b94009bf186664aaa99c83a87fa264a1c8d67b4d273af4af60825f2b27c7947fe6bbd6277e1bf288eed5e8d1780f9a50b239e86b153736bceebccf4ea79d90b3614b3c565b5f828260405160200161485e92919061590a565b60405160208183030381529060405280519060200120905092915050565b5f8082516041036148b0576020830151604084015160608501515f1a6148a487828585614b75565b945094505050506148b7565b505f905060025b9250929050565b5f8160048111156148d1576148d1615d71565b036148d95750565b60018160048111156148ed576148ed615d71565b036149355760405162461bcd60e51b815260206004820152601860248201527745434453413a20696e76616c6964207369676e617475726560401b6044820152606401610b61565b600281600481111561494957614949615d71565b036149965760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610b61565b60038160048111156149aa576149aa615d71565b0361295e5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610b61565b60608315614a705782515f03614a69576001600160a01b0385163b614a695760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610b61565b5081610ce9565b610ce98383614c1a565b612040612961565b63ffffffff83165f908152600c602052604090819020805491516001600160a01b0390921691611b659163c9111bd760e01b91614ad091879187916001810191600290910190602401615d85565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526001600160a01b03831690613801565b614b1a612c4a565b612107612961565b60075461210790600160d81b900463ffffffff1684614c44565b5f8383834630604051602001614b56959493929190615b61565b6040516020818303038152906040528051906020012090509392505050565b5f806fa2a8918ca85bafe22016d0b997e4df60600160ff1b03831115614ba057505f90506003614c11565b5f6001878787876040515f8152602001604052604051614bc39493929190615925565b6020604051602081039080840390855afa158015614be3573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614c0b575f60019250925050614c11565b91505f90505b94509492505050565b815115614c2a5781518083602001fd5b8060405162461bcd60e51b8152600401610b619190614d25565b63ffffffff82165f908152600c602052604090819020805491516001600160a01b0390921691612040916369445c3160e01b91614ad0918691600182019160020190602401615dc0565b508054614c9a90615484565b5f825580601f10614ca9575050565b601f0160209004905f5260205f209081019061295e91905b80821115614cd4575f8155600101614cc1565b5090565b5f5b83811015614cf2578181015183820152602001614cda565b50505f910152565b5f8151808452614d11816020860160208601614cd8565b601f01601f19169290920160200192915050565b602081525f610d506020830184614cfa565b803563ffffffff81168114614d4a575f80fd5b919050565b5f60208284031215614d5f575f80fd5b610d5082614d37565b5f60208284031215614d78575f80fd5b5035919050565b6001600160a01b038116811461295e575f80fd5b5f8060408385031215614da4575f80fd5b8235614daf81614d7f565b946020939093013593505050565b5f60208284031215614dcd575f80fd5b8135610d5081614d7f565b5f805f60608486031215614dea575f80fd5b8335614df581614d7f565b92506020840135614e0581614d7f565b929592945050506040919091013590565b801515811461295e575f80fd5b5f805f60608486031215614e35575f80fd5b614e3e84614d37565b9250614e4c60208501614d37565b91506040840135614e5c81614e16565b809150509250925092565b6001600160a01b0391909116815260200190565b602080825282518282018190525f9190848201906040850190845b81811015614eb857835163ffffffff1683529284019291840191600101614e96565b50909695505050505050565b5f8083601f840112614ed4575f80fd5b5081356001600160401b03811115614eea575f80fd5b6020830191508360208260051b85010111156148b7575f80fd5b5f8060208385031215614f15575f80fd5b82356001600160401b03811115614f2a575f80fd5b614f3685828601614ec4565b90969095509350505050565b63ffffffff91909116815260200190565b5f8060408385031215614f64575f80fd5b823591506020830135614f7681614d7f565b809150509250929050565b6001600160a01b038516815283151560208201526080604082018190525f90614fac90830185614cfa565b8281036060840152614fbe8185614cfa565b979650505050505050565b5f8151808452602080850194508084015f5b838110156150005781516001600160a01b031687529582019590820190600101614fdb565b509495945050505050565b5f8151808452602080850194508084015f5b838110156150005781518752958201959082019060010161501d565b606081525f61504b6060830186614fc9565b60208382038185015261505e828761500b565b848103604086015285518082528287019350908201905f5b81811015615094578451151583529383019391830191600101615076565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b03811182821017156150d8576150d86150a2565b60405290565b604051601f8201601f191681016001600160401b0381118282101715615106576151066150a2565b604052919050565b5f6001600160401b03821115615126576151266150a2565b50601f01601f191660200190565b5f82601f830112615143575f80fd5b81356151566151518261510e565b6150de565b81815284602083860101111561516a575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f8060808587031215615199575f80fd5b8435935060208501356151ab81614d7f565b92506040850135915060608501356001600160401b038111156151cc575f80fd5b6151d887828801615134565b91505092959194509250565b5f805f80608085870312156151f7575f80fd5b61520085614d37565b935061520e60208601614d37565b925060408501356001600160401b03811115615228575f80fd5b61523487828801615134565b925050606085013561524581614e16565b939692955090935050565b5f805f60608486031215615262575f80fd5b83359250602084013561527481614d7f565b91506040840135614e5c81614d7f565b5f60208284031215615294575f80fd5b81356001600160c01b0381168114610d50575f80fd5b61ffff8116811461295e575f80fd5b5f805f606084860312156152cb575f80fd5b83356152d681614e16565b92506020840135615274816152aa565b6001600160c01b0391909116815260200190565b60ff8116811461295e575f80fd5b5f805f805f805f60e0888a03121561531e575f80fd5b873561532981614d7f565b9650602088013561533981614d7f565b955060408801359450606088013593506080880135615357816152fa565b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215615385575f80fd5b823561539081614d7f565b91506020830135614f7681614d7f565b5f805f805f805f806080898b0312156153b7575f80fd5b88356001600160401b03808211156153cd575f80fd5b6153d98c838d01614ec4565b909a50985060208b01359150808211156153f1575f80fd5b6153fd8c838d01614ec4565b909850965060408b0135915080821115615415575f80fd5b6154218c838d01614ec4565b909650945060608b0135915080821115615439575f80fd5b818b0191508b601f83011261544c575f80fd5b81358181111561545a575f80fd5b8c602082850101111561546b575f80fd5b6020830194508093505050509295985092959890939650565b600181811c9082168061549857607f821691505b6020821081036154b657634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52603260045260245ffd5b6001600160a01b039290921682521515602082015260400190565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610c7057610c706154eb565b80820180821115610c7057610c706154eb565b5f6001600160401b0382111561553d5761553d6150a2565b5060051b60200190565b5f61555461515184615525565b8381529050602080820190600585901b840186811115615572575f80fd5b845b81811015615655576001600160401b038135811015615591575f80fd5b813587016040818b0312156155a4575f80fd5b6155ac6150b6565b6155b68235614d7f565b8135815285820135838111156155ca575f80fd5b8083019250508a601f8301126155de575f80fd5b81356155ec61515182615525565b81815260059190911b8301870190878101908d83111561560a575f80fd5b8885015b8381101561563f578681351115615623575f80fd5b6156328f8b8335890101615134565b835291890191890161560e565b5083890152505086525050928201928201615574565b505050509392505050565b5f610d50368484615547565b9283526020830191909152604082015260600190565b918252602082015260400190565b63ffffffff9290921682521515602082015260400190565b5f600182016156b9576156b96154eb565b5060010190565b5f805f606084860312156156d2575f80fd5b83516156dd81614d7f565b60208501519093506156ee81614e16565b60408501519092506001600160401b03811115615709575f80fd5b8401601f81018613615719575f80fd5b80516157276151518261510e565b81815287602083850101111561573b575f80fd5b61574c826020830160208601614cd8565b8093505050509250925092565b601f821115612107575f81815260208120601f850160051c8101602086101561577f5750805b601f850160051c820191505b818110156123755782815560010161578b565b81516001600160401b038111156157b7576157b76150a2565b6157cb816157c58454615484565b84615759565b602080601f8311600181146157fe575f84156157e75750858301515b5f19600386901b1c1916600185901b178555612375565b5f85815260208120601f198616915b8281101561582c5788860151825594840194600190910190840161580d565b508582101561584957878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b63ffffffff92831681529116602082015260400190565b5f60208284031215615880575f80fd5b8151610d5081614e16565b5f808335601e198436030181126158a0575f80fd5b8301803591506001600160401b038211156158b9575f80fd5b6020019150368190038213156148b7575f80fd5b61ffff8281168282160390808211156158e8576158e86154eb565b5092915050565b61ffff8181168382160190808211156158e8576158e86154eb565b61190160f01b81526002810192909252602282015260420190565b93845260ff9290921660208401526040830152606082015260800190565b5f60208284031215615953575f80fd5b81356001600160401b03811115615968575f80fd5b8201601f81018413615978575f80fd5b610ce984823560208401615547565b60a081525f61599960a0830188614fc9565b82810360208401526159ab818861500b565b905082810360408401526159bf8187614fc9565b905082810360608401526159d3818661500b565b91505060018060a01b03831660808301529695505050505050565b5f602082840312156159fe575f80fd5b5051919050565b5f8154615a1181615484565b808552602060018381168015615a2e5760018114615a4857615a73565b60ff1985168884015283151560051b880183019550615a73565b865f52825f205f5b85811015615a6b5781548a8201860152908301908401615a50565b890184019650505b505050505092915050565b602081525f610d506020830184615a05565b5f60208284031215615aa0575f80fd5b8151610d5081614d7f565b92835260208301919091521515604082015260600190565b5f8060408385031215615ad4575f80fd5b8251615adf816152aa565b6020939093015192949293505050565b5f808354615afc81615484565b60018281168015615b145760018114615b2957615b55565b60ff1984168752821515830287019450615b55565b875f526020805f205f5b85811015615b4c5781548a820152908401908201615b33565b50505082870194505b50929695505050505050565b9485526020850193909352604084019190915260608301526001600160a01b0316608082015260a00190565b5f81615b9b57615b9b6154eb565b505f190190565b606081525f615bb46060830186614fc9565b8281036020840152615bc6818661500b565b91505060018060a01b0383166040830152949350505050565b634e487b7160e01b5f52603160045260245ffd5b604081525f615c056040830185615a05565b8281036020840152611bc08185615a05565b5f8251615c28818460208701614cd8565b9190910192915050565b600181815b80851115615c6c57815f1904821115615c5257615c526154eb565b80851615615c5f57918102915b93841c9390800290615c37565b509250929050565b5f82615c8257506001610c70565b81615c8e57505f610c70565b8160018114615ca45760028114615cae57615cca565b6001915050610c70565b60ff841115615cbf57615cbf6154eb565b50506001821b610c70565b5060208310610133831016604e8410600b8410161715615ced575081810a610c70565b615cf78383615c32565b805f1904821115615d0a57615d0a6154eb565b029392505050565b5f610d5060ff841683615c74565b5f60208284031215615d30575f80fd5b8151610d50816152fa565b8082028115828204841417610c7057610c706154eb565b5f82615d6c57634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52602160045260245ffd5b8481526001600160a01b03841660208201526080604082018190525f90615dae90830185615a05565b8281036060840152614fbe8185615a05565b838152606060208201525f615dd86060830185615a05565b82810360408401526112128185615a0556feb3e99edbe0a6168c4e5e3779981b987a4957b59c9d41c08b56a5fd1e774fbe13416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564b8527b93c36dabdfe078af41be789ba946a4adcfeafcf9d8de21d51629859e3cddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efc6dc7171957873ef39aa9e363c5872095067708a59f84b8e467223fb726e49ea8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925ea052d1fb1ecba6aaf6bd32e92f20e7b6a094eaa478248322cc8ff024a90978f572570e8a43782d3698a3fed258c72f9c201c19be1e4764e359d1adc8f00af7aa2646970667358221220d1d96c33fbdcbe143392b9b1527360ff9557035615a71d8aa9c8b591e6e1c4f264736f6c63430008150033

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

0000000000000000000000000269aaa07af2793ebb713ba787316ef579a5299a0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc200000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000038d7ea4c680000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000f537761617020574554482046756e6400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007737770574554480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001

-----Decoded View---------------
Arg [0] : _owner (address): 0x0269aaa07af2793EBB713ba787316Ef579a5299A
Arg [1] : _registry (address): 0x5c52d72694D171a2fa38AC98DFB49598f35aF345
Arg [2] : _asset (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [3] : _name (string): Swaap WETH Fund
Arg [4] : _symbol (string): swpWETH
Arg [5] : _holdingPosition (uint32): 1
Arg [6] : _holdingPositionConfig (bytes): 0x0000000000000000000000000000000000000000000000000000000000000001
Arg [7] : _initialDeposit (uint256): 1000000000000000
Arg [8] : _shareSupplyCap (uint192): 6277101735386680763835789423207666416102355444464034512895

-----Encoded View---------------
15 Constructor Arguments found :
Arg [0] : 0000000000000000000000000269aaa07af2793ebb713ba787316ef579a5299a
Arg [1] : 0000000000000000000000005c52d72694d171a2fa38ac98dfb49598f35af345
Arg [2] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000160
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [6] : 00000000000000000000000000000000000000000000000000000000000001a0
Arg [7] : 00000000000000000000000000000000000000000000000000038d7ea4c68000
Arg [8] : 0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff
Arg [9] : 000000000000000000000000000000000000000000000000000000000000000f
Arg [10] : 537761617020574554482046756e640000000000000000000000000000000000
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000007
Arg [12] : 7377705745544800000000000000000000000000000000000000000000000000
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [14] : 0000000000000000000000000000000000000000000000000000000000000001


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.