ETH Price: $1,798.64 (+7.33%)

Contract

0xC877B52c628Dba77fC55F1DDb140747155C9b39D
 
Transaction Hash
Method
Block
From
To
Withdraw52917672024-06-26 9:15:49301 days ago1719393349IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002120.01004645
Withdraw52904572024-06-26 8:32:09301 days ago1719390729IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001840.01320543
Withdraw52898292024-06-26 8:11:13301 days ago1719389473IN
Juice Finance: USDB Collateral Vault
0 ETH0.00000160.01320544
Withdraw52890632024-06-26 7:45:41301 days ago1719387941IN
Juice Finance: USDB Collateral Vault
0 ETH0.00000270.0131574
Create Account52889532024-06-26 7:42:01301 days ago1719387721IN
Juice Finance: USDB Collateral Vault
0 ETH0.000005420.01173506
Deposit52887002024-06-26 7:33:35301 days ago1719387215IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001710.01225275
Withdraw52886942024-06-26 7:33:23301 days ago1719387203IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001790.0087486
Create Account52886852024-06-26 7:33:05301 days ago1719387185IN
Juice Finance: USDB Collateral Vault
0 ETH0.000005690.01232064
Withdraw52886742024-06-26 7:32:43301 days ago1719387163IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001960.0093
Withdraw52886682024-06-26 7:32:31301 days ago1719387151IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001490.01230292
Withdraw52885232024-06-26 7:27:41301 days ago1719386861IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002080.01291634
Withdraw52884352024-06-26 7:24:45301 days ago1719386685IN
Juice Finance: USDB Collateral Vault
0 ETH0.00000160.01319236
Create Account52882682024-06-26 7:19:11301 days ago1719386351IN
Juice Finance: USDB Collateral Vault
0 ETH0.000006080.01315753
Withdraw52876512024-06-26 6:58:37301 days ago1719385117IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001660.01306369
Withdraw52875012024-06-26 6:53:37301 days ago1719384817IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002330.01316433
Withdraw52874882024-06-26 6:53:11301 days ago1719384791IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002730.01326589
Create Account52857682024-06-26 5:55:51301 days ago1719381351IN
Juice Finance: USDB Collateral Vault
0 ETH0.000006070.0131463
Withdraw52852972024-06-26 5:40:09301 days ago1719380409IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001290.0102
Withdraw52852852024-06-26 5:39:45301 days ago1719380385IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002150.0102
Withdraw52834592024-06-26 4:38:53301 days ago1719376733IN
Juice Finance: USDB Collateral Vault
0 ETH0.00000160.01321179
Withdraw52833592024-06-26 4:35:33301 days ago1719376533IN
Juice Finance: USDB Collateral Vault
0 ETH0.000002870.01315084
Create Account52833362024-06-26 4:34:47301 days ago1719376487IN
Juice Finance: USDB Collateral Vault
0 ETH0.000006040.01307629
Withdraw52829962024-06-26 4:23:27301 days ago1719375807IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001310.00910806
Deposit52829692024-06-26 4:22:33301 days ago1719375753IN
Juice Finance: USDB Collateral Vault
0 ETH0.000001230.00903608
Create Account52829252024-06-26 4:21:05301 days ago1719375665IN
Juice Finance: USDB Collateral Vault
0 ETH0.000004140.00897189
VIEW ADVANCED FILTER

Latest 25 internal transactions (View All)

Parent Transaction Hash Block From To
182657092025-04-22 17:00:3321 hrs ago1745341233
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
181595052025-04-20 6:00:253 days ago1745128825
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
180838972025-04-18 12:00:095 days ago1744977609
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
180749072025-04-18 7:00:295 days ago1744959629
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
179753872025-04-15 23:43:097 days ago1744760589
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
179563232025-04-15 13:07:418 days ago1744722461
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
179072702025-04-14 9:52:359 days ago1744624355
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
177851102025-04-11 14:00:3512 days ago1744380035
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
175901912025-04-07 1:43:1716 days ago1743990197
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
175860022025-04-06 23:23:3916 days ago1743981819
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
175814262025-04-06 20:51:0716 days ago1743972667
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
175762732025-04-06 17:59:2116 days ago1743962361
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
175762682025-04-06 17:59:1116 days ago1743962351
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174987972025-04-04 22:56:4918 days ago1743807409
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174415202025-04-03 15:07:3519 days ago1743692855
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174415172025-04-03 15:07:2919 days ago1743692849
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174415142025-04-03 15:07:2319 days ago1743692843
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174117232025-04-02 22:34:2120 days ago1743633261
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116842025-04-02 22:33:0320 days ago1743633183
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116672025-04-02 22:32:2920 days ago1743633149
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116592025-04-02 22:32:1320 days ago1743633133
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116412025-04-02 22:31:3720 days ago1743633097
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116302025-04-02 22:31:1520 days ago1743633075
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
174116242025-04-02 22:31:0320 days ago1743633063
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
172749962025-03-30 18:36:4723 days ago1743359807
Juice Finance: USDB Collateral Vault
 Contract Creation0 ETH
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
JuiceAccountManager

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 50 runs

Other Settings:
paris EvmVersion, GNU GPLv3 license
File 1 of 73 : JuiceAccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "../managers/StrategyAccountManager.sol";
import "../interfaces/IAssetPriceProvider.sol";
import "../libraries/accounts/AccountLib.sol";
import "../libraries/Errors.sol";
import "./JuiceAccount.sol";
import "../managers/CollateralAccountManager.sol";
import "./periphery/BlastGas.sol";
import "./periphery/BlastPoints.sol";

abstract contract JuiceAccountManagerEvents {
    /// @notice When yield is accrued
    event YieldAccrued(uint256 amount);
    event AutoCompoundingToggled(bool isAutoCompounding);
}

/// @title JuiceAccountManager supports one account implementation
/// @dev Facilitates collateralization of WETH.
/// @notice The AccountManager contract deploys Account contracts.
contract JuiceAccountManager is CollateralAccountManager, JuiceAccountManagerEvents, BlastGas, BlastPoints {
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;
    using Address for address;

    uint256 public constant MINIMUM_COMPOUND_AMOUNT = 1e6;

    bool public isAutoCompounding;

    /// @notice Constructs the factory
    /// @param params The parameters for the JuiceAccountManager
    constructor(
        address protocolGovernor_,
        address pointsOperator_,
        bool isAutoCompounding_,
        InitParams memory params
    )
        CollateralAccountManager(protocolGovernor_, params)
    {
        __BlastGas_init(protocolGovernor_);
        __BlastPoints_init(protocolGovernor_, pointsOperator_);
        IERC20Rebasing(address(params.collateral)).configure(YieldMode.CLAIMABLE);
        isAutoCompounding = isAutoCompounding_;
    }

    function setAutoCompounding(bool _isAutoCompounding) public onlyOwner {
        isAutoCompounding = _isAutoCompounding;
    }

    /// @dev Takes assets from `msg.sender`, deposits them into the contract, and mints shares to the receiver.
    /// The shares are nontransferrable and reside in the receiver's address, but are used to credit the receiver's
    /// account contract.
    function deposit(
        uint256 assets,
        address receiver
    )
        public
        override
        nonReentrant
        returns (uint256 updatedAssets, uint256 shares)
    {
        if (isAutoCompounding) {
            compound();
        }
        (updatedAssets, shares) = _deposit(assets, msg.sender, receiver);
    }

    /// @dev Burns shares from the account of `msg.sender` and sends them to the receiver.
    /// `msg.sender` must be owner of account that owns the shares.
    function withdraw(
        uint256 shares,
        address receiver
    )
        public
        override
        nonReentrant
        returns (uint256 updatedAssets, uint256 updatedShares)
    {
        if (isAutoCompounding) {
            compound();
        }
        (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares);
    }

    function compound() public returns (uint256 earned) {
        IERC20Rebasing collateral = IERC20Rebasing(address(_collateral));
        earned = collateral.getClaimableAmount(address(this));

        // Avoid compounding dust.
        // We assume the claim just works.
        if (earned >= MINIMUM_COMPOUND_AMOUNT) {
            _totalCollateralAssets += earned;
            earned = IERC20Rebasing(address(_collateral)).claim(address(this), earned);
            emit YieldAccrued(earned);
        }
    }

    function totalAssets() public view virtual override returns (uint256) {
        return _totalCollateralAssets + IERC20Rebasing(address(_collateral)).getClaimableAmount(address(this));
    }
}

File 2 of 73 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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 3 of 73 : Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

File 4 of 73 : Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev A clone instance deployment failed.
     */
    error ERC1167FailedCreateClone();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert ERC1167FailedCreateClone();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

File 5 of 73 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

File 6 of 73 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

File 7 of 73 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 8 of 73 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

File 9 of 73 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

File 10 of 73 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) 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 FailedInnerCall();
        }
    }
}

File 11 of 73 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

File 12 of 73 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 13 of 73 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

File 14 of 73 : EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 15 of 73 : Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.

/*//////////////////////////////////////////////////////////////////////////
                                CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);

/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);

/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();

/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);

/*//////////////////////////////////////////////////////////////////////////
                                    CONSTANTS
//////////////////////////////////////////////////////////////////////////*/

/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;

/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;

/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;

/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;

/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;

/*//////////////////////////////////////////////////////////////////////////
                                    FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
    unchecked {
        // Start from 0.5 in the 192.64-bit fixed-point format.
        result = 0x800000000000000000000000000000000000000000000000;

        // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
        //
        // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
        // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
        // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
        // we know that `x & 0xFF` is also 1.
        if (x & 0xFF00000000000000 > 0) {
            if (x & 0x8000000000000000 > 0) {
                result = (result * 0x16A09E667F3BCC909) >> 64;
            }
            if (x & 0x4000000000000000 > 0) {
                result = (result * 0x1306FE0A31B7152DF) >> 64;
            }
            if (x & 0x2000000000000000 > 0) {
                result = (result * 0x1172B83C7D517ADCE) >> 64;
            }
            if (x & 0x1000000000000000 > 0) {
                result = (result * 0x10B5586CF9890F62A) >> 64;
            }
            if (x & 0x800000000000000 > 0) {
                result = (result * 0x1059B0D31585743AE) >> 64;
            }
            if (x & 0x400000000000000 > 0) {
                result = (result * 0x102C9A3E778060EE7) >> 64;
            }
            if (x & 0x200000000000000 > 0) {
                result = (result * 0x10163DA9FB33356D8) >> 64;
            }
            if (x & 0x100000000000000 > 0) {
                result = (result * 0x100B1AFA5ABCBED61) >> 64;
            }
        }

        if (x & 0xFF000000000000 > 0) {
            if (x & 0x80000000000000 > 0) {
                result = (result * 0x10058C86DA1C09EA2) >> 64;
            }
            if (x & 0x40000000000000 > 0) {
                result = (result * 0x1002C605E2E8CEC50) >> 64;
            }
            if (x & 0x20000000000000 > 0) {
                result = (result * 0x100162F3904051FA1) >> 64;
            }
            if (x & 0x10000000000000 > 0) {
                result = (result * 0x1000B175EFFDC76BA) >> 64;
            }
            if (x & 0x8000000000000 > 0) {
                result = (result * 0x100058BA01FB9F96D) >> 64;
            }
            if (x & 0x4000000000000 > 0) {
                result = (result * 0x10002C5CC37DA9492) >> 64;
            }
            if (x & 0x2000000000000 > 0) {
                result = (result * 0x1000162E525EE0547) >> 64;
            }
            if (x & 0x1000000000000 > 0) {
                result = (result * 0x10000B17255775C04) >> 64;
            }
        }

        if (x & 0xFF0000000000 > 0) {
            if (x & 0x800000000000 > 0) {
                result = (result * 0x1000058B91B5BC9AE) >> 64;
            }
            if (x & 0x400000000000 > 0) {
                result = (result * 0x100002C5C89D5EC6D) >> 64;
            }
            if (x & 0x200000000000 > 0) {
                result = (result * 0x10000162E43F4F831) >> 64;
            }
            if (x & 0x100000000000 > 0) {
                result = (result * 0x100000B1721BCFC9A) >> 64;
            }
            if (x & 0x80000000000 > 0) {
                result = (result * 0x10000058B90CF1E6E) >> 64;
            }
            if (x & 0x40000000000 > 0) {
                result = (result * 0x1000002C5C863B73F) >> 64;
            }
            if (x & 0x20000000000 > 0) {
                result = (result * 0x100000162E430E5A2) >> 64;
            }
            if (x & 0x10000000000 > 0) {
                result = (result * 0x1000000B172183551) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x8000000000 > 0) {
                result = (result * 0x100000058B90C0B49) >> 64;
            }
            if (x & 0x4000000000 > 0) {
                result = (result * 0x10000002C5C8601CC) >> 64;
            }
            if (x & 0x2000000000 > 0) {
                result = (result * 0x1000000162E42FFF0) >> 64;
            }
            if (x & 0x1000000000 > 0) {
                result = (result * 0x10000000B17217FBB) >> 64;
            }
            if (x & 0x800000000 > 0) {
                result = (result * 0x1000000058B90BFCE) >> 64;
            }
            if (x & 0x400000000 > 0) {
                result = (result * 0x100000002C5C85FE3) >> 64;
            }
            if (x & 0x200000000 > 0) {
                result = (result * 0x10000000162E42FF1) >> 64;
            }
            if (x & 0x100000000 > 0) {
                result = (result * 0x100000000B17217F8) >> 64;
            }
        }

        if (x & 0xFF000000 > 0) {
            if (x & 0x80000000 > 0) {
                result = (result * 0x10000000058B90BFC) >> 64;
            }
            if (x & 0x40000000 > 0) {
                result = (result * 0x1000000002C5C85FE) >> 64;
            }
            if (x & 0x20000000 > 0) {
                result = (result * 0x100000000162E42FF) >> 64;
            }
            if (x & 0x10000000 > 0) {
                result = (result * 0x1000000000B17217F) >> 64;
            }
            if (x & 0x8000000 > 0) {
                result = (result * 0x100000000058B90C0) >> 64;
            }
            if (x & 0x4000000 > 0) {
                result = (result * 0x10000000002C5C860) >> 64;
            }
            if (x & 0x2000000 > 0) {
                result = (result * 0x1000000000162E430) >> 64;
            }
            if (x & 0x1000000 > 0) {
                result = (result * 0x10000000000B17218) >> 64;
            }
        }

        if (x & 0xFF0000 > 0) {
            if (x & 0x800000 > 0) {
                result = (result * 0x1000000000058B90C) >> 64;
            }
            if (x & 0x400000 > 0) {
                result = (result * 0x100000000002C5C86) >> 64;
            }
            if (x & 0x200000 > 0) {
                result = (result * 0x10000000000162E43) >> 64;
            }
            if (x & 0x100000 > 0) {
                result = (result * 0x100000000000B1721) >> 64;
            }
            if (x & 0x80000 > 0) {
                result = (result * 0x10000000000058B91) >> 64;
            }
            if (x & 0x40000 > 0) {
                result = (result * 0x1000000000002C5C8) >> 64;
            }
            if (x & 0x20000 > 0) {
                result = (result * 0x100000000000162E4) >> 64;
            }
            if (x & 0x10000 > 0) {
                result = (result * 0x1000000000000B172) >> 64;
            }
        }

        if (x & 0xFF00 > 0) {
            if (x & 0x8000 > 0) {
                result = (result * 0x100000000000058B9) >> 64;
            }
            if (x & 0x4000 > 0) {
                result = (result * 0x10000000000002C5D) >> 64;
            }
            if (x & 0x2000 > 0) {
                result = (result * 0x1000000000000162E) >> 64;
            }
            if (x & 0x1000 > 0) {
                result = (result * 0x10000000000000B17) >> 64;
            }
            if (x & 0x800 > 0) {
                result = (result * 0x1000000000000058C) >> 64;
            }
            if (x & 0x400 > 0) {
                result = (result * 0x100000000000002C6) >> 64;
            }
            if (x & 0x200 > 0) {
                result = (result * 0x10000000000000163) >> 64;
            }
            if (x & 0x100 > 0) {
                result = (result * 0x100000000000000B1) >> 64;
            }
        }

        if (x & 0xFF > 0) {
            if (x & 0x80 > 0) {
                result = (result * 0x10000000000000059) >> 64;
            }
            if (x & 0x40 > 0) {
                result = (result * 0x1000000000000002C) >> 64;
            }
            if (x & 0x20 > 0) {
                result = (result * 0x10000000000000016) >> 64;
            }
            if (x & 0x10 > 0) {
                result = (result * 0x1000000000000000B) >> 64;
            }
            if (x & 0x8 > 0) {
                result = (result * 0x10000000000000006) >> 64;
            }
            if (x & 0x4 > 0) {
                result = (result * 0x10000000000000003) >> 64;
            }
            if (x & 0x2 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
            if (x & 0x1 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
        }

        // In the code snippet below, two operations are executed simultaneously:
        //
        // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
        // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
        // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
        //
        // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
        // integer part, $2^n$.
        result *= UNIT;
        result >>= (191 - (x >> 64));
    }
}

/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
///     x >>= 128;
///     result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
    // 2^128
    assembly ("memory-safe") {
        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^64
    assembly ("memory-safe") {
        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^32
    assembly ("memory-safe") {
        let factor := shl(5, gt(x, 0xFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^16
    assembly ("memory-safe") {
        let factor := shl(4, gt(x, 0xFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^8
    assembly ("memory-safe") {
        let factor := shl(3, gt(x, 0xFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^4
    assembly ("memory-safe") {
        let factor := shl(2, gt(x, 0xF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^2
    assembly ("memory-safe") {
        let factor := shl(1, gt(x, 0x3))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^1
    // No need to shift x any more.
    assembly ("memory-safe") {
        let factor := gt(x, 0x1)
        result := or(result, factor)
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
    // 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 ("memory-safe") {
        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) {
        unchecked {
            return prod0 / denominator;
        }
    }

    // Make sure the result is less than 2^256. Also prevents denominator == 0.
    if (prod1 >= denominator) {
        revert PRBMath_MulDiv_Overflow(x, y, denominator);
    }

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

    // Make division exact by subtracting the remainder from [prod1 prod0].
    uint256 remainder;
    assembly ("memory-safe") {
        // Compute remainder using the mulmod Yul instruction.
        remainder := mulmod(x, y, denominator)

        // Subtract 256 bit number from 512-bit number.
        prod1 := sub(prod1, gt(remainder, prod0))
        prod0 := sub(prod0, remainder)
    }

    unchecked {
        // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
        // because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
        // For more detail, see https://cs.stackexchange.com/q/138556/92363.
        uint256 lpotdod = denominator & (~denominator + 1);
        uint256 flippedLpotdod;

        assembly ("memory-safe") {
            // Factor powers of two out of denominator.
            denominator := div(denominator, lpotdod)

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

            // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
            // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
            // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
            flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
        }

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

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

/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
///     x * y = MAX\_UINT256 * UNIT \\
///     (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
    uint256 prod0;
    uint256 prod1;
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    if (prod1 == 0) {
        unchecked {
            return prod0 / UNIT;
        }
    }

    if (prod1 >= UNIT) {
        revert PRBMath_MulDiv18_Overflow(x, y);
    }

    uint256 remainder;
    assembly ("memory-safe") {
        remainder := mulmod(x, y, UNIT)
        result :=
            mul(
                or(
                    div(sub(prod0, remainder), UNIT_LPOTD),
                    mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
                ),
                UNIT_INVERSE
            )
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
        revert PRBMath_MulDivSigned_InputTooSmall();
    }

    // Get hold of the absolute values of x, y and the denominator.
    uint256 xAbs;
    uint256 yAbs;
    uint256 dAbs;
    unchecked {
        xAbs = x < 0 ? uint256(-x) : uint256(x);
        yAbs = y < 0 ? uint256(-y) : uint256(y);
        dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
    }

    // Compute the absolute value of x*y÷denominator. The result must fit in int256.
    uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
    if (resultAbs > uint256(type(int256).max)) {
        revert PRBMath_MulDivSigned_Overflow(x, y);
    }

    // Get the signs of x, y and the denominator.
    uint256 sx;
    uint256 sy;
    uint256 sd;
    assembly ("memory-safe") {
        // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
        sx := sgt(x, sub(0, 1))
        sy := sgt(y, sub(0, 1))
        sd := sgt(denominator, sub(0, 1))
    }

    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
    // If there are, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
    if (x == 0) {
        return 0;
    }

    // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
    //
    // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
    //
    // $$
    // msb(x) <= x <= 2*msb(x)$
    // $$
    //
    // We write $msb(x)$ as $2^k$, and we get:
    //
    // $$
    // k = log_2(x)
    // $$
    //
    // Thus, we can write the initial inequality as:
    //
    // $$
    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
    // $$
    //
    // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
    uint256 xAux = uint256(x);
    result = 1;
    if (xAux >= 2 ** 128) {
        xAux >>= 128;
        result <<= 64;
    }
    if (xAux >= 2 ** 64) {
        xAux >>= 64;
        result <<= 32;
    }
    if (xAux >= 2 ** 32) {
        xAux >>= 32;
        result <<= 16;
    }
    if (xAux >= 2 ** 16) {
        xAux >>= 16;
        result <<= 8;
    }
    if (xAux >= 2 ** 8) {
        xAux >>= 8;
        result <<= 4;
    }
    if (xAux >= 2 ** 4) {
        xAux >>= 4;
        result <<= 2;
    }
    if (xAux >= 2 ** 2) {
        result <<= 1;
    }

    // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
    // most 128 bits, 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 + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;

        // If x is not a perfect square, round the result toward zero.
        uint256 roundedResult = x / result;
        if (result >= roundedResult) {
            result = roundedResult;
        }
    }
}

File 16 of 73 : UD60x18.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

/*

██████╗ ██████╗ ██████╗ ███╗   ███╗ █████╗ ████████╗██╗  ██╗
██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║  ██║
██████╔╝██████╔╝██████╔╝██╔████╔██║███████║   ██║   ███████║
██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║   ██║   ██╔══██║
██║     ██║  ██║██████╔╝██║ ╚═╝ ██║██║  ██║   ██║   ██║  ██║
╚═╝     ╚═╝  ╚═╝╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝

██╗   ██╗██████╗  ██████╗  ██████╗ ██╗  ██╗ ██╗ █████╗
██║   ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗
██║   ██║██║  ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝
██║   ██║██║  ██║██╔═══██╗████╔╝██║ ██╔██╗  ██║██╔══██╗
╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝
 ╚═════╝ ╚═════╝  ╚═════╝  ╚═════╝ ╚═╝  ╚═╝ ╚═╝ ╚════╝

*/

import "./ud60x18/Casting.sol";
import "./ud60x18/Constants.sol";
import "./ud60x18/Conversions.sol";
import "./ud60x18/Errors.sol";
import "./ud60x18/Helpers.sol";
import "./ud60x18/Math.sol";
import "./ud60x18/ValueType.sol";

File 17 of 73 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";

/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because the domain of SD1x18 is a subset of SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}

/// @notice Casts an SD1x18 number into UD2x18.
/// - x must be positive.
function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x);
    }
    result = UD2x18.wrap(uint64(xInt));
}

/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD1x18 x) pure returns (uint256 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
    }
    result = uint256(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
function intoUint128(SD1x18 x) pure returns (uint128 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
    }
    result = uint128(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD1x18 x) pure returns (uint40 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
    }
    if (xInt > int64(uint64(Common.MAX_UINT40))) {
        revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
    }
    result = uint40(uint64(xInt));
}

/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
    result = SD1x18.wrap(x);
}

/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
    result = SD1x18.unwrap(x);
}

/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
    result = SD1x18.wrap(x);
}

File 18 of 73 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD1x18 } from "./ValueType.sol";

/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);

/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);

/// @dev The maximum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);

/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int256 constant uUNIT = 1e18;

File 19 of 73 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD1x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD2x18.
error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);

/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);

File 20 of 73 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD59x18,
    Casting.intoUD2x18,
    Casting.intoUD60x18,
    Casting.intoUint256,
    Casting.intoUint128,
    Casting.intoUint40,
    Casting.unwrap
} for SD1x18 global;

File 21 of 73 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x must be greater than or equal to `uMIN_SD1x18`.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < uMIN_SD1x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
    }
    if (xInt > uMAX_SD1x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(xInt));
}

/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
    }
    if (xInt > int256(uint256(uMAX_UD2x18))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(uint256(xInt)));
}

/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD59x18 x) pure returns (uint256 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
    }
    result = uint256(xInt);
}

/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UINT128`.
function intoUint128(SD59x18 x) pure returns (uint128 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT128))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
    }
    result = uint128(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD59x18 x) pure returns (uint40 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT40))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
    }
    result = uint40(uint256(xInt));
}

/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

File 22 of 73 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD59x18 } from "./ValueType.sol";

// NOTICE: the "u" prefix stands for "unwrapped".

/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);

/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);

/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);

/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);

/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);

/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);

/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);

/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);

/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);

/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);

/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);

/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);

/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);

File 23 of 73 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD59x18 } from "./ValueType.sol";

/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();

/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);

/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);

/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);

/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();

/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);

/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);

/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);

/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);

/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);

/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);

/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();

/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);

/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);

/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);

File 24 of 73 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    return wrap(x.unwrap() + y.unwrap());
}

/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
    return wrap(x.unwrap() & bits);
}

/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    return wrap(x.unwrap() & y.unwrap());
}

/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() == y.unwrap();
}

/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() > y.unwrap();
}

/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() >= y.unwrap();
}

/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
    result = x.unwrap() == 0;
}

/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() << bits);
}

/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() < y.unwrap();
}

/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() <= y.unwrap();
}

/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() % y.unwrap());
}

/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() != y.unwrap();
}

/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(~x.unwrap());
}

/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() | y.unwrap());
}

/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() - y.unwrap());
}

/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(-x.unwrap());
}

/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(x.unwrap() + y.unwrap());
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(x.unwrap() - y.unwrap());
    }
}

/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(-x.unwrap());
    }
}

/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() ^ y.unwrap());
}

File 25 of 73 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
    uEXP_MAX_INPUT,
    uEXP2_MAX_INPUT,
    uHALF_UNIT,
    uLOG2_10,
    uLOG2_E,
    uMAX_SD59x18,
    uMAX_WHOLE_SD59x18,
    uMIN_SD59x18,
    uMIN_WHOLE_SD59x18,
    UNIT,
    uUNIT,
    uUNIT_SQUARED,
    ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than `MIN_SD59x18`.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @param result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
    }
    result = xInt < 0 ? wrap(-xInt) : x;
}

/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();

    unchecked {
        // This operation is equivalent to `x / 2 +  y / 2`, and it can never overflow.
        int256 sum = (xInt >> 1) + (yInt >> 1);

        if (sum < 0) {
            // If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
            // rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
            assembly ("memory-safe") {
                result := add(sum, and(or(xInt, yInt), 1))
            }
        } else {
            // Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
            result = wrap(sum + (xInt & yInt & 1));
        }
    }
}

/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to ceil.
/// @param result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt > uMAX_WHOLE_SD59x18) {
        revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt > 0) {
                resultInt += uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @param result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    // Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
    uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
    }

    // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
    // negative, 0 for positive or zero).
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x must be less than 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();

    // This check prevents values greater than 192e18 from being passed to {exp2}.
    if (xInt > uEXP_MAX_INPUT) {
        revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
    }

    unchecked {
        // Inline the fixed-point multiplication to save gas.
        int256 doubleUnitProduct = xInt * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x is less than -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x must be less than 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        // The inverse of any number less than this is truncated to zero.
        if (xInt < -59_794705707972522261) {
            return ZERO;
        }

        unchecked {
            // Inline the fixed-point inversion to save gas.
            result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
        }
    } else {
        // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
        if (xInt > uEXP2_MAX_INPUT) {
            revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
        }

        unchecked {
            // Convert x to the 192.64-bit fixed-point format.
            uint256 x_192x64 = uint256((xInt << 64) / uUNIT);

            // It is safe to cast the result to int256 due to the checks above.
            result = wrap(int256(Common.exp2(x_192x64)));
        }
    }
}

/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to `MIN_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to floor.
/// @param result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < uMIN_WHOLE_SD59x18) {
        revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt < 0) {
                resultInt -= uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @param result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() % uUNIT);
}

/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == 0 || yInt == 0) {
        return ZERO;
    }

    unchecked {
        // Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
        int256 xyInt = xInt * yInt;
        if (xyInt / xInt != yInt) {
            revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
        }

        // The product must not be negative, since complex numbers are not supported.
        if (xyInt < 0) {
            revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
        // during multiplication. See the comments in {Common.sqrt}.
        uint256 resultUint = Common.sqrt(uint256(xyInt));
        result = wrap(int256(resultUint));
    }
}

/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(uUNIT_SQUARED / x.unwrap());
}

/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
    // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
    // {log2} can return is ~195_205294292027477728.
    result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}

/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        default { result := uMAX_SD59x18 }
    }

    if (result.unwrap() == uMAX_SD59x18) {
        unchecked {
            // Inline the fixed-point division to save gas.
            result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x must be greater than zero.
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt <= 0) {
        revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    unchecked {
        int256 sign;
        if (xInt >= uUNIT) {
            sign = 1;
        } else {
            sign = -1;
            // Inline the fixed-point inversion to save gas.
            xInt = uUNIT_SQUARED / xInt;
        }

        // Calculate the integer part of the logarithm.
        uint256 n = Common.msb(uint256(xInt / uUNIT));

        // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
        // because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
        int256 resultInt = int256(n) * uUNIT;

        // Calculate $y = x * 2^{-n}$.
        int256 y = xInt >> n;

        // If y is the unit number, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultInt * sign);
        }

        // Calculate the fractional part via the iterative approximation.
        // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
        int256 DOUBLE_UNIT = 2e18;
        for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultInt = resultInt + delta;

                // Halve y, which corresponds to z/2 in the Wikipedia article.
                y >>= 1;
            }
        }
        resultInt *= sign;
        result = wrap(resultInt);
    }
}

/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    // Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
    uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
    }

    // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
    // negative, 0 for positive or zero).
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();

    // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
    if (xInt == 0) {
        return yInt == 0 ? UNIT : ZERO;
    }
    // If x is `UNIT`, the result is always `UNIT`.
    else if (xInt == uUNIT) {
        return UNIT;
    }

    // If y is zero, the result is always `UNIT`.
    if (yInt == 0) {
        return UNIT;
    }
    // If y is `UNIT`, the result is always x.
    else if (yInt == uUNIT) {
        return x;
    }

    // Calculate the result using the formula.
    result = exp2(mul(log2(x), y));
}

/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
    uint256 xAbs = uint256(abs(x).unwrap());

    // Calculate the first iteration of the loop in advance.
    uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);

    // Equivalent to `for(y /= 2; y > 0; y /= 2)`.
    uint256 yAux = y;
    for (yAux >>= 1; yAux > 0; yAux >>= 1) {
        xAbs = Common.mulDiv18(xAbs, xAbs);

        // Equivalent to `y % 2 == 1`.
        if (yAux & 1 > 0) {
            resultAbs = Common.mulDiv18(resultAbs, xAbs);
        }
    }

    // The result must fit in SD59x18.
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
    }

    unchecked {
        // Is the base negative and the exponent odd? If yes, the result should be negative.
        int256 resultInt = int256(resultAbs);
        bool isNegative = x.unwrap() < 0 && y & 1 == 1;
        if (isNegative) {
            resultInt = -resultInt;
        }
        result = wrap(resultInt);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x cannot be negative, since complex numbers are not supported.
/// - x must be less than `MAX_SD59x18 / UNIT`.
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
    }
    if (xInt > uMAX_SD59x18 / uUNIT) {
        revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
    }

    unchecked {
        // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
        // In this case, the two numbers are both the square root.
        uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
        result = wrap(int256(resultUint));
    }
}

File 26 of 73 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;

/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoInt256,
    Casting.intoSD1x18,
    Casting.intoUD2x18,
    Casting.intoUD60x18,
    Casting.intoUint256,
    Casting.intoUint128,
    Casting.intoUint40,
    Casting.unwrap
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    Math.abs,
    Math.avg,
    Math.ceil,
    Math.div,
    Math.exp,
    Math.exp2,
    Math.floor,
    Math.frac,
    Math.gm,
    Math.inv,
    Math.log10,
    Math.log2,
    Math.ln,
    Math.mul,
    Math.pow,
    Math.powu,
    Math.sqrt
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    Helpers.add,
    Helpers.and,
    Helpers.eq,
    Helpers.gt,
    Helpers.gte,
    Helpers.isZero,
    Helpers.lshift,
    Helpers.lt,
    Helpers.lte,
    Helpers.mod,
    Helpers.neq,
    Helpers.not,
    Helpers.or,
    Helpers.rshift,
    Helpers.sub,
    Helpers.uncheckedAdd,
    Helpers.uncheckedSub,
    Helpers.uncheckedUnary,
    Helpers.xor
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                    OPERATORS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
    Helpers.add as +,
    Helpers.and2 as &,
    Math.div as /,
    Helpers.eq as ==,
    Helpers.gt as >,
    Helpers.gte as >=,
    Helpers.lt as <,
    Helpers.lte as <=,
    Helpers.mod as %,
    Math.mul as *,
    Helpers.neq as !=,
    Helpers.not as ~,
    Helpers.or as |,
    Helpers.sub as -,
    Helpers.unary as -,
    Helpers.xor as ^
} for SD59x18 global;

File 27 of 73 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";

/// @notice Casts a UD2x18 number into SD1x18.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) {
    uint64 xUint = UD2x18.unwrap(x);
    if (xUint > uint64(uMAX_SD1x18)) {
        revert Errors.PRBMath_UD2x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(xUint));
}

/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}

/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
    result = uint128(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
    result = uint256(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD2x18 x) pure returns (uint40 result) {
    uint64 xUint = UD2x18.unwrap(x);
    if (xUint > uint64(Common.MAX_UINT40)) {
        revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
    result = UD2x18.wrap(x);
}

/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
    result = UD2x18.unwrap(x);
}

/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
    result = UD2x18.wrap(x);
}

File 28 of 73 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD2x18 } from "./ValueType.sol";

/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);

/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);

/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of UD2x18.
uint256 constant uUNIT = 1e18;
UD2x18 constant UNIT = UD2x18.wrap(1e18);

File 29 of 73 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD2x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in SD1x18.
error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x);

/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);

File 30 of 73 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD1x18,
    Casting.intoSD59x18,
    Casting.intoUD60x18,
    Casting.intoUint256,
    Casting.intoUint128,
    Casting.intoUint40,
    Casting.unwrap
} for UD2x18 global;

File 31 of 73 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(int256(uMAX_SD1x18))) {
        revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(uint64(xUint)));
}

/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uMAX_UD2x18) {
        revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(xUint));
}

/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD59x18`.
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(uMAX_SD59x18)) {
        revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
    }
    result = SD59x18.wrap(int256(xUint));
}

/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT128`.
function intoUint128(UD60x18 x) pure returns (uint128 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT128) {
        revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
    }
    result = uint128(xUint);
}

/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD60x18 x) pure returns (uint40 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT40) {
        revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

File 32 of 73 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD60x18 } from "./ValueType.sol";

// NOTICE: the "u" prefix stands for "unwrapped".

/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);

/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);

/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);

/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);

/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);

/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);

/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);

/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);

/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);

/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);

/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);

File 33 of 73 : Conversions.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x) / uUNIT;
}

/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UD60x18 / UNIT`.
///
/// @param x The basic integer to convert.
/// @param result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
    if (x > uMAX_UD60x18 / uUNIT) {
        revert PRBMath_UD60x18_Convert_Overflow(x);
    }
    unchecked {
        result = UD60x18.wrap(x * uUNIT);
    }
}

File 34 of 73 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD60x18 } from "./ValueType.sol";

/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);

/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);

/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);

/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);

/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);

/// @notice Thrown when taking the logarithm of a number less than 1.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);

/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);

File 35 of 73 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() + y.unwrap());
}

/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() & bits);
}

/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() & y.unwrap());
}

/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() == y.unwrap();
}

/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() > y.unwrap();
}

/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() >= y.unwrap();
}

/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
    // This wouldn't work if x could be negative.
    result = x.unwrap() == 0;
}

/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() << bits);
}

/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() < y.unwrap();
}

/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() <= y.unwrap();
}

/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() % y.unwrap());
}

/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() != y.unwrap();
}

/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
    result = wrap(~x.unwrap());
}

/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() | y.unwrap());
}

/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() - y.unwrap());
}

/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(x.unwrap() + y.unwrap());
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(x.unwrap() - y.unwrap());
    }
}

/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() ^ y.unwrap());
}

File 36 of 73 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
    uEXP_MAX_INPUT,
    uEXP2_MAX_INPUT,
    uHALF_UNIT,
    uLOG2_10,
    uLOG2_E,
    uMAX_UD60x18,
    uMAX_WHOLE_UD60x18,
    UNIT,
    uUNIT,
    uUNIT_SQUARED,
    ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();
    unchecked {
        result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
    }
}

/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_UD60x18`.
///
/// @param x The UD60x18 number to ceil.
/// @param result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    if (xUint > uMAX_WHOLE_UD60x18) {
        revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
    }

    assembly ("memory-safe") {
        // Equivalent to `x % UNIT`.
        let remainder := mod(x, uUNIT)

        // Equivalent to `UNIT - remainder`.
        let delta := sub(uUNIT, remainder)

        // Equivalent to `x + remainder > 0 ? delta : 0`.
        result := add(x, mul(delta, gt(remainder, 0)))
    }
}

/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @param result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}

/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x must be less than 133_084258667509499441.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    // This check prevents values greater than 192e18 from being passed to {exp2}.
    if (xUint > uEXP_MAX_INPUT) {
        revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
    }

    unchecked {
        // Inline the fixed-point multiplication to save gas.
        uint256 doubleUnitProduct = xUint * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x must be less than 192e18.
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
    if (xUint > uEXP2_MAX_INPUT) {
        revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
    }

    // Convert x to the 192.64-bit fixed-point format.
    uint256 x_192x64 = (xUint << 64) / uUNIT;

    // Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
    result = wrap(Common.exp2(x_192x64));
}

/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @param result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        // Equivalent to `x % UNIT`.
        let remainder := mod(x, uUNIT)

        // Equivalent to `x - remainder > 0 ? remainder : 0)`.
        result := sub(x, mul(remainder, gt(remainder, 0)))
    }
}

/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @param result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        result := mod(x, uUNIT)
    }
}

/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();
    if (xUint == 0 || yUint == 0) {
        return ZERO;
    }

    unchecked {
        // Checking for overflow this way is faster than letting Solidity do it.
        uint256 xyUint = xUint * yUint;
        if (xyUint / xUint != yUint) {
            revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
        // during multiplication. See the comments in {Common.sqrt}.
        result = wrap(Common.sqrt(xyUint));
    }
}

/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(uUNIT_SQUARED / x.unwrap());
    }
}

/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
        // {log2} can return is ~196_205294292027477728.
        result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
    }
}

/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    if (xUint < uUNIT) {
        revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
        default { result := uMAX_UD60x18 }
    }

    if (result.unwrap() == uMAX_UD60x18) {
        unchecked {
            // Inline the fixed-point division to save gas.
            result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x must be greater than zero.
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    if (xUint < uUNIT) {
        revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    unchecked {
        // Calculate the integer part of the logarithm.
        uint256 n = Common.msb(xUint / uUNIT);

        // This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
        // n is at most 255 and UNIT is 1e18.
        uint256 resultUint = n * uUNIT;

        // Calculate $y = x * 2^{-n}$.
        uint256 y = xUint >> n;

        // If y is the unit number, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultUint);
        }

        // Calculate the fractional part via the iterative approximation.
        // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
        uint256 DOUBLE_UNIT = 2e18;
        for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultUint += delta;

                // Halve y, which corresponds to z/2 in the Wikipedia article.
                y >>= 1;
            }
        }
        result = wrap(resultUint);
    }
}

/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}

/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();

    // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
    if (xUint == 0) {
        return yUint == 0 ? UNIT : ZERO;
    }
    // If x is `UNIT`, the result is always `UNIT`.
    else if (xUint == uUNIT) {
        return UNIT;
    }

    // If y is zero, the result is always `UNIT`.
    if (yUint == 0) {
        return UNIT;
    }
    // If y is `UNIT`, the result is always x.
    else if (yUint == uUNIT) {
        return x;
    }

    // If x is greater than `UNIT`, use the standard formula.
    if (xUint > uUNIT) {
        result = exp2(mul(log2(x), y));
    }
    // Conversely, if x is less than `UNIT`, use the equivalent formula.
    else {
        UD60x18 i = wrap(uUNIT_SQUARED / xUint);
        UD60x18 w = exp2(mul(log2(i), y));
        result = wrap(uUNIT_SQUARED / w.unwrap());
    }
}

/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
    // Calculate the first iteration of the loop in advance.
    uint256 xUint = x.unwrap();
    uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;

    // Equivalent to `for(y /= 2; y > 0; y /= 2)`.
    for (y >>= 1; y > 0; y >>= 1) {
        xUint = Common.mulDiv18(xUint, xUint);

        // Equivalent to `y % 2 == 1`.
        if (y & 1 > 0) {
            resultUint = Common.mulDiv18(resultUint, xUint);
        }
    }
    result = wrap(resultUint);
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must be less than `MAX_UD60x18 / UNIT`.
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    unchecked {
        if (xUint > uMAX_UD60x18 / uUNIT) {
            revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
        }
        // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
        // In this case, the two numbers are both the square root.
        result = wrap(Common.sqrt(xUint * uUNIT));
    }
}

File 37 of 73 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;

/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD1x18,
    Casting.intoUD2x18,
    Casting.intoSD59x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    Math.avg,
    Math.ceil,
    Math.div,
    Math.exp,
    Math.exp2,
    Math.floor,
    Math.frac,
    Math.gm,
    Math.inv,
    Math.ln,
    Math.log10,
    Math.log2,
    Math.mul,
    Math.pow,
    Math.powu,
    Math.sqrt
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    Helpers.add,
    Helpers.and,
    Helpers.eq,
    Helpers.gt,
    Helpers.gte,
    Helpers.isZero,
    Helpers.lshift,
    Helpers.lt,
    Helpers.lte,
    Helpers.mod,
    Helpers.neq,
    Helpers.not,
    Helpers.or,
    Helpers.rshift,
    Helpers.sub,
    Helpers.uncheckedAdd,
    Helpers.uncheckedSub,
    Helpers.xor
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                    OPERATORS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
    Helpers.add as +,
    Helpers.and2 as &,
    Math.div as /,
    Helpers.eq as ==,
    Helpers.gt as >,
    Helpers.gte as >=,
    Helpers.lt as <,
    Helpers.lte as <=,
    Helpers.or as |,
    Helpers.mod as %,
    Math.mul as *,
    Helpers.neq as !=,
    Helpers.not as ~,
    Helpers.sub as -,
    Helpers.xor as ^
} for UD60x18 global;

File 38 of 73 : BaseAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IAccount } from "../interfaces/IAccount.sol";
import { IAccountManager } from "../interfaces/IAccountManager.sol";
import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol";
import { AccountLib } from "../libraries/accounts/AccountLib.sol";
import "../libraries/traits/AddressCheckerTrait.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/ILendingPool.sol";
import "../libraries/Errors.sol";
import "../periphery/Multicall.sol";

/// @title Base Account
/// @notice The Base Account contract is the parent contract for all investment accounts
/// @dev ERC2771Context is initialized with a null address because we override the isTrustedForwarder method to use the
/// Account Manager as the trustedForwarder.
abstract contract BaseAccount is Multicall, IAccount, AddressCheckerTrait, Initializable, Pausable {
    using SafeERC20 for IERC20;

    /////////////////////////////
    // Omega Protocol Contracts
    /////////////////////////////
    /// @dev Accounts use the other contracts in the protocol for various functions
    ///
    /// AccountManager - Referrences this contract for access control purposes
    /// LendingPool - Accesses this contract to borrow and repay as well as to
    ///               Read the debt and collateral amounts.
    /// offchain liquidations.

    /// @notice The Investment Account Manager
    IAccountManager internal _manager;

    /// @notice The asset used by this investment account
    IERC20 public asset;

    /////////////////////////////
    // State Variables
    /////////////////////////////

    /// @notice The owner of this account
    address public owner;

    /// @notice Empty constructor because this contract is deployed as a clone in the manager
    constructor() {
        _disableInitializers();
    }

    /// @notice Initialize this investment account
    /// @param owner_ The borrower that owns this account
    function initialize(address owner_) external virtual initializer {
        _initialize(owner_);
    }

    /// @notice Initialize this investment account
    /// @param owner_ The borrower that owns this account
    function _initialize(address owner_) internal {
        _manager = IAccountManager(msg.sender);
        asset = _manager.getLendAsset();
        owner = owner_;

        // Approve repayments to the lending pool
        asset.safeIncreaseAllowance(_manager.lendingPool(), type(uint256).max);
        // Approve manager to transfer assets
        asset.safeIncreaseAllowance(address(_manager), type(uint256).max);
    }

    ////////////////////////////
    // Access Control Modifiers
    ////////////////////////////

    /// @notice Restricts access to the `manager` of the account
    modifier onlyAccountManager() {
        if (_msgSender() != address(_manager)) revert Errors.Unauthorized();
        _;
    }

    /// @notice Restricts access to the `owner` of the account
    /// @dev We use _msgSender() to allow for meta transactions
    modifier onlyOwner() {
        if (_msgSender() != owner) revert Errors.Unauthorized();
        _;
    }

    modifier onlyRepayer() {
        bool isLiquidationReceiver = false;

        try _manager.isLiquidationReceiver(_msgSender()) returns (bool _isLiquidationReceiver) {
            isLiquidationReceiver = _isLiquidationReceiver;
        } catch {
            isLiquidationReceiver = false;
        }

        if (_msgSender() == owner || _msgSender() == address(_manager) || isLiquidationReceiver) {
            _;
        } else {
            revert Errors.Unauthorized();
        }
    }

    ///////////////////////
    // Admin Methods
    ///////////////////////
    /// @notice The owner of the accountManager is allowed to:
    /// - Pause/unpause the contract

    /// @notice Lets the admin pause the account
    function pause() external onlyAccountManager {
        _pause();
    }

    /// @notice Lets the admin unpause the account
    function unpause() external onlyAccountManager {
        _unpause();
    }

    function multicall(bytes[] calldata data)
        public
        payable
        override
        onlyOwner
        whenNotPaused
        returns (bytes[] memory results)
    {
        results = super.multicall(data);
    }

    //////////////////////////
    // Lending Pool Methods
    //////////////////////////
    /// @notice Interactions to borrow and repay from the `lendingPool`

    /// @notice Borrow from the lending pool
    /// @dev Manager is in charge of making sure this account is still solvent after borrowing.
    /// @dev Loans are assessed by looking at the account's debt and collateral.
    /// @param amount The amount to borrow
    function borrow(uint256 amount) external payable virtual onlyOwner whenNotPaused {
        // Borrow funds
        _manager.borrow(amount);
        emit Borrow(amount);
    }

    /// @notice Repay the lending pool
    /// @param amount The amount to repay
    function repay(uint256 amount) external payable virtual onlyRepayer {
        _manager.repay(address(this), amount);
        emit Repay(amount);
    }

    /// @notice Repay the lending pool
    /// @param amountFrom Additional amount to pull from owner before repayment
    function repayFrom(uint256 amountFrom) external payable virtual onlyOwner {
        asset.safeTransferFrom(_msgSender(), address(this), amountFrom);
        _manager.repay(address(this), asset.balanceOf(address(this)));
        emit Repay(amountFrom);
    }

    ////////////////////
    // Views
    ////////////////////

    /// @notice Returns the AccountManager that created this Account.
    function getManager() external view returns (IAccountManager) {
        return _manager;
    }

    function claim(uint256 amount) external payable onlyOwner whenNotPaused {
        _manager.claim(amount, _msgSender());
        emit Claim(amount);
    }

    function claim(uint256 amount, address recipient) external payable onlyOwner whenNotPaused {
        _manager.claim(amount, recipient);
        emit Claim(amount);
    }
}

File 39 of 73 : ExternalAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./BaseAccount.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import "../libraries/Errors.sol";

/// @title External Account
/// @notice This account type supports borrowing from the lending pool
/// directly to the owners wallet. LTVs on this account type will be
/// less than 100%. This account type relies on off-chain liquidations.
contract ExternalAccount is BaseAccount {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @notice Initialize this permissionless account
    /// @param owner_ The borrower that owns this account
    function initialize(address owner_) public override initializer {
        _initialize(owner_);
    }

    //////////////////////////
    // Lending Pool Methods
    //////////////////////////

    /// @notice Borrow from the lending pool
    /// @param amount The amount to borrow
    function borrow(uint256 amount) external payable override onlyOwner whenNotPaused {
        uint256 amountBorrowed = _manager.borrow(amount);
        asset.safeTransfer(_msgSender(), amountBorrowed);
    }

    /// @notice Repay the lending pool
    /// @param amount The amount to repay
    function repay(uint256 amount) external payable override onlyRepayer whenNotPaused {
        _manager.repay(address(this), amount);
    }

    function getKind() external pure returns (bytes32) {
        return keccak256(abi.encode("OMEGA_EXTERNAL_ACCOUNT"));
    }
}

File 40 of 73 : InternalAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IStrategyVault } from "../interfaces/IStrategyVault.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import { InternalAccountEvents } from "contracts/interfaces/IInternalAccount.sol";
import "./BaseAccount.sol";
import "../libraries/Errors.sol";

/// @title Internal Account
/// @notice This account type is used to manage investments into approved strategies.
/// The account owner can deposit and withdraw from approved strategies to earn profits.
contract InternalAccount is BaseAccount, InternalAccountEvents {
    using SafeERC20 for IERC20;

    /// @notice Initialize this permissioned account
    /// @param owner_  The borrower that owns this account
    function initialize(address owner_) public virtual override initializer {
        _initialize(owner_);
    }

    //////////////////////////
    // Investment Methods
    //////////////////////////
    /// @notice These methods are used to manage permissioned investment into approved investment strategies

    /// @notice Deposit into a Omega Strategy Vault
    /// @dev The `minShares` can be calculated using the `previewDeposit` method on the vault
    /// @param strategy The address of the strategy to deposit into
    /// @param amount The amount to deposit in USDC
    /// @param data encode data for the strategy to process the deposit
    function strategyDeposit(
        address strategy,
        uint256 amount,
        bytes memory data
    )
        external
        payable
        virtual
        onlyOwner
        whenNotPaused
        returns (uint256 receivedShares)
    {
        asset.safeIncreaseAllowance(strategy, amount);

        uint256 executionGasLimit = 0;
        if (strategy != address(0)) {
            executionGasLimit = IStrategyVault(strategy).estimateExecuteDepositGasLimit();
        }

        uint256 executionFee = 0;

        if (executionGasLimit > 0) {
            executionFee = executionGasLimit * tx.gasprice;
        }

        receivedShares = _manager.strategyDeposit{ value: executionFee }(owner, strategy, amount, data);
        emit StrategyDeposit(strategy, amount);
    }

    /// @notice Withdraw from a Omega Strategy Vault
    /// @dev The `minUsdc` can be calculated using the `previewWithdraw` method on the vault
    /// @param strategy The address of the strategy to withdraw from
    /// @param shares The amount to withdraw in vault shares
    /// @param data encoded data for the strategy to process the withdrawal
    function strategyWithdraw(
        address strategy,
        uint256 shares,
        bytes memory data
    )
        external
        payable
        onlyOwner
        whenNotPaused
        returns (uint256 receivedAssets)
    {
        receivedAssets = _strategyWithdraw(strategy, shares, data);
        _manager.strategyWithdrawal(owner, strategy, receivedAssets, false);
    }

    function strategyWithdrawAndRepay(
        address strategy,
        uint256 shares,
        bytes memory data
    )
        external
        payable
        onlyOwner
        whenNotPaused
        returns (uint256 receivedAssets)
    {
        _manager.snapshotAccountHealthFactor();
        receivedAssets = _strategyWithdraw(strategy, shares, data);
        _manager.repay(address(this), receivedAssets);
        _manager.strategyWithdrawal(owner, strategy, receivedAssets, true);
    }

    function _strategyWithdraw(
        address strategy,
        uint256 shares,
        bytes memory data
    )
        internal
        returns (uint256 receivedAssets)
    {
        uint256 executionGasLimit = 0;
        if (strategy != address(0)) {
            executionGasLimit = IStrategyVault(strategy).estimateExecuteWithdrawalGasLimit();
        }

        uint256 executionFee = 0;

        if (executionGasLimit > 0) {
            executionFee = executionGasLimit * tx.gasprice;
        }

        receivedAssets = IStrategyVault(strategy).withdraw{ value: executionFee }(shares, data);
        emit StrategyWithdraw(strategy, receivedAssets);
    }

    //////////////////////////
    // View Methods
    //////////////////////////
    /// @notice These methods are used to view information about this account

    function getKind() external pure virtual returns (bytes32) {
        return keccak256(abi.encode("OMEGA_INTERNAL_ACCOUNT"));
    }

    //////////////////////////
    // Liquidator Methods
    //////////////////////////

    function _preStrategyLiquidation(address recipient) internal view returns (uint256 amountBefore) {
        // Track the amount liquidate by checking the asset balance of the liquidator before and after
        amountBefore = asset.balanceOf(recipient);
    }

    function _postStrategyLiquidation(
        address strategy,
        address recipient,
        uint256 expectedReceived,
        uint256 amountBefore
    )
        internal
    {
        if (asset.balanceOf(address(recipient)) < (expectedReceived + amountBefore)) {
            revert Errors.WithdrawnAssetsNotReceived();
        }

        emit StrategyLiquidated(strategy, expectedReceived);
    }

    function liquidateStrategy(
        address strategy,
        address recipient,
        uint256 minAmount,
        bytes memory data
    )
        external
        payable
        onlyAccountManager
    {
        uint256 amountBefore = _preStrategyLiquidation(recipient);

        uint256 receivedAssets = 0;

        uint256 executionGasLimit = 0;
        if (strategy != address(0)) {
            executionGasLimit = IStrategyVault(strategy).estimateExecuteWithdrawalGasLimit();
        }

        uint256 executionFee = 0;

        if (executionGasLimit > 0) {
            executionFee = executionGasLimit * tx.gasprice;
        }

        if (strategy != address(0)) {
            receivedAssets = IStrategyVault(strategy).liquidate{ value: executionFee }(recipient, minAmount, data);
            _postStrategyLiquidation(strategy, recipient, receivedAssets, amountBefore);
        }
    }
}

File 41 of 73 : IBlast.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

enum YieldMode {
    AUTOMATIC,
    VOID,
    CLAIMABLE
}

enum GasMode {
    VOID,
    CLAIMABLE
}

interface IBlastPoints {
    function configurePointsOperator(address operator) external;
    function configurePointsOperatorOnBehalf(address operator, address contractAddress) external;
    function operators(address contractAddress) external view returns (address);
    function readStatus(address contractAddress) external view returns (address, bool, uint256);
}

interface IBlast {
    // configure
    function configureContract(address contractAddress, YieldMode _yield, GasMode gasMode, address governor) external;
    function configure(YieldMode _yield, GasMode gasMode, address governor) external;

    // base configuration options
    function configureClaimableYield() external;
    function configureClaimableYieldOnBehalf(address contractAddress) external;
    function configureAutomaticYield() external;
    function configureAutomaticYieldOnBehalf(address contractAddress) external;
    function configureVoidYield() external;
    function configureVoidYieldOnBehalf(address contractAddress) external;
    function configureClaimableGas() external;
    function configureClaimableGasOnBehalf(address contractAddress) external;
    function configureVoidGas() external;
    function configureVoidGasOnBehalf(address contractAddress) external;
    function configureGovernor(address _governor) external;
    function configureGovernorOnBehalf(address _newGovernor, address contractAddress) external;

    // claim yield
    function claimYield(address contractAddress, address recipientOfYield, uint256 amount) external returns (uint256);
    function claimAllYield(address contractAddress, address recipientOfYield) external returns (uint256);

    // claim gas
    function claimAllGas(address contractAddress, address recipientOfGas) external returns (uint256);
    function claimGasAtMinClaimRate(
        address contractAddress,
        address recipientOfGas,
        uint256 minClaimRateBips
    )
        external
        returns (uint256);
    function claimMaxGas(address contractAddress, address recipientOfGas) external returns (uint256);
    function claimGas(
        address contractAddress,
        address recipientOfGas,
        uint256 gasToClaim,
        uint256 gasSecondsToConsume
    )
        external
        returns (uint256);

    // read functions
    function readClaimableYield(address contractAddress) external view returns (uint256);
    function readYieldConfiguration(address contractAddress) external view returns (uint8);
    function readGasParams(address contractAddress)
        external
        view
        returns (uint256 etherSeconds, uint256 etherBalance, uint256 lastUpdated, GasMode);
}

File 42 of 73 : IERC20Rebasing.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "./IBlast.sol";

interface IERC20Rebasing {
    // changes the yield mode of the caller and update the balance
    // to reflect the configuration
    function configure(YieldMode) external returns (uint256);
    // "claimable" yield mode accounts can call this to claim their yield
    // to another address
    function claim(address recipient, uint256 amount) external returns (uint256);
    // read the claimable amount for an account
    function getClaimableAmount(address account) external view returns (uint256);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function getConfiguration(address contractAddress) external view returns (uint8);
}

File 43 of 73 : IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.24;

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

File 44 of 73 : IAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "solady/src/tokens/ERC20.sol";
import "../libraries/accounts/AccountLib.sol";
import "../interfaces/IAccountManager.sol";

interface IAccount {
    /// @notice Event emitted when `amount` of `asset` is withdrawn from account
    event Claim(uint256 amount);
    /// @notice Borrow event emitted when `amount` of `asset` is borrowed on behalf of the account
    event Borrow(uint256 amount);
    /// @notice Repay event emitted when `amount` of `asset` is repaid on behalf of the account
    event Repay(uint256 amount);

    function asset() external view returns (IERC20);

    function owner() external view returns (address);

    /// @dev Returns a unique identifier distinguishing this type of account
    function getKind() external view returns (bytes32);

    function getManager() external view returns (IAccountManager);
    function initialize(address owner_) external;

    function pause() external;
    function unpause() external;

    /// Owner interactions

    function borrow(uint256 amount) external payable;
    function repay(uint256 amount) external payable;
    function claim(uint256 amount) external payable;
    function claim(uint256 amount, address recipient) external payable;
}

File 45 of 73 : IAccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import "../libraries/accounts/AccountLib.sol";
import "./ILiquidationReceiver.sol";

interface IAccountManager {
    function lendingPool() external view returns (address);
    function isCreatedAccount(address) external view returns (bool);
    function accountCount() external view returns (uint256);
    function isApprovedStrategy(address strategy) external view returns (bool);
    function isLiquidationReceiver(address receiver) external view returns (bool);

    function pauseAccount(address account) external;
    function unpauseAccount(address account) external;

    function getFeeCollector() external view returns (address);
    function getLiquidationReceiver(
        address account,
        address liquidationFeeTo
    )
        external
        view
        returns (ILiquidationReceiver);
    function getLiquidationFee() external returns (AccountLib.LiquidationFee memory);
    function getAccountOwner(address account) external returns (address owner);

    // Following three functions are only callable by the target Account itself.
    function borrow(uint256 amount) external returns (uint256 borrowedAmount);
    function repay(address account, uint256 amount) external returns (uint256 repaidAmount);
    function claim(uint256 amount, address recipient) external;

    function liquidate(address account, address liquidationFeeTo) external returns (ILiquidationReceiver);

    /// @notice Deposits assets into a strategy on behalf of msg.sender, which must be an Account.
    function strategyDeposit(
        address owner,
        address strategy,
        uint256 assets,
        bytes memory data
    )
        external
        payable
        returns (uint256 shares);
    function strategyWithdrawal(address owner, address strategy, uint256 assets, bool didRepay) external;
    function snapshotAccountHealthFactor() external;

    function setAllowedAccountsMode(bool status) external;
    function setAllowedAccountStatus(address account, bool status) external;

    /// @dev Some strategies have an execution fee that needs to be paid for withdrawal so that must be sent to this
    /// function.
    function liquidateStrategy(
        address account,
        address liquidationFeeTo,
        address strategy,
        bytes memory data
    )
        external
        payable
        returns (ILiquidationReceiver);

    function emitLiquidationFeeEvent(
        address feeCollector,
        address liquidationFeeTo,
        uint256 protocolShare,
        uint256 liquidatorShare
    )
        external;

    function getLendAsset() external view returns (IERC20);
    function getDebtAmount(address account) external view returns (uint256);
    function getTotalCollateralValue(address account) external view returns (uint256 totalValue);

    function getAccountLoan(address account) external view returns (AccountLib.Loan memory loan);
    function getAccountHealth(address account) external view returns (AccountLib.Health memory health);

    /// @notice Returns whether or not an account is liquidatable. If true, return the timestamp its liquidation started
    /// at.
    function getAccountLiquidationStatus(address account) external view returns (AccountLib.LiquidationStatus memory);
}

File 46 of 73 : IAssetPriceOracle.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

/// @notice Interface for a price oracle preconfigured to return the price of an asset.
/// @dev Price can be in any denomination, depending on the preconfiguration.
interface IAssetPriceOracle {
    function getPrice() external view returns (uint256 price);
}

File 47 of 73 : IAssetPriceProvider.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

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

/**
 * @title IAssetPriceProvider interface
 * @notice Interface for the collateral price provider.
 *
 */
interface IAssetPriceProvider {
    /**
     * @dev returns the asset price
     * @param asset the address of the asset
     * @return price of the asset
     *
     */
    function getAssetPrice(address asset) external view returns (uint256);
}

File 48 of 73 : ICollateralAccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import "../libraries/accounts/AccountLib.sol";
import "./ILiquidationReceiver.sol";
import "./IAccountManager.sol";

interface ICollateralAccountManager {
    /// @notice A user has created an account.
    event AccountCreated(address indexed owner, address account);
    /// @notice A user has deposited WETH into the contract.
    event CollateralDeposit(address indexed owner, address account, address sender, uint256 amount);
    /// @notice A user has withdrawn WETH from the contract.
    event CollateralWithdrawal(address indexed owner, address account, address receiver, uint256 amount);
    /// @notice CollateralLiquidation
    event CollateralLiquidation(
        address account, uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded
    );
    event LiquidationParametersUpdated(UD60x18 maxLtv, UD60x18 riskThreshold, UD60x18 liquidationThreshold);

    /// @dev Takes assets from `msg.sender`, deposits them into the contract, and mints shares to the receiver.
    /// The shares are nontransferrable and reside in the receiver's address, but are used to credit the receiver's
    /// account contract.
    function deposit(uint256 assets, address receiver) external returns (uint256 updatedAssets, uint256 shares);

    /// @dev Burns shares from the account of `msg.sender` and sends them to the receiver.
    /// `msg.sender` must be owner of account that owns the shares.
    function withdraw(
        uint256 shares,
        address receiver
    )
        external
        returns (uint256 updatedAssets, uint256 updatedShares);
}

File 49 of 73 : IGasTank.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

interface IGasTank {
    function allowList(address user) external returns (bool allowed);
    function accessControllers(address controller) external returns (bool allowed);
    function deposit() external payable;
    function withdraw(uint256 amount) external;
    function allowListUpdate(address contractAddress, bool allowed) external;
    function accessControllerUpdate(address accessController, bool allowed) external;
    function reimburseGas(address receiver, uint256 amount) external;
}

File 50 of 73 : IInternalAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "solady/src/tokens/ERC20.sol";
import "./IAccount.sol";

abstract contract InternalAccountEvents {
    /// @notice The owner made a deposit of `amount` into `strategy`
    event StrategyDeposit(address strategy, uint256 amount);
    /// @notice The owner withdrew `amount` from `strategy`
    event StrategyWithdraw(address strategy, uint256 amount);
    /// @notice The deposits into `strategy` have been forcibly withdrawn and `receveredAmount` was returned
    /// @dev When strategy == address(0) it indicates a liquidation of the balance in the account
    event StrategyLiquidated(address indexed strategy, uint256 recoveredAmount);
}

interface IInternalAccount is IAccount {
    function strategyDeposit(address strategy, uint256 amount) external;
    function strategyWithdraw(address strategy, uint256 amount) external;
    function liquidateStrategy(
        address strategy,
        address recipient,
        uint256 minAmount,
        bytes memory data
    )
        external
        payable;
}

File 51 of 73 : ILendingPool.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";

interface ILendingPool {
    function allowedLenders(address lender) external view returns (bool);

    function deposit(uint256 amount) external returns (uint256);
    function withdraw(uint256 amount) external returns (uint256);

    function getMinimumOpenBorrow() external view returns (uint256);
    function setMinimumOpenBorrow(uint256 amount) external;

    function setInterestRateStrategy(address newStrategy) external;

    function getDebtAmount(address borrower) external view returns (uint256);
    function getDepositAmount(address lender) external view returns (uint256);
    function getTotalSupply() external view returns (uint256);
    function getTotalBorrow() external view returns (uint256);

    function getAsset() external view returns (IERC20);
    function getNormalizedIncome() external view returns (UD60x18);
    function getNormalizedDebt() external view returns (UD60x18);
    function accrueInterest() external;

    // PermissionedLendingPool Only
    function updateLenderStatus(address lender, bool status) external;

    // AccountManager
    function borrow(uint256 amount, address onBehalfOf) external returns (uint256);

    ///@dev Repays loan of `onBehalfOf`, transferring funds from `onBehalfOf`
    function repay(uint256 amount, address onBehalfOf) external returns (uint256);

    ///@dev Repays loan of `onBehalfOf`, transferring funds from `from`
    function repay(uint256 amount, address onBehalfOf, address from) external returns (uint256);
}

File 52 of 73 : ILiquidationReceiver.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IAccount } from "./IAccount.sol";
import { IAccountManager } from "./IAccountManager.sol";

interface ILiquidationReceiver {
    struct Props {
        IERC20 asset;
        IAccountManager manager;
        IAccount account;
        address liquidationFeeTo;
    }

    function initialize(Props memory props_) external;
    function repay() external;
}

File 53 of 73 : IProtocolGovernor.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18 } from "@prb/math/src/UD60x18.sol";

interface IProtocolGovernor {
    function getOwner() external view returns (address);
    function getAddress(bytes32 id) external view returns (address);
    function getImmutableAddress(bytes32 id) external view returns (address);
    function setFee(bytes32 id, UD60x18 newFee) external;
    function getFee(bytes32 id) external view returns (UD60x18);

    function isProtocolDeprecated() external view returns (bool);
    // Accounts Managers can open loans on behalf of Accounts they create.
    function updateAccountManagerStatus(address manager, bool active) external;
    function isAccountManager(address manager) external view returns (bool);

    // RBAC
    function grantRole(bytes32 role, address account) external;
    function revokeRole(bytes32 role, address account) external;
    function hasRole(bytes32 role, address account) external view returns (bool);
}

File 54 of 73 : IStrategySlippageModel.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18 } from "@prb/math/src/UD60x18.sol";

// Note: This slippage tolerance might be better to increase as a function of elapse
// time. That is, the slippage is higher the longer the account is in liquidation.
// A static slippage like this means we'd need to manually increase the value if the
// position can't be liquidate with the set slippage tolerance.

/// @notice This contract returns the slippageTolerance for a strategy liquidation as a function of how long that
/// strategy has been in
/// liquidation mode.
interface IStrategySlippageModel {
    function calculateSlippage(uint256 timeSinceLiquidationStarted) external view returns (UD60x18 slippageTolerance);
}

File 55 of 73 : IStrategyVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18 } from "@prb/math/src/UD60x18.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Vault } from "contracts/libraries/types/Vault.sol";

abstract contract StrategyVaultEvents {
    /// @notice The deposit cap has been updated to `newDepositCap`
    event DepositCapUpdated(uint256 newDepositCap);
    event MaxDepositPerAccountUpdated(uint256 newMaxDeposit);
    event DepositFeeUpdated(uint256 newDepositFee);
    event WithdrawalFeeUpdated(uint256 newWithdrawalFee);
    event LiquidationSlippageModelUpdated(address newModel);
    event DepositFeeTaken(uint256 amount);
}

/// @title Omega Strategy Vault Interface
///
/// @notice These vaults accept USDC and invest them into a strategy.
/// The deposit is done in USDC but the shares are in the underlying asset.
/// The underlying asset is referred to as `asset` in the contract.
/// These vaults implement _some_ ERC4626 methods.
/// There is one significant change for these vaults: the deposit is
/// done using USDC instead of the `asset` (i.e. the underlying asset).
///
/// @dev Shares are priced in units of the `asset` NOT in USDC
///
interface IStrategyVault {
    function setTotalDepositCap(uint256 newDepositCap) external;
    function setMaxDepositPerAccount(uint256 newMaxDeposit) external;
    function setDepositFee(UD60x18 newDepositFee) external;
    function setWithdrawalFee(UD60x18 newWithdrawalFee) external;

    function getTotalBaseDeposit() external view returns (uint256);
    function getBaseAsset() external view returns (IERC20);
    function getVaultParams() external view returns (Vault.Parameters memory);

    /// @notice Estimate the ETH execution fee needed for this withdrawal
    function estimateExecuteDepositGasLimit() external view returns (uint256);
    function estimateExecuteWithdrawalGasLimit() external view returns (uint256);

    /// @notice Deposits USDC into the vault
    /// @param assets The amount of USDC to deposit
    /// @param data encoded data for the strategy to process the deposit
    /// @param recipient The address to send the share tokens to
    function deposit(
        uint256 assets,
        bytes memory data,
        address recipient
    )
        external
        payable
        returns (uint256 receivedShares);

    /// @notice Withdraws `msg.sender` shares from the vault and sends baseAsset to self.
    /// @param shares The amount of vault shares to withdraw
    /// @param data encoded data for the strategy to process the withdrawal
    function withdraw(uint256 shares, bytes memory data) external payable returns (uint256 receivedAmount);

    /// @notice Performs a complete withdrawal for `msg.sender` and sends funds to receiver.
    function liquidate(address receiver, uint256 minAmount, bytes memory data) external payable returns (uint256);

    /// @notice This function allows users to simulate the effects of their withdrawal at the current block.
    /// @dev Use this to calculate the minAmount of lend token to withdraw during withdrawal
    /// @param shareAmount The amount of shares to redeem
    /// @return The amount of lend token that would be redeemed for the amount of shares provided
    function previewWithdraw(uint256 shareAmount) external view returns (uint256);

    /// @notice This function allows users to simulate the effects of their deposit at the current block.
    /// @dev Use this to calculate the minAmount of shares to mint during deposit
    /// @param assetAmount The amount of assets to deposit
    /// @return The amount of shares that would be minted for the amount of asset provided
    function previewDeposit(uint256 assetAmount) external view returns (uint256);

    function previewDepositOffchain(uint256 assetAmount) external returns (uint256);
    function previewWithdrawOffchain(uint256 shareAmount) external returns (uint256);

    /// @notice Returns value of the position of the account denominated in lending token.
    function getPositionValue(address account) external view returns (uint256);
}

File 56 of 73 : JuiceAccount.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IStrategyVault } from "../interfaces/IStrategyVault.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import { BlastGas } from "contracts/juice/periphery/BlastGas.sol";
import "../external/blast/IERC20Rebasing.sol";
import "../accounts/InternalAccount.sol";
import "../libraries/Errors.sol";
import "../system/ProtocolModule.sol";

/// @title Juice Account
/// @notice This account type is used to manage investments into approved strategies.
/// The account owner can deposit and withdraw from approved strategies to earn profits.
contract JuiceAccount is InternalAccount, BlastGas {
    using SafeERC20 for IERC20;

    /// @notice Initialize this permissioned account
    /// @param owner_  The borrower that owns this account
    function initialize(address owner_) public virtual override initializer {
        _initialize(owner_);

        address _protocolGovernor = ProtocolModule(address(_manager)).getProtocolGovernor();
        __BlastGas_init(_protocolGovernor);

        // Configure Blast Yield
        IERC20Rebasing(address(asset)).configure(YieldMode.CLAIMABLE);

        // Configure Blast Points
        IBlastPoints blast =
            IBlastPoints(IProtocolGovernor(_protocolGovernor).getImmutableAddress(GovernorLib.BLAST_POINTS));
        address operator_ =
            IProtocolGovernor(_protocolGovernor).getAddress(GovernorLib.BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR);

        if (operator_ == address(0)) {
            revert Errors.InvalidParams();
        } else {
            blast.configurePointsOperator(operator_);
        }
    }

    function getKind() external pure override returns (bytes32) {
        return keccak256(abi.encode("JUICE_INVESTMENT_ACCOUNT"));
    }

    function claimYield() external {
        uint256 claimableYield = IERC20Rebasing(address(asset)).getClaimableAmount(address(this));
        address protocolFeeCollector = IProtocolGovernor(ProtocolModule(address(_manager)).getProtocolGovernor())
            .getAddress(GovernorLib.FEE_COLLECTOR);

        if (protocolFeeCollector == address(0)) {
            revert Errors.InvalidParams();
        }

        IERC20Rebasing(address(asset)).claim(protocolFeeCollector, claimableYield);
    }
}

File 57 of 73 : BlastGas.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "../../interfaces/IProtocolGovernor.sol";
import "../../libraries/GovernorLib.sol";
import "../../external/blast/IBlast.sol";

/// @title BlastGas
/// @notice Exposes a method to claim gas refunds from the contract and send them to the protocol.
abstract contract BlastGas {
    IProtocolGovernor private _protocolGovernor;

    event GasRefundClaimed(address indexed recipient, uint256 gasClaimed);

    function __BlastGas_init(address protocolGovernor_) internal {
        _protocolGovernor = IProtocolGovernor(protocolGovernor_);

        IBlast blast = IBlast(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST));
        blast.configureClaimableGas();
    }

    /// @notice Claims the maximum possible gas from the contract with some recipient.
    /// @dev This is permissionless because funds will go to the protocol gasFeeWallet and the maximum possible gas will
    /// be claimed each time.
    /// @dev IBlast.claimMaxGas guarnatees a 100% claim rate, but not all pending gas fees will be claimed.
    /// @dev To check the current gas fee information of a contract, call IBlast.readGasParams(contractAddress).
    function claimMaxGas() external returns (uint256 gasClaimed) {
        IBlast blast = IBlast(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST));
        address _feeCollector = _protocolGovernor.getAddress(GovernorLib.FEE_COLLECTOR);
        gasClaimed = blast.claimMaxGas(address(this), _feeCollector);
        emit GasRefundClaimed(_feeCollector, gasClaimed);
    }
}

File 58 of 73 : BlastPoints.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "../../interfaces/IProtocolGovernor.sol";
import "../../libraries/GovernorLib.sol";
import "../../external/blast/IBlast.sol";

/// @title BlastPoints
/// @notice Configures a hot wallet that operates the points API for this contract.
abstract contract BlastPoints {
    IProtocolGovernor private _protocolGovernor;

    event PointsOperatorConfigured(address indexed operator);

    function __BlastPoints_init(address protocolGovernor_, address pointsOperator_) internal {
        _protocolGovernor = IProtocolGovernor(protocolGovernor_);

        IBlastPoints blast = IBlastPoints(_protocolGovernor.getImmutableAddress(GovernorLib.BLAST_POINTS));
        blast.configurePointsOperator(pointsOperator_);
    }
}

File 59 of 73 : Errors.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

// @notice Collections of protocol error messages.
library Errors {
    // GENERAL

    /// @notice Unauthorized access
    error Unauthorized();
    /// @notice Disabled functionality
    error FunctionalityDisabled();
    /// @notice Functionality not supported
    error FunctionalityNotSupported();
    /// @notice Invalid parameters passed to function
    error InvalidParams();
    /// @notice ZeroAddress
    error ZeroAddress();
    /// @notice Contract does not exist
    error ContractDoesNotExist();
    /// @notice Invalid amount requested by caller
    error InvalidAmount();
    /// @notice when parameter cannot be equal to zero
    error ParamCannotBeZero();
    /// @notice ERC20 is not transferrable
    error TransferDisabled();
    /// @notice Address doesn't have role
    error UnauthorizedRole(address account, string role);
    /// @notice Action disabled because contract is deprecated
    error Deprecated();

    // ACCESS
    // NOTE: maybe this should be refactored into a generic Errors
    /// @notice Only the lending pool can call this function
    error OnlyLendingPool();

    // COLLATERAL
    /// @notice Invalid collateral monitor update
    error InvalidCollateralMonitorUpdate();
    error NoTellorValueRetrieved(uint256 timestamp);
    error StaleTellorValue(uint256 value, uint256 timestamp);
    error StaleTellorEVMCallTimestamp(uint256 callTimestamp);
    error CannotGoBackInTime();

    error InvalidYieldClaimed(uint256 expectedYield, uint256 actualYield);

    // LENDING
    /// @notice Insufficient liquidity to fulfill action
    error InsufficientLiquidity();
    /// @notice User doesn't have enough collateral backing their position
    error InsufficientCollateral();
    /// @notice Requested borrow is not greater than minimum open borrow amount
    error InvalidMinimumOpenBorrow();

    /// @notice Deposit cap exceeded
    error DepositCapExceeded();
    /// @notice Max deposit per account exceeded
    error MaxDepositPerAccountExceeded();

    // FLASH LOANS
    /// @notice Invalid flash loan balance
    error InvalidFlashLoanBalance();
    /// @notice Invalid flash loan asset
    error InvalidFlashLoanAsset();
    /// @notice Flash loan unpaid
    error InvalidPostFlashLoanBalance();
    /// @notice Invalid flash loan fee
    error InsufficientFlashLoanFeeAmount();
    /// @notice Flash loan recipient doesn't return success
    error InvalidFlashLoanRecipientReturn();

    // ACCOUNTS
    /// @notice Account failed solvency check after some action.
    /// @dev The account's debt isn't sufficiently collateralized and/or the account is liquidatable.
    error AccountInsolvent();
    /// @dev Account cannot be liquidated
    error AccountHealthy();
    /// @notice Account is being liquidated
    error AccountBeingLiquidated();
    /// @notice Account is not being liquidated
    error AccountNotBeingLiquidated();
    /// @notice Account hasn't been created yet
    error AccountNotCreated();

    // INVESTMENT
    /// @notice Account is not liquidatable
    error NotLiquidatable();
    /// @notice Account is not repayable
    error NotRepayable();

    /// @notice Account type invalid
    error InvalidAccountType();

    /// @notice Interaction with a strategy that is not approved
    error StrategyNotApproved();
    /// @notice Liquidator has no funds to repay
    error NoLiquidatorFunds();
    /// @notice Requested profit is not claimable from account (if account has debt or not enough profit to fill request
    /// amount)
    error NotClaimableProfit();
    /// @notice Used when Gelato automation task was already started
    error AlreadyStartedTask();
    /// @notice Assets not received
    error WithdrawnAssetsNotReceived();

    ///////////////////////////
    // Multi-step Strategies
    ///////////////////////////

    /// @notice Account is attempting to withdraw more strategy shares than their unlocked share balance.
    /// @dev An account's balanceOf(strategyShareToken) is their totalShareBalance.
    /// Since some strategies are multi-step, when a account withdraws, those shares are added to a separate variable
    /// known
    /// as their lockedShareBalance.
    /// A account's unlocked share balance when it comes to withdrawals is their totalShareBalance - lockedShareBalance.
    error PendingStrategyWithdrawal(address account);

    /// @notice Account cannot deposit into the same multi-step strategy until their previous deposit has cleared.
    error PendingStrategyDeposit(address account);

    //////////////////////////
    /// OmegaGMXStrategyVault
    //////////////////////////

    /// @notice When already exist a depositKey in the vault
    error MustNotHavePendingValue();
    /// @notice When not sending eth to pay for the fee in a deposit or withdrawal
    error MustSendETHForExecutionFee();

    /// Pyth
    error PythPriceFeedNotFound(address asset);
    error PythInvalidNonPositivePrice(address asset);

    // Particle
    error ExistingPosition();
    error NoPosition();

    // strategy
    error Strategy__MinAssetValueDeposited();
    error Strategy__MinReceivedAssets();
    error Strategy__Expired();
}

File 60 of 73 : GovernorLib.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

/// @notice Store keys used by stores in a Governor contract (ProtocolGovernor, etc).
library GovernorLib {
    ///////////////
    // COMMON
    ///////////////

    /// @notice Returns price of an asset given some address. Prices are denominated in the lending pool loan asset.
    bytes32 public constant PRICE_PROVIDER = keccak256(abi.encode("PRICE_PROVIDER"));

    /// @notice Address that receives fee generated by lending, accounts, and strategies
    bytes32 public constant FEE_COLLECTOR = keccak256(abi.encode("FEE_COLLECTOR"));

    /// @notice Address that is responsible for issuing gas reimbursements to protocol contracts
    bytes32 public constant GAS_TANK = keccak256(abi.encode("GAS_TANK"));

    /// @notice Lending Pool
    bytes32 public constant LENDING_POOL = keccak256(abi.encode("LENDING_POOL"));

    /// @notice Gelato Automate
    bytes32 public constant GELATO_AUTOMATE = keccak256(abi.encode("GELATO_AUTOMATE"));

    /// @notice Asset used to facilitate lending and borrowing.
    bytes32 public constant LEND_ASSET = keccak256(abi.encode("LEND_ASSET"));

    /// @notice Blast native contract implementing IBlast interface for configuring gas refunds and native ETH rebasing.
    bytes32 public constant BLAST = keccak256(abi.encode("BLAST"));

    /// @notice Blast native contract used on contract initialization to assign an operator that configures points
    /// received by that smart contract.
    bytes32 public constant BLAST_POINTS = keccak256(abi.encode("BLAST_POINTS"));

    bytes32 public constant BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR =
        keccak256(abi.encode("BLAST_POINTS_JUICE_ACCOUNTS_OPERATOR"));

    /// @dev Currently unused. Was meant to allow Accounts to redirect yield from idle borrow back to Lending Pool.
    bytes32 public constant BLAST_LENDER_YIELD_SINK = keccak256(abi.encode("BLAST_LENDER_YIELD_SINK"));

    ///////////////
    // FEES
    ///////////////

    bytes32 public constant LENDING_FEE = keccak256(abi.encode("LENDING_FEE"));

    bytes32 public constant FLASH_LOAN_FEE = keccak256(abi.encode("FLASH_LOAN_FEE"));

    /// @notice % taken from any funds used to repay debt during liquidating state.
    /*
    If an Account with 100 USDB Strategy position gets liquidated with protocolShare of 4%, liquidatorShare of 1%.
        If no slippage, 100 USDB is received by Repayment contract.
        
        Repayment contract is executed with:
            - 4 USDB going to protocol
            - 1 USDB going to liquidator
            - 95 USDB going to repay Account debt
    */
    bytes32 public constant PROTOCOL_LIQUIDATION_SHARE = keccak256(abi.encode("PROTOCOL_LIQUIDATION_SHARE"));

    bytes32 public constant LIQUIDATOR_SHARE = keccak256(abi.encode("LIQUIDATOR_SHARE"));
}

File 61 of 73 : Roles.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "./Errors.sol";
import "../interfaces/IProtocolGovernor.sol";

/// @notice List of permissions that can be granted to addresses.
library Roles {
    /// @notice Gas tank depositor
    bytes32 public constant GAS_TANK_DEPOSITOR = keccak256(abi.encode("GAS_TANK_DEPOSITOR"));

    /// @notice Protocol maintainer
    /// @dev A trusted address that can perform maintenance tasks. This will likely be a hot wallet.
    bytes32 public constant PROTOCOL_MAINTAINER = keccak256(abi.encode("PROTOCOL_MAINTAINER"));

    function _validateRole(
        IProtocolGovernor governor,
        address account,
        bytes32 role,
        string memory roleName
    )
        internal
        view
    {
        if (!governor.hasRole(role, account)) {
            revert Errors.UnauthorizedRole(account, roleName);
        }
    }
}

File 62 of 73 : AccountLib.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";

library AccountLib {
    /// @notice The type of account that can be created
    enum Type {
        EXTERNAL, // Accounts that allow taking funds out of the protocol
        INTERNAL // Accounts that require funds remain in the protocol

    }

    /// @notice The health of the account
    /// The collateral and equity values are all denominated in the debt amount.
    struct Health {
        uint256 debtAmount;
        uint256 collateralValue;
        uint256 investmentValue;
        UD60x18 healthFactor;
        bool isLiquidatable;
        bool isRisky;
        bool hasBadDebt;
    }

    /// @notice Expected values resulting from a collateral liquidation.
    /// @param actualDebtToLiquidate the amount of debt to cover for the account
    /// @param collateralAmount the amount of collateral to receive
    /// @param bonusCollateral the amount of bonus collateral included in the collateralAmount
    struct CollateralLiquidation {
        uint256 actualDebtToLiquidate;
        uint256 collateralAmount;
        uint256 bonusCollateral;
    }

    /// @notice The state of an account's lending pool loan
    struct Loan {
        /// @notice The amount of debt the borrower has
        uint256 debtAmount;
        /// @notice The value of the borrowers collateral in debt token
        uint256 collateralValue;
        /// @notice The current loan to value ratio of the borrower
        UD60x18 ltv;
        /// @notice Borrower cannot perform a borrow if it puts their ltv over this amount
        UD60x18 maxLtv;
    }

    struct LiquidationStatus {
        bool isLiquidating;
        uint256 liquidationStartTime;
    }

    /*  @notice Liquidator fee.
        @dev protocolShare + liquidatorShare = liquidationFee.
        liquidationFee is % deducted from liquidated funds before they are used towards repayment.
    */
    struct LiquidationFee {
        UD60x18 protocolShare;
        UD60x18 liquidatorShare;
    }

    /// @notice
    struct CreateAccountProps {
        address owner;
        AccountLib.Type accountType;
    }

    /// @notice Custom meta txn for creating an account
    struct CreateAccountData {
        address owner;
        uint256 accountType;
        bytes signature;
    }

    /// @notice Data to sign when creating an account gaslessly
    struct CreateAccount {
        address owner;
        uint256 accountType;
    }
}

File 63 of 73 : AddressCheckerTrait.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "../Errors.sol";

/// @title Address checker trait
/// @notice Introduces methods and modifiers for checking addresses
abstract contract AddressCheckerTrait {
    /// @dev Prevents a contract using an address if it is a zero address
    modifier nonZeroAddress(address _address) {
        if (_address == address(0)) {
            revert Errors.ZeroAddress();
        }
        _;
    }

    /// @dev Prevents a contract using an address if it is either a zero address or is not an existing contract
    modifier nonZeroAddressAndContract(address _address) {
        if (_address == address(0)) {
            revert Errors.ZeroAddress();
        }
        if (!_contractExists(_address)) {
            revert Errors.ContractDoesNotExist();
        }
        _;
    }

    /// @notice Returns true if addr is a contract address
    /// @param addr The address to check
    function _contractExists(address addr) internal view returns (bool) {
        return addr.code.length > 0;
    }
}

File 64 of 73 : Vault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import { IStrategySlippageModel } from "contracts/interfaces/IStrategySlippageModel.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

library Vault {
    struct BaseInitProps {
        address protocolGovernor;
        string vaultName;
        string vaultSymbol;
        address baseAsset;
    }

    struct Parameters {
        /// @notice The maximum amount of baseAsset that can be deposited into the vault per user.
        uint256 maxDepositPerAccount;
        /// @notice The total cap to apply to deposits in baseAsset.
        uint256 totalDepositCap;
        UD60x18 depositFee;
        UD60x18 withdrawalFee;
        IStrategySlippageModel liquidationSlippageModel;
    }
}

File 65 of 73 : AccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import "solady/src/utils/FixedPointMathLib.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { ProtocolModule, ProtocolGovernor } from "../system/ProtocolModule.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { ILendingPool } from "../interfaces/ILendingPool.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol";
import { BaseAccount } from "../accounts/BaseAccount.sol";
import { IAccount } from "../interfaces/IAccount.sol";
import { IAssetPriceOracle } from "../interfaces/IAssetPriceOracle.sol";
import { InternalAccount } from "../accounts/InternalAccount.sol";
import { ExternalAccount } from "../accounts/ExternalAccount.sol";
import "../interfaces/IStrategyVault.sol";
import "../interfaces/IAccountManager.sol";
import "../interfaces/IInternalAccount.sol";
import "../interfaces/IAssetPriceProvider.sol";
import "../interfaces/ILiquidationReceiver.sol";
import "../libraries/accounts/AccountLib.sol";
import "../libraries/Errors.sol";

/// @title Account Factory Events
/// @dev Place all events used by the AccountManager contract here
abstract contract AccountManagerEvents {
    /// @notice Additional fees charged to an account (in addition to their lending pool debt).
    event FeesCharged(address indexed account, uint256 amount);
    /// @notice Account liquidation started
    event AccountLiquidationStarted(address indexed account);
    /// @notice Account liquidation completed
    event AccountLiquidationCompleted(address indexed account);
    /// @notice A user has borrowed.
    event AccountBorrowed(address indexed owner, address indexed account, uint256 amount);
    /// @notice A user has repaid.
    event AccountRepaid(address indexed owner, address indexed account, uint256 amount);
    event LiquidationFeesTaken(
        address indexed feeCollector, address indexed liquidator, uint256 protocolShare, uint256 liquidatorShare
    );
    /// @dev LiquidationReceiver is created per (account, liquidationFeeTo).
    event LiquidationReceiverCreated(
        address indexed account, address indexed liquidationFeeTo, address liquidationReceiver
    );
    /// @notice User claimed assets from their account.
    event AccountClaimed(address indexed owner, address indexed account, uint256 amount);
}

/// @title AccountManager
/// @notice The AccountManager contract deploys Account contracts.
/// Investment Accounts are only createable by the owner of this contract or
/// accounts approved by the admin (known as account creators).
abstract contract AccountManager is IAccountManager, Pausable, AccountManagerEvents, ProtocolModule, ReentrancyGuard {
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;
    using Address for address;
    using FixedPointMathLib for uint256;

    error OldAccountDoesNotExist();
    error HealthFactorSnapshotNotFound();
    error RemainingDebtLeft();

    /// @notice The LendingPool contract address for Investment Accounts to use
    ILendingPool internal immutable _lendingPool;

    IERC20 internal immutable _lendAsset;

    /// @notice An mapping of all Account contracts that have been created
    mapping(address => bool) public isCreatedAccount;

    /// @notice Account to their owner.
    mapping(address => address) internal _accountOwnerCache;

    mapping(address => uint256) internal _accountLiquidationStartTime;
    mapping(address => mapping(address => ILiquidationReceiver)) public liquidationReceiver;
    mapping(address => bool) internal _isLiquidationReceiver;

    /// @notice Counter to keep track of the number of Account contracts that have been created
    uint256 public accountCount;

    bool public allowedAccountsMode;

    mapping(address => bool) public isAccountAllowed;

    /// @dev Used for storing the health factor of an account for comparison before and after some action.
    mapping(address => UD60x18) internal _accountHealthFactorSnapshot;

    // Account configurations
    ///////////////////////////
    address immutable liquidationReceiverImpl;

    modifier onlyAccount() {
        if (!isCreatedAccount[msg.sender]) {
            revert Errors.Unauthorized();
        }
        if (allowedAccountsMode && !isAccountAllowed[msg.sender]) {
            revert Errors.Unauthorized();
        }
        _;
    }

    /// @notice Constructs the factory
    constructor(
        address protocolGovernor_,
        address liquidationReceiverImpl_
    )
        ProtocolModule(protocolGovernor_)
        nonZeroAddressAndContract(address(_getPriceProvider()))
        nonZeroAddressAndContract(_getLendingPool())
        nonZeroAddressAndContract(liquidationReceiverImpl_)
    {
        liquidationReceiverImpl = liquidationReceiverImpl_;
        _lendingPool = ILendingPool(_getLendingPool());
        _lendAsset = IERC20(_getLendAsset());
        allowedAccountsMode = true;
    }

    //////////////////////////
    // Account Administration
    //////////////////////////

    function setAllowedAccountsMode(bool status) external onlyOwner {
        allowedAccountsMode = status;
    }

    function setAllowedAccountStatus(address account, bool status) external onlyOwner {
        isAccountAllowed[account] = status;
    }

    function isLiquidationReceiver(address receiver) external view returns (bool) {
        return _isLiquidationReceiver[receiver];
    }

    function getAccountOwner(address account) external view returns (address owner) {
        owner = _accountOwnerCache[account];
    }

    /// @notice Let the owner pause deposits and borrows
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Let the owner unpause deposits and borrows
    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Lets the admin pause the account
    function pauseAccount(address account) external onlyOwner {
        IAccount(account).pause();
    }

    /// @notice Lets the admin unpause the account
    function unpauseAccount(address account) external onlyOwner {
        IAccount(account).unpause();
    }

    /////////////////////////////
    // Account Functionality
    /////////////////////////////

    function borrow(uint256 amount) external virtual onlyAccount nonReentrant returns (uint256 borrowed) {
        borrowed = _borrow(msg.sender, amount);
    }

    function _borrow(address caller, uint256 amount) internal whenNotPaused returns (uint256 borrowed) {
        borrowed = _lendingPool.borrow(amount, caller);

        _requireSolventCheckBorrow(caller, true);

        emit AccountBorrowed(_accountOwnerCache[caller], caller, borrowed);

        this._afterBorrow(caller, borrowed);
    }

    function repay(address account, uint256 amount) external virtual nonReentrant returns (uint256 repaid) {
        // Debt repaid is onBehalfOf, funds are transferred from `from`.
        repaid = _lendingPool.repay(amount, account, msg.sender);

        emit AccountRepaid(_accountOwnerCache[account], account, repaid);

        this._afterRepay(account, repaid);
    }

    /// @notice Called by Account when its Owner wants to withdraw excess funds.
    /// @param amount The amount to withdraw
    /// @param recipient The address to send the assets to
    function claim(uint256 amount, address recipient) external nonZeroAddress(recipient) onlyAccount nonReentrant {
        _lendAsset.safeTransferFrom(msg.sender, recipient, amount);
        _requireSolventCheckBorrow(msg.sender, true);

        emit AccountClaimed(_accountOwnerCache[msg.sender], msg.sender, amount);
    }

    /// @dev Account cannot do any actions involving snapshots if it is being liquidated.
    function snapshotAccountHealthFactor() external onlyAccount {
        AccountLib.Health memory health = getAccountHealth(msg.sender);
        if (health.isLiquidatable) revert Errors.AccountBeingLiquidated();
        _accountHealthFactorSnapshot[msg.sender] = health.healthFactor;
    }

    /// @notice Mark an account as liquidatable.
    function liquidate(
        address account,
        address liquidationFeeTo
    )
        external
        returns (ILiquidationReceiver liquidationReceiver_)
    {
        return _startLiquidation(account, liquidationFeeTo);
    }

    function emitLiquidationFeeEvent(
        address feeCollector_,
        address liquidationFeeTo,
        uint256 protocolShare,
        uint256 liquidatorShare
    )
        external
    {
        if (!_isLiquidationReceiver[msg.sender]) revert Errors.Unauthorized();
        emit LiquidationFeesTaken(feeCollector_, liquidationFeeTo, protocolShare, liquidatorShare);
    }

    /// @dev Starts the liquidation process on an Account if it is liquidatable.
    function _startLiquidation(
        address account,
        address liquidationFeeTo
    )
        internal
        returns (ILiquidationReceiver liquidationReceiver_)
    {
        AccountLib.Health memory health = getAccountHealth(account);

        if (!health.isLiquidatable) revert Errors.AccountHealthy();

        liquidationReceiver_ = liquidationReceiver[account][liquidationFeeTo];

        // Create the liquidator receiver.
        if (address(liquidationReceiver_) == address(0)) {
            liquidationReceiver_ = ILiquidationReceiver(
                Clones.cloneDeterministic(liquidationReceiverImpl, keccak256(abi.encode(account, liquidationFeeTo)))
            );
            liquidationReceiver_.initialize(
                ILiquidationReceiver.Props({
                    account: IAccount(account),
                    manager: IAccountManager(address(this)),
                    liquidationFeeTo: liquidationFeeTo,
                    asset: _lendAsset
                })
            );
            liquidationReceiver[account][liquidationFeeTo] = liquidationReceiver_;
            _isLiquidationReceiver[address(liquidationReceiver_)] = true;
            emit LiquidationReceiverCreated(account, liquidationFeeTo, address(liquidationReceiver_));
        }

        // Account has idle borrowed funds, transfer them to the liquidator receiver.
        if (_lendAsset.balanceOf(address(account)) > 0) {
            _lendAsset.safeTransferFrom(
                address(account), address(liquidationReceiver_), _lendAsset.balanceOf(address(account))
            );
            liquidationReceiver_.repay();
        }

        // Mark account as liquidatable if it isn't already.
        if (_accountLiquidationStartTime[account] == 0) {
            _accountLiquidationStartTime[account] = block.timestamp;
            emit AccountLiquidationStarted(account);
            this._afterLiquidationStarted(account);
        }
    }

    function _completeLiquidation(address account) external onlySelf {
        delete _accountLiquidationStartTime[account];
        emit AccountLiquidationCompleted(account);
        this._afterLiquidationCompleted(account);
    }

    /// @dev Used to get the health factor of an account at the current block number.
    function _getLatestAccountHealthFactorSnapshot(address account) internal view returns (UD60x18 healthFactor) {
        healthFactor = _accountHealthFactorSnapshot[account];
        if (healthFactor == ZERO) revert HealthFactorSnapshotNotFound();
    }

    /////////////////////////
    // Account Views
    /////////////////////////

    function lendingPool() external view returns (address) {
        return address(_lendingPool);
    }

    function getLiquidationReceiver(
        address account,
        address liquidationFeeTo
    )
        external
        view
        returns (ILiquidationReceiver)
    {
        return ILiquidationReceiver(
            Clones.predictDeterministicAddress(
                liquidationReceiverImpl, keccak256(abi.encode(account, liquidationFeeTo))
            )
        );
    }

    function getFeeCollector() external view returns (address) {
        return _getFeeCollector();
    }

    function getLendAsset() external view returns (IERC20) {
        return _lendingPool.getAsset();
    }

    function getAccountLiquidationStatus(address account) external view returns (AccountLib.LiquidationStatus memory) {
        return AccountLib.LiquidationStatus({
            isLiquidating: _accountLiquidationStartTime[account] > 0,
            liquidationStartTime: _accountLiquidationStartTime[account]
        });
    }

    function getLiquidationFee() external view returns (AccountLib.LiquidationFee memory fee) {
        fee.protocolShare = _protocolLiquidationShare();
        fee.liquidatorShare = _liquidatorShare();
    }

    function getDebtAmount(address account) public view virtual returns (uint256) {
        return _lendingPool.getDebtAmount(account);
    }

    function getAccountLoan(address account) public view returns (AccountLib.Loan memory) {
        uint256 collateralValue = getTotalCollateralValue(account);
        uint256 debt = getDebtAmount(account);
        UD60x18 ltv = ZERO;
        if (collateralValue > 0) {
            ltv = ud(debt).div(ud(collateralValue));
        }
        return AccountLib.Loan({
            debtAmount: debt,
            collateralValue: collateralValue,
            ltv: ltv,
            maxLtv: _getAccountMaxLtv(account)
        });
    }

    function getAccountHealth(address) public view virtual returns (AccountLib.Health memory health);

    /// @dev Total value of investments sitting in the Account.
    function getTotalAccountValue(address account) public view virtual returns (uint256 totalValue);

    /// @dev Total value of collateral attributed to the Account.
    function getTotalCollateralValue(address account) public view virtual returns (uint256 totalValue) { }

    /// @notice Used to ensure the account has performed an operation that doesn't put their loan into an insolvent
    /// state.
    function _requireSolvent(address account) internal view {
        _requireSolventCheckBorrow(account, false);
    }

    function _requireSolventCheckBorrow(address account, bool checkBorrow) internal view {
        // Actions depending on solvency cannot be performed during liquidation state.
        if (_accountLiquidationStartTime[account] > 0) {
            revert Errors.AccountBeingLiquidated();
        }

        // Only perform solvency check if Account has debt.
        if (getDebtAmount(account) > 0) {
            AccountLib.Health memory health = getAccountHealth(account);

            if (checkBorrow) {
                uint256 borrowLimit = ud(health.collateralValue).mul(_getAccountMaxLtv(account)).unwrap();

                // Check if borrowed debt is fully collateralized based off max ltv.
                if (health.debtAmount > borrowLimit) {
                    revert Errors.AccountInsolvent();
                }
            }

            // If debt is considered fully collateralized, check if the account is at risk (this keeps it some % above
            // the liquidation threshold).
            if (health.isRisky) {
                revert Errors.AccountInsolvent();
            }
        }
    }

    ///////////////////
    // HOOKS
    ///////////////////

    function _afterRepay(address account, uint256) external virtual onlySelf {
        if (_accountLiquidationStartTime[account] > 0) {
            AccountLib.Health memory health = getAccountHealth(account);
            if (!health.isLiquidatable) {
                this._completeLiquidation(account);
            }
        }
    }

    function _afterBorrow(address account, uint256 borrowed) external virtual onlySelf { }

    function _afterLiquidationStarted(address account) external virtual onlySelf { }

    function _afterLiquidationCompleted(address account) external virtual onlySelf { }

    //////////////////
    // INTERNAL
    //////////////////

    function _getAccountMaxLtv(address account) internal view virtual returns (UD60x18);

    /// @notice Hashes an address with this contract's address
    /// @param addr The address to convert
    function _salt(address addr) internal view virtual returns (bytes32) {
        return keccak256(abi.encodePacked(addr));
    }
}

File 66 of 73 : CollateralAccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../managers/StrategyAccountManager.sol";
import "../interfaces/IAssetPriceProvider.sol";
import "../libraries/accounts/AccountLib.sol";
import "../libraries/Errors.sol";
import "../system/ERC20CollateralVault.sol";
import "../system/ProtocolModule.sol";
import "contracts/interfaces/ICollateralAccountManager.sol";

/// @title CollateralAccountManager supports one account implementation
/// @notice The AccountManager contract deploys Account contracts.
abstract contract CollateralAccountManager is
    StrategyAccountManager,
    ICollateralAccountManager,
    ERC20CollateralVault
{
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;
    using Address for address;

    UD60x18 public constant LIQUIDATION_BONUS = UD60x18.wrap(1.05e18); // 105% or 5%

    /// @notice The max loan to value for Accounts
    /// @dev If 200%, loan can be maximum 200% of their collateral value
    UD60x18 public maxLtv;

    /// @notice The risk threshold for accounts
    /// @dev (Investment value + Equity value) / Debt value > riskThreshold
    UD60x18 public riskThreshold;

    /// @notice The risk threshold for accounts
    /// @dev (Investment value + Equity value) / Debt value > liquidationThreshold
    UD60x18 public liquidationThreshold;

    /// @notice The implementation address of the Internal/External
    /// Account contracts to use for cloning
    address public immutable accountImplementation;

    mapping(address => address) internal _ownerAccountCache;

    struct InitParams {
        address account;
        address liquidationReceiver;
        address collateral;
        UD60x18 maxLtv;
        UD60x18 riskThreshold;
        UD60x18 liquidationThreshold;
        string name;
        string symbol;
        uint8 decimals;
    }

    /// @notice Constructs the factory
    /// @param params The parameters
    constructor(
        address protocolGovernor_,
        InitParams memory params
    )
        StrategyAccountManager(protocolGovernor_, params.liquidationReceiver)
        ERC20CollateralVault(params.collateral, params.name, params.symbol, params.decimals)
        nonZeroAddressAndContract(params.account)
    {
        accountImplementation = params.account;

        _validateLiquidationParameters(params.maxLtv, params.riskThreshold, params.liquidationThreshold);

        maxLtv = params.maxLtv;
        riskThreshold = params.riskThreshold;
        liquidationThreshold = params.liquidationThreshold;
    }

    function _validateLiquidationParameters(
        UD60x18 maxLtv_,
        UD60x18 riskThreshold_,
        UD60x18 liquidationThreshold_
    )
        internal
        pure
    {
        UD60x18 ratio = riskThreshold_.div(liquidationThreshold_);
        UD60x18 inverseLtv = UNIT + (UNIT / maxLtv_);

        if (ratio <= UNIT || ratio >= inverseLtv) {
            revert Errors.InvalidParams();
        }
    }

    /// @dev Updates maxLtv and riskThreshold.
    /// riskThreshold must always be less than maxLtv.
    function updateLiquidationParameters(
        UD60x18 maxLtv_,
        UD60x18 riskThreshold_,
        UD60x18 liquidationThreshold_
    )
        external
        onlyOwner
    {
        _validateLiquidationParameters(maxLtv_, riskThreshold_, liquidationThreshold_);
        maxLtv = maxLtv_;
        riskThreshold = riskThreshold_;
        liquidationThreshold = liquidationThreshold_;
        emit LiquidationParametersUpdated(maxLtv, riskThreshold, liquidationThreshold);
    }

    /// @dev This call requires that this contract is the account manager on the lending pool
    function createAccount() public nonReentrant returns (address payable account) {
        account = _createAccount(msg.sender);
    }

    function _createAccount(address caller) internal returns (address payable account) {
        address owner = caller;

        if (_ownerAccountCache[owner] != address(0)) {
            revert Errors.InvalidParams();
        }

        account = payable(Clones.cloneDeterministic(accountImplementation, _salt(owner)));

        // Record the account was created
        isCreatedAccount[account] = true;
        _ownerAccountCache[owner] = account;
        _accountOwnerCache[account] = owner;
        accountCount += 1;

        emit AccountCreated(owner, account);

        // Initialize the account
        IAccount(account).initialize(owner);
    }

    /// @dev Takes assets from `msg.sender`, deposits them into the contract, and mints shares to the receiver.
    /// The shares are nontransferrable and reside in the receiver's address, but are used to credit the receiver's
    /// account contract.
    function deposit(
        uint256 assets,
        address receiver
    )
        public
        virtual
        override(ERC20CollateralVault, ICollateralAccountManager)
        nonReentrant
        returns (uint256 updatedAssets, uint256 shares)
    {
        (updatedAssets, shares) = _deposit(assets, msg.sender, receiver);
    }

    function _deposit(
        uint256 assets,
        address caller,
        address receiver
    )
        internal
        returns (uint256 updatedAssets, uint256 shares)
    {
        address _receiverAccount = getAccount(receiver);
        if (!isCreatedAccount[_receiverAccount]) {
            revert Errors.InvalidParams();
        }
        (updatedAssets, shares) = super.deposit(assets, receiver);
        emit CollateralDeposit(receiver, _receiverAccount, caller, updatedAssets);
    }

    /// @dev Burns shares from the account of `msg.sender` and sends them to the receiver.
    /// `msg.sender` must be owner of account that owns the shares.
    function withdraw(
        uint256 shares,
        address receiver
    )
        public
        virtual
        override(ERC20CollateralVault, ICollateralAccountManager)
        nonReentrant
        returns (uint256 updatedAssets, uint256 updatedShares)
    {
        (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares);
    }

    function _withdraw(
        address caller,
        address receiver,
        uint256 shares
    )
        internal
        override
        returns (uint256 updatedAssets, uint256 updatedShares)
    {
        (updatedAssets, updatedShares) = super._withdraw(caller, receiver, shares);
        address account = getAccount(caller);
        _requireSolventCheckBorrow(account, true);
        emit CollateralWithdrawal(caller, getAccount(caller), receiver, updatedAssets);
    }

    ///////////////////////////
    // COLLATERAL LIQUIDATIONS
    ///////////////////////////

    /// @dev This calculation assumes that debt asset and collateral asset have the same decimals and have 18 decimal
    /// precision.
    function liquidateCollateral(address account, uint256 debtToCover, address liquidationFeeTo) public {
        AccountLib.Health memory health = getAccountHealth(account);

        if (!health.isLiquidatable) revert Errors.AccountHealthy();

        // Mark account as liquidatable if it isn't already.
        if (_accountLiquidationStartTime[account] == 0) {
            _accountLiquidationStartTime[account] = block.timestamp;
            emit AccountLiquidationStarted(account);
            this._afterLiquidationStarted(account);
        }

        // The collateral is credited to the owner of the Account, not the Account itself.
        address accountOwner = _accountOwnerCache[account];
        uint256 debtAmount = getDebtAmount(account);

        AccountLib.CollateralLiquidation memory _result =
            _simulateCollateralLiquidation(accountOwner, debtAmount, debtToCover);

        // Transfer collateral to caller and their fee wallet
        _withdrawAssets(accountOwner, msg.sender, _result.collateralAmount - _result.bonusCollateral);
        _withdrawAssets(accountOwner, liquidationFeeTo, _result.bonusCollateral);

        // Transfer debt from sender to account.
        _lendAsset.safeTransferFrom(msg.sender, account, _result.actualDebtToLiquidate);
        IAccount(account).repay(_result.actualDebtToLiquidate);

        emit CollateralLiquidation(
            account, _result.collateralAmount, _result.bonusCollateral, _result.actualDebtToLiquidate
        );
    }

    function simulateCollateralLiquidation(
        address account,
        uint256 debtToCover
    )
        external
        view
        returns (AccountLib.CollateralLiquidation memory)
    {
        // The collateral is credited to the owner of the Account, not the Account itself.
        address accountOwner = _accountOwnerCache[account];
        uint256 debtAmount = getDebtAmount(account);

        return _simulateCollateralLiquidation(accountOwner, debtAmount, debtToCover);
    }

    function _simulateCollateralLiquidation(
        address accountOwner,
        uint256 debtAmount,
        uint256 debtToCover
    )
        public
        view
        returns (AccountLib.CollateralLiquidation memory)
    {
        uint256 actualDebtToLiquidate = debtToCover > debtAmount ? debtAmount : debtToCover;
        uint256 collateralBalance = balanceOfAssets(accountOwner);
        (uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded) =
            _calculateAvailableCollateralToLiquidate(actualDebtToLiquidate, collateralBalance);

        if (debtAmountNeeded < actualDebtToLiquidate) {
            actualDebtToLiquidate = debtAmountNeeded;
        }

        return AccountLib.CollateralLiquidation({
            actualDebtToLiquidate: actualDebtToLiquidate,
            collateralAmount: collateralAmount,
            bonusCollateral: bonusCollateral
        });
    }

    function _calculateAvailableCollateralToLiquidate(
        uint256 debtToCover,
        uint256 collateralBalance
    )
        internal
        view
        returns (uint256 collateralAmount, uint256 bonusCollateral, uint256 debtAmountNeeded)
    {
        // TODO: revisit this if it matters because getAssetPrice is in decimals of lend asset.
        UD60x18 collateralPrice = ud(_getPriceProvider().getAssetPrice(address(_collateral)));

        uint256 maxCollateralAssetsToLiquidate = ud(debtToCover).mul(LIQUIDATION_BONUS).div(collateralPrice).unwrap();
        if (maxCollateralAssetsToLiquidate > collateralBalance) {
            collateralAmount = collateralBalance;
            debtAmountNeeded = collateralPrice.mul(ud(collateralAmount)).div(LIQUIDATION_BONUS).unwrap();
        } else {
            collateralAmount = maxCollateralAssetsToLiquidate;
            debtAmountNeeded = debtToCover;
        }

        UD60x18 debtAmountInCollateral = ud(debtAmountNeeded).div(collateralPrice);
        bonusCollateral = ud(collateralAmount).sub(debtAmountInCollateral).unwrap();
    }

    function _getAccountMaxLtv(address) internal view override returns (UD60x18) {
        return maxLtv;
    }

    /////////////////////////
    // Account Views
    /////////////////////////

    /// @notice Returns the Account contract address for a given owner, even if it hasn't been created yet.
    /// Returns address(0) if the account is not valid
    /// @param owner_  The owner of the Account contract
    function getAccount(address owner_) public view returns (address account) {
        account = _ownerAccountCache[owner_];
        if (account == address(0)) {
            account = Clones.predictDeterministicAddress(accountImplementation, _salt(owner_));
        }
    }

    function getAccountHealth(address account) public view override returns (AccountLib.Health memory health) {
        uint256 investmentValue = getTotalAccountValue(account);
        uint256 collateralValue = getTotalCollateralValue(account);
        uint256 debtAmount = getDebtAmount(account);
        uint256 equity = collateralValue + investmentValue;

        health = AccountLib.Health({
            isLiquidatable: false,
            isRisky: false,
            hasBadDebt: false,
            healthFactor: ZERO,
            debtAmount: debtAmount,
            collateralValue: collateralValue,
            investmentValue: investmentValue
        });

        if (debtAmount > 0 && equity > 0) {
            health.healthFactor = ud(equity).div(ud(debtAmount));
            health.isRisky = health.healthFactor < riskThreshold;
            health.isLiquidatable = health.healthFactor < liquidationThreshold;
        } else if (debtAmount > 0) {
            health.hasBadDebt = true;
        }
    }

    /// @dev The nontransferrable collateral vault shares are assigned to the owner of the account so we base
    /// @dev the value
    function getTotalCollateralValue(address account) public view override returns (uint256 totalValue) {
        address owner = _accountOwnerCache[account];
        uint256 assets = balanceOfAssets(owner);
        uint256 price = _getPriceProvider().getAssetPrice(address(_collateral));
        totalValue = (assets * price) / (10 ** _collateralAssetDecimals);
    }
}

File 67 of 73 : StrategyAccountManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "./AccountManager.sol";
import "solady/src/utils/FixedPointMathLib.sol";

/// @title Account Factory Events
/// @dev Place all events used by the AccountManager contract here
abstract contract StrategyAccountManagerEvents {
    /// @notice The owner has made their first deposit into `strategy`
    event StrategyActivated(address indexed owner, address indexed account, address indexed strategy);
    /// @notice The owner has withdrawn their last deposit from `strategy`
    event StrategyDeactivated(address indexed owner, address indexed account, address indexed strategy);
    /// @notice The admin has approved the account to use `strategy`
    event StrategyUpdated(address strategy, bool approval);
    /// @notice The slippage tolerated for withdraws from strategies has been updated to `tolerance`
    event MaximumSlippageToleranceUpdated(UD60x18 tolerance);
}

/// @title AccountManager
/// @notice The AccountManager contract deploys Account contracts.
/// Investment Accounts are only createable by the owner of this contract or
/// accounts approved by the admin (known as account creators).
abstract contract StrategyAccountManager is AccountManager, StrategyAccountManagerEvents {
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for IERC20;
    using Address for address;

    /// @notice The strategies that are approved to use for permissioned accounts
    mapping(address => bool) public approvedStrategies;

    /// @notice Map of accounts to their active strategies
    mapping(address => EnumerableSet.AddressSet) internal _activeStrategies;

    /// @notice Constructs the factory
    constructor(
        address protocolGovernor_,
        address liquidationReceiverImpl_
    )
        AccountManager(protocolGovernor_, liquidationReceiverImpl_)
    { }

    /// @notice Get an active strategy's address by index
    /// @param index The index of the active strategy
    function getActiveStrategy(address account, uint256 index) external view returns (address) {
        return _activeStrategies[account].at(index);
    }

    /// @notice Get the number of active strategies
    function getActiveStrategyCount(address account) external view returns (uint256) {
        return _activeStrategies[account].length();
    }

    /// @dev This is called by the Account to check if the strategy is approved.
    /// @dev Mainly to consolidate events into the Manager though.
    function strategyDeposit(
        address owner,
        address strategy,
        uint256 amount,
        bytes memory data
    )
        external
        payable
        virtual
        onlyAccount
        nonReentrant
        returns (uint256 shares)
    {
        shares = _strategyDeposit(msg.sender, owner, strategy, amount, data);
    }

    function _strategyDeposit(
        address caller,
        address owner,
        address strategy,
        uint256 amount,
        bytes memory data
    )
        internal
        returns (uint256 shares)
    {
        if (!approvedStrategies[strategy]) {
            revert Errors.StrategyNotApproved();
        }

        if (_activeStrategies[caller].add(strategy)) {
            emit StrategyActivated(owner, caller, strategy);
        }

        uint256 executionGasLimit = 0;
        if (strategy != address(0)) {
            executionGasLimit = IStrategyVault(strategy).estimateExecuteDepositGasLimit();
        }

        uint256 executionFee = 0;

        if (executionGasLimit > 0) {
            executionFee = executionGasLimit * tx.gasprice;
        }

        shares = IStrategyVault(strategy).deposit{ value: executionFee }(amount, data, caller);

        _requireSolventCheckBorrow(caller, true);
    }

    function strategyWithdrawal(
        address owner,
        address strategy,
        uint256 assets,
        bool didRepay
    )
        external
        virtual
        onlyAccount
        nonReentrant
    {
        _strategyWithdrawal(msg.sender, owner, strategy, assets, didRepay);
    }

    function _strategyWithdrawal(address caller, address owner, address strategy, uint256, bool didRepay) internal {
        // Deactivate the strategy if it has no more funds
        // Strategy balanceOf will not return less than 0
        // slither-disable-next-line incorrect-equality
        if (strategy != address(0) && IStrategyVault(strategy).getPositionValue(caller) == 0) {
            // slither-disable-next-line unused-return
            _activeStrategies[caller].remove(strategy);

            emit StrategyDeactivated(owner, caller, strategy);
        }

        // Caller repaid with strategy withdrawal, skip solvency check and make sure their health factor improved.
        // They should have requested for a snapshot to be taken earlier.
        if (didRepay) {
            UD60x18 lastHealthFactor = _getLatestAccountHealthFactorSnapshot(caller);
            UD60x18 currentHealthFactor = getAccountHealth(caller).healthFactor;

            if (lastHealthFactor > currentHealthFactor && getAccountHealth(caller).debtAmount > 0) {
                revert Errors.AccountInsolvent();
            }
            _accountHealthFactorSnapshot[caller] = ZERO;
        } else {
            _requireSolvent(caller);
        }
    }

    /// @dev LiquidationReceiver is the recipient of the liquidated funds.
    /// In case of multi transaction withdrawal strategies, liquidator must wait for liquidationReceiver to receive
    /// funds before
    /// calling liquidationReceiver.repay().
    function liquidateStrategy(
        address account,
        address liquidationFeeTo,
        address strategy,
        bytes memory data
    )
        external
        payable
        virtual
        returns (ILiquidationReceiver liquidationReceiver_)
    {
        if (!approvedStrategies[strategy]) {
            revert Errors.StrategyNotApproved();
        }

        liquidationReceiver_ = _startLiquidation(account, liquidationFeeTo);

        // We calculate this as the strategy level now. Leftover for backwards compatibility.
        uint256 minAmountAfterSlippage = 0;

        uint256 executionGasLimit = 0;
        if (strategy != address(0)) {
            executionGasLimit = IStrategyVault(strategy).estimateExecuteWithdrawalGasLimit();
        }

        uint256 executionFee = 0;

        if (executionGasLimit > 0) {
            executionFee = executionGasLimit * tx.gasprice;
        }

        IInternalAccount(account).liquidateStrategy{ value: executionFee }(
            strategy, address(liquidationReceiver_), minAmountAfterSlippage, data
        );

        // Deactivate the strategy if it has no more funds
        // Strategy balanceOf will not return less than 0
        // slither-disable-next-line incorrect-equality
        if (strategy != address(0) && IStrategyVault(strategy).getPositionValue(account) == 0) {
            // slither-disable-next-line unused-return
            _activeStrategies[account].remove(strategy);

            emit StrategyDeactivated(_accountOwnerCache[account], account, strategy);
        }

        if (_lendAsset.balanceOf(address(liquidationReceiver_)) > 0) {
            liquidationReceiver_.repay();
        }
    }

    /// @notice Get the value of all strategies investments
    /// @return totalValue The value of all strategy investments in lendAsset
    function getTotalAccountValue(address account) public view override returns (uint256 totalValue) {
        totalValue = _lendAsset.balanceOf(address(account));
        // Sum the value of all active strategy vaults
        // Note: This needs attention as getPositionValue may revert, it contains external calls
        // slither-disable-next-line calls-loop
        for (uint256 i = 0; i < _activeStrategies[account].length(); i++) {
            // Note: This needs attention as getPositionValue may revert, it contains external calls
            // slither-disable-next-line calls-loop
            totalValue += IStrategyVault(_activeStrategies[account].at(i)).getPositionValue(account);
        }
    }

    function updateStrategyApproval(address strategy, bool approval) external onlyOwner {
        approvedStrategies[strategy] = approval;
        emit StrategyUpdated(strategy, approval);
    }

    function isApprovedStrategy(address strategy) external view returns (bool) {
        return approvedStrategies[strategy];
    }
}

File 68 of 73 : Multicall.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

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

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

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

            results[i] = result;
        }
    }
}

File 69 of 73 : ERC20CollateralVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "../libraries/Errors.sol";
import "../libraries/traits/AddressCheckerTrait.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "solady/src/tokens/ERC20.sol";
import "solady/src/utils/FixedPointMathLib.sol";

/// @notice A vault that holds a single asset as collateral.
/// @dev It discards stealth donations and tracks its underlying collateral balance manually.
/// It is non-transferrable because of how it is used to track the collateral backing loans taken by user owned smart
/// contract accounts.
abstract contract ERC20CollateralVault is ERC20, AddressCheckerTrait {
    using SafeERC20 for IERC20;
    using FixedPointMathLib for uint256;

    IERC20 internal immutable _collateral;

    uint256 internal _totalCollateralAssets;

    uint8 internal immutable _collateralAssetDecimals;

    string private _name;
    string private _symbol;

    constructor(
        address collateral_,
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    )
        nonZeroAddressAndContract(collateral_)
    {
        _collateral = IERC20(collateral_);
        _collateralAssetDecimals = decimals_;
        _name = name_;
        _symbol = symbol_;
    }

    function name() public view override returns (string memory) {
        return _name;
    }

    function symbol() public view override returns (string memory) {
        return _symbol;
    }

    function decimals() public view override returns (uint8) {
        return _collateralAssetDecimals;
    }

    function deposit(uint256 assets, address receiver) public virtual returns (uint256 updatedAssets, uint256 shares) {
        (updatedAssets, shares) = _deposit(msg.sender, receiver, assets);
    }

    function withdraw(
        uint256 shares,
        address receiver
    )
        public
        virtual
        returns (uint256 updatedAssets, uint256 updatedShares)
    {
        (updatedAssets, updatedShares) = _withdraw(msg.sender, receiver, shares);
    }

    function previewDeposit(uint256 assets) public view virtual returns (uint256 updatedAssets, uint256 shares) {
        shares = _convertToShares(assets);
        updatedAssets = _convertToAssets(shares);
    }

    function previewWithdraw(uint256 shares) public view virtual returns (uint256 assets, uint256 updatedShares) {
        assets = _convertToAssets(shares);
        updatedShares = shares;
    }

    function _deposit(
        address caller,
        address receiver,
        uint256 assets
    )
        internal
        virtual
        returns (uint256 updatedAssets, uint256 shares)
    {
        (updatedAssets, shares) = previewDeposit(assets);
        _totalCollateralAssets += updatedAssets;
        _collateral.safeTransferFrom(caller, address(this), updatedAssets);
        _mint(receiver, shares);
    }

    function _withdraw(
        address caller,
        address receiver,
        uint256 shares
    )
        internal
        virtual
        returns (uint256 updatedAssets, uint256 updatedShares)
    {
        (updatedAssets, updatedShares) = previewWithdraw(shares);
        _totalCollateralAssets -= updatedAssets;
        _burn(caller, updatedShares);
        _collateral.safeTransfer(receiver, updatedAssets);
    }

    function _withdrawAssets(address caller, address receiver, uint256 assets) internal virtual {
        // Round up the amount of shares to burn given some assets.
        uint256 shares = assets.mulDivUp(totalSupply(), totalAssets());
        _totalCollateralAssets -= assets;
        shares = balanceOf(caller) < shares ? balanceOf(caller) : shares;
        _burn(caller, shares);
        _collateral.safeTransfer(receiver, assets);
    }

    /// @dev Returns the shares minted for given assets, rounding down.
    function _convertToShares(uint256 assets) internal view returns (uint256) {
        return totalSupply() == 0 ? assets : assets * totalSupply() / totalAssets();
    }

    /// @dev Returns the assets transferred for given shares, rounding down.
    function _convertToAssets(uint256 shares) internal view returns (uint256) {
        return totalSupply() == 0 ? shares : shares * totalAssets() / totalSupply();
    }

    function balanceOfAssets(address account) public view returns (uint256 assets) {
        return _convertToAssets(balanceOf(account));
    }

    function totalAssets() public view virtual returns (uint256) {
        return _totalCollateralAssets;
    }

    /// @notice Disables transfers other than mint and burn
    /// @dev Done explicitly because solady transfers do not prevent transferring to zero address.
    function transfer(address, uint256) public pure override returns (bool) {
        revert Errors.TransferDisabled();
    }

    function transferFrom(address, address, uint256) public pure override returns (bool) {
        revert Errors.TransferDisabled();
    }
}

File 70 of 73 : ProtocolGovernor.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import { UD60x18, ud, UNIT, ZERO } from "@prb/math/src/UD60x18.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "../libraries/Errors.sol";
import "../libraries/traits/AddressCheckerTrait.sol";
import "../libraries/GovernorLib.sol";
import "../interfaces/IProtocolGovernor.sol";
import "../libraries/Roles.sol";

abstract contract ProtocolGovernorEvents {
    event FeeUpdated(bytes32 indexed id, UD60x18 newFee);
    event AddressSet(bytes32 indexed id, address newAddress);
    event ImmutableAddressSet(bytes32 indexed id, address newAddress);
    event ManagerStatusUpdated(address indexed manager, bool status);
    event InvestmentAccountRegistered(address indexed account);
    event InvestmentAccountCreditIncreased(address indexed account, uint256 amount);
    event InvestmentAccountCreditDecreased(address indexed account, uint256 amount);
    event RoleSet(bytes32 indexed role, address indexed account, bool status);
    event ProtocolDeprecatedStatusSet(bool status);
}

/**
 * @title ProtocolGovernor
 * @dev Allows for storing and management of common protocol data (roles, addresses, configuration).
 */
contract ProtocolGovernor is Ownable2Step, AddressCheckerTrait, ProtocolGovernorEvents, IProtocolGovernor {
    /// @notice Map of contract names to their contract addresses.
    mapping(bytes32 => address) internal _addresses;

    /// @notice Immutable map of contract names to their contract addresses.
    mapping(bytes32 => address) internal _immutableAddresses;

    /// @notice Map of fee IDs to their fees.
    /// @dev Fees cannot be greater than or equal to 100%.
    mapping(bytes32 => UD60x18) internal _fees;

    /// @notice Managers that can register accounts.
    mapping(address => bool) internal _managers;

    /// @notice Tracking roles granted to addresses.
    mapping(address => mapping(bytes32 => bool)) internal _roles;

    /// @notice If true, the protocol is deprecated and no longer accepting inflows (lending pool deposit, borrow,
    /// strategy deposit should be disabled).
    bool private _isProtocolDeprecated;

    /// @dev Parameters for initializing the Protocol Governor
    struct InitParams {
        address lendAsset; // Address of the asset
        address feeCollector;
    }

    constructor(InitParams memory params)
        Ownable(msg.sender)
        nonZeroAddress(params.feeCollector)
        nonZeroAddressAndContract(params.lendAsset)
    {
        _setImmutableAddress(GovernorLib.LEND_ASSET, params.lendAsset);
        _setAddress(GovernorLib.FEE_COLLECTOR, params.feeCollector);

        _fees[GovernorLib.LENDING_FEE] = ud(0.1e18);
        _fees[GovernorLib.PROTOCOL_LIQUIDATION_SHARE] = ud(0.05e18);
        _fees[GovernorLib.LIQUIDATOR_SHARE] = ZERO;
        _fees[GovernorLib.FLASH_LOAN_FEE] = ud(0);
    }

    /**
     * @dev Only allows addresses that are the protocol admin to call the function.
     */
    modifier onlyProtocolOwner() {
        if (owner() != _msgSender()) {
            revert Errors.UnauthorizedRole(_msgSender(), "PROTOCOL_ADMIN");
        }
        _;
    }

    modifier onlyManager() {
        if (!_managers[_msgSender()]) {
            revert Errors.UnauthorizedRole(_msgSender(), "ACCOUNT_MANAGER");
        }
        _;
    }

    function getOwner() external view returns (address) {
        return Ownable.owner();
    }

    function setProtocolDeprecatedStatus(bool status) external onlyProtocolOwner {
        _isProtocolDeprecated = status;
        emit ProtocolDeprecatedStatusSet(status);
    }

    function isProtocolDeprecated() external view returns (bool) {
        return _isProtocolDeprecated;
    }

    ////////////////////
    // ADDRESS PROVIDER
    //////////////////////

    /// @dev Sets an address by id
    function setAddress(bytes32 id, address addr) public onlyProtocolOwner {
        _setAddress(id, addr);
    }

    function _setAddress(bytes32 id, address addr) internal nonZeroAddress(addr) {
        _addresses[id] = addr;
        emit AddressSet(id, addr);
    }

    // @dev Initialize an address by id, this cannot be changed after being set.
    function setImmutableAddress(bytes32 id, address addr) public onlyProtocolOwner {
        _setImmutableAddress(id, addr);
    }

    function _setImmutableAddress(bytes32 id, address addr) internal nonZeroAddress(addr) {
        if (_immutableAddresses[id] != address(0)) {
            revert Errors.InvalidParams();
        }
        _immutableAddresses[id] = addr;
        emit ImmutableAddressSet(id, addr);
    }

    /// @dev Returns an address by id
    function getAddress(bytes32 id) external view returns (address) {
        return _addresses[id];
    }

    /// @dev Returns an immutable address by id
    function getImmutableAddress(bytes32 id) external view returns (address) {
        return _immutableAddresses[id];
    }

    ///////////////////////
    // FEE CONFIGURATION
    ///////////////////////

    /// @notice newFee cannot be 100% (it must be < 1e18)
    function setFee(bytes32 id, UD60x18 newFee) external onlyProtocolOwner {
        if (newFee >= UNIT) {
            revert Errors.InvalidParams();
        }
        _fees[id] = newFee;
        emit FeeUpdated(id, newFee);
    }

    function getFee(bytes32 id) external view returns (UD60x18) {
        return _fees[id];
    }

    /////////////////////
    // Protocol wide ACL
    /////////////////////

    function grantRole(bytes32 role, address account) external onlyProtocolOwner {
        _roles[account][role] = true;
        emit RoleSet(role, account, true);
    }

    function revokeRole(bytes32 role, address account) external onlyProtocolOwner {
        _roles[account][role] = false;
        emit RoleSet(role, account, false);
    }

    function hasRole(bytes32 role, address account) external view returns (bool) {
        return _roles[account][role];
    }

    function updateAccountManagerStatus(address manager, bool status) external onlyProtocolOwner {
        _managers[manager] = status;
        emit ManagerStatusUpdated(manager, status);
    }

    function isAccountManager(address manager) external view returns (bool) {
        return _managers[manager];
    }
}

File 71 of 73 : ProtocolModule.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

import "./ProtocolGovernor.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { Errors } from "../libraries/Errors.sol";
import "../libraries/traits/AddressCheckerTrait.sol";
import { UD60x18, ud } from "@prb/math/src/UD60x18.sol";
import "../interfaces/IGasTank.sol";
import "../interfaces/IAssetPriceProvider.sol";
import "../interfaces/IProtocolGovernor.sol";
import "../interfaces/IStrategySlippageModel.sol";
import "../libraries/GovernorLib.sol";
import "../libraries/Roles.sol";

/**
 * @title ProtocolModule
 * @dev Contract for shared protocol functionality
 */
abstract contract ProtocolModule is Context, AddressCheckerTrait {
    using Roles for IProtocolGovernor;

    IProtocolGovernor internal immutable _protocolGovernor;

    /**
     * @dev Constructor that initializes the role store for this contract.
     * @param protocolGovernor_ The contract instance to use as the role store.
     */
    constructor(address protocolGovernor_) {
        _protocolGovernor = IProtocolGovernor(protocolGovernor_);
    }

    /////////////////
    /// PERMISSIONS
    /////////////////

    modifier whenProtocolNotDeprecated() {
        require(!_protocolGovernor.isProtocolDeprecated(), "PROTOCOL_DEPRECATED");
        _;
    }

    /**
     * @dev Only allows the contract's own address to call the function.
     */
    modifier onlySelf() {
        if (msg.sender != address(this)) {
            revert Errors.UnauthorizedRole(msg.sender, "SELF");
        }
        _;
    }

    modifier onlyAccountManager() {
        if (!_protocolGovernor.isAccountManager(_msgSender())) {
            revert Errors.UnauthorizedRole(_msgSender(), "ACCOUNT_MANAGER");
        }
        _;
    }

    modifier onlyGasTankDepositor() {
        _protocolGovernor._validateRole(msg.sender, Roles.GAS_TANK_DEPOSITOR, "GAS_TANK_DEPOSITOR");
        _;
    }

    modifier onlyProtocolMaintainer() {
        _protocolGovernor._validateRole(msg.sender, Roles.PROTOCOL_MAINTAINER, "PROTOCOL_MAINTAINER");
        _;
    }

    /**
     * @dev Only allows addresses that are the protocol admin to call the function.
     */
    modifier onlyOwner() {
        if (!_isOwner(_msgSender())) {
            revert Errors.UnauthorizedRole(_msgSender(), "PROTOCOL_ADMIN");
        }
        _;
    }

    function _isOwner(address account) internal view returns (bool) {
        if (_protocolGovernor.getOwner() != account) {
            return false;
        }
        return true;
    }

    /////////////////////
    // ADDRESS PROVIDER
    /////////////////////

    function getProtocolGovernor() external view virtual returns (address) {
        return address(_protocolGovernor);
    }

    /// @notice Returns fee collector
    function _getFeeCollector() internal view returns (address) {
        return _protocolGovernor.getAddress(GovernorLib.FEE_COLLECTOR);
    }

    /// @notice Returns asset price provider address.
    /// @dev This price provider MUST return the asset prices denominated in lend asset.
    /// @dev If lend asset is USDC, asset prices must be in USDC.
    function _getPriceProvider() internal view returns (IAssetPriceProvider) {
        return IAssetPriceProvider(_protocolGovernor.getAddress(GovernorLib.PRICE_PROVIDER));
    }

    /// @notice Gas Tank
    function _getGasTank() internal view returns (IGasTank) {
        return IGasTank(_protocolGovernor.getAddress(GovernorLib.GAS_TANK));
    }

    function _getLendAsset() internal view returns (address) {
        return _protocolGovernor.getImmutableAddress(GovernorLib.LEND_ASSET);
    }

    function _getLendingPool() internal view returns (address) {
        return _protocolGovernor.getImmutableAddress(GovernorLib.LENDING_POOL);
    }

    // FEE CONFIGURATION
    //////////////////////

    function _lendingFee() internal view returns (UD60x18) {
        return _protocolGovernor.getFee(GovernorLib.LENDING_FEE);
    }

    function _flashLoanFee() internal view returns (UD60x18) {
        return _protocolGovernor.getFee(GovernorLib.FLASH_LOAN_FEE);
    }

    function _protocolLiquidationShare() internal view returns (UD60x18) {
        return _protocolGovernor.getFee(GovernorLib.PROTOCOL_LIQUIDATION_SHARE);
    }

    function _liquidatorShare() internal view returns (UD60x18) {
        return _protocolGovernor.getFee(GovernorLib.LIQUIDATOR_SHARE);
    }
}

File 72 of 73 : ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
///   minting and transferring zero tokens, as well as self-approvals.
///   For performance, this implementation WILL NOT revert for such actions.
///   Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
///   the total sum of all balances must be equal to `totalSupply()`.
/// - Check that the overridden function is actually used in the function you want to
///   change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC20 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The total supply has overflowed.
    error TotalSupplyOverflow();

    /// @dev The allowance has overflowed.
    error AllowanceOverflow();

    /// @dev The allowance has underflowed.
    error AllowanceUnderflow();

    /// @dev Insufficient balance.
    error InsufficientBalance();

    /// @dev Insufficient allowance.
    error InsufficientAllowance();

    /// @dev The permit is invalid.
    error InvalidPermit();

    /// @dev The permit has expired.
    error PermitExpired();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
    event Transfer(address indexed from, address indexed to, uint256 amount);

    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
    uint256 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
    uint256 private constant _APPROVAL_EVENT_SIGNATURE =
        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The storage slot for the total supply.
    uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;

    /// @dev The balance slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _BALANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let balanceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;

    /// @dev The allowance slot of (`owner`, `spender`) is given by:
    /// ```
    ///     mstore(0x20, spender)
    ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let allowanceSlot := keccak256(0x0c, 0x34)
    /// ```
    uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;

    /// @dev The nonce slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _NONCES_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let nonceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _NONCES_SLOT_SEED = 0x38377508;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
    uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;

    /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
    bytes32 private constant _DOMAIN_TYPEHASH =
        0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    /// @dev `keccak256("1")`.
    bytes32 private constant _VERSION_HASH =
        0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;

    /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
    bytes32 private constant _PERMIT_TYPEHASH =
        0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ERC20 METADATA                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the name of the token.
    function name() public view virtual returns (string memory);

    /// @dev Returns the symbol of the token.
    function symbol() public view virtual returns (string memory);

    /// @dev Returns the decimals places of the token.
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           ERC20                            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the amount of tokens in existence.
    function totalSupply() public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_TOTAL_SUPPLY_SLOT)
        }
    }

    /// @dev Returns the amount of tokens owned by `owner`.
    function balanceOf(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
    function allowance(address owner, address spender)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x34))
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
    ///
    /// Emits a {Approval} event.
    function approve(address spender, uint256 amount) public virtual returns (bool) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Transfer `amount` tokens from the caller to `to`.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    ///
    /// Emits a {Transfer} event.
    function transfer(address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(msg.sender, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, caller())
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(msg.sender, to, amount);
        return true;
    }

    /// @dev Transfers `amount` tokens from `from` to `to`.
    ///
    /// Note: Does not update the allowance if it is the maximum uint256 value.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
    ///
    /// Emits a {Transfer} event.
    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the allowance slot and load its value.
            mstore(0x20, caller())
            mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if add(allowance_, 1) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
        return true;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          EIP-2612                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev For more performance, override to return the constant value
    /// of `keccak256(bytes(name()))` if `name()` will never change.
    function _constantNameHash() internal view virtual returns (bytes32 result) {}

    /// @dev Returns the current nonce for `owner`.
    /// This value is used to compute the signature for EIP-2612 permit.
    function nonces(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the nonce slot and load its value.
            mstore(0x0c, _NONCES_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
    /// authorized by a signed approval by `owner`.
    ///
    /// Emits a {Approval} event.
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        /// @solidity memory-safe-assembly
        assembly {
            // Revert if the block timestamp is greater than `deadline`.
            if gt(timestamp(), deadline) {
                mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
                revert(0x1c, 0x04)
            }
            let m := mload(0x40) // Grab the free memory pointer.
            // Clean the upper 96 bits.
            owner := shr(96, shl(96, owner))
            spender := shr(96, shl(96, spender))
            // Compute the nonce slot and load its value.
            mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
            mstore(0x00, owner)
            let nonceSlot := keccak256(0x0c, 0x20)
            let nonceValue := sload(nonceSlot)
            // Prepare the domain separator.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), _VERSION_HASH)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            mstore(0x2e, keccak256(m, 0xa0))
            // Prepare the struct hash.
            mstore(m, _PERMIT_TYPEHASH)
            mstore(add(m, 0x20), owner)
            mstore(add(m, 0x40), spender)
            mstore(add(m, 0x60), value)
            mstore(add(m, 0x80), nonceValue)
            mstore(add(m, 0xa0), deadline)
            mstore(0x4e, keccak256(m, 0xc0))
            // Prepare the ecrecover calldata.
            mstore(0x00, keccak256(0x2c, 0x42))
            mstore(0x20, and(0xff, v))
            mstore(0x40, r)
            mstore(0x60, s)
            let t := staticcall(gas(), 1, 0, 0x80, 0x20, 0x20)
            // If the ecrecover fails, the returndatasize will be 0x00,
            // `owner` will be checked if it equals the hash at 0x00,
            // which evaluates to false (i.e. 0), and we will revert.
            // If the ecrecover succeeds, the returndatasize will be 0x20,
            // `owner` will be compared against the returned address at 0x20.
            if iszero(eq(mload(returndatasize()), owner)) {
                mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
                revert(0x1c, 0x04)
            }
            // Increment and store the updated nonce.
            sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
            // Compute the allowance slot and store the value.
            // The `owner` is already at slot 0x20.
            mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
            sstore(keccak256(0x2c, 0x34), value)
            // Emit the {Approval} event.
            log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero pointer.
        }
    }

    /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
    function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
        bytes32 nameHash = _constantNameHash();
        //  We simply calculate it on-the-fly to allow for cases where the `name` may change.
        if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Grab the free memory pointer.
            mstore(m, _DOMAIN_TYPEHASH)
            mstore(add(m, 0x20), nameHash)
            mstore(add(m, 0x40), _VERSION_HASH)
            mstore(add(m, 0x60), chainid())
            mstore(add(m, 0x80), address())
            result := keccak256(m, 0xa0)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL MINT FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Mints `amount` tokens to `to`, increasing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _mint(address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(address(0), to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
            let totalSupplyAfter := add(totalSupplyBefore, amount)
            // Revert if the total supply overflows.
            if lt(totalSupplyAfter, totalSupplyBefore) {
                mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                revert(0x1c, 0x04)
            }
            // Store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(address(0), to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL BURN FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Burns `amount` tokens from `from`, reducing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _burn(address from, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, address(0), amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, from)
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Subtract and store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
            // Emit the {Transfer} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
        }
        _afterTokenTransfer(from, address(0), amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL TRANSFER FUNCTIONS                 */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Moves `amount` of tokens from `from` to `to`.
    function _transfer(address from, address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL ALLOWANCE FUNCTIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if add(allowance_, 1) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
    ///
    /// Emits a {Approval} event.
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let owner_ := shl(96, owner)
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     HOOKS TO OVERRIDE                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Hook that is called before any transfer of tokens.
    /// This includes minting and burning.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /// @dev Hook that is called after any transfer of tokens.
    /// This includes minting and burning.
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

File 73 of 73 : FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

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

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

            // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // `k` is in the range `[-61, 195]`.

            // Evaluate using a (6, 7)-term rational approximation.
            // `p` is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already `2**96` too large.
                r := sdiv(p, q)
            }

            // r should be in the range `(0.09, 0.25) * 2**96`.

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            // - The `1e18 / 2**96` factor for base conversion.
            // We do this all at once, with an intermediate result in `2**213`
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            int256 wad = int256(WAD);
            int256 p = x;
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (w >> 63 == 0) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == 0) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != 0);
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c != 0) {
                int256 t = w | 1;
                /// @solidity memory-safe-assembly
                assembly {
                    x := sdiv(mul(x, wad), t)
                }
                x = (t * (wad + lnWad(x)));
                /// @solidity memory-safe-assembly
                assembly {
                    w := sdiv(x, add(wad, t))
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                // 512-bit multiply `[p1 p0] = x * y`.
                // 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 = p1 * 2**256 + p0`.

                // Least significant 256 bits of the product.
                result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                let mm := mulmod(x, y, not(0))
                // Most significant 256 bits of the product.
                let p1 := sub(mm, add(result, lt(mm, result)))

                // Handle non-overflow cases, 256 by 256 division.
                if iszero(p1) {
                    if iszero(d) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    result := div(result, d)
                    break
                }

                // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                if iszero(gt(d, p1)) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }

                /*------------------- 512 by 256 division --------------------*/

                // Make division exact by subtracting the remainder from `[p1 p0]`.
                // Compute remainder using mulmod.
                let r := mulmod(x, y, d)
                // `t` is the least significant bit of `d`.
                // Always greater or equal to 1.
                let t := and(d, sub(0, d))
                // Divide `d` by `t`, which is a power of two.
                d := div(d, t)
                // Invert `d mod 2**256`
                // Now that `d` is an odd number, it has an inverse
                // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                // Compute the inverse by starting with a seed that is correct
                // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                let inv := xor(2, mul(3, d))
                // 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 := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                result :=
                    mul(
                        // Divide [p1 p0] by the factors of two.
                        // Shift in bits from `p1` into `p0`. For this we need
                        // to flip `t` such that it is `2**256 / t`.
                        or(
                            mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                            div(sub(result, r), t)
                        ),
                        // inverse mod 2**256
                        mul(inv, sub(2, mul(d, inv)))
                    )
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        result = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                result := add(result, 1)
                if iszero(result) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if iszero(iszero(x)) {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))

            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))

            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)

            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            z = 10 ** 9;
            if (x <= type(uint256).max / 10 ** 36 - 1) {
                x *= 10 ** 18;
                z = 1;
            }
            z *= sqrt(x);
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`.
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            z = 10 ** 12;
            if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                if (x >= type(uint256).max / 10 ** 36) {
                    x *= 10 ** 18;
                    z = 10 ** 6;
                } else {
                    x *= 10 ** 36;
                    z = 1;
                }
            }
            z *= cbrt(x);
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

Settings
{
  "evmVersion": "paris",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 50
  },
  "remappings": [],
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"protocolGovernor_","type":"address"},{"internalType":"address","name":"pointsOperator_","type":"address"},{"internalType":"bool","name":"isAutoCompounding_","type":"bool"},{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationReceiver","type":"address"},{"internalType":"address","name":"collateral","type":"address"},{"internalType":"UD60x18","name":"maxLtv","type":"uint256"},{"internalType":"UD60x18","name":"riskThreshold","type":"uint256"},{"internalType":"UD60x18","name":"liquidationThreshold","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint8","name":"decimals","type":"uint8"}],"internalType":"struct CollateralAccountManager.InitParams","name":"params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccountBeingLiquidated","type":"error"},{"inputs":[],"name":"AccountHealthy","type":"error"},{"inputs":[],"name":"AccountInsolvent","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AllowanceOverflow","type":"error"},{"inputs":[],"name":"AllowanceUnderflow","type":"error"},{"inputs":[],"name":"ContractDoesNotExist","type":"error"},{"inputs":[],"name":"ERC1167FailedCreateClone","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"HealthFactorSnapshotNotFound","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidParams","type":"error"},{"inputs":[],"name":"InvalidPermit","type":"error"},{"inputs":[],"name":"OldAccountDoesNotExist","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"PermitExpired","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"RemainingDebtLeft","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"StrategyNotApproved","type":"error"},{"inputs":[],"name":"TotalSupplyOverflow","type":"error"},{"inputs":[],"name":"TransferDisabled","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"string","name":"role","type":"string"}],"name":"UnauthorizedRole","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountBorrowed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"AccountCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AccountLiquidationCompleted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AccountLiquidationStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AccountRepaid","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":false,"internalType":"bool","name":"isAutoCompounding","type":"bool"}],"name":"AutoCompoundingToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtAmountNeeded","type":"uint256"}],"name":"CollateralLiquidation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesCharged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"gasClaimed","type":"uint256"}],"name":"GasRefundClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"feeCollector","type":"address"},{"indexed":true,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"uint256","name":"protocolShare","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"liquidatorShare","type":"uint256"}],"name":"LiquidationFeesTaken","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"UD60x18","name":"maxLtv","type":"uint256"},{"indexed":false,"internalType":"UD60x18","name":"riskThreshold","type":"uint256"},{"indexed":false,"internalType":"UD60x18","name":"liquidationThreshold","type":"uint256"}],"name":"LiquidationParametersUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"liquidationFeeTo","type":"address"},{"indexed":false,"internalType":"address","name":"liquidationReceiver","type":"address"}],"name":"LiquidationReceiverCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"UD60x18","name":"tolerance","type":"uint256"}],"name":"MaximumSlippageToleranceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"PointsOperatorConfigured","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyActivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"StrategyDeactivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"strategy","type":"address"},{"indexed":false,"internalType":"bool","name":"approval","type":"bool"}],"name":"StrategyUpdated","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":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"YieldAccrued","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"result","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATION_BONUS","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_COMPOUND_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"borrowed","type":"uint256"}],"name":"_afterBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_afterLiquidationCompleted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_afterLiquidationStarted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"_afterRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"_completeLiquidation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"accountOwner","type":"address"},{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"debtToCover","type":"uint256"}],"name":"_simulateCollateralLiquidation","outputs":[{"components":[{"internalType":"uint256","name":"actualDebtToLiquidate","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"bonusCollateral","type":"uint256"}],"internalType":"struct AccountLib.CollateralLiquidation","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accountCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accountImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allowedAccountsMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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":[{"internalType":"address","name":"","type":"address"}],"name":"approvedStrategies","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOfAssets","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"borrowed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimMaxGas","outputs":[{"internalType":"uint256","name":"gasClaimed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"compound","outputs":[{"internalType":"uint256","name":"earned","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"createAccount","outputs":[{"internalType":"address payable","name":"account","type":"address"}],"stateMutability":"nonpayable","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":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"feeCollector_","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"},{"internalType":"uint256","name":"protocolShare","type":"uint256"},{"internalType":"uint256","name":"liquidatorShare","type":"uint256"}],"name":"emitLiquidationFeeEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner_","type":"address"}],"name":"getAccount","outputs":[{"internalType":"address","name":"account","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountHealth","outputs":[{"components":[{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"uint256","name":"investmentValue","type":"uint256"},{"internalType":"UD60x18","name":"healthFactor","type":"uint256"},{"internalType":"bool","name":"isLiquidatable","type":"bool"},{"internalType":"bool","name":"isRisky","type":"bool"},{"internalType":"bool","name":"hasBadDebt","type":"bool"}],"internalType":"struct AccountLib.Health","name":"health","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLiquidationStatus","outputs":[{"components":[{"internalType":"bool","name":"isLiquidating","type":"bool"},{"internalType":"uint256","name":"liquidationStartTime","type":"uint256"}],"internalType":"struct AccountLib.LiquidationStatus","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLoan","outputs":[{"components":[{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"UD60x18","name":"ltv","type":"uint256"},{"internalType":"UD60x18","name":"maxLtv","type":"uint256"}],"internalType":"struct AccountLib.Loan","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountOwner","outputs":[{"internalType":"address","name":"owner","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getActiveStrategy","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getActiveStrategyCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getDebtAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFeeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLendAsset","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidationFee","outputs":[{"components":[{"internalType":"UD60x18","name":"protocolShare","type":"uint256"},{"internalType":"UD60x18","name":"liquidatorShare","type":"uint256"}],"internalType":"struct AccountLib.LiquidationFee","name":"fee","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"getLiquidationReceiver","outputs":[{"internalType":"contract ILiquidationReceiver","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getProtocolGovernor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalAccountValue","outputs":[{"internalType":"uint256","name":"totalValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalCollateralValue","outputs":[{"internalType":"uint256","name":"totalValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isAccountAllowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"isApprovedStrategy","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isAutoCompounding","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isCreatedAccount","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"isLiquidationReceiver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lendingPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"liquidate","outputs":[{"internalType":"contract ILiquidationReceiver","name":"liquidationReceiver_","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"debtToCover","type":"uint256"},{"internalType":"address","name":"liquidationFeeTo","type":"address"}],"name":"liquidateCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"liquidationFeeTo","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"liquidateStrategy","outputs":[{"internalType":"contract ILiquidationReceiver","name":"liquidationReceiver_","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"liquidationReceiver","outputs":[{"internalType":"contract ILiquidationReceiver","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidationThreshold","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLtv","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"pauseAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"updatedShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repay","outputs":[{"internalType":"uint256","name":"repaid","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"riskThreshold","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bool","name":"status","type":"bool"}],"name":"setAllowedAccountStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"status","type":"bool"}],"name":"setAllowedAccountsMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_isAutoCompounding","type":"bool"}],"name":"setAutoCompounding","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"debtToCover","type":"uint256"}],"name":"simulateCollateralLiquidation","outputs":[{"components":[{"internalType":"uint256","name":"actualDebtToLiquidate","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"bonusCollateral","type":"uint256"}],"internalType":"struct AccountLib.CollateralLiquidation","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"snapshotAccountHealthFactor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"strategyDeposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"bool","name":"didRepay","type":"bool"}],"name":"strategyWithdrawal","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":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"unpauseAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"UD60x18","name":"maxLtv_","type":"uint256"},{"internalType":"UD60x18","name":"riskThreshold_","type":"uint256"},{"internalType":"UD60x18","name":"liquidationThreshold_","type":"uint256"}],"name":"updateLiquidationParameters","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"bool","name":"approval","type":"bool"}],"name":"updateStrategyApproval","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"updatedAssets","type":"uint256"},{"internalType":"uint256","name":"updatedShares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

6101606040523480156200001257600080fd5b50604051620060e0380380620060e0833981016040819052620000359162000a15565b604081015160c082015160e083015161010084015160208501516000805460ff191690556001600160a01b03891660805260018055889486949093909290918690818162000082620003a6565b6001600160a01b038116620000aa5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b620000d357604051630b0f2dd560e31b815260040160405180910390fd5b620000dd6200046a565b6001600160a01b038116620001055760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200012e57604051630b0f2dd560e31b815260040160405180910390fd5b826001600160a01b038116620001575760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200018057604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b03841660e052620001976200046a565b6001600160a01b031660a052620001ad620004ae565b6001600160a01b0390811660c0526008805460ff191660011790558b975087169550620001f39450505050505760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b6200021c57604051630b0f2dd560e31b815260040160405180910390fd5b6001600160a01b0385166101005260ff821661012052600e62000240858262000bec565b50600f6200024f848262000bec565b505084519350506001600160a01b03831691506200028290505760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381163b620002ab57604051630b0f2dd560e31b815260040160405180910390fd5b81516001600160a01b0316610140526060820151608083015160a0840151620002d6929190620004f0565b506060810151601055608081015160115560a0015160125550620002fa8462000570565b62000306848462000697565b80604001516001600160a01b0316631a33757d60026040518263ffffffff1660e01b815260040162000339919062000cb8565b6020604051808303816000875af115801562000359573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200037f919062000ce1565b505060158054911515600160a01b0260ff60a01b199092169190911790555062000d579050565b60006080516001600160a01b03166321f8a721604051602001620003ec906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200042191815260200190565b602060405180830381865afa1580156200043f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000465919062000cfb565b905090565b60006080516001600160a01b031663c824e157604051602001620003ec906020808252600c908201526b13115391125391d7d413d3d360a21b604082015260600190565b60006080516001600160a01b031663c824e157604051602001620003ec906020808252600a90820152691311539117d054d4d15560b21b604082015260600190565b6000620004fe8383620007d0565b9050600062000529670de0b6b3a764000062000523670de0b6b3a764000088620007d0565b620007f5565b90506200053e82670de0b6b3a7640000101590565b806200054a5750818111155b156200056957604051635435b28960e11b815260040160405180910390fd5b5050505050565b601480546001600160a01b0383166001600160a01b031990911681179091556040516000919063c824e15790620005c39060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401620005f891815260200190565b602060405180830381865afa15801562000616573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200063c919062000cfb565b9050806001600160a01b0316634e606c476040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156200067a57600080fd5b505af11580156200068f573d6000803e3d6000fd5b505050505050565b601580546001600160a01b0384166001600160a01b031990911681179091556040516000919063c824e15790620006f1906020016020808252600c908201526b424c4153545f504f494e545360a01b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016200072691815260200190565b602060405180830381865afa15801562000744573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200076a919062000cfb565b6040516336b91f2b60e01b81526001600160a01b038481166004830152919250908216906336b91f2b90602401600060405180830381600087803b158015620007b257600080fd5b505af1158015620007c7573d6000803e3d6000fd5b50505050505050565b6000620007ee620007eb84670de0b6b3a76400008562000807565b90565b9392505050565b6000620007ee620007eb838562000d19565b600080806000198587098587029250828110838203039150508060000362000846578382816200083b576200083b62000d41565b0492505050620007ee565b8381106200087c57604051630c740aef60e31b815260048101879052602481018690526044810185905260640160405180910390fd5b600084868809600260036001881981018916988990049182028318808302840302808302840302808302840302808302840302808302840302918202909203026000889003889004909101858311909403939093029303949094049190911702949350505050565b80516001600160a01b0381168114620008fc57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b03811182821017156200093d576200093d62000901565b60405290565b604051601f8201601f191681016001600160401b03811182821017156200096e576200096e62000901565b604052919050565b600082601f8301126200098857600080fd5b81516001600160401b03811115620009a457620009a462000901565b6020620009ba601f8301601f1916820162000943565b8281528582848701011115620009cf57600080fd5b60005b83811015620009ef578581018301518282018401528201620009d2565b506000928101909101919091529392505050565b805160ff81168114620008fc57600080fd5b6000806000806080858703121562000a2c57600080fd5b62000a3785620008e4565b935062000a4760208601620008e4565b92506040850151801515811462000a5d57600080fd5b60608601519092506001600160401b038082111562000a7b57600080fd5b90860190610120828903121562000a9157600080fd5b62000a9b62000917565b62000aa683620008e4565b815262000ab660208401620008e4565b602082015262000ac960408401620008e4565b6040820152606083015160608201526080830151608082015260a083015160a082015260c08301518281111562000aff57600080fd5b62000b0d8a82860162000976565b60c08301525060e08301518281111562000b2657600080fd5b62000b348a82860162000976565b60e083015250610100915062000b4c82840162000a03565b8282015280935050505092959194509250565b600181811c9082168062000b7457607f821691505b60208210810362000b9557634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000be7576000816000526020600020601f850160051c8101602086101562000bc65750805b601f850160051c820191505b818110156200068f5782815560010162000bd2565b505050565b81516001600160401b0381111562000c085762000c0862000901565b62000c208162000c19845462000b5f565b8462000b9b565b602080601f83116001811462000c58576000841562000c3f5750858301515b600019600386901b1c1916600185901b1785556200068f565b600085815260208120601f198616915b8281101562000c895788860151825594840194600190910190840162000c68565b508582101562000ca85787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b602081016003831062000cdb57634e487b7160e01b600052602160045260246000fd5b91905290565b60006020828403121562000cf457600080fd5b5051919050565b60006020828403121562000d0e57600080fd5b620007ee82620008e4565b8082018082111562000d3b57634e487b7160e01b600052601160045260246000fd5b92915050565b634e487b7160e01b600052601260045260246000fd5b60805160a05160c05160e05161010051610120516101405161527162000e6f6000396000818161053701528181612d6c0152613b0101526000818161067f01526119a6015260008181610fb4015281816119230152818161299001528181612a4a015281816139c901528181613ff3015281816141e001526146c50152600081816117b201526135a40152600081816110560152818161222d0152818161271d01528181612c5e0152818161360501528181613757015281816137da015261386f015260008181610ba30152818161139901528181611cd901528181611d530152613d00015260008181610a1201528181612ed001528181612f6b0152818161324901528181614058015261413c01526152716000f3fe6080604052600436106103e75760003560e01c80638456cb591161020a578063c5ebeaec11610119578063e4af29fc116100a6578063e4af29fc14610dbc578063e59e801814610dd2578063ea29dad314610e4e578063ef48644614610e6e578063ef8b30f714610e8e578063f2468d8714610eae578063f69e204614610ece578063f9566d8214610ee3578063fbcbc0f114610f03578063fbf4198414610f2357600080fd5b8063c5ebeaec14610c75578063c613aec014610c95578063ca8bcd661461097b578063cb6c0c9a14610cc5578063d505accf14610ce5578063d8cab31814610d05578063dd62ed3e14610d26578063dd76401714610d5c578063ddd5e1b214610d7c578063e1d5c06414610d9c57600080fd5b80639d919c63116101975780639d919c6314610b3d5780639dca362f14610b7f578063a59a997314610b94578063a612ce2b14610bc7578063a9059cbb14610be7578063b17e32f914610c02578063b2b8c93f14610c17578063b3c0a0b314610c2c578063b43e6cb414610c3f578063bd1c5d7414610c5557600080fd5b80638456cb59146109ce57806386b9d81f146109e357806389dbb85714610a0357806390401a7a14610a365780639159b20614610a5657806394408b9a14610a7657806395d89b4114610a96578063971d6c9514610aab578063985d28aa14610acb57806399f8148e14610b0457600080fd5b80633a12c6da116103065780635af451cc116102935780635af451cc146108a45780635c975abb146108b95780636806eaab146108d15780636a11d0b2146108f15780636c648fc4146109085780636e553f651461092857806370a08231146109485780637af0bdfd146109685780637b91c2651461097b5780637ecebe001461099b57600080fd5b80633a12c6da146106da5780633f4ba83a146106f05780634031234c14610705578063410051a51461071b578063442b172c1461076e57806347a873cb146107a757806347e41a89146107c7578063484d1ad6146108445780635507f5e9146108645780635a287cb21461088457600080fd5b806312fde4b71161038457806312fde4b7146105665780631534a2771461057b57806318160ddd146105bc5780631e8a84b1146105d95780631fd9a8c6146105fb57806322867d781461062b57806323b872dd1461064b578063313ce5671461066b5780633574d4c4146106a95780633644e515146106c557600080fd5b8062f714ce146103ec57806301e1d114146104265780630674fa411461044957806306fdde03146104695780630914b18f1461048b578063095ea7b3146104cb5780630a28a477146104eb5780630ba212ee1461050b57806311464fbe14610525575b600080fd5b3480156103f857600080fd5b5061040c6104073660046149ec565b610f53565b604080519283526020830191909152015b60405180910390f35b34801561043257600080fd5b5061043b610f9a565b60405190815260200161041d565b34801561045557600080fd5b5061043b610464366004614a1c565b61103c565b34801561047557600080fd5b5061047e6111a1565b60405161041d9190614a89565b34801561049757600080fd5b506104bb6104a6366004614a1c565b60026020526000908152604090205460ff1681565b604051901515815260200161041d565b3480156104d757600080fd5b506104bb6104e6366004614a9c565b611233565b3480156104f757600080fd5b5061040c610506366004614ac8565b611287565b34801561051757600080fd5b506008546104bb9060ff1681565b34801561053157600080fd5b506105597f000000000000000000000000000000000000000000000000000000000000000081565b60405161041d9190614ae1565b34801561057257600080fd5b50610559611299565b34801561058757600080fd5b50610559610596366004614af5565b60056020908152600092835260408084209091529082529020546001600160a01b031681565b3480156105c857600080fd5b506805345cdf77eb68f44c5461043b565b3480156105e557600080fd5b506105f96105f4366004614b31565b6112a3565b005b34801561060757600080fd5b506104bb610616366004614a1c565b60096020526000908152604090205460ff1681565b34801561063757600080fd5b5061043b610646366004614a9c565b611363565b34801561065757600080fd5b506104bb610666366004614b5f565b6114bc565b34801561067757600080fd5b5060405160ff7f000000000000000000000000000000000000000000000000000000000000000016815260200161041d565b3480156106b557600080fd5b5061043b670e92596fd629000081565b3480156106d157600080fd5b5061043b6114d7565b3480156106e657600080fd5b5061043b60105481565b3480156106fc57600080fd5b506105f9611554565b34801561071157600080fd5b5061043b60125481565b34801561072757600080fd5b5061073b610736366004614a1c565b611571565b60405161041d91908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b34801561077a57600080fd5b50610559610789366004614a1c565b6001600160a01b039081166000908152600360205260409020541690565b3480156107b357600080fd5b506105f96107c2366004614a9c565b6115fe565b3480156107d357600080fd5b506108276107e2366004614a1c565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526004808452938220548015158652915291815282015290565b60408051825115158152602092830151928101929092520161041d565b34801561085057600080fd5b506105f961085f366004614a1c565b6116b0565b34801561087057600080fd5b506105f961087f366004614ba0565b611719565b34801561089057600080fd5b5061055961089f366004614af5565b6117ab565b3480156108b057600080fd5b506105f9611806565b3480156108c557600080fd5b5060005460ff166104bb565b3480156108dd57600080fd5b506105f96108ec366004614bf3565b6118ba565b3480156108fd57600080fd5b5061043b620f424081565b34801561091457600080fd5b5061043b610923366004614a1c565b6118e0565b34801561093457600080fd5b5061040c6109433660046149ec565b6119e9565b34801561095457600080fd5b5061043b610963366004614a1c565b611a1b565b61043b610976366004614cb3565b611a33565b34801561098757600080fd5b506105f9610996366004614a1c565b611ac9565b3480156109a757600080fd5b5061043b6109b6366004614a1c565b6338377508600c908152600091909152602090205490565b3480156109da57600080fd5b506105f9611aee565b3480156109ef57600080fd5b506105596109fe366004614af5565b611b09565b348015610a0f57600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610559565b348015610a4257600080fd5b50610559610a51366004614a9c565b611b15565b348015610a6257600080fd5b5061043b610a71366004614a1c565b611b37565b348015610a8257600080fd5b506105f9610a91366004614a1c565b611b4a565b348015610aa257600080fd5b5061047e611b98565b348015610ab757600080fd5b506105f9610ac6366004614d1f565b611ba7565b348015610ad757600080fd5b506104bb610ae6366004614a1c565b6001600160a01b03166000908152600b602052604090205460ff1690565b348015610b1057600080fd5b506104bb610b1f366004614a1c565b6001600160a01b031660009081526006602052604090205460ff1690565b348015610b4957600080fd5b50610b5d610b58366004614d65565b611c32565b604080518251815260208084015190820152918101519082015260600161041d565b348015610b8b57600080fd5b50610559611c9e565b348015610ba057600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610559565b348015610bd357600080fd5b5061043b610be2366004614a1c565b611cbf565b348015610bf357600080fd5b506104bb610666366004614a9c565b348015610c0e57600080fd5b50610559611d4f565b348015610c2357600080fd5b5061043b611dd3565b610559610c3a366004614d9a565b611fe8565b348015610c4b57600080fd5b5061043b60115481565b348015610c6157600080fd5b506105f9610c70366004614df7565b612308565b348015610c8157600080fd5b5061043b610c90366004614ac8565b61237b565b348015610ca157600080fd5b506104bb610cb0366004614a1c565b600b6020526000908152604090205460ff1681565b348015610cd157600080fd5b506105f9610ce0366004614b31565b61240b565b348015610cf157600080fd5b506105f9610d00366004614e23565b612449565b348015610d1157600080fd5b506015546104bb90600160a01b900460ff1681565b348015610d3257600080fd5b5061043b610d41366004614af5565b602052637f5e9f20600c908152600091909152603490205490565b348015610d6857600080fd5b506105f9610d77366004614a1c565b6125d2565b348015610d8857600080fd5b506105f9610d973660046149ec565b612672565b348015610da857600080fd5b5061043b610db7366004614a1c565b6127a9565b348015610dc857600080fd5b5061043b60075481565b348015610dde57600080fd5b50610df2610ded366004614a1c565b6127ca565b60405161041d9190600060e0820190508251825260208301516020830152604083015160408301526060830151606083015260808301511515608083015260a0830151151560a083015260c0830151151560c083015292915050565b348015610e5a57600080fd5b506105f9610e69366004614bf3565b6128d1565b348015610e7a57600080fd5b506105f9610e89366004614a9c565b612902565b348015610e9a57600080fd5b5061040c610ea9366004614ac8565b612924565b348015610eba57600080fd5b50610b5d610ec9366004614a9c565b612942565b348015610eda57600080fd5b5061043b61297e565b348015610eef57600080fd5b506105f9610efe366004614e9a565b612b04565b348015610f0f57600080fd5b50610559610f1e366004614a1c565b612d47565b348015610f2f57600080fd5b50610f38612d99565b6040805182518152602092830151928101929092520161041d565b600080610f5e612dc7565b601554600160a01b900460ff1615610f7a57610f7861297e565b505b610f85338486612df1565b9092509050610f9360018055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e12f3a6190610fe9903090600401614ae1565b602060405180830381865afa158015611006573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102a9190614edc565b600d546110379190614f0b565b905090565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a082319061108b908590600401614ae1565b602060405180830381865afa1580156110a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110cc9190614edc565b905060005b6001600160a01b0383166000908152600c602052604090206110f290612e72565b81101561119b576001600160a01b0383166000908152600c6020526040902061111b9082612e7c565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b81526004016111469190614ae1565b602060405180830381865afa158015611163573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111879190614edc565b6111919083614f0b565b91506001016110d1565b50919050565b6060600e80546111b090614f1e565b80601f01602080910402602001604051908101604052809291908181526020018280546111dc90614f1e565b80156112295780601f106111fe57610100808354040283529160200191611229565b820191906000526020600020905b81548152906001019060200180831161120c57829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b60008061129383612e88565b93915050565b6000611037612ecc565b6112ac33612f5d565b61130057335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b0382166000818152600b6020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b600061136d612dc7565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f0000000000000000000000000000000000000000000000000000000000000000169063c883b2e5906064016020604051808303816000875af11580156113e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114069190614edc565b6001600160a01b0384811660008181526003602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906114819086908590600401614f52565b600060405180830381600087803b15801561149b57600080fd5b505af11580156114af573d6000803e3d6000fd5b5050505061128160018055565b600060405163a24e573d60e01b815260040160405180910390fd5b6000806114e26111a1565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b61155d33612f5d565b61156757336112b2565b61156f613009565b565b61159c6040518060800160405280600081526020016000815260200160008152602001600081525090565b60006115a7836118e0565b905060006115b484611cbf565b9050600082156115cd576115ca83835b90613055565b90505b60405180608001604052808381526020018481526020018281526020016115f360105490565b905295945050505050565b3330146116205733604051637974da6f60e01b81526004016112f79190614f6b565b6001600160a01b038216600090815260046020526040902054156116ac576000611649836127ca565b905080608001516116aa5760405163dd76401760e01b8152309063dd76401790611677908690600401614ae1565b600060405180830381600087803b15801561169157600080fd5b505af11580156116a5573d6000803e3d6000fd5b505050505b505b5050565b6116b933612f5d565b6116c357336112b2565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156116fe57600080fd5b505af1158015611712573d6000803e3d6000fd5b5050505050565b3360009081526002602052604090205460ff16611748576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561176a57503360009081526009602052604090205460ff16155b15611787576040516282b42960e81b815260040160405180910390fd5b61178f612dc7565b61179c338585858561306d565b6117a560018055565b50505050565b60006117ff7f000000000000000000000000000000000000000000000000000000000000000084846040516020016117e4929190614f9b565b604051602081830303815290604052805190602001206131e5565b9392505050565b3360009081526002602052604090205460ff16611835576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561185757503360009081526009602052604090205460ff16155b15611874576040516282b42960e81b815260040160405180910390fd5b600061187f336127ca565b90508060800151156118a457604051635e3b451760e11b815260040160405180910390fd5b60600151336000908152600a6020526040902055565b6118c333612f5d565b6118cd57336112b2565b6008805460ff1916911515919091179055565b6001600160a01b038082166000908152600360205260408120549091168161190782611b37565b90506000611913613245565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b815260040161195e9190614ae1565b602060405180830381865afa15801561197b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061199f9190614edc565b90506119cc7f0000000000000000000000000000000000000000000000000000000000000000600a615099565b6119d682846150a8565b6119e091906150d5565b95945050505050565b6000806119f4612dc7565b601554600160a01b900460ff1615611a1057611a0e61297e565b505b610f858433856132a8565b6387a211a2600c908152600091909152602090205490565b3360009081526002602052604081205460ff16611a62576040516282b42960e81b815260040160405180910390fd5b60085460ff168015611a8457503360009081526009602052604090205460ff16155b15611aa1576040516282b42960e81b815260040160405180910390fd5b611aa9612dc7565b611ab63386868686613340565b9050611ac160018055565b949350505050565b333014611aeb5733604051637974da6f60e01b81526004016112f79190614f6b565b50565b611af733612f5d565b611b0157336112b2565b61156f613503565b60006117ff8383613540565b6001600160a01b0382166000908152600c602052604081206117ff9083612e7c565b6000611281611b4583611a1b565b612e88565b611b5333612f5d565b611b5d57336112b2565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156116fe57600080fd5b6060600f80546111b090614f1e565b3360009081526006602052604090205460ff16611bd6576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611c24929190918252602082015260400190565b60405180910390a350505050565b611c3a6149b6565b6000838311611c495782611c4b565b835b90506000611c5886611b37565b90506000806000611c6985856139a8565b92509250925084811015611c7b578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611ca8612dc7565b611cb133613abf565b9050611cbc60018055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a612ce2b90611d0e908590600401614ae1565b602060405180830381865afa158015611d2b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112819190614edc565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611daf573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061103791906150f7565b60145460405160009182916001600160a01b039091169063c824e15790611e169060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611e4a91815260200190565b602060405180830381865afa158015611e67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e8b91906150f7565b6014546040519192506000916001600160a01b03909116906321f8a72190611eb590602001615114565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611ee991815260200190565b602060405180830381865afa158015611f06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f2a91906150f7565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d90611f5b9030908590600401614f9b565b6020604051808303816000875af1158015611f7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9e9190614edc565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b84604051611fdb91815260200190565b60405180910390a2505090565b6001600160a01b0382166000908152600b602052604081205460ff1661202157604051631a22ce4f60e11b815260040160405180910390fd5b61202b8585613540565b90506000806001600160a01b038516156120a457846001600160a01b031663ea2c58046040518163ffffffff1660e01b8152600401602060405180830381865afa15801561207d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120a19190614edc565b90505b600081156120b9576120b63a836150a8565b90505b604051639035268760e01b81526001600160a01b0389169063903526879083906120ed908a90899089908c9060040161513b565b6000604051808303818588803b15801561210657600080fd5b505af115801561211a573d6000803e3d6000fd5b50505050506001600160a01b038616158015906121a15750604051630e041fb560e11b81526001600160a01b03871690631c083f6a9061215e908b90600401614ae1565b602060405180830381865afa15801561217b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061219f9190614edc565b155b15612213576001600160a01b0388166000908152600c602052604090206121c89087613c4b565b506001600160a01b03888116600081815260036020526040808220549051848b169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190612262908890600401614ae1565b602060405180830381865afa15801561227f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122a39190614edc565b11156122fd57836001600160a01b031663402d88836040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156122e457600080fd5b505af11580156122f8573d6000803e3d6000fd5b505050505b505050949350505050565b61231133612f5d565b61231b57336112b2565b612326838383613c60565b60108390556011829055601281905560408051848152602081018490529081018290527fafabe1c7d6c2e86cbfc67a8ba53d25a7f8ef59b97d972dd4bf7d7525ba7fdddf9060600160405180910390a1505050565b3360009081526002602052604081205460ff166123aa576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156123cc57503360009081526009602052604090205460ff16155b156123e9576040516282b42960e81b815260040160405180910390fd5b6123f1612dc7565b6123fb3383613cd0565b905061240660018055565b919050565b61241433612f5d565b61241e57336112b2565b6001600160a01b03919091166000908152600960205260409020805460ff1916911515919091179055565b60006124536111a1565b8051906020012090508442111561247257631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d511461257e5763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b3330146125f45733604051637974da6f60e01b81526004016112f79190614f6b565b6001600160a01b038116600081815260046020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c26590612658908490600401614ae1565b600060405180830381600087803b1580156116fe57600080fd5b806001600160a01b03811661269a5760405163d92e233d60e01b815260040160405180910390fd5b3360009081526002602052604090205460ff166126c9576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156126eb57503360009081526009602052604090205460ff16155b15612708576040516282b42960e81b815260040160405180910390fd5b612710612dc7565b6127456001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016338486613e30565b612750336001613e8a565b336000818152600360209081526040918290205491518681526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a36116aa60018055565b6001600160a01b0381166000908152600c6020526040812061128190612e72565b6128106040518060e00160405280600081526020016000815260200160008152602001600081526020016000151581526020016000151581526020016000151581525090565b600061281b8361103c565b90506000612828846118e0565b9050600061283585611cbf565b905060006128438484614f0b565b6040805160e081018252848152602081018690529081018690526000606082018190526080820181905260a0820181905260c082015295509050811580159061288c5750600081115b156128ba5761289b82826115c4565b60608601819052601154811060a08701526012541160808601526128c8565b81156128c857600160c08601525b50505050919050565b6128da33612f5d565b6128e457336112b2565b60158054911515600160a01b0260ff60a01b19909216919091179055565b3330146116ac5733604051637974da6f60e01b81526004016112f79190614f6b565b60008061293083613f4c565b905061293b81612e88565b9150915091565b61294a6149b6565b6001600160a01b038084166000908152600360205260408120549091169061297185611cbf565b90506119e0828286611c32565b60405163e12f3a6160e01b81526000907f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b0382169063e12f3a61906129cf903090600401614ae1565b602060405180830381865afa1580156129ec573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a109190614edc565b9150620f42408210612b005781600d6000828254612a2e9190614f0b565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063aad3ec9690612a819030908690600401614f52565b6020604051808303816000875af1158015612aa0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ac49190614edc565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612af791815260200190565b60405180910390a15b5090565b6000612b0f846127ca565b90508060800151612b3357604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600460205260408120549003612be9576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612bb6908790600401614ae1565b600060405180830381600087803b158015612bd057600080fd5b505af1158015612be4573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526003602052604081205490911690612c1086611cbf565b90506000612c1f838388611c32565b9050612c3f833383604001518460200151612c3a919061516e565b613f7c565b612c4e83868360400151613f7c565b8051612c88906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169033908a90613e30565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612ccd57600080fd5b505af1158015612ce1573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b038082166000908152601360205260409020541680612406576112817f0000000000000000000000000000000000000000000000000000000000000000612d948461401a565b6131e5565b6040805180820190915260008082526020820152612db5614054565b8152612dbf614138565b602082015290565b600260015403612dea57604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b600080612dff85858561419d565b90925090506000612e0f86612d47565b9050612e1c816001613e8a565b856001600160a01b03167f0b260cc77140cab3405675836fc971314e656137208b77414be51fafd58ae34b612e5088612d47565b8786604051612e6193929190615181565b60405180910390a250935093915050565b6000611281825490565b60006117ff838361420f565b6000612e9b6805345cdf77eb68f44c5490565b15612b00576805345cdf77eb68f44c54612eb3610f9a565b612ebd90846150a8565b612ec791906150d5565b611281565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a721604051602001612f0c90615114565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612f4091815260200190565b602060405180830381865afa158015611daf573d6000803e3d6000fd5b6000816001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015612fc7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612feb91906150f7565b6001600160a01b03161461300157506000919050565b506001919050565b613011614239565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405161304b9190614ae1565b60405180910390a1565b60006117ff611cbc84670de0b6b3a76400008561425c565b6001600160a01b038316158015906130ef5750604051630e041fb560e11b81526001600160a01b03841690631c083f6a906130ac908890600401614ae1565b602060405180830381865afa1580156130c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130ed9190614edc565b155b15613162576001600160a01b0385166000908152600c602052604090206131169084613c4b565b50826001600160a01b0316856001600160a01b0316856001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b80156131dc57600061317386614330565b90506000613180876127ca565b606001519050818110801561319e5750600061319b886127ca565b51115b156131bc576040516334b3313560e11b815260040160405180910390fd5b50506001600160a01b0385166000908152600a6020526040812055611712565b61171285614367565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c820120607882015260556043909101206000906117ff565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166321f8a721604051602001612f0c906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b60008060006132b684612d47565b6001600160a01b03811660009081526002602052604090205490915060ff166132f257604051635435b28960e11b815260040160405180910390fd5b6132fc8685614372565b60405191945092506001600160a01b038516907fd88c5369d398bea6a7390a17ce98af43f4aacc78fd3587bc368993d98206a30490612e6190849089908890615181565b6001600160a01b0383166000908152600b602052604081205460ff1661337957604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b0386166000908152600c6020526040902061339b908561438b565b156133eb57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b60006001600160a01b0385161561346157846001600160a01b0316638a7c32e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561343a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061345e9190614edc565b90505b60008115613476576134733a836150a8565b90505b604051634b18bb2360e11b81526001600160a01b0387169063963176469083906134a890899089908e906004016151a5565b60206040518083038185885af11580156134c6573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906134eb9190614edc565b92506134f8886001613e8a565b505095945050505050565b61350b6143a0565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861303e3390565b60008061354c846127ca565b9050806080015161357057604051636caa790760e01b815260040160405180910390fd5b6001600160a01b03808516600090815260056020908152604080832087851684529091529020541691508161373d576135f17f000000000000000000000000000000000000000000000000000000000000000085856040516020016135d6929190614f9b565b604051602081830303815290604052805190602001206143c4565b604080516080810182526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561369b57600080fd5b505af11580156136af573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260056020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600690915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f163790613734908690614ae1565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a082319061378c908890600401614ae1565b602060405180830381865afa1580156137a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137cd9190614edc565b11156138eb5761389784837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231886040518263ffffffff1660e01b81526004016138249190614ae1565b602060405180830381865afa158015613841573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138659190614edc565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016929190613e30565b816001600160a01b031663402d88836040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156138d257600080fd5b505af11580156138e6573d6000803e3d6000fd5b505050505b6001600160a01b03841660009081526004602052604081205490036139a1576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd669061396e908790600401614ae1565b600060405180830381600087803b15801561398857600080fd5b505af115801561399c573d6000803e3d6000fd5b505050505b5092915050565b600080600080613a456139b9613245565b6001600160a01b031663b3596f077f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b8152600401613a049190614ae1565b602060405180830381865afa158015613a21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cbc9190614edc565b90506000613a64611cbc836115c4670e92596fd62900008b5b90614432565b905085811115613a9157859450613a8a611cbc670e92596fd62900006115c48589614432565b9250613a98565b8094508692505b6000613aa483856115c4565b9050613ab3611cbc8783614441565b94505050509250925092565b6001600160a01b03808216600090815260136020526040812054909183911615613afc57604051635435b28960e11b815260040160405180910390fd5b613b2e7f0000000000000000000000000000000000000000000000000000000000000000613b298361401a565b6143c4565b6001600160a01b038082166000818152600260209081526040808320805460ff191660019081179091559487168084526013835281842080546001600160a01b0319908116871790915594845260039092528220805490931617909155600780549395509192613b9f908490614f0b565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051613bdf9190614ae1565b60405180910390a260405163189acdbd60e31b81526001600160a01b0383169063c4d66de890613c13908490600401614ae1565b600060405180830381600087803b158015613c2d57600080fd5b505af1158015613c41573d6000803e3d6000fd5b5050505050919050565b60006117ff836001600160a01b038416614450565b6000613c6c8383613055565b90506000613c93670de0b6b3a7640000613c8e670de0b6b3a764000088613055565b614543565b9050613ca782670de0b6b3a7640000101590565b80613cb25750818111155b1561171257604051635435b28960e11b815260040160405180910390fd5b6000613cda6143a0565b604051630967fa2960e31b8152600481018390526001600160a01b0384811660248301527f00000000000000000000000000000000000000000000000000000000000000001690634b3fd148906044016020604051808303816000875af1158015613d49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d6d9190614edc565b9050613d7a836001613e8a565b6001600160a01b0380841660008181526003602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d3390613dcb9085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef48644690613df89086908590600401614f52565b600060405180830381600087803b158015613e1257600080fd5b505af1158015613e26573d6000803e3d6000fd5b5050505092915050565b6117a584856001600160a01b03166323b872dd868686604051602401613e5893929190615181565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614552565b6001600160a01b03821660009081526004602052604090205415613ec157604051635e3b451760e11b815260040160405180910390fd5b6000613ecc83611cbf565b11156116ac576000613edd836127ca565b90508115613f29576000613f00611cbc613ef660105490565b6020850151613a5e565b90508082600001511115613f27576040516334b3313560e11b815260040160405180910390fd5b505b8060a00151156116aa576040516334b3313560e11b815260040160405180910390fd5b6000613f5f6805345cdf77eb68f44c5490565b15612b0057613f6c610f9a565b6805345cdf77eb68f44c54612eb3565b6000613fa2613f926805345cdf77eb68f44c5490565b613f9a610f9a565b8491906145ac565b905081600d6000828254613fb6919061516e565b90915550819050613fc685611a1b565b10613fd15780613fda565b613fda84611a1b565b9050613fe684826145db565b6117a56001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168484614666565b6040516001600160601b0319606083901b166020820152600090603401604051602081830303815290604052805190602001209050919050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a56040516020016140c3906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016140f791815260200190565b602060405180830381865afa158015614114573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110379190614edc565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e5f3d3a56040516020016140c39060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b6000806141a983611287565b809250819350505081600d60008282546141c3919061516e565b909155506141d3905085826145db565b6142076001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168584614666565b935093915050565b6000826000018281548110614226576142266151d6565b9060005260206000200154905092915050565b60005460ff1661156f57604051638dfc202b60e01b815260040160405180910390fd5b60008080600019858709858702925082811083820303915050806000036142965783828161428c5761428c6150bf565b04925050506117ff565b8381106142c757604051630c740aef60e31b81526004810187905260248101869052604481018590526064016112f7565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6001600160a01b0381166000908152600a60205260409020548061240657604051636571f87b60e11b815260040160405180910390fd5b611aeb816000613e8a565b60008061438033848661468c565b909590945092505050565b60006117ff836001600160a01b0384166146f7565b60005460ff161561156f5760405163d93c066560e01b815260040160405180910390fd5b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b038116611281576040516330be1a3d60e21b815260040160405180910390fd5b60006117ff611cbc8484614746565b60006117ff611cbc838561516e565b6000818152600183016020526040812054801561453957600061447460018361516e565b85549091506000906144889060019061516e565b90508082146144ed5760008660000182815481106144a8576144a86151d6565b90600052602060002001549050808760000184815481106144cb576144cb6151d6565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806144fe576144fe6151ec565b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050611281565b6000915050611281565b60006117ff611cbc8385614f0b565b60006145676001600160a01b038416836147fc565b9050805160001415801561458c57508080602001905181019061458a9190615202565b155b156116aa5782604051635274afe760e01b81526004016112f79190614ae1565b60008260001904841183021582026145cc5763ad251c276000526004601cfd5b50910281810615159190040190565b6145e7826000836116aa565b6387a211a2600c52816000526020600c208054808311156146105763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a36116ac826000836116aa565b6116aa83846001600160a01b031663a9059cbb8585604051602401613e58929190614f52565b60008061469883612924565b809250819350505081600d60008282546146b29190614f0b565b909155506146ed90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016863085613e30565b614207848261480a565b600081815260018301602052604081205461473e57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611281565b506000611281565b600080806000198486098486029250828110838203039150508060000361477a5750670de0b6b3a764000090049050611281565b670de0b6b3a764000081106147ac57604051635173648d60e01b815260048101869052602481018590526044016112f7565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b60606117ff8383600061489d565b614816600083836116aa565b6805345cdf77eb68f44c548181018181101561483a5763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a36116ac600083836116aa565b6060814710156148c2573060405163cd78605960e01b81526004016112f79190614ae1565b600080856001600160a01b031684866040516148de919061521f565b60006040518083038185875af1925050503d806000811461491b576040519150601f19603f3d011682016040523d82523d6000602084013e614920565b606091505b509150915061493086838361493a565b9695505050505050565b60608261494f5761494a8261498d565b6117ff565b815115801561496657506001600160a01b0384163b155b156149865783604051639996b31560e01b81526004016112f79190614ae1565b50806117ff565b80511561499d5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b0381168114611aeb57600080fd5b600080604083850312156149ff57600080fd5b823591506020830135614a11816149d7565b809150509250929050565b600060208284031215614a2e57600080fd5b81356117ff816149d7565b60005b83811015614a54578181015183820152602001614a3c565b50506000910152565b60008151808452614a75816020860160208601614a39565b601f01601f19169290920160200192915050565b6020815260006117ff6020830184614a5d565b60008060408385031215614aaf57600080fd5b8235614aba816149d7565b946020939093013593505050565b600060208284031215614ada57600080fd5b5035919050565b6001600160a01b0391909116815260200190565b60008060408385031215614b0857600080fd5b8235614b13816149d7565b91506020830135614a11816149d7565b8015158114611aeb57600080fd5b60008060408385031215614b4457600080fd5b8235614b4f816149d7565b91506020830135614a1181614b23565b600080600060608486031215614b7457600080fd5b8335614b7f816149d7565b92506020840135614b8f816149d7565b929592945050506040919091013590565b60008060008060808587031215614bb657600080fd5b8435614bc1816149d7565b93506020850135614bd1816149d7565b9250604085013591506060850135614be881614b23565b939692955090935050565b600060208284031215614c0557600080fd5b81356117ff81614b23565b634e487b7160e01b600052604160045260246000fd5b600082601f830112614c3757600080fd5b813567ffffffffffffffff80821115614c5257614c52614c10565b604051601f8301601f19908116603f01168101908282118183101715614c7a57614c7a614c10565b81604052838152866020858801011115614c9357600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060008060808587031215614cc957600080fd5b8435614cd4816149d7565b93506020850135614ce4816149d7565b925060408501359150606085013567ffffffffffffffff811115614d0757600080fd5b614d1387828801614c26565b91505092959194509250565b60008060008060808587031215614d3557600080fd5b8435614d40816149d7565b93506020850135614d50816149d7565b93969395505050506040820135916060013590565b600080600060608486031215614d7a57600080fd5b8335614d85816149d7565b95602085013595506040909401359392505050565b60008060008060808587031215614db057600080fd5b8435614dbb816149d7565b93506020850135614dcb816149d7565b92506040850135614ddb816149d7565b9150606085013567ffffffffffffffff811115614d0757600080fd5b600080600060608486031215614e0c57600080fd5b505081359360208301359350604090920135919050565b600080600080600080600060e0888a031215614e3e57600080fd5b8735614e49816149d7565b96506020880135614e59816149d7565b95506040880135945060608801359350608088013560ff81168114614e7d57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b600080600060608486031215614eaf57600080fd5b8335614eba816149d7565b9250602084013591506040840135614ed1816149d7565b809150509250925092565b600060208284031215614eee57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561128157611281614ef5565b600181811c90821680614f3257607f821691505b60208210810361119b57634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b80851115614ff0578160001904821115614fd657614fd6614ef5565b80851615614fe357918102915b93841c9390800290614fba565b509250929050565b60008261500757506001611281565b8161501457506000611281565b816001811461502a576002811461503457615050565b6001915050611281565b60ff84111561504557615045614ef5565b50506001821b611281565b5060208310610133831016604e8410600b8410161715615073575081810a611281565b61507d8383614fb5565b806000190482111561509157615091614ef5565b029392505050565b60006117ff60ff841683614ff8565b808202811582820484141761128157611281614ef5565b634e487b7160e01b600052601260045260246000fd5b6000826150f257634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561510957600080fd5b81516117ff816149d7565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061493090830184614a5d565b8181038181111561128157611281614ef5565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8381526060602082015260006151be6060830185614a5d565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561521457600080fd5b81516117ff81614b23565b60008251615231818460208701614a39565b919091019291505056fea264697066735822122003035e1b37f67f6030b7aef7fd6bc1ed4aa963127836189fc58c0a4d4981b0f864736f6c634300081800330000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f7000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000800000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b680000000000000000000000001801de9f9f58a9e2414e6414672d33eac4a6f3b0000000000000000000000000430000000000000000000000000000000000000300000000000000000000000000000000000000000000000029a2241af62c000000000000000000000000000000000000000000000000000010a741a4627800000000000000000000000000000000000000000000000000000ff59ee833b3000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205553444220436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765553444200000000000000000000000000000000000000000000000000

Deployed Bytecode

0x6080604052600436106103e75760003560e01c80638456cb591161020a578063c5ebeaec11610119578063e4af29fc116100a6578063e4af29fc14610dbc578063e59e801814610dd2578063ea29dad314610e4e578063ef48644614610e6e578063ef8b30f714610e8e578063f2468d8714610eae578063f69e204614610ece578063f9566d8214610ee3578063fbcbc0f114610f03578063fbf4198414610f2357600080fd5b8063c5ebeaec14610c75578063c613aec014610c95578063ca8bcd661461097b578063cb6c0c9a14610cc5578063d505accf14610ce5578063d8cab31814610d05578063dd62ed3e14610d26578063dd76401714610d5c578063ddd5e1b214610d7c578063e1d5c06414610d9c57600080fd5b80639d919c63116101975780639d919c6314610b3d5780639dca362f14610b7f578063a59a997314610b94578063a612ce2b14610bc7578063a9059cbb14610be7578063b17e32f914610c02578063b2b8c93f14610c17578063b3c0a0b314610c2c578063b43e6cb414610c3f578063bd1c5d7414610c5557600080fd5b80638456cb59146109ce57806386b9d81f146109e357806389dbb85714610a0357806390401a7a14610a365780639159b20614610a5657806394408b9a14610a7657806395d89b4114610a96578063971d6c9514610aab578063985d28aa14610acb57806399f8148e14610b0457600080fd5b80633a12c6da116103065780635af451cc116102935780635af451cc146108a45780635c975abb146108b95780636806eaab146108d15780636a11d0b2146108f15780636c648fc4146109085780636e553f651461092857806370a08231146109485780637af0bdfd146109685780637b91c2651461097b5780637ecebe001461099b57600080fd5b80633a12c6da146106da5780633f4ba83a146106f05780634031234c14610705578063410051a51461071b578063442b172c1461076e57806347a873cb146107a757806347e41a89146107c7578063484d1ad6146108445780635507f5e9146108645780635a287cb21461088457600080fd5b806312fde4b71161038457806312fde4b7146105665780631534a2771461057b57806318160ddd146105bc5780631e8a84b1146105d95780631fd9a8c6146105fb57806322867d781461062b57806323b872dd1461064b578063313ce5671461066b5780633574d4c4146106a95780633644e515146106c557600080fd5b8062f714ce146103ec57806301e1d114146104265780630674fa411461044957806306fdde03146104695780630914b18f1461048b578063095ea7b3146104cb5780630a28a477146104eb5780630ba212ee1461050b57806311464fbe14610525575b600080fd5b3480156103f857600080fd5b5061040c6104073660046149ec565b610f53565b604080519283526020830191909152015b60405180910390f35b34801561043257600080fd5b5061043b610f9a565b60405190815260200161041d565b34801561045557600080fd5b5061043b610464366004614a1c565b61103c565b34801561047557600080fd5b5061047e6111a1565b60405161041d9190614a89565b34801561049757600080fd5b506104bb6104a6366004614a1c565b60026020526000908152604090205460ff1681565b604051901515815260200161041d565b3480156104d757600080fd5b506104bb6104e6366004614a9c565b611233565b3480156104f757600080fd5b5061040c610506366004614ac8565b611287565b34801561051757600080fd5b506008546104bb9060ff1681565b34801561053157600080fd5b506105597f0000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b6881565b60405161041d9190614ae1565b34801561057257600080fd5b50610559611299565b34801561058757600080fd5b50610559610596366004614af5565b60056020908152600092835260408084209091529082529020546001600160a01b031681565b3480156105c857600080fd5b506805345cdf77eb68f44c5461043b565b3480156105e557600080fd5b506105f96105f4366004614b31565b6112a3565b005b34801561060757600080fd5b506104bb610616366004614a1c565b60096020526000908152604090205460ff1681565b34801561063757600080fd5b5061043b610646366004614a9c565b611363565b34801561065757600080fd5b506104bb610666366004614b5f565b6114bc565b34801561067757600080fd5b5060405160ff7f000000000000000000000000000000000000000000000000000000000000001216815260200161041d565b3480156106b557600080fd5b5061043b670e92596fd629000081565b3480156106d157600080fd5b5061043b6114d7565b3480156106e657600080fd5b5061043b60105481565b3480156106fc57600080fd5b506105f9611554565b34801561071157600080fd5b5061043b60125481565b34801561072757600080fd5b5061073b610736366004614a1c565b611571565b60405161041d91908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b34801561077a57600080fd5b50610559610789366004614a1c565b6001600160a01b039081166000908152600360205260409020541690565b3480156107b357600080fd5b506105f96107c2366004614a9c565b6115fe565b3480156107d357600080fd5b506108276107e2366004614a1c565b60408051808201825260008082526020918201819052825180840184526001600160a01b03949094168082526004808452938220548015158652915291815282015290565b60408051825115158152602092830151928101929092520161041d565b34801561085057600080fd5b506105f961085f366004614a1c565b6116b0565b34801561087057600080fd5b506105f961087f366004614ba0565b611719565b34801561089057600080fd5b5061055961089f366004614af5565b6117ab565b3480156108b057600080fd5b506105f9611806565b3480156108c557600080fd5b5060005460ff166104bb565b3480156108dd57600080fd5b506105f96108ec366004614bf3565b6118ba565b3480156108fd57600080fd5b5061043b620f424081565b34801561091457600080fd5b5061043b610923366004614a1c565b6118e0565b34801561093457600080fd5b5061040c6109433660046149ec565b6119e9565b34801561095457600080fd5b5061043b610963366004614a1c565b611a1b565b61043b610976366004614cb3565b611a33565b34801561098757600080fd5b506105f9610996366004614a1c565b611ac9565b3480156109a757600080fd5b5061043b6109b6366004614a1c565b6338377508600c908152600091909152602090205490565b3480156109da57600080fd5b506105f9611aee565b3480156109ef57600080fd5b506105596109fe366004614af5565b611b09565b348015610a0f57600080fd5b507f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a610559565b348015610a4257600080fd5b50610559610a51366004614a9c565b611b15565b348015610a6257600080fd5b5061043b610a71366004614a1c565b611b37565b348015610a8257600080fd5b506105f9610a91366004614a1c565b611b4a565b348015610aa257600080fd5b5061047e611b98565b348015610ab757600080fd5b506105f9610ac6366004614d1f565b611ba7565b348015610ad757600080fd5b506104bb610ae6366004614a1c565b6001600160a01b03166000908152600b602052604090205460ff1690565b348015610b1057600080fd5b506104bb610b1f366004614a1c565b6001600160a01b031660009081526006602052604090205460ff1690565b348015610b4957600080fd5b50610b5d610b58366004614d65565b611c32565b604080518251815260208084015190820152918101519082015260600161041d565b348015610b8b57600080fd5b50610559611c9e565b348015610ba057600080fd5b507f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a610559565b348015610bd357600080fd5b5061043b610be2366004614a1c565b611cbf565b348015610bf357600080fd5b506104bb610666366004614a9c565b348015610c0e57600080fd5b50610559611d4f565b348015610c2357600080fd5b5061043b611dd3565b610559610c3a366004614d9a565b611fe8565b348015610c4b57600080fd5b5061043b60115481565b348015610c6157600080fd5b506105f9610c70366004614df7565b612308565b348015610c8157600080fd5b5061043b610c90366004614ac8565b61237b565b348015610ca157600080fd5b506104bb610cb0366004614a1c565b600b6020526000908152604090205460ff1681565b348015610cd157600080fd5b506105f9610ce0366004614b31565b61240b565b348015610cf157600080fd5b506105f9610d00366004614e23565b612449565b348015610d1157600080fd5b506015546104bb90600160a01b900460ff1681565b348015610d3257600080fd5b5061043b610d41366004614af5565b602052637f5e9f20600c908152600091909152603490205490565b348015610d6857600080fd5b506105f9610d77366004614a1c565b6125d2565b348015610d8857600080fd5b506105f9610d973660046149ec565b612672565b348015610da857600080fd5b5061043b610db7366004614a1c565b6127a9565b348015610dc857600080fd5b5061043b60075481565b348015610dde57600080fd5b50610df2610ded366004614a1c565b6127ca565b60405161041d9190600060e0820190508251825260208301516020830152604083015160408301526060830151606083015260808301511515608083015260a0830151151560a083015260c0830151151560c083015292915050565b348015610e5a57600080fd5b506105f9610e69366004614bf3565b6128d1565b348015610e7a57600080fd5b506105f9610e89366004614a9c565b612902565b348015610e9a57600080fd5b5061040c610ea9366004614ac8565b612924565b348015610eba57600080fd5b50610b5d610ec9366004614a9c565b612942565b348015610eda57600080fd5b5061043b61297e565b348015610eef57600080fd5b506105f9610efe366004614e9a565b612b04565b348015610f0f57600080fd5b50610559610f1e366004614a1c565b612d47565b348015610f2f57600080fd5b50610f38612d99565b6040805182518152602092830151928101929092520161041d565b600080610f5e612dc7565b601554600160a01b900460ff1615610f7a57610f7861297e565b505b610f85338486612df1565b9092509050610f9360018055565b9250929050565b60405163e12f3a6160e01b81526000906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003169063e12f3a6190610fe9903090600401614ae1565b602060405180830381865afa158015611006573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102a9190614edc565b600d546110379190614f0b565b905090565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a082319061108b908590600401614ae1565b602060405180830381865afa1580156110a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110cc9190614edc565b905060005b6001600160a01b0383166000908152600c602052604090206110f290612e72565b81101561119b576001600160a01b0383166000908152600c6020526040902061111b9082612e7c565b6001600160a01b0316631c083f6a846040518263ffffffff1660e01b81526004016111469190614ae1565b602060405180830381865afa158015611163573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111879190614edc565b6111919083614f0b565b91506001016110d1565b50919050565b6060600e80546111b090614f1e565b80601f01602080910402602001604051908101604052809291908181526020018280546111dc90614f1e565b80156112295780601f106111fe57610100808354040283529160200191611229565b820191906000526020600020905b81548152906001019060200180831161120c57829003601f168201915b5050505050905090565b600082602052637f5e9f20600c5233600052816034600c205581600052602c5160601c337f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206000a35060015b92915050565b60008061129383612e88565b93915050565b6000611037612ecc565b6112ac33612f5d565b61130057335b60408051637974da6f60e01b81526001600160a01b0390921660048301526024820152600e60448201526d282927aa27a1a7a62fa0a226a4a760911b60648201526084015b60405180910390fd5b6001600160a01b0382166000818152600b6020908152604091829020805460ff19168515159081179091558251938452908301527ffc2e7375e815d084de88de8e8e356e71102275019b06a1b529eee0c8ab57cd34910160405180910390a15050565b600061136d612dc7565b60405163c883b2e560e01b8152600481018390526001600160a01b0384811660248301523360448301527f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a169063c883b2e5906064016020604051808303816000875af11580156113e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114069190614edc565b6001600160a01b0384811660008181526003602090815260409182902054915185815294955091939216917fa42e379bd7db0adade1690b7b2b3b81c2419c87c3c9f0c4f4f5a4da3ce8a8966910160405180910390a36040516347a873cb60e01b815230906347a873cb906114819086908590600401614f52565b600060405180830381600087803b15801561149b57600080fd5b505af11580156114af573d6000803e3d6000fd5b5050505061128160018055565b600060405163a24e573d60e01b815260040160405180910390fd5b6000806114e26111a1565b8051906020012090506040517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81528160208201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604082015246606082015230608082015260a081209250505090565b61155d33612f5d565b61156757336112b2565b61156f613009565b565b61159c6040518060800160405280600081526020016000815260200160008152602001600081525090565b60006115a7836118e0565b905060006115b484611cbf565b9050600082156115cd576115ca83835b90613055565b90505b60405180608001604052808381526020018481526020018281526020016115f360105490565b905295945050505050565b3330146116205733604051637974da6f60e01b81526004016112f79190614f6b565b6001600160a01b038216600090815260046020526040902054156116ac576000611649836127ca565b905080608001516116aa5760405163dd76401760e01b8152309063dd76401790611677908690600401614ae1565b600060405180830381600087803b15801561169157600080fd5b505af11580156116a5573d6000803e3d6000fd5b505050505b505b5050565b6116b933612f5d565b6116c357336112b2565b806001600160a01b0316638456cb596040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156116fe57600080fd5b505af1158015611712573d6000803e3d6000fd5b5050505050565b3360009081526002602052604090205460ff16611748576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561176a57503360009081526009602052604090205460ff16155b15611787576040516282b42960e81b815260040160405180910390fd5b61178f612dc7565b61179c338585858561306d565b6117a560018055565b50505050565b60006117ff7f0000000000000000000000001801de9f9f58a9e2414e6414672d33eac4a6f3b084846040516020016117e4929190614f9b565b604051602081830303815290604052805190602001206131e5565b9392505050565b3360009081526002602052604090205460ff16611835576040516282b42960e81b815260040160405180910390fd5b60085460ff16801561185757503360009081526009602052604090205460ff16155b15611874576040516282b42960e81b815260040160405180910390fd5b600061187f336127ca565b90508060800151156118a457604051635e3b451760e11b815260040160405180910390fd5b60600151336000908152600a6020526040902055565b6118c333612f5d565b6118cd57336112b2565b6008805460ff1916911515919091179055565b6001600160a01b038082166000908152600360205260408120549091168161190782611b37565b90506000611913613245565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000036040518263ffffffff1660e01b815260040161195e9190614ae1565b602060405180830381865afa15801561197b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061199f9190614edc565b90506119cc7f0000000000000000000000000000000000000000000000000000000000000012600a615099565b6119d682846150a8565b6119e091906150d5565b95945050505050565b6000806119f4612dc7565b601554600160a01b900460ff1615611a1057611a0e61297e565b505b610f858433856132a8565b6387a211a2600c908152600091909152602090205490565b3360009081526002602052604081205460ff16611a62576040516282b42960e81b815260040160405180910390fd5b60085460ff168015611a8457503360009081526009602052604090205460ff16155b15611aa1576040516282b42960e81b815260040160405180910390fd5b611aa9612dc7565b611ab63386868686613340565b9050611ac160018055565b949350505050565b333014611aeb5733604051637974da6f60e01b81526004016112f79190614f6b565b50565b611af733612f5d565b611b0157336112b2565b61156f613503565b60006117ff8383613540565b6001600160a01b0382166000908152600c602052604081206117ff9083612e7c565b6000611281611b4583611a1b565b612e88565b611b5333612f5d565b611b5d57336112b2565b806001600160a01b0316633f4ba83a6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156116fe57600080fd5b6060600f80546111b090614f1e565b3360009081526006602052604090205460ff16611bd6576040516282b42960e81b815260040160405180910390fd5b826001600160a01b0316846001600160a01b03167fb15b5161080eeb6130c6088d7b1e8eceb1092d2a15836c769bd094d9a68c8c6b8484604051611c24929190918252602082015260400190565b60405180910390a350505050565b611c3a6149b6565b6000838311611c495782611c4b565b835b90506000611c5886611b37565b90506000806000611c6985856139a8565b92509250925084811015611c7b578094505b506040805160608101825294855260208501929092529083015250949350505050565b6000611ca8612dc7565b611cb133613abf565b9050611cbc60018055565b90565b60405163a612ce2b60e01b81526000906001600160a01b037f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a169063a612ce2b90611d0e908590600401614ae1565b602060405180830381865afa158015611d2b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112819190614edc565b60007f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a6001600160a01b0316635c222bad6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611daf573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061103791906150f7565b60145460405160009182916001600160a01b039091169063c824e15790611e169060200160208082526005908201526410931054d560da1b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611e4a91815260200190565b602060405180830381865afa158015611e67573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e8b91906150f7565b6014546040519192506000916001600160a01b03909116906321f8a72190611eb590602001615114565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611ee991815260200190565b602060405180830381865afa158015611f06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f2a91906150f7565b60405163662aa11d60e01b81529091506001600160a01b0383169063662aa11d90611f5b9030908590600401614f9b565b6020604051808303816000875af1158015611f7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9e9190614edc565b9250806001600160a01b03167f9c3c39d0eedd3d18612a0e8e76cc7bc873815d3e19206dbbf9825989b1c95e6b84604051611fdb91815260200190565b60405180910390a2505090565b6001600160a01b0382166000908152600b602052604081205460ff1661202157604051631a22ce4f60e11b815260040160405180910390fd5b61202b8585613540565b90506000806001600160a01b038516156120a457846001600160a01b031663ea2c58046040518163ffffffff1660e01b8152600401602060405180830381865afa15801561207d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120a19190614edc565b90505b600081156120b9576120b63a836150a8565b90505b604051639035268760e01b81526001600160a01b0389169063903526879083906120ed908a90899089908c9060040161513b565b6000604051808303818588803b15801561210657600080fd5b505af115801561211a573d6000803e3d6000fd5b50505050506001600160a01b038616158015906121a15750604051630e041fb560e11b81526001600160a01b03871690631c083f6a9061215e908b90600401614ae1565b602060405180830381865afa15801561217b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061219f9190614edc565b155b15612213576001600160a01b0388166000908152600c602052604090206121c89087613c4b565b506001600160a01b03888116600081815260036020526040808220549051848b169491909116917f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e291a45b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a0823190612262908890600401614ae1565b602060405180830381865afa15801561227f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122a39190614edc565b11156122fd57836001600160a01b031663402d88836040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156122e457600080fd5b505af11580156122f8573d6000803e3d6000fd5b505050505b505050949350505050565b61231133612f5d565b61231b57336112b2565b612326838383613c60565b60108390556011829055601281905560408051848152602081018490529081018290527fafabe1c7d6c2e86cbfc67a8ba53d25a7f8ef59b97d972dd4bf7d7525ba7fdddf9060600160405180910390a1505050565b3360009081526002602052604081205460ff166123aa576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156123cc57503360009081526009602052604090205460ff16155b156123e9576040516282b42960e81b815260040160405180910390fd5b6123f1612dc7565b6123fb3383613cd0565b905061240660018055565b919050565b61241433612f5d565b61241e57336112b2565b6001600160a01b03919091166000908152600960205260409020805460ff1916911515919091179055565b60006124536111a1565b8051906020012090508442111561247257631a15a3cc6000526004601cfd5b6040518860601b60601c98508760601b60601c975065383775081901600e52886000526020600c2080547f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f83528360208401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6604084015246606084015230608084015260a08320602e527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c983528a60208401528960408401528860608401528060808401528760a084015260c08320604e526042602c206000528660ff1660205285604052846060526020806080600060015afa8b3d511461257e5763ddafbaef6000526004601cfd5b0190556303faf4f960a51b88176040526034602c2087905587897f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925602060608501a360405250506000606052505050505050565b3330146125f45733604051637974da6f60e01b81526004016112f79190614f6b565b6001600160a01b038116600081815260046020526040808220829055517fccfc0aeacebc685763eb86a3e35dfeac830fd983f2f597b3f142ee667d28acc49190a2604051637b91c26560e01b81523090637b91c26590612658908490600401614ae1565b600060405180830381600087803b1580156116fe57600080fd5b806001600160a01b03811661269a5760405163d92e233d60e01b815260040160405180910390fd5b3360009081526002602052604090205460ff166126c9576040516282b42960e81b815260040160405180910390fd5b60085460ff1680156126eb57503360009081526009602052604090205460ff16155b15612708576040516282b42960e81b815260040160405180910390fd5b612710612dc7565b6127456001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316338486613e30565b612750336001613e8a565b336000818152600360209081526040918290205491518681526001600160a01b03909216917f01bfef2bf622406285ca1a4057a39432c0ba15e2069c29ae6098c22affdeaf45910160405180910390a36116aa60018055565b6001600160a01b0381166000908152600c6020526040812061128190612e72565b6128106040518060e00160405280600081526020016000815260200160008152602001600081526020016000151581526020016000151581526020016000151581525090565b600061281b8361103c565b90506000612828846118e0565b9050600061283585611cbf565b905060006128438484614f0b565b6040805160e081018252848152602081018690529081018690526000606082018190526080820181905260a0820181905260c082015295509050811580159061288c5750600081115b156128ba5761289b82826115c4565b60608601819052601154811060a08701526012541160808601526128c8565b81156128c857600160c08601525b50505050919050565b6128da33612f5d565b6128e457336112b2565b60158054911515600160a01b0260ff60a01b19909216919091179055565b3330146116ac5733604051637974da6f60e01b81526004016112f79190614f6b565b60008061293083613f4c565b905061293b81612e88565b9150915091565b61294a6149b6565b6001600160a01b038084166000908152600360205260408120549091169061297185611cbf565b90506119e0828286611c32565b60405163e12f3a6160e01b81526000907f0000000000000000000000004300000000000000000000000000000000000003906001600160a01b0382169063e12f3a61906129cf903090600401614ae1565b602060405180830381865afa1580156129ec573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a109190614edc565b9150620f42408210612b005781600d6000828254612a2e9190614f0b565b9091555050604051635569f64b60e11b81526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003169063aad3ec9690612a819030908690600401614f52565b6020604051808303816000875af1158015612aa0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ac49190614edc565b91507f3b6bc0ba304eaa17cdca1b053baac859e721c7a775cddefc825f6286641311fc82604051612af791815260200190565b60405180910390a15b5090565b6000612b0f846127ca565b90508060800151612b3357604051636caa790760e01b815260040160405180910390fd5b6001600160a01b0384166000908152600460205260408120549003612be9576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd6690612bb6908790600401614ae1565b600060405180830381600087803b158015612bd057600080fd5b505af1158015612be4573d6000803e3d6000fd5b505050505b6001600160a01b0380851660009081526003602052604081205490911690612c1086611cbf565b90506000612c1f838388611c32565b9050612c3f833383604001518460200151612c3a919061516e565b613f7c565b612c4e83868360400151613f7c565b8051612c88906001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003169033908a90613e30565b8051604051631b8fec7360e11b815260048101919091526001600160a01b0388169063371fd8e690602401600060405180830381600087803b158015612ccd57600080fd5b505af1158015612ce1573d6000803e3d6000fd5b505050602080830151604080850151855182516001600160a01b038e168152948501939093529083015260608201527fe32ec3ea3154879f27d5367898ab3a5ac6b68bf921d7cc610720f417c5cb243c915060800160405180910390a150505050505050565b6001600160a01b038082166000908152601360205260409020541680612406576112817f0000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b68612d948461401a565b6131e5565b6040805180820190915260008082526020820152612db5614054565b8152612dbf614138565b602082015290565b600260015403612dea57604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b600080612dff85858561419d565b90925090506000612e0f86612d47565b9050612e1c816001613e8a565b856001600160a01b03167f0b260cc77140cab3405675836fc971314e656137208b77414be51fafd58ae34b612e5088612d47565b8786604051612e6193929190615181565b60405180910390a250935093915050565b6000611281825490565b60006117ff838361420f565b6000612e9b6805345cdf77eb68f44c5490565b15612b00576805345cdf77eb68f44c54612eb3610f9a565b612ebd90846150a8565b612ec791906150d5565b611281565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b03166321f8a721604051602001612f0c90615114565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612f4091815260200190565b602060405180830381865afa158015611daf573d6000803e3d6000fd5b6000816001600160a01b03167f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663893d20e86040518163ffffffff1660e01b8152600401602060405180830381865afa158015612fc7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612feb91906150f7565b6001600160a01b03161461300157506000919050565b506001919050565b613011614239565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405161304b9190614ae1565b60405180910390a1565b60006117ff611cbc84670de0b6b3a76400008561425c565b6001600160a01b038316158015906130ef5750604051630e041fb560e11b81526001600160a01b03841690631c083f6a906130ac908890600401614ae1565b602060405180830381865afa1580156130c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130ed9190614edc565b155b15613162576001600160a01b0385166000908152600c602052604090206131169084613c4b565b50826001600160a01b0316856001600160a01b0316856001600160a01b03167f9910e38adb465481c843222dba5590cfcb99a51e28f2fc633b66289ef06ba4e260405160405180910390a45b80156131dc57600061317386614330565b90506000613180876127ca565b606001519050818110801561319e5750600061319b886127ca565b51115b156131bc576040516334b3313560e11b815260040160405180910390fd5b50506001600160a01b0385166000908152600a6020526040812055611712565b61171285614367565b6040513060388201526f5af43d82803e903d91602b57fd5bf3ff602482015260148101839052733d602d80600a3d3981f3363d3d373d3d3d363d738152605881018290526037600c820120607882015260556043909101206000906117ff565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b03166321f8a721604051602001612f0c906020808252600e908201526d282924a1a2afa82927ab24a222a960911b604082015260600190565b60008060006132b684612d47565b6001600160a01b03811660009081526002602052604090205490915060ff166132f257604051635435b28960e11b815260040160405180910390fd5b6132fc8685614372565b60405191945092506001600160a01b038516907fd88c5369d398bea6a7390a17ce98af43f4aacc78fd3587bc368993d98206a30490612e6190849089908890615181565b6001600160a01b0383166000908152600b602052604081205460ff1661337957604051631a22ce4f60e11b815260040160405180910390fd5b6001600160a01b0386166000908152600c6020526040902061339b908561438b565b156133eb57836001600160a01b0316866001600160a01b0316866001600160a01b03167ff6fa2840bdce616f9e9bbe7d65ca8bcca0532f1c4aa348c65c79c2cbf6ebf1f960405160405180910390a45b60006001600160a01b0385161561346157846001600160a01b0316638a7c32e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561343a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061345e9190614edc565b90505b60008115613476576134733a836150a8565b90505b604051634b18bb2360e11b81526001600160a01b0387169063963176469083906134a890899089908e906004016151a5565b60206040518083038185885af11580156134c6573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906134eb9190614edc565b92506134f8886001613e8a565b505095945050505050565b61350b6143a0565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861303e3390565b60008061354c846127ca565b9050806080015161357057604051636caa790760e01b815260040160405180910390fd5b6001600160a01b03808516600090815260056020908152604080832087851684529091529020541691508161373d576135f17f0000000000000000000000001801de9f9f58a9e2414e6414672d33eac4a6f3b085856040516020016135d6929190614f9b565b604051602081830303815290604052805190602001206143c4565b604080516080810182526001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003811682523060208301908152888216838501908152888316606085019081529451630415cc1560e01b81529351831660048501529051821660248401525181166044830152915182166064820152919350831690630415cc1590608401600060405180830381600087803b15801561369b57600080fd5b505af11580156136af573d6000803e3d6000fd5b505050506001600160a01b03848116600081815260056020908152604080832088861680855290835281842080546001600160a01b0319169689169687179055948352600690915290819020805460ff19166001179055517f39ee3b3ae7d535f7a027ce37245120586dd668f09e21538a7e0e8d7d5b3f163790613734908690614ae1565b60405180910390a35b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316906370a082319061378c908890600401614ae1565b602060405180830381865afa1580156137a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137cd9190614edc565b11156138eb5761389784837f00000000000000000000000043000000000000000000000000000000000000036001600160a01b03166370a08231886040518263ffffffff1660e01b81526004016138249190614ae1565b602060405180830381865afa158015613841573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138659190614edc565b6001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316929190613e30565b816001600160a01b031663402d88836040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156138d257600080fd5b505af11580156138e6573d6000803e3d6000fd5b505050505b6001600160a01b03841660009081526004602052604081205490036139a1576001600160a01b038416600081815260046020526040808220429055517fdcd8b95bdfd2ffcc332acd69f71c9319a5a1006ca18c94d83d854e591cb6e0439190a2604051636545e6b360e11b8152309063ca8bcd669061396e908790600401614ae1565b600060405180830381600087803b15801561398857600080fd5b505af115801561399c573d6000803e3d6000fd5b505050505b5092915050565b600080600080613a456139b9613245565b6001600160a01b031663b3596f077f00000000000000000000000043000000000000000000000000000000000000036040518263ffffffff1660e01b8152600401613a049190614ae1565b602060405180830381865afa158015613a21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cbc9190614edc565b90506000613a64611cbc836115c4670e92596fd62900008b5b90614432565b905085811115613a9157859450613a8a611cbc670e92596fd62900006115c48589614432565b9250613a98565b8094508692505b6000613aa483856115c4565b9050613ab3611cbc8783614441565b94505050509250925092565b6001600160a01b03808216600090815260136020526040812054909183911615613afc57604051635435b28960e11b815260040160405180910390fd5b613b2e7f0000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b68613b298361401a565b6143c4565b6001600160a01b038082166000818152600260209081526040808320805460ff191660019081179091559487168084526013835281842080546001600160a01b0319908116871790915594845260039092528220805490931617909155600780549395509192613b9f908490614f0b565b92505081905550806001600160a01b03167fac631f3001b55ea1509cf3d7e74898f85392a61a76e8149181ae1259622dabc883604051613bdf9190614ae1565b60405180910390a260405163189acdbd60e31b81526001600160a01b0383169063c4d66de890613c13908490600401614ae1565b600060405180830381600087803b158015613c2d57600080fd5b505af1158015613c41573d6000803e3d6000fd5b5050505050919050565b60006117ff836001600160a01b038416614450565b6000613c6c8383613055565b90506000613c93670de0b6b3a7640000613c8e670de0b6b3a764000088613055565b614543565b9050613ca782670de0b6b3a7640000101590565b80613cb25750818111155b1561171257604051635435b28960e11b815260040160405180910390fd5b6000613cda6143a0565b604051630967fa2960e31b8152600481018390526001600160a01b0384811660248301527f0000000000000000000000004a1d9220e11a47d8ab22ccd82da616740cf0920a1690634b3fd148906044016020604051808303816000875af1158015613d49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d6d9190614edc565b9050613d7a836001613e8a565b6001600160a01b0380841660008181526003602052604090819020549051919216907f44dd1331990f12a8382e7da57756538a810f52fa13c1bb0d0ca6b14225be6d3390613dcb9085815260200190565b60405180910390a36040516377a4322360e11b8152309063ef48644690613df89086908590600401614f52565b600060405180830381600087803b158015613e1257600080fd5b505af1158015613e26573d6000803e3d6000fd5b5050505092915050565b6117a584856001600160a01b03166323b872dd868686604051602401613e5893929190615181565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614552565b6001600160a01b03821660009081526004602052604090205415613ec157604051635e3b451760e11b815260040160405180910390fd5b6000613ecc83611cbf565b11156116ac576000613edd836127ca565b90508115613f29576000613f00611cbc613ef660105490565b6020850151613a5e565b90508082600001511115613f27576040516334b3313560e11b815260040160405180910390fd5b505b8060a00151156116aa576040516334b3313560e11b815260040160405180910390fd5b6000613f5f6805345cdf77eb68f44c5490565b15612b0057613f6c610f9a565b6805345cdf77eb68f44c54612eb3565b6000613fa2613f926805345cdf77eb68f44c5490565b613f9a610f9a565b8491906145ac565b905081600d6000828254613fb6919061516e565b90915550819050613fc685611a1b565b10613fd15780613fda565b613fda84611a1b565b9050613fe684826145db565b6117a56001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003168484614666565b6040516001600160601b0319606083901b166020820152600090603401604051602081830303815290604052805190602001209050919050565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663e5f3d3a56040516020016140c3906020808252601a908201527950524f544f434f4c5f4c49515549444154494f4e5f534841524560301b604082015260600190565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016140f791815260200190565b602060405180830381865afa158015614114573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110379190614edc565b60007f0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a6001600160a01b031663e5f3d3a56040516020016140c39060208082526010908201526f4c495155494441544f525f534841524560801b604082015260600190565b6000806141a983611287565b809250819350505081600d60008282546141c3919061516e565b909155506141d3905085826145db565b6142076001600160a01b037f0000000000000000000000004300000000000000000000000000000000000003168584614666565b935093915050565b6000826000018281548110614226576142266151d6565b9060005260206000200154905092915050565b60005460ff1661156f57604051638dfc202b60e01b815260040160405180910390fd5b60008080600019858709858702925082811083820303915050806000036142965783828161428c5761428c6150bf565b04925050506117ff565b8381106142c757604051630c740aef60e31b81526004810187905260248101869052604481018590526064016112f7565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6001600160a01b0381166000908152600a60205260409020548061240657604051636571f87b60e11b815260040160405180910390fd5b611aeb816000613e8a565b60008061438033848661468c565b909590945092505050565b60006117ff836001600160a01b0384166146f7565b60005460ff161561156f5760405163d93c066560e01b815260040160405180910390fd5b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b1760205281603760096000f590506001600160a01b038116611281576040516330be1a3d60e21b815260040160405180910390fd5b60006117ff611cbc8484614746565b60006117ff611cbc838561516e565b6000818152600183016020526040812054801561453957600061447460018361516e565b85549091506000906144889060019061516e565b90508082146144ed5760008660000182815481106144a8576144a86151d6565b90600052602060002001549050808760000184815481106144cb576144cb6151d6565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806144fe576144fe6151ec565b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050611281565b6000915050611281565b60006117ff611cbc8385614f0b565b60006145676001600160a01b038416836147fc565b9050805160001415801561458c57508080602001905181019061458a9190615202565b155b156116aa5782604051635274afe760e01b81526004016112f79190614ae1565b60008260001904841183021582026145cc5763ad251c276000526004601cfd5b50910281810615159190040190565b6145e7826000836116aa565b6387a211a2600c52816000526020600c208054808311156146105763f4d678b86000526004601cfd5b82900390556805345cdf77eb68f44c8054829003905560008181526001600160a01b0383167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602083a36116ac826000836116aa565b6116aa83846001600160a01b031663a9059cbb8585604051602401613e58929190614f52565b60008061469883612924565b809250819350505081600d60008282546146b29190614f0b565b909155506146ed90506001600160a01b037f000000000000000000000000430000000000000000000000000000000000000316863085613e30565b614207848261480a565b600081815260018301602052604081205461473e57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611281565b506000611281565b600080806000198486098486029250828110838203039150508060000361477a5750670de0b6b3a764000090049050611281565b670de0b6b3a764000081106147ac57604051635173648d60e01b815260048101869052602481018590526044016112f7565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b60606117ff8383600061489d565b614816600083836116aa565b6805345cdf77eb68f44c548181018181101561483a5763e5cfe9576000526004601cfd5b806805345cdf77eb68f44c5550506387a211a2600c52816000526020600c208181540181555080602052600c5160601c60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602080a36116ac600083836116aa565b6060814710156148c2573060405163cd78605960e01b81526004016112f79190614ae1565b600080856001600160a01b031684866040516148de919061521f565b60006040518083038185875af1925050503d806000811461491b576040519150601f19603f3d011682016040523d82523d6000602084013e614920565b606091505b509150915061493086838361493a565b9695505050505050565b60608261494f5761494a8261498d565b6117ff565b815115801561496657506001600160a01b0384163b155b156149865783604051639996b31560e01b81526004016112f79190614ae1565b50806117ff565b80511561499d5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b0381168114611aeb57600080fd5b600080604083850312156149ff57600080fd5b823591506020830135614a11816149d7565b809150509250929050565b600060208284031215614a2e57600080fd5b81356117ff816149d7565b60005b83811015614a54578181015183820152602001614a3c565b50506000910152565b60008151808452614a75816020860160208601614a39565b601f01601f19169290920160200192915050565b6020815260006117ff6020830184614a5d565b60008060408385031215614aaf57600080fd5b8235614aba816149d7565b946020939093013593505050565b600060208284031215614ada57600080fd5b5035919050565b6001600160a01b0391909116815260200190565b60008060408385031215614b0857600080fd5b8235614b13816149d7565b91506020830135614a11816149d7565b8015158114611aeb57600080fd5b60008060408385031215614b4457600080fd5b8235614b4f816149d7565b91506020830135614a1181614b23565b600080600060608486031215614b7457600080fd5b8335614b7f816149d7565b92506020840135614b8f816149d7565b929592945050506040919091013590565b60008060008060808587031215614bb657600080fd5b8435614bc1816149d7565b93506020850135614bd1816149d7565b9250604085013591506060850135614be881614b23565b939692955090935050565b600060208284031215614c0557600080fd5b81356117ff81614b23565b634e487b7160e01b600052604160045260246000fd5b600082601f830112614c3757600080fd5b813567ffffffffffffffff80821115614c5257614c52614c10565b604051601f8301601f19908116603f01168101908282118183101715614c7a57614c7a614c10565b81604052838152866020858801011115614c9357600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060008060808587031215614cc957600080fd5b8435614cd4816149d7565b93506020850135614ce4816149d7565b925060408501359150606085013567ffffffffffffffff811115614d0757600080fd5b614d1387828801614c26565b91505092959194509250565b60008060008060808587031215614d3557600080fd5b8435614d40816149d7565b93506020850135614d50816149d7565b93969395505050506040820135916060013590565b600080600060608486031215614d7a57600080fd5b8335614d85816149d7565b95602085013595506040909401359392505050565b60008060008060808587031215614db057600080fd5b8435614dbb816149d7565b93506020850135614dcb816149d7565b92506040850135614ddb816149d7565b9150606085013567ffffffffffffffff811115614d0757600080fd5b600080600060608486031215614e0c57600080fd5b505081359360208301359350604090920135919050565b600080600080600080600060e0888a031215614e3e57600080fd5b8735614e49816149d7565b96506020880135614e59816149d7565b95506040880135945060608801359350608088013560ff81168114614e7d57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b600080600060608486031215614eaf57600080fd5b8335614eba816149d7565b9250602084013591506040840135614ed1816149d7565b809150509250925092565b600060208284031215614eee57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561128157611281614ef5565b600181811c90821680614f3257607f821691505b60208210810361119b57634e487b7160e01b600052602260045260246000fd5b6001600160a01b03929092168252602082015260400190565b6001600160a01b039190911681526040602082018190526004908201526329a2a62360e11b606082015260800190565b6001600160a01b0392831681529116602082015260400190565b600181815b80851115614ff0578160001904821115614fd657614fd6614ef5565b80851615614fe357918102915b93841c9390800290614fba565b509250929050565b60008261500757506001611281565b8161501457506000611281565b816001811461502a576002811461503457615050565b6001915050611281565b60ff84111561504557615045614ef5565b50506001821b611281565b5060208310610133831016604e8410600b8410161715615073575081810a611281565b61507d8383614fb5565b806000190482111561509157615091614ef5565b029392505050565b60006117ff60ff841683614ff8565b808202811582820484141761128157611281614ef5565b634e487b7160e01b600052601260045260246000fd5b6000826150f257634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561510957600080fd5b81516117ff816149d7565b6020808252600d908201526c2322a2afa1a7a62622a1aa27a960991b604082015260600190565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061493090830184614a5d565b8181038181111561128157611281614ef5565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8381526060602082015260006151be6060830185614a5d565b905060018060a01b0383166040830152949350505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b60006020828403121561521457600080fd5b81516117ff81614b23565b60008251615231818460208701614a39565b919091019291505056fea264697066735822122003035e1b37f67f6030b7aef7fd6bc1ed4aa963127836189fc58c0a4d4981b0f864736f6c63430008180033

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

0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f7000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000800000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b680000000000000000000000001801de9f9f58a9e2414e6414672d33eac4a6f3b0000000000000000000000000430000000000000000000000000000000000000300000000000000000000000000000000000000000000000029a2241af62c000000000000000000000000000000000000000000000000000010a741a4627800000000000000000000000000000000000000000000000000000ff59ee833b3000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000234a756963652046696e616e6365205553444220436f6c6c61746572616c205661756c74000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000076a63765553444200000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : protocolGovernor_ (address): 0x5bbc51EdA8508F598E01eeCd1EA129E741bCc25a
Arg [1] : pointsOperator_ (address): 0x02F6EEb4E33bbA64bcBEA18bd149B9031C2735F7
Arg [2] : isAutoCompounding_ (bool): True
Arg [3] : params (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]

-----Encoded View---------------
18 Constructor Arguments found :
Arg [0] : 0000000000000000000000005bbc51eda8508f598e01eecd1ea129e741bcc25a
Arg [1] : 00000000000000000000000002f6eeb4e33bba64bcbea18bd149b9031c2735f7
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [4] : 0000000000000000000000008e0aed420fe97cc3ada9cb2bbb77f34a0c444b68
Arg [5] : 0000000000000000000000001801de9f9f58a9e2414e6414672d33eac4a6f3b0
Arg [6] : 0000000000000000000000004300000000000000000000000000000000000003
Arg [7] : 00000000000000000000000000000000000000000000000029a2241af62c0000
Arg [8] : 00000000000000000000000000000000000000000000000010a741a462780000
Arg [9] : 0000000000000000000000000000000000000000000000000ff59ee833b30000
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000023
Arg [14] : 4a756963652046696e616e6365205553444220436f6c6c61746572616c205661
Arg [15] : 756c740000000000000000000000000000000000000000000000000000000000
Arg [16] : 0000000000000000000000000000000000000000000000000000000000000007
Arg [17] : 6a63765553444200000000000000000000000000000000000000000000000000


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.