ETH Price: $3,071.10 (+2.44%)
Gas: 4 Gwei

Token

Fluid USD Coin (fUSDC)
 

Overview

Max Total Supply

69,510,087.284578 fUSDC

Holders

177 ( 1.685%)

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 6 Decimals)

Balance
4,768.24189 fUSDC

Value
$0.00
0xafb15e4f247ea0ba77ec8a4039607e9d9b5cbf0a
Loading...
Loading
Loading...
Loading
Loading...
Loading

OVERVIEW

Fluid is a DeFi protocol that optimizes asset utilization through advanced liquidation mechanisms and a universal liquidity layer. Fluid features multiple applications built on top including Lending, Vaults and Dex protocols.

# Exchange Pair Price  24H Volume % Volume

Contract Source Code Verified (Exact Match)

Contract Name:
fToken

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 10000000 runs

Other Settings:
paris EvmVersion
File 1 of 31 : IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

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

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);
}

File 2 of 31 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    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.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

File 3 of 31 : draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation 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.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

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

pragma solidity ^0.8.0;

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

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

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

File 5 of 31 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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 6 of 31 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

File 8 of 31 : Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 9 of 31 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

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

File 10 of 31 : EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

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

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

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

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

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

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

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

File 11 of 31 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

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

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

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

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

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

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "./math/Math.sol";

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

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

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

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

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

File 14 of 31 : iProxy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IProxy {
    function setAdmin(address newAdmin_) external;

    function setDummyImplementation(address newDummyImplementation_) external;

    function addImplementation(address implementation_, bytes4[] calldata sigs_) external;

    function removeImplementation(address implementation_) external;

    function getAdmin() external view returns (address);

    function getDummyImplementation() external view returns (address);

    function getImplementationSigs(address impl_) external view returns (bytes4[] memory);

    function getSigsImplementation(bytes4 sig_) external view returns (address);

    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}

File 15 of 31 : bigMathMinified.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

/// @title library that represents a number in BigNumber(coefficient and exponent) format to store in smaller bits.
/// @notice the number is divided into two parts: a coefficient and an exponent. This comes at a cost of losing some precision
/// at the end of the number because the exponent simply fills it with zeroes. This precision is oftentimes negligible and can
/// result in significant gas cost reduction due to storage space reduction.
/// Also note, a valid big number is as follows: if the exponent is > 0, then coefficient last bits should be occupied to have max precision.
/// @dev roundUp is more like a increase 1, which happens everytime for the same number.
/// roundDown simply sets trailing digits after coefficientSize to zero (floor), only once for the same number.
library BigMathMinified {
    /// @dev constants to use for `roundUp` input param to increase readability
    bool internal constant ROUND_DOWN = false;
    bool internal constant ROUND_UP = true;

    /// @dev converts `normal` number to BigNumber with `exponent` and `coefficient` (or precision).
    /// e.g.:
    /// 5035703444687813576399599 (normal) = (coefficient[32bits], exponent[8bits])[40bits]
    /// 5035703444687813576399599 (decimal) => 10000101010010110100000011111011110010100110100000000011100101001101001101011101111 (binary)
    ///                                     => 10000101010010110100000011111011000000000000000000000000000000000000000000000000000
    ///                                                                        ^-------------------- 51(exponent) -------------- ^
    /// coefficient = 1000,0101,0100,1011,0100,0000,1111,1011               (2236301563)
    /// exponent =                                            0011,0011     (51)
    /// bigNumber =   1000,0101,0100,1011,0100,0000,1111,1011,0011,0011     (572493200179)
    ///
    /// @param normal number which needs to be converted into Big Number
    /// @param coefficientSize at max how many bits of precision there should be (64 = uint64 (64 bits precision))
    /// @param exponentSize at max how many bits of exponent there should be (8 = uint8 (8 bits exponent))
    /// @param roundUp signals if result should be rounded down or up
    /// @return bigNumber converted bigNumber (coefficient << exponent)
    function toBigNumber(
        uint256 normal,
        uint256 coefficientSize,
        uint256 exponentSize,
        bool roundUp
    ) internal pure returns (uint256 bigNumber) {
        assembly {
            let lastBit_
            let number_ := normal
            if gt(number_, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                number_ := shr(0x80, number_)
                lastBit_ := 0x80
            }
            if gt(number_, 0xFFFFFFFFFFFFFFFF) {
                number_ := shr(0x40, number_)
                lastBit_ := add(lastBit_, 0x40)
            }
            if gt(number_, 0xFFFFFFFF) {
                number_ := shr(0x20, number_)
                lastBit_ := add(lastBit_, 0x20)
            }
            if gt(number_, 0xFFFF) {
                number_ := shr(0x10, number_)
                lastBit_ := add(lastBit_, 0x10)
            }
            if gt(number_, 0xFF) {
                number_ := shr(0x8, number_)
                lastBit_ := add(lastBit_, 0x8)
            }
            if gt(number_, 0xF) {
                number_ := shr(0x4, number_)
                lastBit_ := add(lastBit_, 0x4)
            }
            if gt(number_, 0x3) {
                number_ := shr(0x2, number_)
                lastBit_ := add(lastBit_, 0x2)
            }
            if gt(number_, 0x1) {
                lastBit_ := add(lastBit_, 1)
            }
            if gt(number_, 0) {
                lastBit_ := add(lastBit_, 1)
            }
            if lt(lastBit_, coefficientSize) {
                // for throw exception
                lastBit_ := coefficientSize
            }
            let exponent := sub(lastBit_, coefficientSize)
            let coefficient := shr(exponent, normal)
            if and(roundUp, gt(exponent, 0)) {
                // rounding up is only needed if exponent is > 0, as otherwise the coefficient fully holds the original number
                coefficient := add(coefficient, 1)
                if eq(shl(coefficientSize, 1), coefficient) {
                    // case were coefficient was e.g. 111, with adding 1 it became 1000 (in binary) and coefficientSize 3 bits
                    // final coefficient would exceed it's size. -> reduce coefficent to 100 and increase exponent by 1.
                    coefficient := shl(sub(coefficientSize, 1), 1)
                    exponent := add(exponent, 1)
                }
            }
            if iszero(lt(exponent, shl(exponentSize, 1))) {
                // if exponent is >= exponentSize, the normal number is too big to fit within
                // BigNumber with too small sizes for coefficient and exponent
                revert(0, 0)
            }
            bigNumber := shl(exponentSize, coefficient)
            bigNumber := add(bigNumber, exponent)
        }
    }

    /// @dev get `normal` number from `bigNumber`, `exponentSize` and `exponentMask`
    function fromBigNumber(
        uint256 bigNumber,
        uint256 exponentSize,
        uint256 exponentMask
    ) internal pure returns (uint256 normal) {
        assembly {
            let coefficient := shr(exponentSize, bigNumber)
            let exponent := and(bigNumber, exponentMask)
            normal := shl(exponent, coefficient)
        }
    }

    /// @dev gets the most significant bit `lastBit` of a `normal` number (length of given number of binary format).
    /// e.g.
    /// 5035703444687813576399599 = 10000101010010110100000011111011110010100110100000000011100101001101001101011101111
    /// lastBit =                   ^---------------------------------   83   ----------------------------------------^
    function mostSignificantBit(uint256 normal) internal pure returns (uint lastBit) {
        assembly {
            let number_ := normal
            if gt(normal, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                number_ := shr(0x80, number_)
                lastBit := 0x80
            }
            if gt(number_, 0xFFFFFFFFFFFFFFFF) {
                number_ := shr(0x40, number_)
                lastBit := add(lastBit, 0x40)
            }
            if gt(number_, 0xFFFFFFFF) {
                number_ := shr(0x20, number_)
                lastBit := add(lastBit, 0x20)
            }
            if gt(number_, 0xFFFF) {
                number_ := shr(0x10, number_)
                lastBit := add(lastBit, 0x10)
            }
            if gt(number_, 0xFF) {
                number_ := shr(0x8, number_)
                lastBit := add(lastBit, 0x8)
            }
            if gt(number_, 0xF) {
                number_ := shr(0x4, number_)
                lastBit := add(lastBit, 0x4)
            }
            if gt(number_, 0x3) {
                number_ := shr(0x2, number_)
                lastBit := add(lastBit, 0x2)
            }
            if gt(number_, 0x1) {
                lastBit := add(lastBit, 1)
            }
            if gt(number_, 0) {
                lastBit := add(lastBit, 1)
            }
        }
    }
}

File 16 of 31 : errorTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

library LibsErrorTypes {
    /***********************************|
    |         LiquidityCalcs            | 
    |__________________________________*/

    /// @notice thrown when supply or borrow exchange price is zero at calc token data (token not configured yet)
    uint256 internal constant LiquidityCalcs__ExchangePriceZero = 70001;

    /// @notice thrown when rate data is set to a version that is not implemented
    uint256 internal constant LiquidityCalcs__UnsupportedRateVersion = 70002;

    /***********************************|
    |           SafeTransfer            | 
    |__________________________________*/

    /// @notice thrown when safe transfer from for an ERC20 fails
    uint256 internal constant SafeTransfer__TransferFromFailed = 71001;

    /// @notice thrown when safe transfer for an ERC20 fails
    uint256 internal constant SafeTransfer__TransferFailed = 71002;
}

File 17 of 31 : liquidityCalcs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { LibsErrorTypes as ErrorTypes } from "./errorTypes.sol";
import { LiquiditySlotsLink } from "./liquiditySlotsLink.sol";
import { BigMathMinified } from "./bigMathMinified.sol";

/// @notice implements calculation methods used for Fluid liquidity such as updated exchange prices,
/// borrow rate, withdrawal / borrow limits, revenue amount.
library LiquidityCalcs {
    error FluidLiquidityCalcsError(uint256 errorId_);

    /// @notice emitted if the calculated borrow rate surpassed max borrow rate (16 bits) and was capped at maximum value 65535
    event BorrowRateMaxCap();

    /// @dev constants as from Liquidity variables.sol
    uint256 internal constant EXCHANGE_PRICES_PRECISION = 1e12;

    /// @dev Ignoring leap years
    uint256 internal constant SECONDS_PER_YEAR = 365 days;
    // constants used for BigMath conversion from and to storage
    uint256 internal constant DEFAULT_EXPONENT_SIZE = 8;
    uint256 internal constant DEFAULT_EXPONENT_MASK = 0xFF;

    uint256 internal constant FOUR_DECIMALS = 1e4;
    uint256 internal constant TWELVE_DECIMALS = 1e12;
    uint256 internal constant X14 = 0x3fff;
    uint256 internal constant X15 = 0x7fff;
    uint256 internal constant X16 = 0xffff;
    uint256 internal constant X18 = 0x3ffff;
    uint256 internal constant X24 = 0xffffff;
    uint256 internal constant X33 = 0x1ffffffff;
    uint256 internal constant X64 = 0xffffffffffffffff;

    ///////////////////////////////////////////////////////////////////////////
    //////////                  CALC EXCHANGE PRICES                  /////////
    ///////////////////////////////////////////////////////////////////////////

    /// @dev calculates interest (exchange prices) for a token given its' exchangePricesAndConfig from storage.
    /// @param exchangePricesAndConfig_ exchange prices and config packed uint256 read from storage
    /// @return supplyExchangePrice_ updated supplyExchangePrice
    /// @return borrowExchangePrice_ updated borrowExchangePrice
    function calcExchangePrices(
        uint256 exchangePricesAndConfig_
    ) internal view returns (uint256 supplyExchangePrice_, uint256 borrowExchangePrice_) {
        // Extracting exchange prices
        supplyExchangePrice_ =
            (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_SUPPLY_EXCHANGE_PRICE) &
            X64;
        borrowExchangePrice_ =
            (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_BORROW_EXCHANGE_PRICE) &
            X64;

        if (supplyExchangePrice_ == 0 || borrowExchangePrice_ == 0) {
            revert FluidLiquidityCalcsError(ErrorTypes.LiquidityCalcs__ExchangePriceZero);
        }

        uint256 temp_ = exchangePricesAndConfig_ & X16; // temp_ = borrowRate

        unchecked {
            // last timestamp can not be > current timestamp
            uint256 secondsSinceLastUpdate_ = block.timestamp -
                ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_LAST_TIMESTAMP) & X33);

            uint256 borrowRatio_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_BORROW_RATIO) &
                X15;
            if (secondsSinceLastUpdate_ == 0 || temp_ == 0 || borrowRatio_ == 1) {
                // if no time passed, borrow rate is 0, or no raw borrowings: no exchange price update needed
                // (if borrowRatio_ == 1 means there is only borrowInterestFree, as first bit is 1 and rest is 0)
                return (supplyExchangePrice_, borrowExchangePrice_);
            }

            // calculate new borrow exchange price.
            // formula borrowExchangePriceIncrease: previous price * borrow rate * secondsSinceLastUpdate_.
            // nominator is max uint112 (uint64 * uint16 * uint32). Divisor can not be 0.
            borrowExchangePrice_ +=
                (borrowExchangePrice_ * temp_ * secondsSinceLastUpdate_) /
                (SECONDS_PER_YEAR * FOUR_DECIMALS);

            // FOR SUPPLY EXCHANGE PRICE:
            // all yield paid by borrowers (in mode with interest) goes to suppliers in mode with interest.
            // formula: previous price * supply rate * secondsSinceLastUpdate_.
            // where supply rate = (borrow rate  - revenueFee%) * ratioSupplyYield. And
            // ratioSupplyYield = utilization * supplyRatio * borrowRatio
            //
            // Example:
            // supplyRawInterest is 80, supplyInterestFree is 20. totalSupply is 100. BorrowedRawInterest is 50.
            // BorrowInterestFree is 10. TotalBorrow is 60. borrow rate 40%, revenueFee 10%.
            // yield is 10 (so half a year must have passed).
            // supplyRawInterest must become worth 89. totalSupply must become 109. BorrowedRawInterest must become 60.
            // borrowInterestFree must still be 10. supplyInterestFree still 20. totalBorrow 70.
            // supplyExchangePrice would have to go from 1 to 1,125 (+ 0.125). borrowExchangePrice from 1 to 1,2 (+0.2).
            // utilization is 60%. supplyRatio = 20 / 80 = 25% (only 80% of lenders receiving yield).
            // borrowRatio = 10 / 50 = 20% (only 83,333% of borrowers paying yield):
            // x of borrowers paying yield = 100% - (20 / (100 + 20)) = 100% - 16.6666666% = 83,333%.
            // ratioSupplyYield = 60% * 83,33333% * (100% + 20%) = 62,5%
            // supplyRate = (40% * (100% - 10%)) * = 36% * 62,5% = 22.5%
            // increase in supplyExchangePrice, assuming 100 as previous price.
            // 100 * 22,5% * 1/2 (half a year) = 0,1125.
            // cross-check supplyRawInterest worth = 80 * 1.1125 = 89. totalSupply worth = 89 + 20.

            // -------------- 1. calculate ratioSupplyYield --------------------------------
            // step1: utilization * supplyRatio (or actually part of lenders receiving yield)

            // temp_ => supplyRatio (in 1e2: 100% = 10_000; 1% = 100 -> max value 16_383)
            // if first bit 0 then ratio is supplyInterestFree / supplyWithInterest (supplyWithInterest is bigger)
            // else ratio is supplyWithInterest / supplyInterestFree (supplyInterestFree is bigger)
            temp_ = (exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_SUPPLY_RATIO) & X15;

            if (temp_ == 1) {
                // if no raw supply: no exchange price update needed
                // (if supplyRatio_ == 1 means there is only supplyInterestFree, as first bit is 1 and rest is 0)
                return (supplyExchangePrice_, borrowExchangePrice_);
            }

            // ratioSupplyYield precision is 1e27 as 100% for increased precision when supplyInterestFree > supplyWithInterest
            if (temp_ & 1 == 1) {
                // ratio is supplyWithInterest / supplyInterestFree (supplyInterestFree is bigger)
                temp_ = temp_ >> 1;

                // Note: case where temp_ == 0 (only supplyInterestFree, no yield) already covered by early return
                // in the if statement a little above.

                // based on above example but supplyRawInterest is 20, supplyInterestFree is 80. no fee.
                // supplyRawInterest must become worth 30. totalSupply must become 110.
                // supplyExchangePrice would have to go from 1 to 1,5. borrowExchangePrice from 1 to 1,2.
                // so ratioSupplyYield must come out as 2.5 (250%).
                // supplyRatio would be (20 * 10_000 / 80) = 2500. but must be inverted.
                temp_ = (1e27 * FOUR_DECIMALS) / temp_; // e.g. 1e31 / 2500 = 4e27. (* 1e27 for precision)
                // e.g. 5_000 * (1e27 + 4e27) / 1e27 = 25_000 (=250%).
                temp_ =
                    // utilization * (100% + 100% / supplyRatio)
                    (((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_UTILIZATION) & X14) *
                        (1e27 + temp_)) / // extract utilization (max 16_383 so there is no way this can overflow).
                    (FOUR_DECIMALS);
                // max possible value of temp_ here is 16383 * (1e27 + 1e31) / 1e4 = ~1.64e31
            } else {
                // ratio is supplyInterestFree / supplyWithInterest (supplyWithInterest is bigger)
                temp_ = temp_ >> 1;
                // if temp_ == 0 then only supplyWithInterest => full yield. temp_ is already 0

                // e.g. 5_000 * 10_000 + (20 * 10_000 / 80) / 10_000 = 5000 * 12500 / 10000 = 6250 (=62.5%).
                temp_ =
                    // 1e27 * utilization * (100% + supplyRatio) / 100%
                    (1e27 *
                        ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_UTILIZATION) & X14) * // extract utilization (max 16_383 so there is no way this can overflow).
                        (FOUR_DECIMALS + temp_)) /
                    (FOUR_DECIMALS * FOUR_DECIMALS);
                // max possible temp_ value: 1e27 * 16383 * 2e4 / 1e8 = 3.2766e27
            }
            // from here temp_ => ratioSupplyYield (utilization * supplyRatio part) scaled by 1e27. max possible value ~1.64e31

            // step2 of ratioSupplyYield: add borrowRatio (only x% of borrowers paying yield)
            if (borrowRatio_ & 1 == 1) {
                // ratio is borrowWithInterest / borrowInterestFree (borrowInterestFree is bigger)
                borrowRatio_ = borrowRatio_ >> 1;
                // borrowRatio_ => x of total bororwers paying yield. scale to 1e27.

                // Note: case where borrowRatio_ == 0 (only borrowInterestFree, no yield) already covered
                // at the beginning of the method by early return if `borrowRatio_ == 1`.

                // based on above example but borrowRawInterest is 10, borrowInterestFree is 50. no fee. borrowRatio = 20%.
                // so only 16.66% of borrowers are paying yield. so the 100% - part of the formula is not needed.
                // x of borrowers paying yield = (borrowRatio / (100 + borrowRatio)) = 16.6666666%
                // borrowRatio_ => x of total bororwers paying yield. scale to 1e27.
                borrowRatio_ = (borrowRatio_ * 1e27) / (FOUR_DECIMALS + borrowRatio_);
                // max value here for borrowRatio_ is (1e31 / (1e4 + 1e4))= 5e26 (= 50% of borrowers paying yield).
            } else {
                // ratio is borrowInterestFree / borrowWithInterest (borrowWithInterest is bigger)
                borrowRatio_ = borrowRatio_ >> 1;

                // borrowRatio_ => x of total bororwers paying yield. scale to 1e27.
                // x of borrowers paying yield = 100% - (borrowRatio / (100 + borrowRatio)) = 100% - 16.6666666% = 83,333%.
                borrowRatio_ = (1e27 - ((borrowRatio_ * 1e27) / (FOUR_DECIMALS + borrowRatio_)));
                // borrowRatio can never be > 100%. so max subtraction can be 100% - 100% / 200%.
                // or if borrowRatio_ is 0 -> 100% - 0. or if borrowRatio_ is 1 -> 100% - 1 / 101.
                // max value here for borrowRatio_ is 1e27 - 0 = 1e27 (= 100% of borrowers paying yield).
            }

            // temp_ => ratioSupplyYield. scaled down from 1e25 = 1% each to normal percent precision 1e2 = 1%.
            // max nominator value is ~1.64e31 * 1e27 = 1.64e58. max result = 1.64e8
            temp_ = (FOUR_DECIMALS * temp_ * borrowRatio_) / 1e54;

            // 2. calculate supply rate
            // temp_ => supply rate (borrow rate  - revenueFee%) * ratioSupplyYield.
            // division part is done in next step to increase precision. (divided by 2x FOUR_DECIMALS, fee + borrowRate)
            // Note that all calculation divisions for supplyExchangePrice are rounded down.
            // Note supply rate can be bigger than the borrowRate, e.g. if there are only few lenders with interest
            // but more suppliers not earning interest.
            temp_ = ((exchangePricesAndConfig_ & X16) * // borrow rate
                temp_ * // ratioSupplyYield
                (FOUR_DECIMALS - ((exchangePricesAndConfig_ >> LiquiditySlotsLink.BITS_EXCHANGE_PRICES_FEE) & X14))); // revenueFee
            // fee can not be > 100%. max possible = 65535 * ~1.64e8 * 1e4 =~1.074774e17.

            // 3. calculate increase in supply exchange price
            supplyExchangePrice_ += ((supplyExchangePrice_ * temp_ * secondsSinceLastUpdate_) /
                (SECONDS_PER_YEAR * FOUR_DECIMALS * FOUR_DECIMALS * FOUR_DECIMALS));
            // max possible nominator = max uint 64 * 1.074774e17 * max uint32 = ~8.52e45. Denominator can not be 0.
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    //////////                     CALC REVENUE                       /////////
    ///////////////////////////////////////////////////////////////////////////

    /// @dev gets the `revenueAmount_` for a token given its' totalAmounts and exchangePricesAndConfig from storage
    /// and the current balance of the Fluid liquidity contract for the token.
    /// @param totalAmounts_ total amounts packed uint256 read from storage
    /// @param exchangePricesAndConfig_ exchange prices and config packed uint256 read from storage
    /// @param liquidityTokenBalance_   current balance of Liquidity contract (IERC20(token_).balanceOf(address(this)))
    /// @return revenueAmount_ collectable revenue amount
    function calcRevenue(
        uint256 totalAmounts_,
        uint256 exchangePricesAndConfig_,
        uint256 liquidityTokenBalance_
    ) internal view returns (uint256 revenueAmount_) {
        // @dev no need to super-optimize this method as it is only used by admin

        // calculate the new exchange prices based on earned interest
        (uint256 supplyExchangePrice_, uint256 borrowExchangePrice_) = calcExchangePrices(exchangePricesAndConfig_);

        // total supply = interest free + with interest converted from raw
        uint256 totalSupply_ = getTotalSupply(totalAmounts_, supplyExchangePrice_);

        if (totalSupply_ > 0) {
            // available revenue: balanceOf(token) + totalBorrowings - totalLendings.
            revenueAmount_ = liquidityTokenBalance_ + getTotalBorrow(totalAmounts_, borrowExchangePrice_);
            // ensure there is no possible case because of rounding etc. where this would revert,
            // explicitly check if >
            revenueAmount_ = revenueAmount_ > totalSupply_ ? revenueAmount_ - totalSupply_ : 0;
            // Note: if utilization > 100% (totalSupply < totalBorrow), then all the amount above 100% utilization
            // can only be revenue.
        } else {
            // if supply is 0, then rest of balance can be withdrawn as revenue so that no amounts get stuck
            revenueAmount_ = liquidityTokenBalance_;
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    //////////                      CALC LIMITS                       /////////
    ///////////////////////////////////////////////////////////////////////////

    /// @dev calculates withdrawal limit before an operate execution:
    /// amount of user supply that must stay supplied (not amount that can be withdrawn).
    /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
    /// @param userSupplyData_ user supply data packed uint256 from storage
    /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and converted from BigMath
    /// @return currentWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction.
    ///         returned value is in raw for with interest mode, normal amount for interest free mode!
    function calcWithdrawalLimitBeforeOperate(
        uint256 userSupplyData_,
        uint256 userSupply_
    ) internal view returns (uint256 currentWithdrawalLimit_) {
        // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet).
        // first tx where timestamp is 0 will enter `if (lastWithdrawalLimit_ == 0)` because lastWithdrawalLimit_ is not set yet.
        // returning max withdrawal allowed, which is not exactly right but doesn't matter because the first interaction must be
        // a deposit anyway. Important is that it would not revert.

        // Note the first time a deposit brings the user supply amount to above the base withdrawal limit, the active limit
        // is the fully expanded limit immediately.

        // extract last set withdrawal limit
        uint256 lastWithdrawalLimit_ = (userSupplyData_ >>
            LiquiditySlotsLink.BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT) & X64;
        lastWithdrawalLimit_ =
            (lastWithdrawalLimit_ >> DEFAULT_EXPONENT_SIZE) <<
            (lastWithdrawalLimit_ & DEFAULT_EXPONENT_MASK);
        if (lastWithdrawalLimit_ == 0) {
            // withdrawal limit is not activated. Max withdrawal allowed
            return 0;
        }

        uint256 maxWithdrawableLimit_;
        uint256 temp_;
        unchecked {
            // extract max withdrawable percent of user supply and
            // calculate maximum withdrawable amount expandPercentage of user supply at full expansion duration elapsed
            // e.g.: if 10% expandPercentage, meaning 10% is withdrawable after full expandDuration has elapsed.

            // userSupply_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            maxWithdrawableLimit_ =
                (((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14) * userSupply_) /
                FOUR_DECIMALS;

            // time elapsed since last withdrawal limit was set (in seconds)
            // @dev last process timestamp is guaranteed to exist for withdrawal, as a supply must have happened before.
            // last timestamp can not be > current timestamp
            temp_ =
                block.timestamp -
                ((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP) & X33);
        }
        // calculate withdrawable amount of expandPercent that is elapsed of expandDuration.
        // e.g. if 60% of expandDuration has elapsed, then user should be able to withdraw 6% of user supply, down to 94%.
        // Note: no explicit check for this needed, it is covered by setting minWithdrawalLimit_ if needed.
        temp_ =
            (maxWithdrawableLimit_ * temp_) /
            // extract expand duration: After this, decrement won't happen (user can withdraw 100% of withdraw limit)
            ((userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_DURATION) & X24); // expand duration can never be 0
        // calculate expanded withdrawal limit: last withdrawal limit - withdrawable amount.
        // Note: withdrawable amount here can grow bigger than userSupply if timeElapsed is a lot bigger than expandDuration,
        // which would cause the subtraction `lastWithdrawalLimit_ - withdrawableAmount_` to revert. In that case, set 0
        // which will cause minimum (fully expanded) withdrawal limit to be set in lines below.
        unchecked {
            // underflow explicitly checked & handled
            currentWithdrawalLimit_ = lastWithdrawalLimit_ > temp_ ? lastWithdrawalLimit_ - temp_ : 0;
            // calculate minimum withdrawal limit: minimum amount of user supply that must stay supplied at full expansion.
            // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
            temp_ = userSupply_ - maxWithdrawableLimit_;
        }
        // if withdrawal limit is decreased below minimum then set minimum
        // (e.g. when more than expandDuration time has elapsed)
        if (temp_ > currentWithdrawalLimit_) {
            currentWithdrawalLimit_ = temp_;
        }
    }

    /// @dev calculates withdrawal limit after an operate execution:
    /// amount of user supply that must stay supplied (not amount that can be withdrawn).
    /// i.e. if user has supplied 100m and can withdraw 5M, this method returns the 95M, not the withdrawable amount 5M
    /// @param userSupplyData_ user supply data packed uint256 from storage
    /// @param userSupply_ current user supply amount already extracted from `userSupplyData_` and added / subtracted with the executed operate amount
    /// @param newWithdrawalLimit_ current withdrawal limit updated for expansion since last interaction, result from `calcWithdrawalLimitBeforeOperate`
    /// @return withdrawalLimit_ updated withdrawal limit that should be written to storage. returned value is in
    ///                          raw for with interest mode, normal amount for interest free mode!
    function calcWithdrawalLimitAfterOperate(
        uint256 userSupplyData_,
        uint256 userSupply_,
        uint256 newWithdrawalLimit_
    ) internal pure returns (uint256) {
        // temp_ => base withdrawal limit. below this, maximum withdrawals are allowed
        uint256 temp_ = (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        // if user supply is below base limit then max withdrawals are allowed
        if (userSupply_ < temp_) {
            return 0;
        }
        // temp_ => withdrawal limit expandPercent (is in 1e2 decimals)
        temp_ = (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_EXPAND_PERCENT) & X14;
        unchecked {
            // temp_ => minimum withdrawal limit: userSupply - max withdrawable limit (userSupply * expandPercent))
            // userSupply_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            // subtraction can not underflow as maxWithdrawableLimit_ is a percentage amount (<=100%) of userSupply_
            temp_ = userSupply_ - ((userSupply_ * temp_) / FOUR_DECIMALS);
        }
        // if new (before operation) withdrawal limit is less than minimum limit then set minimum limit.
        // e.g. can happen on new deposits. withdrawal limit is instantly fully expanded in a scenario where
        // increased deposit amount outpaces withrawals.
        if (temp_ > newWithdrawalLimit_) {
            return temp_;
        }
        return newWithdrawalLimit_;
    }

    /// @dev calculates borrow limit before an operate execution:
    /// total amount user borrow can reach (not borrowable amount in current operation).
    /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
    /// @param userBorrowData_ user borrow data packed uint256 from storage
    /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_`
    /// @return currentBorrowLimit_ current borrow limit updated for expansion since last interaction. returned value is in
    ///                             raw for with interest mode, normal amount for interest free mode!
    function calcBorrowLimitBeforeOperate(
        uint256 userBorrowData_,
        uint256 userBorrow_
    ) internal view returns (uint256 currentBorrowLimit_) {
        // @dev must support handling the case where timestamp is 0 (config is set but no interactions yet) -> base limit.
        // first tx where timestamp is 0 will enter `if (maxExpandedBorrowLimit_ < baseBorrowLimit_)` because `userBorrow_` and thus
        // `maxExpansionLimit_` and thus `maxExpandedBorrowLimit_` is 0 and `baseBorrowLimit_` can not be 0.

        // temp_ = extract borrow expand percent (is in 1e2 decimals)
        uint256 temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14;

        uint256 maxExpansionLimit_;
        uint256 maxExpandedBorrowLimit_;
        unchecked {
            // calculate max expansion limit: Max amount limit can expand to since last interaction
            // userBorrow_ needs to be atleast 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            maxExpansionLimit_ = ((userBorrow_ * temp_) / FOUR_DECIMALS);

            // calculate max borrow limit: Max point limit can increase to since last interaction
            maxExpandedBorrowLimit_ = userBorrow_ + maxExpansionLimit_;
        }

        // currentBorrowLimit_ = extract base borrow limit
        currentBorrowLimit_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
        currentBorrowLimit_ =
            (currentBorrowLimit_ >> DEFAULT_EXPONENT_SIZE) <<
            (currentBorrowLimit_ & DEFAULT_EXPONENT_MASK);

        if (maxExpandedBorrowLimit_ < currentBorrowLimit_) {
            return currentBorrowLimit_;
        }
        // time elapsed since last borrow limit was set (in seconds)
        unchecked {
            // temp_ = timeElapsed_ (last timestamp can not be > current timestamp)
            temp_ =
                block.timestamp -
                ((userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP) & X33); // extract last udpate timestamp
        }

        // currentBorrowLimit_ = expandedBorrowableAmount + extract last set borrow limit
        currentBorrowLimit_ =
            // calculate borrow limit expansion since last interaction for `expandPercent` that is elapsed of `expandDuration`.
            // divisor is extract expand duration (after this, full expansion to expandPercentage happened).
            ((maxExpansionLimit_ * temp_) /
                ((userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_DURATION) & X24)) + // expand duration can never be 0
            //  extract last set borrow limit
            BigMathMinified.fromBigNumber(
                (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT) & X64,
                DEFAULT_EXPONENT_SIZE,
                DEFAULT_EXPONENT_MASK
            );

        // if timeElapsed is bigger than expandDuration, new borrow limit would be > max expansion,
        // so set to `maxExpandedBorrowLimit_` in that case.
        // also covers the case where last process timestamp = 0 (timeElapsed would simply be very big)
        if (currentBorrowLimit_ > maxExpandedBorrowLimit_) {
            currentBorrowLimit_ = maxExpandedBorrowLimit_;
        }
        // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
        temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        if (currentBorrowLimit_ > temp_) {
            currentBorrowLimit_ = temp_;
        }
    }

    /// @dev calculates borrow limit after an operate execution:
    /// total amount user borrow can reach (not borrowable amount in current operation).
    /// i.e. if user has borrowed 50M and can still borrow 5M, this method returns the total 55M, not the borrowable amount 5M
    /// @param userBorrowData_ user borrow data packed uint256 from storage
    /// @param userBorrow_ current user borrow amount already extracted from `userBorrowData_` and added / subtracted with the executed operate amount
    /// @param newBorrowLimit_ current borrow limit updated for expansion since last interaction, result from `calcBorrowLimitBeforeOperate`
    /// @return borrowLimit_ updated borrow limit that should be written to storage.
    ///                      returned value is in raw for with interest mode, normal amount for interest free mode!
    function calcBorrowLimitAfterOperate(
        uint256 userBorrowData_,
        uint256 userBorrow_,
        uint256 newBorrowLimit_
    ) internal pure returns (uint256 borrowLimit_) {
        // temp_ = extract borrow expand percent
        uint256 temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_EXPAND_PERCENT) & X14; // (is in 1e2 decimals)

        unchecked {
            // borrowLimit_ = calculate maximum borrow limit at full expansion.
            // userBorrow_ needs to be at least 1e73 to overflow max limit of ~1e77 in uint256 (no token in existence where this is possible).
            borrowLimit_ = userBorrow_ + ((userBorrow_ * temp_) / FOUR_DECIMALS);
        }

        // temp_ = extract base borrow limit
        temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_BASE_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        if (borrowLimit_ < temp_) {
            // below base limit, borrow limit is always base limit
            return temp_;
        }
        // temp_ = extract hard max borrow limit. Above this user can never borrow (not expandable above)
        temp_ = (userBorrowData_ >> LiquiditySlotsLink.BITS_USER_BORROW_MAX_BORROW_LIMIT) & X18;
        temp_ = (temp_ >> DEFAULT_EXPONENT_SIZE) << (temp_ & DEFAULT_EXPONENT_MASK);

        // make sure fully expanded borrow limit is not above hard max borrow limit
        if (borrowLimit_ > temp_) {
            borrowLimit_ = temp_;
        }
        // if new borrow limit (from before operate) is > max borrow limit, set max borrow limit.
        // (e.g. on a repay shrinking instantly to fully expanded borrow limit from new borrow amount. shrinking is instant)
        if (newBorrowLimit_ > borrowLimit_) {
            return borrowLimit_;
        }
        return newBorrowLimit_;
    }

    ///////////////////////////////////////////////////////////////////////////
    //////////                      CALC RATES                        /////////
    ///////////////////////////////////////////////////////////////////////////

    /// @dev Calculates new borrow rate from utilization for a token
    /// @param rateData_ rate data packed uint256 from storage for the token
    /// @param utilization_ totalBorrow / totalSupply. 1e4 = 100% utilization
    /// @return rate_ rate for that particular token in 1e2 precision (e.g. 5% rate = 500)
    function calcBorrowRateFromUtilization(uint256 rateData_, uint256 utilization_) internal returns (uint256 rate_) {
        // extract rate version: 4 bits (0xF) starting from bit 0
        uint256 rateVersion_ = (rateData_ & 0xF);

        if (rateVersion_ == 1) {
            rate_ = calcRateV1(rateData_, utilization_);
        } else if (rateVersion_ == 2) {
            rate_ = calcRateV2(rateData_, utilization_);
        } else {
            revert FluidLiquidityCalcsError(ErrorTypes.LiquidityCalcs__UnsupportedRateVersion);
        }

        if (rate_ > X16) {
            // hard cap for borrow rate at maximum value 16 bits (65535) to make sure it does not overflow storage space.
            // this is unlikely to ever happen if configs stay within expected levels.
            rate_ = X16;
            // emit event to more easily become aware
            emit BorrowRateMaxCap();
        }
    }

    /// @dev calculates the borrow rate based on utilization for rate data version 1 (with one kink) in 1e2 precision
    /// @param rateData_ rate data packed uint256 from storage for the token
    /// @param utilization_  in 1e2 (100% = 1e4)
    /// @return rate_ rate in 1e2 precision
    function calcRateV1(uint256 rateData_, uint256 utilization_) internal pure returns (uint256 rate_) {
        /// For rate v1 (one kink) ------------------------------------------------------
        /// Next 16  bits =>  4 - 19 => Rate at utilization 0% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  20- 35 => Utilization at kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  36- 51 => Rate at utilization kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  52- 67 => Rate at utilization 100% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Last 188 bits =>  68-255 => blank, might come in use in future

        // y = mx + c.
        // y is borrow rate
        // x is utilization
        // m = slope (m can be 0 but never negative)
        // c is constant (c can be negative)

        uint256 y1_;
        uint256 y2_;
        uint256 x1_;
        uint256 x2_;

        // extract kink1: 16 bits (0xFFFF) starting from bit 20
        // kink is in 1e2, same as utilization, so no conversion needed for direct comparison of the two
        uint256 kink1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_UTILIZATION_AT_KINK) & X16;
        if (utilization_ < kink1_) {
            // if utilization is less than kink
            y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_ZERO) & X16;
            y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK) & X16;
            x1_ = 0; // 0%
            x2_ = kink1_;
        } else {
            // else utilization is greater than kink
            y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK) & X16;
            y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_MAX) & X16;
            x1_ = kink1_;
            x2_ = FOUR_DECIMALS; // 100%
        }

        int256 constant_;
        uint256 slope_;
        unchecked {
            // calculating slope with twelve decimal precision. m = (y2 - y1) / (x2 - x1).
            // utilization of x2 can not be <= utilization of x1 (so no underflow or 0 divisor) and rate at y2 can not be < rate at y1
            // y is in 1e2 so can not overflow when multiplied with TWELVE_DECIMALS
            slope_ = ((y2_ - y1_) * TWELVE_DECIMALS) / (x2_ - x1_);

            // calculating constant at 12 decimal precision. slope is already in 12 decimal hence only multiple with y1. c = y - mx.
            // maximum y1_ value is 65535. 65535 * 1e12 can not overflow int256
            // maximum slope is 65535 - 0 * TWELVE_DECIMALS / 1 = 65535 * 1e12;
            // maximum x1_ is 100% (9_999 actually) => slope_ * x1_ can not overflow int256
            // subtraction most extreme case would be  0 - max value slope_ * x1_ => can not underflow int256
            constant_ = int256(y1_ * TWELVE_DECIMALS) - int256(slope_ * x1_);

            // calculating new borrow rate
            // - slope_ max value is 65535 * 1e12,
            // - utilization max value is let's say 500% (extreme case where borrow rate increases borrow amount without new supply)
            // - constant max value is 65535 * 1e12
            // so max values are 65535 * 1e12 * 50_000 + 65535 * 1e12 -> 3.2768*10^21, which easily fits int256
            // divisor TWELVE_DECIMALS can not be 0
            rate_ = (uint256(int256(slope_ * utilization_) + constant_)) / TWELVE_DECIMALS;
        }
    }

    /// @dev calculates the borrow rate based on utilization for rate data version 2 (with two kinks) in 1e4 precision
    /// @param rateData_ rate data packed uint256 from storage for the token
    /// @param utilization_  in 1e2 (100% = 1e4)
    /// @return rate_ rate in 1e4 precision
    function calcRateV2(uint256 rateData_, uint256 utilization_) internal pure returns (uint256 rate_) {
        /// For rate v2 (two kinks) -----------------------------------------------------
        /// Next 16  bits =>  4 - 19 => Rate at utilization 0% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  20- 35 => Utilization at kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  36- 51 => Rate at utilization kink1 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  52- 67 => Utilization at kink2 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  68- 83 => Rate at utilization kink2 (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Next 16  bits =>  84- 99 => Rate at utilization 100% (in 1e2: 100% = 10_000; 1% = 100 -> max value 65535)
        /// Last 156 bits => 100-255 => blank, might come in use in future

        // y = mx + c.
        // y is borrow rate
        // x is utilization
        // m = slope (m can be 0 but never negative)
        // c is constant (c can be negative)

        uint256 y1_;
        uint256 y2_;
        uint256 x1_;
        uint256 x2_;

        // extract kink1: 16 bits (0xFFFF) starting from bit 20
        // kink is in 1e2, same as utilization, so no conversion needed for direct comparison of the two
        uint256 kink1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_UTILIZATION_AT_KINK1) & X16;
        if (utilization_ < kink1_) {
            // if utilization is less than kink1
            y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_ZERO) & X16;
            y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1) & X16;
            x1_ = 0; // 0%
            x2_ = kink1_;
        } else {
            // extract kink2: 16 bits (0xFFFF) starting from bit 52
            uint256 kink2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_UTILIZATION_AT_KINK2) & X16;
            if (utilization_ < kink2_) {
                // if utilization is less than kink2
                y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1) & X16;
                y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2) & X16;
                x1_ = kink1_;
                x2_ = kink2_;
            } else {
                // else utilization is greater than kink2
                y1_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2) & X16;
                y2_ = (rateData_ >> LiquiditySlotsLink.BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_MAX) & X16;
                x1_ = kink2_;
                x2_ = FOUR_DECIMALS;
            }
        }

        int256 constant_;
        uint256 slope_;
        unchecked {
            // calculating slope with twelve decimal precision. m = (y2 - y1) / (x2 - x1).
            // utilization of x2 can not be <= utilization of x1 (so no underflow or 0 divisor) and rate at y2 can not be < rate at y1
            // y is in 1e2 so can not overflow when multiplied with TWELVE_DECIMALS
            slope_ = ((y2_ - y1_) * TWELVE_DECIMALS) / (x2_ - x1_);

            // calculating constant at 12 decimal precision. slope is already in 12 decimal hence only multiple with y1. c = y - mx.
            // maximum y1_ value is 65535. 65535 * 1e12 can not overflow int256
            // maximum slope is 65535 - 0 * TWELVE_DECIMALS / 1 = 65535 * 1e12;
            // maximum x1_ is 100% (9_999 actually) => slope_ * x1_ can not overflow int256
            // subtraction most extreme case would be  0 - max value slope_ * x1_ => can not underflow int256
            constant_ = int256(y1_ * TWELVE_DECIMALS) - int256(slope_ * x1_);

            // calculating new borrow rate
            // - slope_ max value is 65535 * 1e12,
            // - utilization max value is let's say 500% (extreme case where borrow rate increases borrow amount without new supply)
            // - constant max value is 65535 * 1e12
            // so max values are 65535 * 1e12 * 50_000 + 65535 * 1e12 -> 3.2768*10^21, which easily fits int256
            // divisor TWELVE_DECIMALS can not be 0
            rate_ = (uint256(int256(slope_ * utilization_) + constant_)) / TWELVE_DECIMALS;
        }
    }

    /// @dev reads the total supply out of Liquidity packed storage `totalAmounts_` for `supplyExchangePrice_`
    function getTotalSupply(
        uint256 totalAmounts_,
        uint256 supplyExchangePrice_
    ) internal pure returns (uint256 totalSupply_) {
        // totalSupply_ => supplyInterestFree
        totalSupply_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_SUPPLY_INTEREST_FREE) & X64;
        totalSupply_ = (totalSupply_ >> DEFAULT_EXPONENT_SIZE) << (totalSupply_ & DEFAULT_EXPONENT_MASK);

        uint256 totalSupplyRaw_ = totalAmounts_ & X64; // no shifting as supplyRaw is first 64 bits
        totalSupplyRaw_ = (totalSupplyRaw_ >> DEFAULT_EXPONENT_SIZE) << (totalSupplyRaw_ & DEFAULT_EXPONENT_MASK);

        // totalSupply = supplyInterestFree + supplyRawInterest normalized from raw
        totalSupply_ += ((totalSupplyRaw_ * supplyExchangePrice_) / EXCHANGE_PRICES_PRECISION);
    }

    /// @dev reads the total borrow out of Liquidity packed storage `totalAmounts_` for `borrowExchangePrice_`
    function getTotalBorrow(
        uint256 totalAmounts_,
        uint256 borrowExchangePrice_
    ) internal pure returns (uint256 totalBorrow_) {
        // totalBorrow_ => borrowInterestFree
        // no & mask needed for borrow interest free as it occupies the last bits in the storage slot
        totalBorrow_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_BORROW_INTEREST_FREE);
        totalBorrow_ = (totalBorrow_ >> DEFAULT_EXPONENT_SIZE) << (totalBorrow_ & DEFAULT_EXPONENT_MASK);

        uint256 totalBorrowRaw_ = (totalAmounts_ >> LiquiditySlotsLink.BITS_TOTAL_AMOUNTS_BORROW_WITH_INTEREST) & X64;
        totalBorrowRaw_ = (totalBorrowRaw_ >> DEFAULT_EXPONENT_SIZE) << (totalBorrowRaw_ & DEFAULT_EXPONENT_MASK);

        // totalBorrow = borrowInterestFree + borrowRawInterest normalized from raw
        totalBorrow_ += ((totalBorrowRaw_ * borrowExchangePrice_) / EXCHANGE_PRICES_PRECISION);
    }
}

File 18 of 31 : liquiditySlotsLink.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

/// @notice library that helps in reading / working with storage slot data of Fluid Liquidity.
/// @dev as all data for Fluid Liquidity is internal, any data must be fetched directly through manual
/// slot reading through this library or, if gas usage is less important, through the FluidLiquidityResolver.
library LiquiditySlotsLink {
    /// @dev storage slot for status at Liquidity
    uint256 internal constant LIQUIDITY_STATUS_SLOT = 1;
    /// @dev storage slot for auths mapping at Liquidity
    uint256 internal constant LIQUIDITY_AUTHS_MAPPING_SLOT = 2;
    /// @dev storage slot for guardians mapping at Liquidity
    uint256 internal constant LIQUIDITY_GUARDIANS_MAPPING_SLOT = 3;
    /// @dev storage slot for user class mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_CLASS_MAPPING_SLOT = 4;
    /// @dev storage slot for exchangePricesAndConfig mapping at Liquidity
    uint256 internal constant LIQUIDITY_EXCHANGE_PRICES_MAPPING_SLOT = 5;
    /// @dev storage slot for rateData mapping at Liquidity
    uint256 internal constant LIQUIDITY_RATE_DATA_MAPPING_SLOT = 6;
    /// @dev storage slot for totalAmounts mapping at Liquidity
    uint256 internal constant LIQUIDITY_TOTAL_AMOUNTS_MAPPING_SLOT = 7;
    /// @dev storage slot for user supply double mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_SUPPLY_DOUBLE_MAPPING_SLOT = 8;
    /// @dev storage slot for user borrow double mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_BORROW_DOUBLE_MAPPING_SLOT = 9;
    /// @dev storage slot for listed tokens array at Liquidity
    uint256 internal constant LIQUIDITY_LISTED_TOKENS_ARRAY_SLOT = 10;

    // --------------------------------
    // @dev stacked uint256 storage slots bits position data for each:

    // ExchangePricesAndConfig
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATE = 0;
    uint256 internal constant BITS_EXCHANGE_PRICES_FEE = 16;
    uint256 internal constant BITS_EXCHANGE_PRICES_UTILIZATION = 30;
    uint256 internal constant BITS_EXCHANGE_PRICES_UPDATE_THRESHOLD = 44;
    uint256 internal constant BITS_EXCHANGE_PRICES_LAST_TIMESTAMP = 58;
    uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_EXCHANGE_PRICE = 91;
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_EXCHANGE_PRICE = 155;
    uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_RATIO = 219;
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATIO = 234;

    // RateData:
    uint256 internal constant BITS_RATE_DATA_VERSION = 0;
    // RateData: V1
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_ZERO = 4;
    uint256 internal constant BITS_RATE_DATA_V1_UTILIZATION_AT_KINK = 20;
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK = 36;
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_MAX = 52;
    // RateData: V2
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_ZERO = 4;
    uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK1 = 20;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1 = 36;
    uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK2 = 52;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2 = 68;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_MAX = 84;

    // TotalAmounts
    uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_WITH_INTEREST = 0;
    uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_INTEREST_FREE = 64;
    uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_WITH_INTEREST = 128;
    uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_INTEREST_FREE = 192;

    // UserSupplyData
    uint256 internal constant BITS_USER_SUPPLY_MODE = 0;
    uint256 internal constant BITS_USER_SUPPLY_AMOUNT = 1;
    uint256 internal constant BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT = 65;
    uint256 internal constant BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT = 200;
    uint256 internal constant BITS_USER_SUPPLY_IS_PAUSED = 255;

    // UserBorrowData
    uint256 internal constant BITS_USER_BORROW_MODE = 0;
    uint256 internal constant BITS_USER_BORROW_AMOUNT = 1;
    uint256 internal constant BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT = 65;
    uint256 internal constant BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_BORROW_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_BORROW_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_BORROW_BASE_BORROW_LIMIT = 200;
    uint256 internal constant BITS_USER_BORROW_MAX_BORROW_LIMIT = 218;
    uint256 internal constant BITS_USER_BORROW_IS_PAUSED = 255;

    // --------------------------------

    /// @notice Calculating the slot ID for Liquidity contract for single mapping at `slot_` for `key_`
    function calculateMappingStorageSlot(uint256 slot_, address key_) internal pure returns (bytes32) {
        return keccak256(abi.encode(key_, slot_));
    }

    /// @notice Calculating the slot ID for Liquidity contract for double mapping at `slot_` for `key1_` and `key2_`
    function calculateDoubleMappingStorageSlot(
        uint256 slot_,
        address key1_,
        address key2_
    ) internal pure returns (bytes32) {
        bytes32 intermediateSlot_ = keccak256(abi.encode(key1_, slot_));
        return keccak256(abi.encode(key2_, intermediateSlot_));
    }
}

File 19 of 31 : safeTransfer.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity 0.8.21;

import { LibsErrorTypes as ErrorTypes } from "./errorTypes.sol";

/// @notice provides minimalistic methods for safe transfers, e.g. ERC20 safeTransferFrom
library SafeTransfer {
    error FluidSafeTransferError(uint256 errorId_);

    /// @dev Transfer `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.
    /// Minimally modified from Solmate SafeTransferLib (address as input param for token, Custom Error):
    /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L31-L63
    function safeTransferFrom(address token_, address from_, address to_, uint256 amount_) internal {
        bool success_;

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

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from_" argument.
            mstore(add(freeMemoryPointer, 36), and(to_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to_" argument.
            mstore(add(freeMemoryPointer, 68), amount_) // Append the "amount_" argument. Masking not required as it's a full 32 byte type.

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

        if (!success_) {
            revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFromFailed);
        }
    }

    /// @dev Transfer `amount_` of `token_` to `to_`.
    /// If `token_` returns no value, non-reverting calls are assumed to be successful.
    /// Minimally modified from Solmate SafeTransferLib (address as input param for token, Custom Error):
    /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L65-L95
    function safeTransfer(address token_, address to_, uint256 amount_) internal {
        bool success_;

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

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to_, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to_" argument.
            mstore(add(freeMemoryPointer, 36), amount_) // Append the "amount_" argument. Masking not required as it's a full 32 byte type.

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

        if (!success_) {
            revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed);
        }
    }

    /// @dev Transfer `amount_` of ` native token to `to_`.
    /// Minimally modified from Solmate SafeTransferLib (Custom Error):
    /// https://github.com/transmissions11/solmate/blob/50e15bb566f98b7174da9b0066126a4c3e75e0fd/src/utils/SafeTransferLib.sol#L15-L25
    function safeTransferNative(address to_, uint256 amount_) internal {
        bool success_;

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

        if (!success_) {
            revert FluidSafeTransferError(ErrorTypes.SafeTransfer__TransferFailed);
        }
    }
}

File 20 of 31 : structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

abstract contract Structs {
    struct AddressBool {
        address addr;
        bool value;
    }

    struct AddressUint256 {
        address addr;
        uint256 value;
    }

    /// @notice struct to set borrow rate data for version 1
    struct RateDataV1Params {
        ///
        /// @param token for rate data
        address token;
        ///
        /// @param kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink usually means slow increase in rate, once utilization is above kink borrow rate increases fast
        uint256 kink;
        ///
        /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
        /// i.e. constant minimum borrow rate
        /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
        uint256 rateAtUtilizationZero;
        ///
        /// @param rateAtUtilizationKink borrow rate when utilization is at kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at kink then rateAtUtilizationKink would be 700
        uint256 rateAtUtilizationKink;
        ///
        /// @param rateAtUtilizationMax borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
        uint256 rateAtUtilizationMax;
    }

    /// @notice struct to set borrow rate data for version 2
    struct RateDataV2Params {
        ///
        /// @param token for rate data
        address token;
        ///
        /// @param kink1 first kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink 1 usually means slow increase in rate, once utilization is above kink 1 borrow rate increases faster
        uint256 kink1;
        ///
        /// @param kink2 second kink in borrow rate. in 1e2: 100% = 10_000; 1% = 100
        /// utilization below kink 2 usually means slow / medium increase in rate, once utilization is above kink 2 borrow rate increases fast
        uint256 kink2;
        ///
        /// @param rateAtUtilizationZero desired borrow rate when utilization is zero. in 1e2: 100% = 10_000; 1% = 100
        /// i.e. constant minimum borrow rate
        /// e.g. at utilization = 0.01% rate could still be at least 4% (rateAtUtilizationZero would be 400 then)
        uint256 rateAtUtilizationZero;
        ///
        /// @param rateAtUtilizationKink1 desired borrow rate when utilization is at first kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at first kink then rateAtUtilizationKink would be 700
        uint256 rateAtUtilizationKink1;
        ///
        /// @param rateAtUtilizationKink2 desired borrow rate when utilization is at second kink. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 7% at second kink then rateAtUtilizationKink would be 1_200
        uint256 rateAtUtilizationKink2;
        ///
        /// @param rateAtUtilizationMax desired borrow rate when utilization is maximum at 100%. in 1e2: 100% = 10_000; 1% = 100
        /// e.g. when rate should be 125% at 100% then rateAtUtilizationMax would be 12_500
        uint256 rateAtUtilizationMax;
    }

    /// @notice struct to set token config
    struct TokenConfig {
        ///
        /// @param token address
        address token;
        ///
        /// @param fee charges on borrower's interest. in 1e2: 100% = 10_000; 1% = 100
        uint256 fee;
        ///
        /// @param threshold on when to update the storage slot. in 1e2: 100% = 10_000; 1% = 100
        uint256 threshold;
    }

    /// @notice struct to set user supply & withdrawal config
    struct UserSupplyConfig {
        ///
        /// @param user address
        address user;
        ///
        /// @param token address
        address token;
        ///
        /// @param mode: 0 = without interest. 1 = with interest
        uint8 mode;
        ///
        /// @param expandPercent withdrawal limit expand percent. in 1e2: 100% = 10_000; 1% = 100
        /// Also used to calculate rate at which withdrawal limit should decrease (instant).
        uint256 expandPercent;
        ///
        /// @param expandDuration withdrawal limit expand duration in seconds.
        /// used to calculate rate together with expandPercent
        uint256 expandDuration;
        ///
        /// @param baseWithdrawalLimit base limit, below this, user can withdraw the entire amount.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 baseWithdrawalLimit;
    }

    /// @notice struct to set user borrow & payback config
    struct UserBorrowConfig {
        ///
        /// @param user address
        address user;
        ///
        /// @param token address
        address token;
        ///
        /// @param mode: 0 = without interest. 1 = with interest
        uint8 mode;
        ///
        /// @param expandPercent debt limit expand percent. in 1e2: 100% = 10_000; 1% = 100
        /// Also used to calculate rate at which debt limit should decrease (instant).
        uint256 expandPercent;
        ///
        /// @param expandDuration debt limit expand duration in seconds.
        /// used to calculate rate together with expandPercent
        uint256 expandDuration;
        ///
        /// @param baseDebtCeiling base borrow limit. until here, borrow limit remains as baseDebtCeiling
        /// (user can borrow until this point at once without stepped expansion). Above this, automated limit comes in place.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 baseDebtCeiling;
        ///
        /// @param maxDebtCeiling max borrow ceiling, maximum amount the user can borrow.
        /// amount in raw (to be multiplied with exchange price) or normal depends on configured mode in user config for the token:
        /// with interest -> raw, without interest -> normal
        uint256 maxDebtCeiling;
    }
}

File 21 of 31 : iLiquidity.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IProxy } from "../../infiniteProxy/interfaces/iProxy.sol";
import { Structs as AdminModuleStructs } from "../adminModule/structs.sol";

interface IFluidLiquidityAdmin {
    /// @notice adds/removes auths. Auths generally could be contracts which can have restricted actions defined on contract.
    ///         auths can be helpful in reducing governance overhead where it's not needed.
    /// @param authsStatus_ array of structs setting allowed status for an address.
    ///                     status true => add auth, false => remove auth
    function updateAuths(AdminModuleStructs.AddressBool[] calldata authsStatus_) external;

    /// @notice adds/removes guardians. Only callable by Governance.
    /// @param guardiansStatus_ array of structs setting allowed status for an address.
    ///                         status true => add guardian, false => remove guardian
    function updateGuardians(AdminModuleStructs.AddressBool[] calldata guardiansStatus_) external;

    /// @notice changes the revenue collector address (contract that is sent revenue). Only callable by Governance.
    /// @param revenueCollector_  new revenue collector address
    function updateRevenueCollector(address revenueCollector_) external;

    /// @notice changes current status, e.g. for pausing or unpausing all user operations. Only callable by Auths.
    /// @param newStatus_ new status
    ///        status = 2 -> pause, status = 1 -> resume.
    function changeStatus(uint256 newStatus_) external;

    /// @notice                  update tokens rate data version 1. Only callable by Auths.
    /// @param tokensRateData_   array of RateDataV1Params with rate data to set for each token
    function updateRateDataV1s(AdminModuleStructs.RateDataV1Params[] calldata tokensRateData_) external;

    /// @notice                  update tokens rate data version 2. Only callable by Auths.
    /// @param tokensRateData_   array of RateDataV2Params with rate data to set for each token
    function updateRateDataV2s(AdminModuleStructs.RateDataV2Params[] calldata tokensRateData_) external;

    /// @notice updates token configs: fee charge on borrowers interest & storage update utilization threshold.
    ///         Only callable by Auths.
    /// @param tokenConfigs_ contains token address, fee & utilization threshold
    function updateTokenConfigs(AdminModuleStructs.TokenConfig[] calldata tokenConfigs_) external;

    /// @notice updates user classes: 0 is for new protocols, 1 is for established protocols.
    ///         Only callable by Auths.
    /// @param userClasses_ struct array of uint256 value to assign for each user address
    function updateUserClasses(AdminModuleStructs.AddressUint256[] calldata userClasses_) external;

    /// @notice sets user supply configs per token basis. Eg: with interest or interest-free and automated limits.
    ///         Only callable by Auths.
    /// @param userSupplyConfigs_ struct array containing user supply config, see `UserSupplyConfig` struct for more info
    function updateUserSupplyConfigs(AdminModuleStructs.UserSupplyConfig[] memory userSupplyConfigs_) external;

    /// @notice setting user borrow configs per token basis. Eg: with interest or interest-free and automated limits.
    ///         Only callable by Auths.
    /// @param userBorrowConfigs_ struct array containing user borrow config, see `UserBorrowConfig` struct for more info
    function updateUserBorrowConfigs(AdminModuleStructs.UserBorrowConfig[] memory userBorrowConfigs_) external;

    /// @notice pause operations for a particular user in class 0 (class 1 users can't be paused by guardians).
    /// Only callable by Guardians.
    /// @param user_          address of user to pause operations for
    /// @param supplyTokens_  token addresses to pause withdrawals for
    /// @param borrowTokens_  token addresses to pause borrowings for
    function pauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external;

    /// @notice unpause operations for a particular user in class 0 (class 1 users can't be paused by guardians).
    /// Only callable by Guardians.
    /// @param user_          address of user to unpause operations for
    /// @param supplyTokens_  token addresses to unpause withdrawals for
    /// @param borrowTokens_  token addresses to unpause borrowings for
    function unpauseUser(address user_, address[] calldata supplyTokens_, address[] calldata borrowTokens_) external;

    /// @notice         collects revenue for tokens to configured revenueCollector address.
    /// @param tokens_  array of tokens to collect revenue for
    /// @dev            Note that this can revert if token balance is < revenueAmount (utilization > 100%)
    function collectRevenue(address[] calldata tokens_) external;

    /// @notice gets the current updated exchange prices for n tokens and updates all prices, rates related data in storage.
    /// @param tokens_ tokens to update exchange prices for
    /// @return supplyExchangePrices_ new supply rates of overall system for each token
    /// @return borrowExchangePrices_ new borrow rates of overall system for each token
    function updateExchangePrices(
        address[] calldata tokens_
    ) external returns (uint256[] memory supplyExchangePrices_, uint256[] memory borrowExchangePrices_);
}

interface IFluidLiquidityLogic is IFluidLiquidityAdmin {
    /// @notice Single function which handles supply, withdraw, borrow & payback
    /// @param token_ address of token (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native)
    /// @param supplyAmount_ if +ve then supply, if -ve then withdraw, if 0 then nothing
    /// @param borrowAmount_ if +ve then borrow, if -ve then payback, if 0 then nothing
    /// @param withdrawTo_ if withdrawal then to which address
    /// @param borrowTo_ if borrow then to which address
    /// @param callbackData_ callback data passed to `liquidityCallback` method of protocol
    /// @return memVar3_ updated supplyExchangePrice
    /// @return memVar4_ updated borrowExchangePrice
    /// @dev to trigger skipping in / out transfers when in&out amounts balance themselves out (gas optimization):
    /// -   supply(+) == borrow(+), withdraw(-) == payback(-).
    /// -   `withdrawTo_` / `borrowTo_` must be msg.sender (protocol)
    /// -   `callbackData_` MUST be encoded so that "from" address is at last 20 bytes (if this optimization is desired),
    ///     also for native token operations where liquidityCallback is not triggered!
    ///     from address must come at last position if there is more data. I.e. encode like:
    ///     abi.encode(otherVar1, otherVar2, FROM_ADDRESS). Note dynamic types used with abi.encode come at the end
    ///     so if dynamic types are needed, you must use abi.encodePacked to ensure the from address is at the end.
    function operate(
        address token_,
        int256 supplyAmount_,
        int256 borrowAmount_,
        address withdrawTo_,
        address borrowTo_,
        bytes calldata callbackData_
    ) external payable returns (uint256 memVar3_, uint256 memVar4_);
}

interface IFluidLiquidity is IProxy, IFluidLiquidityLogic {}

File 22 of 31 : error.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

abstract contract Error {
    error FluidLendingError(uint256 errorId_);
}

File 23 of 31 : errorTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

library ErrorTypes {
    /***********************************|
    |               fToken              | 
    |__________________________________*/

    /// @notice thrown when a deposit amount is too small to increase BigMath stored balance in Liquidity.
    /// precision of BigMath is 1e12, so if token holds 120_000_000_000 USDC, min amount to make a difference would be 0.1 USDC.
    /// i.e. user would send a very small deposit which mints no shares -> revert
    uint256 internal constant fToken__DepositInsignificant = 20001;

    /// @notice thrown when minimum output amount is not reached, e.g. for minimum shares minted (deposit) or
    ///         minimum assets received (redeem)
    uint256 internal constant fToken__MinAmountOut = 20002;

    /// @notice thrown when maximum amount is surpassed, e.g. for maximum shares burned (withdraw) or
    ///         maximum assets input (mint)
    uint256 internal constant fToken__MaxAmount = 20003;

    /// @notice thrown when invalid params are sent to a method, e.g. zero address
    uint256 internal constant fToken__InvalidParams = 20004;

    /// @notice thrown when an unauthorized caller is trying to execute an auth-protected method
    uint256 internal constant fToken__Unauthorized = 20005;

    /// @notice thrown when a with permit / signature method is called from msg.sender that is the owner.
    /// Should call the method without permit instead if msg.sender is the owner.
    uint256 internal constant fToken__PermitFromOwnerCall = 20006;

    /// @notice thrown when a reentrancy is detected.
    uint256 internal constant fToken__Reentrancy = 20007;

    /// @notice thrown when _tokenExchangePrice overflows type(uint64).max
    uint256 internal constant fToken__ExchangePriceOverflow = 20008;

    /// @notice thrown when msg.sender is not rebalancer
    uint256 internal constant fToken__NotRebalancer = 20009;

    /// @notice thrown when rebalance is called with msg.value > 0 for non NativeUnderlying fToken
    uint256 internal constant fToken__NotNativeUnderlying = 20010;

    /// @notice thrown when the received new liquidity exchange price is of unexpected value (< than the old one)
    uint256 internal constant fToken__LiquidityExchangePriceUnexpected = 20011;

    /***********************************|
    |     fToken Native Underlying      | 
    |__________________________________*/

    /// @notice thrown when native deposit is called but sent along `msg.value` does not cover the deposit amount
    uint256 internal constant fTokenNativeUnderlying__TransferInsufficient = 21001;

    /// @notice thrown when a liquidity callback is called for a native token operation
    uint256 internal constant fTokenNativeUnderlying__UnexpectedLiquidityCallback = 21002;

    /***********************************|
    |         Lending Factory         | 
    |__________________________________*/

    /// @notice thrown when a method is called with invalid params
    uint256 internal constant LendingFactory__InvalidParams = 22001;

    /// @notice thrown when the provided input param address is zero
    uint256 internal constant LendingFactory__ZeroAddress = 22002;

    /// @notice thrown when the token already exists
    uint256 internal constant LendingFactory__TokenExists = 22003;

    /// @notice thrown when the fToken has not yet been configured at Liquidity
    uint256 internal constant LendingFactory__LiquidityNotConfigured = 22004;

    /// @notice thrown when an unauthorized caller is trying to execute an auth-protected method
    uint256 internal constant LendingFactory__Unauthorized = 22005;

    /***********************************|
    |   Lending Rewards Rate Model      | 
    |__________________________________*/

    /// @notice thrown when invalid params are given as input
    uint256 internal constant LendingRewardsRateModel__InvalidParams = 23001;

    /// @notice thrown when calculated rewards rate is exceeding the maximum rate
    uint256 internal constant LendingRewardsRateModel__MaxRate = 23002;

    /// @notice thrown when start is called by any other address other than initiator
    uint256 internal constant LendingRewardsRateModel__NotTheInitiator = 23003;

    /// @notice thrown when start is called after the rewards are already started
    uint256 internal constant LendingRewardsRateModel__AlreadyStarted = 23004;

    /// @notice thrown when the provided input param address is zero
    uint256 internal constant LendingRewardsRateModel__ZeroAddress = 23005;
}

File 24 of 31 : events.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IFluidLendingRewardsRateModel  } from "../interfaces/iLendingRewardsRateModel.sol";

abstract contract Events {
    /// @notice emitted whenever admin updates rewards rate model
    event LogUpdateRewards(IFluidLendingRewardsRateModel  indexed rewardsRateModel);

    /// @notice emitted whenever rebalance is executed to fund difference between Liquidity deposit and totalAssets()
    ///         as rewards through the rebalancer.
    event LogRebalance(uint256 assets);

    /// @notice emitted whenever exchange rates are updated
    event LogUpdateRates(uint256 tokenExchangePrice, uint256 liquidityExchangePrice);

    /// @notice emitted whenever funds for a certain `token` are rescued to Liquidity
    event LogRescueFunds(address indexed token);

    /// @notice emitted whenever rebalancer address is updated
    event LogUpdateRebalancer(address indexed rebalancer);
}

File 25 of 31 : main.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { ERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { FixedPointMathLib } from "solmate/src/utils/FixedPointMathLib.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol";
import { IFluidLendingRewardsRateModel } from "../interfaces/iLendingRewardsRateModel.sol";
import { IFluidLendingFactory } from "../interfaces/iLendingFactory.sol";
import { IFToken, IFTokenAdmin } from "../interfaces/iFToken.sol";
import { LiquidityCalcs } from "../../../libraries/liquidityCalcs.sol";
import { BigMathMinified } from "../../../libraries/bigMathMinified.sol";
import { LiquiditySlotsLink } from "../../../libraries/liquiditySlotsLink.sol";
import { SafeTransfer } from "../../../libraries/safeTransfer.sol";
import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol";
import { Variables } from "./variables.sol";
import { Events } from "./events.sol";
import { ErrorTypes } from "../errorTypes.sol";
import { Error } from "../error.sol";

/// @dev ReentrancyGuard based on OpenZeppelin implementation.
/// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.8/contracts/security/ReentrancyGuard.sol
abstract contract ReentrancyGuard is Error, Variables {
    uint8 internal constant REENTRANCY_NOT_ENTERED = 1;
    uint8 internal constant REENTRANCY_ENTERED = 2;

    constructor() {
        _status = REENTRANCY_NOT_ENTERED;
    }

    /// @dev checks that no reentrancy occurs, reverts if so. Calling the method in the modifier reduces
    /// bytecode size as modifiers are inlined into bytecode
    function _checkReentrancy() internal {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status != REENTRANCY_NOT_ENTERED) {
            revert FluidLendingError(ErrorTypes.fToken__Reentrancy);
        }

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

    /// @dev Prevents a contract from calling itself, directly or indirectly.
    /// See OpenZeppelin implementation for more info
    modifier nonReentrant() {
        _checkReentrancy();

        _;

        // storing original value triggers a refund (see https://eips.ethereum.org/EIPS/eip-2200)
        _status = REENTRANCY_NOT_ENTERED;
    }
}

/// @dev internal methods for fToken contracts
abstract contract fTokenCore is Error, IERC4626, IFToken, Variables, Events, ReentrancyGuard {
    using FixedPointMathLib for uint256;

    /// @dev Gets current (updated) Liquidity supply exchange price for the underyling asset
    function _getLiquidityExchangePrice() internal view returns (uint256 supplyExchangePrice_) {
        (supplyExchangePrice_, ) = LiquidityCalcs.calcExchangePrices(
            LIQUIDITY.readFromStorage(LIQUIDITY_EXCHANGE_PRICES_SLOT)
        );
    }

    /// @dev Gets current Liquidity supply balance of `address(this)` for the underyling asset
    function _getLiquidityBalance() internal view returns (uint256 balance_) {
        // extract user supply amount
        uint256 userSupplyRaw_ = BigMathMinified.fromBigNumber(
            (LIQUIDITY.readFromStorage(LIQUIDITY_USER_SUPPLY_SLOT) >> LiquiditySlotsLink.BITS_USER_SUPPLY_AMOUNT) &
                LiquidityCalcs.X64,
            LiquidityCalcs.DEFAULT_EXPONENT_SIZE,
            LiquidityCalcs.DEFAULT_EXPONENT_MASK
        );

        unchecked {
            // can not overflow as userSupplyRaw_ can be maximally type(int128).max, liquidity exchange price type(uint64).max
            return (userSupplyRaw_ * _getLiquidityExchangePrice()) / EXCHANGE_PRICES_PRECISION;
        }
    }

    /// @dev Gets current Liquidity underlying token balance
    function _getLiquidityUnderlyingBalance() internal view virtual returns (uint256) {
        return ASSET.balanceOf(address(LIQUIDITY));
    }

    /// @dev Gets current withdrawable amount at Liquidity `withdrawalLimit_` (withdrawal limit or balance).
    function _getLiquidityWithdrawable() internal view returns (uint256 withdrawalLimit_) {
        uint256 userSupplyData_ = LIQUIDITY.readFromStorage(LIQUIDITY_USER_SUPPLY_SLOT);
        uint256 userSupply_ = BigMathMinified.fromBigNumber(
            (userSupplyData_ >> LiquiditySlotsLink.BITS_USER_SUPPLY_AMOUNT) & LiquidityCalcs.X64,
            LiquidityCalcs.DEFAULT_EXPONENT_SIZE,
            LiquidityCalcs.DEFAULT_EXPONENT_MASK
        );
        withdrawalLimit_ = LiquidityCalcs.calcWithdrawalLimitBeforeOperate(userSupplyData_, userSupply_);

        // convert raw amounts to normal amounts
        unchecked {
            // can not overflow as userSupply_ can be maximally type(int128).max
            // and withdrawalLimit is smaller than userSupply_
            uint256 liquidityExchangePrice_ = _getLiquidityExchangePrice();
            withdrawalLimit_ = (withdrawalLimit_ * liquidityExchangePrice_) / EXCHANGE_PRICES_PRECISION;
            userSupply_ = (userSupply_ * liquidityExchangePrice_) / EXCHANGE_PRICES_PRECISION;
        }

        withdrawalLimit_ = userSupply_ > withdrawalLimit_ ? userSupply_ - withdrawalLimit_ : 0;

        uint256 balanceAtLiquidity_ = _getLiquidityUnderlyingBalance();

        return balanceAtLiquidity_ > withdrawalLimit_ ? withdrawalLimit_ : balanceAtLiquidity_;
    }

    /// @dev Calculates new token exchange price based on the current liquidity exchange price `newLiquidityExchangePrice_` and rewards rate.
    /// @param newLiquidityExchangePrice_ new (current) liquidity exchange price
    function _calculateNewTokenExchangePrice(
        uint256 newLiquidityExchangePrice_
    ) internal view returns (uint256 newTokenExchangePrice_, bool rewardsEnded_) {
        uint256 oldTokenExchangePrice_ = _tokenExchangePrice;
        uint256 oldLiquidityExchangePrice_ = _liquidityExchangePrice;

        if (newLiquidityExchangePrice_ < oldLiquidityExchangePrice_) {
            // liquidity exchange price should only ever increase. If not, something went wrong and avoid
            // proceeding with unknown outcome.
            revert FluidLendingError(ErrorTypes.fToken__LiquidityExchangePriceUnexpected);
        }

        uint256 totalReturnInPercent_; // rewardsRateInPercent + liquidityReturnInPercent
        if (_rewardsActive) {
            {
                // get rewards rate per year
                // only trigger call to rewardsRateModel if rewards are actually active to save gas
                uint256 rewardsRate_;
                uint256 rewardsStartTime_;
                (rewardsRate_, rewardsEnded_, rewardsStartTime_) = _rewardsRateModel.getRate(
                    // use old tokenExchangeRate to calculate the total assets input for the rewards rate
                    (oldTokenExchangePrice_ * totalSupply()) / EXCHANGE_PRICES_PRECISION
                );

                if (rewardsRate_ > MAX_REWARDS_RATE || rewardsEnded_) {
                    // rewardsRate is capped, if it is bigger > MAX_REWARDS_RATE, then the rewardsRateModel
                    // is configured wrongly (which should not be possible). Setting rewards to 0 in that case here.
                    rewardsRate_ = 0;
                }

                uint256 lastUpdateTimestamp_ = _lastUpdateTimestamp;
                if (lastUpdateTimestamp_ < rewardsStartTime_) {
                    // if last update was before the rewards started, make sure rewards actually only accrue
                    // from the actual rewards start time, not from the last update timestamp to avoid overpayment.
                    lastUpdateTimestamp_ = rewardsStartTime_;

                    // Note: overpayment for block.timestamp being > rewards end time does not happen because
                    // rewardsRate_ is forced 0 then.
                }

                // calculate rewards return in percent: (rewards_rate * time passed) / seconds_in_a_year.
                unchecked {
                    // rewardsRate * timeElapsed / SECONDS_PER_YEAR.
                    // no safe checks needed here because timeElapsed can not underflow,
                    // rewardsRate is in 1e12 at max value being MAX_REWARDS_RATE = 25e12
                    // max value would be 25e12 * 8589934591 / 31536000 (with buffers) = 6.8e15
                    totalReturnInPercent_ =
                        (rewardsRate_ * (block.timestamp - lastUpdateTimestamp_)) /
                        SECONDS_PER_YEAR;
                }
            }
        }

        unchecked {
            // calculate liquidityReturnInPercent: (newLiquidityExchangePrice_ - oldLiquidityExchangePrice_) / oldLiquidityExchangePrice_.
            // and add it to totalReturnInPercent_ that already holds rewardsRateInPercent_.
            // max value (in absolute extreme unrealistic case) would be: 6.8e15 + (((max uint64 - 1e12) * 1e12) / 1e12) = 1.845e19
            // oldLiquidityExchangePrice_ can not be 0, minimal value is 1e12. subtraction can not underflow because new exchange price
            // can only be >= oldLiquidityExchangePrice_.
            totalReturnInPercent_ +=
                ((newLiquidityExchangePrice_ - oldLiquidityExchangePrice_) * 1e14) /
                oldLiquidityExchangePrice_;
        }

        // newTokenExchangePrice_ = oldTokenExchangePrice_ + oldTokenExchangePrice_ * totalReturnInPercent_
        newTokenExchangePrice_ = oldTokenExchangePrice_ + ((oldTokenExchangePrice_ * totalReturnInPercent_) / 1e14); // divided by 100% (1e14)
    }

    /// @dev calculates new exchange prices, updates values in storage and returns new tokenExchangePrice (with reward rates)
    function _updateRates(
        uint256 liquidityExchangePrice_,
        bool forceUpdateStorage_
    ) internal returns (uint256 tokenExchangePrice_) {
        bool rewardsEnded_;
        (tokenExchangePrice_, rewardsEnded_) = _calculateNewTokenExchangePrice(liquidityExchangePrice_);
        if (_rewardsActive || forceUpdateStorage_) {
            // Solidity will NOT cause a revert if values are too big to fit max uint type size. Explicitly check before
            // writing to storage. Also see https://github.com/ethereum/solidity/issues/10195.
            if (tokenExchangePrice_ > type(uint64).max) {
                revert FluidLendingError(ErrorTypes.fToken__ExchangePriceOverflow);
            }

            _tokenExchangePrice = uint64(tokenExchangePrice_);
            _liquidityExchangePrice = uint64(liquidityExchangePrice_);
            _lastUpdateTimestamp = uint40(block.timestamp);

            emit LogUpdateRates(tokenExchangePrice_, liquidityExchangePrice_);
        }

        if (rewardsEnded_) {
            // set rewardsActive flag to false to save gas for all future exchange prices calculations,
            // without having to explicitly require setting `updateRewards` to address zero.
            // Note that it would be fine that even the current tx does not update exchange prices in storage,
            // because if rewardsEnded_ is true, rewardsRate_ must be 0, so the only yield is from LIQUIDITY.
            // But to be extra safe, writing to storage in that one case too before setting _rewardsActive to false.
            _rewardsActive = false;
        }

        return tokenExchangePrice_;
    }

    /// @dev splits a bytes signature `sig` into `v`, `r`, `s`.
    /// Taken from https://docs.soliditylang.org/en/v0.8.17/solidity-by-example.html
    function _splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        require(sig.length == 65);

        assembly {
            // first 32 bytes, after the length prefix.
            r := mload(add(sig, 32))
            // second 32 bytes.
            s := mload(add(sig, 64))
            // final byte (first byte of the next 32 bytes).
            v := byte(0, mload(add(sig, 96)))
        }

        return (v, r, s);
    }

    /// @dev Deposit `assets_` amount of tokens to Liquidity
    /// @param assets_ The amount of tokens to deposit
    /// @param liquidityCallbackData_ callback data passed to Liquidity for `liquidityCallback`
    /// @return exchangePrice_ liquidity exchange price for token
    function _depositToLiquidity(
        uint256 assets_,
        bytes memory liquidityCallbackData_
    ) internal virtual returns (uint256 exchangePrice_) {
        // @dev Note: Although there might be some small difference between the `assets_` amount and the actual amount
        // accredited at Liquidity due to BigMath rounding down, this amount is so small that it can be ignored.
        // because of BigMath precision of 7.2057594e16 for a coefficient size of 56, it would require >72 trillion DAI
        // to "benefit" 1 DAI in additional shares minted. Considering gas cost + APR per second, this ensures such
        // a manipulation attempt becomes extremely unlikely.

        // send funds to Liquidity protocol to generate yield
        (exchangePrice_, ) = LIQUIDITY.operate(
            address(ASSET),
            SafeCast.toInt256(assets_),
            0,
            address(0),
            address(0),
            liquidityCallbackData_ // callback data. -> "from" for transferFrom in `liquidityCallback`
        );
    }

    /// @dev Withdraw `assets_` amount of tokens from Liquidity directly to `receiver_`
    /// @param assets_    The amount of tokens to withdraw
    /// @param receiver_  the receiver address of withdraw amount
    /// @return exchangePrice_   liquidity exchange price for token
    function _withdrawFromLiquidity(
        uint256 assets_,
        address receiver_
    ) internal virtual returns (uint256 exchangePrice_) {
        // @dev See similar comment in `_depositToLiquidity()` regarding burning a tiny bit of additional shares here
        // because of inaccuracies in Liquidity userSupply BigMath being rounded down.

        // get funds back from Liquidity protocol to send to the user
        (exchangePrice_, ) = LIQUIDITY.operate(
            address(ASSET),
            -SafeCast.toInt256(assets_),
            0,
            receiver_,
            address(0),
            new bytes(0) // callback data -> withdraw doesn't trigger a callback
        );
    }

    /// @dev deposits `assets_` into liquidity and mints shares for `receiver_`. Returns amount of `sharesMinted_`.
    function _executeDeposit(
        uint256 assets_,
        address receiver_,
        bytes memory liquidityCallbackData_
    ) internal virtual validAddress(receiver_) returns (uint256 sharesMinted_) {
        // send funds to Liquidity protocol to generate yield -> returns updated liquidityExchangePrice
        uint256 tokenExchangePrice_ = _depositToLiquidity(assets_, liquidityCallbackData_);

        // update the exchange prices
        tokenExchangePrice_ = _updateRates(tokenExchangePrice_, false);

        // calculate the shares to mint
        // not using previewDeposit here because we just got newTokenExchangePrice_
        sharesMinted_ = (assets_ * EXCHANGE_PRICES_PRECISION) / tokenExchangePrice_;

        if (sharesMinted_ == 0) {
            revert FluidLendingError(ErrorTypes.fToken__DepositInsignificant);
        }

        _mint(receiver_, sharesMinted_);

        emit Deposit(msg.sender, receiver_, assets_, sharesMinted_);
    }

    /// @dev withdraws `assets_` from liquidity to `receiver_` and burns shares from `owner_`.
    /// Returns amount of `sharesBurned_`.
    /// requires nonReentrant! modifier on calling method otherwise ERC777s could reenter!
    function _executeWithdraw(
        uint256 assets_,
        address receiver_,
        address owner_
    ) internal virtual validAddress(receiver_) returns (uint256 sharesBurned_) {
        // burn shares for assets_ amount: assets_ * EXCHANGE_PRICES_PRECISION / updatedTokenTexchangePrice. Rounded up.
        // Note to be extra safe we do the shares burn before the withdrawFromLiquidity, even though that would return the
        // updated liquidityExchangePrice and thus save gas.
        sharesBurned_ = assets_.mulDivUp(EXCHANGE_PRICES_PRECISION, _updateRates(_getLiquidityExchangePrice(), false));

        /*
            The `mulDivUp` function is designed to round up the result of multiplication followed by division. 
            Given non-zero `assets_` and the rounding-up behavior of this function, `sharesBurned_` will always 
            be at least 1 if there's any remainder in the division.
            Thus, if `assets_` is non-zero, `sharesBurned_` can never be 0. The nature of the function ensures 
            that even the smallest fractional result (greater than 0) will be rounded up to 1. Hence, there's no need 
            to check for a rounding error that results in 0.
            Furthermore, if `assets_` was 0, an error 'UserModule__OperateAmountsZero' would already have been thrown 
            during the `operate` function, ensuring the contract never reaches this point with a zero `assets_` value.
            Note: If ever the logic or the function behavior changes in the future, this assertion may need to be reconsidered.
        */

        _burn(owner_, sharesBurned_);

        // withdraw from liquidity directly to _receiver.
        _withdrawFromLiquidity(assets_, receiver_);

        emit Withdraw(msg.sender, receiver_, owner_, assets_, sharesBurned_);
    }
}

/// @notice fToken view methods. Implements view methods for ERC4626 compatibility
abstract contract fTokenViews is fTokenCore {
    using FixedPointMathLib for uint256;

    /// @inheritdoc IFToken
    function getData()
        public
        view
        returns (
            IFluidLiquidity liquidity_,
            IFluidLendingFactory lendingFactory_,
            IFluidLendingRewardsRateModel lendingRewardsRateModel_,
            IAllowanceTransfer permit2_,
            address rebalancer_,
            bool rewardsActive_,
            uint256 liquidityBalance_,
            uint256 liquidityExchangePrice_,
            uint256 tokenExchangePrice_
        )
    {
        liquidityExchangePrice_ = _getLiquidityExchangePrice();

        bool rewardsEnded_;
        (tokenExchangePrice_, rewardsEnded_) = _calculateNewTokenExchangePrice(liquidityExchangePrice_);

        return (
            LIQUIDITY,
            LENDING_FACTORY,
            _rewardsRateModel,
            PERMIT2,
            _rebalancer,
            _rewardsActive && !rewardsEnded_,
            _getLiquidityBalance(),
            liquidityExchangePrice_,
            tokenExchangePrice_
        );
    }

    /// @inheritdoc IERC4626
    function asset() public view virtual override returns (address) {
        return address(ASSET);
    }

    /// @inheritdoc IERC4626
    function totalAssets() public view virtual override returns (uint256) {
        (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice());
        return
            // all the underlying tokens are stored in Liquidity contract at all times
            (tokenExchangePrice_ * totalSupply()) / EXCHANGE_PRICES_PRECISION;
    }

    /// @inheritdoc IERC4626
    function convertToShares(uint256 assets_) public view virtual override returns (uint256) {
        (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice());
        return assets_.mulDivDown(EXCHANGE_PRICES_PRECISION, tokenExchangePrice_);
    }

    /// @inheritdoc IERC4626
    function convertToAssets(uint256 shares_) public view virtual override returns (uint256) {
        (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice());
        return shares_.mulDivDown(tokenExchangePrice_, EXCHANGE_PRICES_PRECISION);
    }

    /// @inheritdoc IERC4626
    /// @notice returned amount might be slightly different from actual amount at execution.
    function previewDeposit(uint256 assets_) public view virtual override returns (uint256) {
        return convertToShares(assets_);
    }

    /// @inheritdoc IERC4626
    function previewMint(uint256 shares_) public view virtual override returns (uint256) {
        (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice());
        return shares_.mulDivUp(tokenExchangePrice_, EXCHANGE_PRICES_PRECISION);
    }

    /// @inheritdoc IERC4626
    function previewWithdraw(uint256 assets_) public view virtual override returns (uint256) {
        (uint256 tokenExchangePrice_, ) = _calculateNewTokenExchangePrice(_getLiquidityExchangePrice());
        return assets_.mulDivUp(EXCHANGE_PRICES_PRECISION, tokenExchangePrice_);
    }

    /// @inheritdoc IERC4626
    /// @notice returned amount might be slightly different from actual amount at execution.
    function previewRedeem(uint256 shares_) public view virtual override returns (uint256) {
        return convertToAssets(shares_);
    }

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

    /// @inheritdoc IERC4626
    function maxDeposit(address) public view virtual override returns (uint256) {
        // read total supplyInterest_ for the token at Liquidity and convert from BigMath
        uint256 supplyInterest_ = LIQUIDITY.readFromStorage(LIQUIDITY_TOTAL_AMOUNTS_SLOT) & LiquidityCalcs.X64;
        supplyInterest_ =
            (supplyInterest_ >> LiquidityCalcs.DEFAULT_EXPONENT_SIZE) <<
            (supplyInterest_ & LiquidityCalcs.DEFAULT_EXPONENT_MASK);

        unchecked {
            // normalize from raw
            supplyInterest_ = (supplyInterest_ * _getLiquidityExchangePrice()) / EXCHANGE_PRICES_PRECISION;
            // compare against hardcoded max possible value for total supply considering BigMath rounding down:
            // type(int128).max) after BigMath rounding (first 56 bits precision, then 71 bits getting set to 0)
            // so 1111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000000000
            // = 170141183460469229370504062281061498880. using minus 1
            if (supplyInterest_ > 170141183460469229370504062281061498879) {
                return 0;
            }
            // type(int128).max is the maximum interactable amount at Liquidity. But also total token amounts
            // must not overflow type(int128).max, so max depositable is type(int128).max - totalSupply.
            return uint256(uint128(type(int128).max)) - supplyInterest_;
        }
    }

    /// @inheritdoc IERC4626
    function maxMint(address) public view virtual override returns (uint256) {
        return convertToShares(maxDeposit(address(0)));
    }

    /// @inheritdoc IERC4626
    function maxWithdraw(address owner_) public view virtual override returns (uint256) {
        uint256 maxWithdrawableAtLiquidity_ = _getLiquidityWithdrawable();
        uint256 ownerBalance_ = convertToAssets(balanceOf(owner_));
        return maxWithdrawableAtLiquidity_ < ownerBalance_ ? maxWithdrawableAtLiquidity_ : ownerBalance_;
    }

    /// @inheritdoc IERC4626
    function maxRedeem(address owner_) public view virtual override returns (uint256) {
        uint256 maxWithdrawableAtLiquidity_ = convertToShares(_getLiquidityWithdrawable());
        uint256 ownerBalance_ = balanceOf(owner_);
        return maxWithdrawableAtLiquidity_ < ownerBalance_ ? maxWithdrawableAtLiquidity_ : ownerBalance_;
    }

    /// @inheritdoc IFToken
    function minDeposit() public view returns (uint256) {
        uint256 minBigMathRounding_ = 1 <<
            (LIQUIDITY.readFromStorage(LIQUIDITY_TOTAL_AMOUNTS_SLOT) & LiquidityCalcs.DEFAULT_EXPONENT_MASK); // 1 << total supply exponent
        uint256 previewMint_ = previewMint(1); // rounds up
        return minBigMathRounding_ > previewMint_ ? minBigMathRounding_ : previewMint_;
    }
}

/// @notice fToken admin related methods. fToken admins are Lending Factory auths. Possible actions are
/// updating rewards, funding rewards, and rescuing any stuck funds (fToken contract itself never holds any funds).
abstract contract fTokenAdmin is fTokenCore, fTokenViews {
    /// @dev checks if `msg.sender` is an allowed auth at LendingFactory. internal method instead of modifier
    ///      to reduce bytecode size.
    function _checkIsLendingFactoryAuth() internal view {
        if (!LENDING_FACTORY.isAuth(msg.sender)) {
            revert FluidLendingError(ErrorTypes.fToken__Unauthorized);
        }
    }

    /// @inheritdoc IFTokenAdmin
    function updateRewards(IFluidLendingRewardsRateModel rewardsRateModel_) external {
        _checkIsLendingFactoryAuth();

        // @dev no check for address zero needed here, as that is actually explicitly checked where _rewardsRateModel
        // is used. In fact it is beneficial to set _rewardsRateModel to address zero when there are no rewards.

        // apply current rewards rate before updating to new one
        updateRates();

        _rewardsRateModel = rewardsRateModel_;

        // set flag _rewardsActive
        _rewardsActive = address(rewardsRateModel_) != address(0);

        emit LogUpdateRewards(rewardsRateModel_);
    }

    /// @inheritdoc IFTokenAdmin
    function rebalance() external payable virtual nonReentrant returns (uint256 assets_) {
        if (msg.sender != _rebalancer) {
            revert FluidLendingError(ErrorTypes.fToken__NotRebalancer);
        }
        if (msg.value > 0) {
            revert FluidLendingError(ErrorTypes.fToken__NotNativeUnderlying);
        }
        // calculating difference in assets. if liquidity balance is bigger it'll throw which is an expected behaviour
        assets_ = totalAssets() - _getLiquidityBalance();
        // send funds to Liquidity protocol
        uint256 liquidityExchangePrice_ = _depositToLiquidity(assets_, abi.encode(msg.sender));

        // update the exchange prices, always updating on storage
        _updateRates(liquidityExchangePrice_, true);

        // no shares are minted when funding fToken contract for rewards

        emit LogRebalance(assets_);
    }

    /// @inheritdoc IFTokenAdmin
    function updateRebalancer(address newRebalancer_) public validAddress(newRebalancer_) {
        _checkIsLendingFactoryAuth();

        _rebalancer = newRebalancer_;

        emit LogUpdateRebalancer(newRebalancer_);
    }

    /// @inheritdoc IFTokenAdmin
    function updateRates() public returns (uint256 tokenExchangePrice_, uint256 liquidityExchangePrice_) {
        liquidityExchangePrice_ = _getLiquidityExchangePrice();
        tokenExchangePrice_ = _updateRates(liquidityExchangePrice_, true);
    }

    /// @inheritdoc IFTokenAdmin
    //
    // @dev this contract never holds any funds:
    // -> deposited funds are directly sent to Liquidity.
    // -> rewards are also stored at Liquidity.
    function rescueFunds(address token_) external virtual nonReentrant {
        _checkIsLendingFactoryAuth();
        SafeTransfer.safeTransfer(address(token_), address(LIQUIDITY), IERC20(token_).balanceOf(address(this)));
        emit LogRescueFunds(token_);
    }
}

/// @notice fToken public executable actions: deposit, mint, mithdraw and redeem.
/// All actions are optionally also available with an additional param to limit the maximum slippage, e.g. maximum
/// assets used for minting x amount of shares.
abstract contract fTokenActions is fTokenCore, fTokenViews {
    /// @dev reverts if `amount_` is < `minAmountOut_`. Used to reduce bytecode size.
    function _revertIfBelowMinAmountOut(uint256 amount_, uint256 minAmountOut_) internal pure {
        if (amount_ < minAmountOut_) {
            revert FluidLendingError(ErrorTypes.fToken__MinAmountOut);
        }
    }

    /// @dev reverts if `amount_` is > `maxAmount_`. Used to reduce bytecode size.
    function _revertIfAboveMaxAmount(uint256 amount_, uint256 maxAmount_) internal pure {
        if (amount_ > maxAmount_) {
            revert FluidLendingError(ErrorTypes.fToken__MaxAmount);
        }
    }

    /*//////////////////////////////////////////////////////////////
                                DEPOSIT
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC4626
    /// @notice If `assets_` equals uint256.max then the whole balance of `msg.sender` is deposited.
    ///         `assets_` must at least be `minDeposit()` amount; reverts `fToken__DepositInsignificant()` if not.
    ///         Recommended to use `deposit()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return shares_ actually minted shares
    function deposit(
        uint256 assets_,
        address receiver_
    ) public virtual override nonReentrant returns (uint256 shares_) {
        if (assets_ == type(uint256).max) {
            assets_ = ASSET.balanceOf(msg.sender);
        }

        // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback`
        shares_ = _executeDeposit(assets_, receiver_, abi.encode(msg.sender));
    }

    /// @notice same as {fToken-deposit} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached
    function deposit(uint256 assets_, address receiver_, uint256 minAmountOut_) external returns (uint256 shares_) {
        shares_ = deposit(assets_, receiver_);
        _revertIfBelowMinAmountOut(shares_, minAmountOut_);
    }

    /*//////////////////////////////////////////////////////////////
                                   MINT 
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC4626
    /// @notice If `shares_` equals uint256.max then the whole balance of `msg.sender` is deposited.
    ///         `shares_` must at least be `minMint()` amount; reverts `fToken__DepositInsignificant()` if not.
    ///         Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount.
    ///         Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert.
    ///         Recommended to use `mint()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return assets_ deposited assets amount
    function mint(uint256 shares_, address receiver_) public virtual override nonReentrant returns (uint256 assets_) {
        if (shares_ == type(uint256).max) {
            assets_ = ASSET.balanceOf(msg.sender);
        } else {
            // No need to check for rounding error, previewMint rounds up.
            assets_ = previewMint(shares_);
        }

        // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback`

        _executeDeposit(assets_, receiver_, abi.encode(msg.sender));
    }

    /// @notice same as {fToken-mint} but with an additional setting for maximum assets input amount.
    /// reverts with `fToken__MaxAmount()` if `maxAssets_` of assets is surpassed to mint `shares_`.
    function mint(uint256 shares_, address receiver_, uint256 maxAssets_) external returns (uint256 assets_) {
        assets_ = mint(shares_, receiver_);
        _revertIfAboveMaxAmount(assets_, maxAssets_);
    }

    /*//////////////////////////////////////////////////////////////
                                WITHDRAW
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC4626
    /// @notice If `assets_` equals uint256.max then the whole fToken balance of `owner_` is withdrawn. This does not
    ///         consider withdrawal limit at Liquidity so best to check with `maxWithdraw()` before.
    ///         Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount.
    ///         Recommended to use `withdraw()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return shares_ burned shares
    function withdraw(
        uint256 assets_,
        address receiver_,
        address owner_
    ) public virtual override nonReentrant returns (uint256 shares_) {
        if (assets_ == type(uint256).max) {
            assets_ = previewRedeem(balanceOf(owner_));
        }
        shares_ = _executeWithdraw(assets_, receiver_, owner_);

        if (msg.sender != owner_) {
            _spendAllowance(owner_, msg.sender, shares_);
        }
    }

    /// @notice same as {fToken-withdraw} but with an additional setting for maximum shares burned.
    /// reverts with `fToken__MaxAmount()` if `maxSharesBurn_` of shares burned is surpassed.
    function withdraw(
        uint256 assets_,
        address receiver_,
        address owner_,
        uint256 maxSharesBurn_
    ) external returns (uint256 shares_) {
        shares_ = withdraw(assets_, receiver_, owner_);
        _revertIfAboveMaxAmount(shares_, maxSharesBurn_);
    }

    /*//////////////////////////////////////////////////////////////
                                REDEEM
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IERC4626
    /// @notice If `shares_` equals uint256.max then the whole balance of `owner_` is withdrawn.This does not
    ///         consider withdrawal limit at Liquidity so best to check with `maxRedeem()` before.
    ///         Recommended to use `withdraw()` over redeem because it is more gas efficient and can set specific amount.
    ///         Recommended to use `redeem()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return assets_ withdrawn assets amount
    function redeem(
        uint256 shares_,
        address receiver_,
        address owner_
    ) public virtual override nonReentrant returns (uint256 assets_) {
        if (shares_ == type(uint256).max) {
            shares_ = balanceOf(owner_);
        }

        assets_ = previewRedeem(shares_);

        uint256 burnedShares_ = _executeWithdraw(assets_, receiver_, owner_);

        if (msg.sender != owner_) {
            _spendAllowance(owner_, msg.sender, burnedShares_);
        }
    }

    /// @notice same as {fToken-redeem} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of assets is not reached.
    function redeem(
        uint256 shares_,
        address receiver_,
        address owner_,
        uint256 minAmountOut_
    ) external returns (uint256 assets_) {
        assets_ = redeem(shares_, receiver_, owner_);
        _revertIfBelowMinAmountOut(assets_, minAmountOut_);
    }
}

/// @notice fTokens support EIP-2612 permit approvals via signature so this contract implements
/// withdrawals (withdraw / redeem) with signature used for approval of the fToken shares.
abstract contract fTokenEIP2612Withdrawals is fTokenActions {
    /// @dev creates `sharesToPermit_` allowance for `owner_` via EIP2612 `deadline_` and `signature_`
    function _allowViaPermitEIP2612(
        address owner_,
        uint256 sharesToPermit_,
        uint256 deadline_,
        bytes calldata signature_
    ) internal {
        (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_);
        // spender = msg.sender
        permit(owner_, msg.sender, sharesToPermit_, deadline_, v_, r_, s_);
    }

    /// @notice withdraw amount of `assets_` with ERC-2612 permit signature for fToken approval.
    /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`.
    /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount.
    /// allowance via signature (`sharesToPermit_`) should cover `previewWithdraw(assets_)` plus a little buffer to avoid revert.
    /// Inherent trust assumption that `msg.sender` will set `receiver_` and `maxSharesBurn_` as `owner_` intends
    /// (which is always the case when giving allowance to some spender).
    /// @param sharesToPermit_ shares amount to use for EIP2612 permit(). Should cover `previewWithdraw(assets_)` + small buffer.
    /// @param assets_ amount of assets to withdraw
    /// @param receiver_ receiver of withdrawn assets
    /// @param owner_ owner to withdraw from (must be signature signer)
    /// @param maxSharesBurn_ maximum accepted amount of shares burned
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for ERC-2612 permit
    /// @return shares_ burned shares amount
    function withdrawWithSignature(
        uint256 sharesToPermit_,
        uint256 assets_,
        address receiver_,
        address owner_,
        uint256 maxSharesBurn_,
        uint256 deadline_,
        bytes calldata signature_
    ) external virtual nonReentrant returns (uint256 shares_) {
        if (msg.sender == owner_) {
            // no sense in operating with permit if msg.sender is owner. should call normal `withdraw()` instead.
            revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall);
        }

        // create allowance through signature_
        _allowViaPermitEIP2612(owner_, sharesToPermit_, deadline_, signature_);

        // execute withdraw to get shares_ to spend amount
        shares_ = _executeWithdraw(assets_, receiver_, owner_);

        _revertIfAboveMaxAmount(shares_, maxSharesBurn_);

        _spendAllowance(owner_, msg.sender, shares_);
    }

    /// @notice redeem amount of `shares_` with ERC-2612 permit signature for fToken approval.
    /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`.
    /// Note there might be tiny inaccuracies between requested `shares_` to redeem and actually burned shares.
    /// allowance via signature must cover `shares_` plus a tiny buffer.
    /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends
    ///       (which is always the case when giving allowance to some spender).
    /// Recommended to use `withdraw()` over redeem because it is more gas efficient and can set specific amount.
    /// @param shares_ amount of shares to redeem
    /// @param receiver_ receiver of withdrawn assets
    /// @param owner_ owner to withdraw from (must be signature signer)
    /// @param minAmountOut_ minimum accepted amount of assets withdrawn
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for ERC-2612 permit
    /// @return assets_ withdrawn assets amount
    function redeemWithSignature(
        uint256 shares_,
        address receiver_,
        address owner_,
        uint256 minAmountOut_,
        uint256 deadline_,
        bytes calldata signature_
    ) external virtual nonReentrant returns (uint256 assets_) {
        if (msg.sender == owner_) {
            // no sense in operating with permit if msg.sender is owner. should call normal `redeem()` instead.
            revert FluidLendingError(ErrorTypes.fToken__PermitFromOwnerCall);
        }

        assets_ = previewRedeem(shares_);
        _revertIfBelowMinAmountOut(assets_, minAmountOut_);

        // create allowance through signature_
        _allowViaPermitEIP2612(owner_, shares_, deadline_, signature_);

        // execute withdraw to get actual shares to spend amount
        uint256 sharesToSpend_ = _executeWithdraw(assets_, receiver_, owner_);

        _spendAllowance(owner_, msg.sender, sharesToSpend_);
    }
}

/// @notice implements fTokens support for deposit / mint via EIP-2612 permit.
/// @dev methods revert if underlying asset does not support EIP-2612.
abstract contract fTokenEIP2612Deposits is fTokenActions {
    /// @notice deposit `assets_` amount with EIP-2612 Permit2 signature for underlying asset approval.
    ///         IMPORTANT: This will revert if the underlying `asset()` does not support EIP-2612.
    ///         reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached.
    ///         `assets_` must at least be `minDeposit()` amount; reverts `fToken__DepositInsignificant()` if not.
    /// @param assets_ amount of assets to deposit
    /// @param receiver_ receiver of minted fToken shares
    /// @param minAmountOut_ minimum accepted amount of shares minted
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for EIP-2612 Permit
    /// @return shares_ amount of minted shares
    function depositWithSignatureEIP2612(
        uint256 assets_,
        address receiver_,
        uint256 minAmountOut_,
        uint256 deadline_,
        bytes calldata signature_
    ) external returns (uint256 shares_) {
        // create allowance through signature_ and spend it
        (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_);

        // EIP-2612 permit for underlying asset from owner (msg.sender) to spender (this contract)
        IERC20Permit(address(ASSET)).permit(msg.sender, address(this), assets_, deadline_, v_, r_, s_);

        // deposit() includes nonReentrant modifier which is enough to have from this point forward
        shares_ = deposit(assets_, receiver_);
        _revertIfBelowMinAmountOut(shares_, minAmountOut_);
    }

    /// @notice mint amount of `shares_` with EIP-2612 Permit signature for underlying asset approval.
    ///         IMPORTANT: This will revert if the underlying `asset()` does not support EIP-2612.
    ///         Signature should approve a little bit more than expected assets amount (`previewMint()`) to avoid reverts.
    ///         `shares_` must at least be `minMint()` amount; reverts with `fToken__DepositInsignificant()` if not.
    ///         Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount.
    ///         Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert.
    /// @param shares_ amount of shares to mint
    /// @param receiver_ receiver of minted fToken shares
    /// @param maxAssets_ maximum accepted amount of assets used as input to mint `shares_`
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for EIP-2612 Permit
    /// @return assets_ deposited assets amount
    function mintWithSignatureEIP2612(
        uint256 shares_,
        address receiver_,
        uint256 maxAssets_,
        uint256 deadline_,
        bytes calldata signature_
    ) external returns (uint256 assets_) {
        assets_ = previewMint(shares_);

        // create allowance through signature_ and spend it
        (uint8 v_, bytes32 r_, bytes32 s_) = _splitSignature(signature_);

        // EIP-2612 permit for underlying asset from owner (msg.sender) to spender (this contract)
        IERC20Permit(address(ASSET)).permit(msg.sender, address(this), assets_, deadline_, v_, r_, s_);

        // mint() includes nonReentrant modifier which is enough to have from this point forward
        assets_ = mint(shares_, receiver_);
        _revertIfAboveMaxAmount(assets_, maxAssets_);
    }
}

/// @notice implements fTokens support for deposit / mint via Permit2 signature.
abstract contract fTokenPermit2Deposits is fTokenActions {
    /// @inheritdoc IFToken
    function depositWithSignature(
        uint256 assets_,
        address receiver_,
        uint256 minAmountOut_,
        IAllowanceTransfer.PermitSingle calldata permit_,
        bytes calldata signature_
    ) external nonReentrant returns (uint256 shares_) {
        // give allowance to address(this) via Permit2 signature -> to spend allowance in LiquidityCallback
        // to transfer funds directly from msg.sender to liquidity
        PERMIT2.permit(
            // owner - Who signed the permit and also holds the tokens
            // @dev Note if this is modified to not be msg.sender, extra steps would be needed for security!
            // the caller could use this signature and deposit to the balance of receiver_, which could be set to any address,
            // because it is not included in the signature. Use permitWitnessTransferFrom in that case. Same for `minAmountOut_`.
            msg.sender,
            permit_, // permit message
            signature_ // packed signature of signing the EIP712 hash of `permit_`
        );

        // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback`

        shares_ = _executeDeposit(assets_, receiver_, abi.encode(true, msg.sender));
        _revertIfBelowMinAmountOut(shares_, minAmountOut_);
    }

    /// @inheritdoc IFToken
    function mintWithSignature(
        uint256 shares_,
        address receiver_,
        uint256 maxAssets_,
        IAllowanceTransfer.PermitSingle calldata permit_,
        bytes calldata signature_
    ) external nonReentrant returns (uint256 assets_) {
        assets_ = previewMint(shares_);
        _revertIfAboveMaxAmount(assets_, maxAssets_);

        // give allowance to address(this) via Permit2 PermitSingle. to spend allowance in LiquidityCallback
        // to transfer funds directly from msg.sender to liquidity
        PERMIT2.permit(
            // owner - Who signed the permit and also holds the tokens
            // @dev Note if this is modified to not be msg.sender, extra steps would be needed for security!
            // the caller could use this signature and deposit to the balance of receiver_, which could be set to any address,
            // because it is not included in the signature. Use permitWitnessTransferFrom in that case. Same for `minAmountOut_`.
            msg.sender,
            permit_, // permit message
            signature_ // packed signature of signing the EIP712 hash of `permit_`
        );

        // @dev transfer of tokens from `msg.sender` to liquidity contract happens via `liquidityCallback`

        _executeDeposit(assets_, receiver_, abi.encode(true, msg.sender));
    }
}

/// @title Fluid fToken (Lending with interest)
/// @notice fToken is a token that can be used to supply liquidity to the Fluid Liquidity pool and earn interest for doing so.
/// The fToken is backed by the underlying balance and can be redeemed for the underlying token at any time.
/// The interest is earned via Fluid Liquidity, e.g. because borrowers pay a borrow rate on it. In addition, fTokens may also
/// have active rewards going on that count towards the earned yield for fToken holders.
/// @dev The fToken implements the ERC20 and ERC4626 standard, which means it can be transferred, minted and burned.
/// The fToken supports EIP-2612 permit approvals via signature.
/// The fToken implements withdrawals via EIP-2612 permits and deposits with Permit2 or EIP-2612 (if underlying supports it) signatures.
/// fTokens are not upgradeable.
/// @dev For view methods / accessing data, use the "LendingResolver" periphery contract.
contract fToken is fTokenAdmin, fTokenActions, fTokenEIP2612Withdrawals, fTokenPermit2Deposits, fTokenEIP2612Deposits {
    /// @param liquidity_ liquidity contract address
    /// @param lendingFactory_ lending factory contract address
    /// @param asset_ underlying token address
    constructor(
        IFluidLiquidity liquidity_,
        IFluidLendingFactory lendingFactory_,
        IERC20 asset_
    ) Variables(liquidity_, lendingFactory_, asset_) {
        // set initial values for _liquidityExchangePrice, _tokenExchangePrice and _lastUpdateTimestamp
        _liquidityExchangePrice = uint64(_getLiquidityExchangePrice());
        _tokenExchangePrice = uint64(EXCHANGE_PRICES_PRECISION);
        _lastUpdateTimestamp = uint40(block.timestamp);
    }

    /// @inheritdoc IERC20Metadata
    function decimals() public view virtual override(ERC20, IERC20Metadata) returns (uint8) {
        return DECIMALS;
    }

    /// @inheritdoc IFToken
    function liquidityCallback(address token_, uint256 amount_, bytes calldata data_) external virtual override {
        if (msg.sender != address(LIQUIDITY) || token_ != address(ASSET) || _status != REENTRANCY_ENTERED) {
            // caller must be liquidity, token must match, and reentrancy status must be REENTRANCY_ENTERED
            revert FluidLendingError(ErrorTypes.fToken__Unauthorized);
        }

        // callback data can be a) an address only b) an address + transfer via permit2 flag set to true
        // for a) length will be 32, for b) length is 64
        if (data_.length == 32) {
            address from_ = abi.decode(data_, (address));

            // transfer `amount_` from `from_` (original deposit msg.sender) to liquidity contract
            SafeTransfer.safeTransferFrom(address(ASSET), from_, address(LIQUIDITY), amount_);
        } else {
            (bool isPermit2_, address from_) = abi.decode(data_, (bool, address));
            if (!isPermit2_) {
                // unexepcted liquidity callback data
                revert FluidLendingError(ErrorTypes.fToken__InvalidParams);
            }

            // transfer `amount_` from `from_` (original deposit msg.sender) to liquidity contract via PERMIT2
            PERMIT2.transferFrom(from_, address(LIQUIDITY), uint160(amount_), address(ASSET));
        }
    }
}

File 26 of 31 : variables.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";

import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol";
import { LiquiditySlotsLink } from "../../../libraries/liquiditySlotsLink.sol";
import { IFToken } from "../interfaces/iFToken.sol";
import { IAllowanceTransfer } from "../interfaces/permit2/iAllowanceTransfer.sol";
import { IFluidLendingRewardsRateModel  } from "../interfaces/iLendingRewardsRateModel.sol";
import { IFluidLendingFactory } from "../interfaces/iLendingFactory.sol";
import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol";
import { ErrorTypes } from "../errorTypes.sol";
import { Error } from "../error.sol";

abstract contract Constants {
    /// @dev permit2 contract, deployed to same address on EVM networks, see https://github.com/Uniswap/permit2
    IAllowanceTransfer internal constant PERMIT2 = IAllowanceTransfer(0x000000000022D473030F116dDEE9F6B43aC78BA3);

    /// @dev precision for exchange prices
    uint256 internal constant EXCHANGE_PRICES_PRECISION = 1e12;

    /// @dev Ignoring leap years
    uint256 internal constant SECONDS_PER_YEAR = 365 days;

    /// @dev max allowed reward rate is 50%
    uint256 internal constant MAX_REWARDS_RATE = 50 * 1e12; // 50%;

    /// @dev address of the Liquidity contract.
    IFluidLiquidity internal immutable LIQUIDITY;

    /// @dev address of the Lending factory contract.
    IFluidLendingFactory internal immutable LENDING_FACTORY;

    /// @dev address of the underlying asset contract.
    IERC20 internal immutable ASSET;

    /// @dev number of decimals for the fToken, same as ASSET
    uint8 internal immutable DECIMALS;

    /// @dev slot ids in Liquidity contract for underlying token.
    /// Helps in low gas fetch from liquidity contract by skipping delegate call with `readFromStorage`
    bytes32 internal immutable LIQUIDITY_EXCHANGE_PRICES_SLOT;
    bytes32 internal immutable LIQUIDITY_TOTAL_AMOUNTS_SLOT;
    bytes32 internal immutable LIQUIDITY_USER_SUPPLY_SLOT;

    /// @param liquidity_ liquidity contract address
    /// @param lendingFactory_ lending factory contract address
    /// @param asset_ underlying token address
    constructor(IFluidLiquidity liquidity_, IFluidLendingFactory lendingFactory_, IERC20 asset_) {
        DECIMALS = IERC20Metadata(address(asset_)).decimals();
        ASSET = asset_;
        LIQUIDITY = liquidity_;
        LENDING_FACTORY = lendingFactory_;

        LIQUIDITY_EXCHANGE_PRICES_SLOT = LiquiditySlotsLink.calculateMappingStorageSlot(
            LiquiditySlotsLink.LIQUIDITY_EXCHANGE_PRICES_MAPPING_SLOT,
            _getLiquiditySlotLinksAsset()
        );
        LIQUIDITY_TOTAL_AMOUNTS_SLOT = LiquiditySlotsLink.calculateMappingStorageSlot(
            LiquiditySlotsLink.LIQUIDITY_TOTAL_AMOUNTS_MAPPING_SLOT,
            _getLiquiditySlotLinksAsset()
        );
        LIQUIDITY_USER_SUPPLY_SLOT = LiquiditySlotsLink.calculateDoubleMappingStorageSlot(
            LiquiditySlotsLink.LIQUIDITY_USER_SUPPLY_DOUBLE_MAPPING_SLOT,
            address(this),
            _getLiquiditySlotLinksAsset()
        );
    }

    /// @dev gets asset address for liquidity slot links, extracted to separate method so it can be overridden if needed
    function _getLiquiditySlotLinksAsset() internal view virtual returns (address) {
        return address(ASSET);
    }
}

abstract contract Variables is ERC20, ERC20Permit, Error, Constants, IFToken {
    /// @dev prefix for token name. fToken will append the underlying asset name
    string private constant TOKEN_NAME_PREFIX = "Fluid ";
    /// @dev prefix for token symbol. fToken will append the underlying asset symbol
    string private constant TOKEN_SYMBOL_PREFIX = "f";

    // ------------ storage variables from inherited contracts come before vars here --------
    // _________ ERC20 _______________
    // ----------------------- slot 0 ---------------------------
    // mapping(address => uint256) private _balances;

    // ----------------------- slot 1 ---------------------------
    // mapping(address => mapping(address => uint256)) private _allowances;

    // ----------------------- slot 2 ---------------------------
    // uint256 private _totalSupply;

    // ----------------------- slot 3 ---------------------------
    // string private _name;
    // ----------------------- slot 4 ---------------------------
    // string private _symbol;

    // _________ ERC20Permit _______________
    // ----------------------- slot 5 ---------------------------
    // mapping(address => Counters.Counter) private _nonces;

    // ----------------------- slot 6 ---------------------------
    // bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    // ----------------------- slot 7 ---------------------------
    /// @dev address of the LendingRewardsRateModel.
    IFluidLendingRewardsRateModel  internal _rewardsRateModel;

    // -> 12 bytes empty
    uint96 private __placeholder_gap;

    // ----------------------- slot 8 ---------------------------
    // optimized to put all storage variables where a SSTORE happens on actions in the same storage slot

    /// @dev exchange price for the underlying assset in the liquidity protocol (without rewards)
    uint64 internal _liquidityExchangePrice; // in 1e12 -> (max value 18_446_744,073709551615)

    /// @dev exchange price between fToken and the underlying assset (with rewards)
    uint64 internal _tokenExchangePrice; // in 1e12 -> (max value 18_446_744,073709551615)

    /// @dev timestamp when exchange prices were updated the last time
    uint40 internal _lastUpdateTimestamp;

    /// @dev status for reentrancy guard
    uint8 internal _status;

    /// @dev flag to signal if rewards are active without having to read slot 6
    bool internal _rewardsActive;

    // 72 bits empty (9 bytes)

    // ----------------------- slot 9 ---------------------------
    /// @dev rebalancer address allowed to call `rebalance()` and source for funding rewards (ReserveContract).
    address internal _rebalancer;

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

    /// @param liquidity_ liquidity contract address
    /// @param lendingFactory_ lending factory contract address
    /// @param asset_ underlying token address
    constructor(
        IFluidLiquidity liquidity_,
        IFluidLendingFactory lendingFactory_,
        IERC20 asset_
    )
        validAddress(address(liquidity_))
        validAddress(address(lendingFactory_))
        validAddress(address(asset_))
        Constants(liquidity_, lendingFactory_, asset_)
        ERC20(
            string(abi.encodePacked(TOKEN_NAME_PREFIX, IERC20Metadata(address(asset_)).name())),
            string(abi.encodePacked(TOKEN_SYMBOL_PREFIX, IERC20Metadata(address(asset_)).symbol()))
        )
        ERC20Permit(string(abi.encodePacked(TOKEN_NAME_PREFIX, IERC20Metadata(address(asset_)).name())))
    {}

    /// @dev checks that address is not the zero address, reverts if so. Calling the method in the modifier reduces
    /// bytecode size as modifiers are inlined into bytecode
    function _checkValidAddress(address value_) internal pure {
        if (value_ == address(0)) {
            revert FluidLendingError(ErrorTypes.fToken__InvalidParams);
        }
    }

    /// @dev validates that an address is not the zero address
    modifier validAddress(address value_) {
        _checkValidAddress(value_);
        _;
    }
}

File 27 of 31 : iFToken.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";

import { IAllowanceTransfer } from "./permit2/iAllowanceTransfer.sol";
import { IFluidLendingRewardsRateModel } from "./iLendingRewardsRateModel.sol";
import { IFluidLendingFactory } from "./iLendingFactory.sol";
import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol";

interface IFTokenAdmin {
    /// @notice updates the rewards rate model contract.
    ///         Only callable by LendingFactory auths.
    /// @param rewardsRateModel_  the new rewards rate model contract address.
    ///                           can be set to address(0) to set no rewards (to save gas)
    function updateRewards(IFluidLendingRewardsRateModel rewardsRateModel_) external;

    /// @notice Balances out the difference between fToken supply at Liquidity vs totalAssets().
    ///         Deposits underlying from rebalancer address into Liquidity but doesn't mint any shares
    ///         -> thus making deposit available as rewards.
    ///         Only callable by rebalancer.
    /// @return assets_ amount deposited to Liquidity
    function rebalance() external payable returns (uint256 assets_);

    /// @notice gets the liquidity exchange price of the underlying asset, calculates the updated exchange price (with reward rates)
    ///         and writes those values to storage.
    ///         Callable by anyone.
    /// @return tokenExchangePrice_ exchange price of fToken share to underlying asset
    /// @return liquidityExchangePrice_ exchange price at Liquidity for the underlying asset
    function updateRates() external returns (uint256 tokenExchangePrice_, uint256 liquidityExchangePrice_);

    /// @notice sends any potentially stuck funds to Liquidity contract. Only callable by LendingFactory auths.
    function rescueFunds(address token_) external;

    /// @notice Updates the rebalancer address (ReserveContract). Only callable by LendingFactory auths.
    function updateRebalancer(address rebalancer_) external;
}

interface IFToken is IERC4626, IFTokenAdmin {
    /// @notice returns minimum amount required for deposit (rounded up)
    function minDeposit() external view returns (uint256);

    /// @notice returns config, rewards and exchange prices data in a single view method.
    /// @return liquidity_ address of the Liquidity contract.
    /// @return lendingFactory_ address of the Lending factory contract.
    /// @return lendingRewardsRateModel_ address of the rewards rate model contract. changeable by LendingFactory auths.
    /// @return permit2_ address of the Permit2 contract used for deposits / mint with signature
    /// @return rebalancer_ address of the rebalancer allowed to execute `rebalance()`
    /// @return rewardsActive_ true if rewards are currently active
    /// @return liquidityBalance_ current Liquidity supply balance of `address(this)` for the underyling asset
    /// @return liquidityExchangePrice_ (updated) exchange price for the underlying assset in the liquidity protocol (without rewards)
    /// @return tokenExchangePrice_ (updated) exchange price between fToken and the underlying assset (with rewards)
    function getData()
        external
        view
        returns (
            IFluidLiquidity liquidity_,
            IFluidLendingFactory lendingFactory_,
            IFluidLendingRewardsRateModel lendingRewardsRateModel_,
            IAllowanceTransfer permit2_,
            address rebalancer_,
            bool rewardsActive_,
            uint256 liquidityBalance_,
            uint256 liquidityExchangePrice_,
            uint256 tokenExchangePrice_
        );

    /// @notice transfers `amount_` of `token_` to liquidity. Only callable by liquidity contract.
    /// @dev this callback is used to optimize gas consumption (reducing necessary token transfers).
    function liquidityCallback(address token_, uint256 amount_, bytes calldata data_) external;

    /// @notice deposit `assets_` amount with Permit2 signature for underlying asset approval.
    ///         reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached.
    ///         `assets_` must at least be `minDeposit()` amount; reverts otherwise.
    /// @param assets_ amount of assets to deposit
    /// @param receiver_ receiver of minted fToken shares
    /// @param minAmountOut_ minimum accepted amount of shares minted
    /// @param permit_ Permit2 permit message
    /// @param signature_  packed signature of signing the EIP712 hash of `permit_`
    /// @return shares_ amount of minted shares
    function depositWithSignature(
        uint256 assets_,
        address receiver_,
        uint256 minAmountOut_,
        IAllowanceTransfer.PermitSingle calldata permit_,
        bytes calldata signature_
    ) external returns (uint256 shares_);

    /// @notice mint amount of `shares_` with Permit2 signature for underlying asset approval.
    ///         Signature should approve a little bit more than expected assets amount (`previewMint()`) to avoid reverts.
    ///         `shares_` must at least be `minMint()` amount; reverts otherwise.
    ///         Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount.
    ///         Recommended to use `deposit()` over mint because it is more gas efficient and less likely to revert.
    /// @param shares_ amount of shares to mint
    /// @param receiver_ receiver of minted fToken shares
    /// @param maxAssets_ maximum accepted amount of assets used as input to mint `shares_`
    /// @param permit_ Permit2 permit message
    /// @param signature_  packed signature of signing the EIP712 hash of `permit_`
    /// @return assets_ deposited assets amount
    function mintWithSignature(
        uint256 shares_,
        address receiver_,
        uint256 maxAssets_,
        IAllowanceTransfer.PermitSingle calldata permit_,
        bytes calldata signature_
    ) external returns (uint256 assets_);
}

interface IFTokenNativeUnderlying is IFToken {
    /// @notice address that is mapped to the chain native token at Liquidity
    function NATIVE_TOKEN_ADDRESS() external view returns (address);

    /// @notice deposits `msg.value` amount of native token for `receiver_`.
    ///         `msg.value` must be at least `minDeposit()` amount; reverts otherwise.
    ///         Recommended to use `depositNative()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return shares_ actually minted shares
    function depositNative(address receiver_) external payable returns (uint256 shares_);

    /// @notice same as {depositNative} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of shares is not reached
    function depositNative(address receiver_, uint256 minAmountOut_) external payable returns (uint256 shares_);

    /// @notice mints `shares_` for `receiver_`, paying with underlying native token.
    ///         `shares_` must at least be `minMint()` amount; reverts otherwise.
    ///         `shares_` set to type(uint256).max not supported.
    ///         Note there might be tiny inaccuracies between requested `shares_` and actually received shares amount.
    ///         Recommended to use `depositNative()` over mint because it is more gas efficient and less likely to revert.
    ///         Recommended to use `mintNative()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return assets_ deposited assets amount
    function mintNative(uint256 shares_, address receiver_) external payable returns (uint256 assets_);

    /// @notice same as {mintNative} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MaxAmount()` if `maxAssets_` of assets is surpassed to mint `shares_`.
    function mintNative(
        uint256 shares_,
        address receiver_,
        uint256 maxAssets_
    ) external payable returns (uint256 assets_);

    /// @notice withdraws `assets_` amount in native underlying to `receiver_`, burning shares of `owner_`.
    ///         If `assets_` equals uint256.max then the whole fToken balance of `owner_` is withdrawn.This does not
    ///         consider withdrawal limit at liquidity so best to check with `maxWithdraw()` before.
    ///         Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount.
    ///         Recommended to use `withdrawNative()` with a `maxSharesBurn_` param instead to set acceptable limit.
    /// @return shares_ burned shares
    function withdrawNative(uint256 assets_, address receiver_, address owner_) external returns (uint256 shares_);

    /// @notice same as {withdrawNative} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MaxAmount()` if `maxSharesBurn_` of shares burned is surpassed.
    function withdrawNative(
        uint256 assets_,
        address receiver_,
        address owner_,
        uint256 maxSharesBurn_
    ) external returns (uint256 shares_);

    /// @notice redeems `shares_` to native underlying to `receiver_`, burning shares of `owner_`.
    ///         If `shares_` equals uint256.max then the whole balance of `owner_` is withdrawn.This does not
    ///         consider withdrawal limit at liquidity so best to check with `maxRedeem()` before.
    ///         Recommended to use `withdrawNative()` over redeem because it is more gas efficient and can set specific amount.
    ///         Recommended to use `redeemNative()` with a `minAmountOut_` param instead to set acceptable limit.
    /// @return assets_ withdrawn assets amount
    function redeemNative(uint256 shares_, address receiver_, address owner_) external returns (uint256 assets_);

    /// @notice same as {redeemNative} but with an additional setting for minimum output amount.
    /// reverts with `fToken__MinAmountOut()` if `minAmountOut_` of assets is not reached.
    function redeemNative(
        uint256 shares_,
        address receiver_,
        address owner_,
        uint256 minAmountOut_
    ) external returns (uint256 assets_);

    /// @notice withdraw amount of `assets_` in native token with ERC-2612 permit signature for fToken approval.
    /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`.
    /// Note there might be tiny inaccuracies between requested `assets_` and actually received assets amount.
    /// allowance via signature should cover `previewWithdraw(assets_)` plus a little buffer to avoid revert.
    /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends
    /// (which is always the case when giving allowance to some spender).
    /// @param sharesToPermit_ shares amount to use for EIP2612 permit(). Should cover `previewWithdraw(assets_)` + small buffer.
    /// @param assets_ amount of assets to withdraw
    /// @param receiver_ receiver of withdrawn assets
    /// @param owner_ owner to withdraw from (must be signature signer)
    /// @param maxSharesBurn_ maximum accepted amount of shares burned
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for ERC-2612 permit
    /// @return shares_ burned shares amount
    function withdrawWithSignatureNative(
        uint256 sharesToPermit_,
        uint256 assets_,
        address receiver_,
        address owner_,
        uint256 maxSharesBurn_,
        uint256 deadline_,
        bytes calldata signature_
    ) external returns (uint256 shares_);

    /// @notice redeem amount of `shares_` as native token with ERC-2612 permit signature for fToken approval.
    /// `owner_` signs ERC-2612 permit `signature_` to give allowance of fTokens to `msg.sender`.
    /// Note there might be tiny inaccuracies between requested `shares_` to redeem and actually burned shares.
    /// allowance via signature must cover `shares_` plus a tiny buffer.
    /// Inherent trust assumption that `msg.sender` will set `receiver_` and `minAmountOut_` as `owner_` intends
    ///       (which is always the case when giving allowance to some spender).
    /// Recommended to use `withdrawNative()` over redeem because it is more gas efficient and can set specific amount.
    /// @param shares_ amount of shares to redeem
    /// @param receiver_ receiver of withdrawn assets
    /// @param owner_ owner to withdraw from (must be signature signer)
    /// @param minAmountOut_ minimum accepted amount of assets withdrawn
    /// @param deadline_ deadline for signature validity
    /// @param signature_  packed signature of signing the EIP712 hash for ERC-2612 permit
    /// @return assets_ withdrawn assets amount
    function redeemWithSignatureNative(
        uint256 shares_,
        address receiver_,
        address owner_,
        uint256 minAmountOut_,
        uint256 deadline_,
        bytes calldata signature_
    ) external returns (uint256 assets_);
}

File 28 of 31 : iLendingFactory.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IFluidLiquidity } from "../../../liquidity/interfaces/iLiquidity.sol";

interface IFluidLendingFactoryAdmin {
    /// @notice reads if a certain `auth_` address is an allowed auth or not. Owner is auth by default.
    function isAuth(address auth_) external view returns (bool);

    /// @notice              Sets an address as allowed auth or not. Only callable by owner.
    /// @param auth_         address to set auth value for
    /// @param allowed_      bool flag for whether address is allowed as auth or not
    function setAuth(address auth_, bool allowed_) external;

    /// @notice reads if a certain `deployer_` address is an allowed deployer or not. Owner is deployer by default.
    function isDeployer(address deployer_) external view returns (bool);

    /// @notice              Sets an address as allowed deployer or not. Only callable by owner.
    /// @param deployer_     address to set deployer value for
    /// @param allowed_      bool flag for whether address is allowed as deployer or not
    function setDeployer(address deployer_, bool allowed_) external;

    /// @notice              Sets the `creationCode_` bytecode for a certain `fTokenType_`. Only callable by auths.
    /// @param fTokenType_   the fToken Type used to refer the creation code
    /// @param creationCode_ contract creation code. can be set to bytes(0) to remove a previously available `fTokenType_`
    function setFTokenCreationCode(string memory fTokenType_, bytes calldata creationCode_) external;

    /// @notice creates token for `asset_` for a lending protocol with interest. Only callable by deployers.
    /// @param  asset_              address of the asset
    /// @param  fTokenType_         type of fToken:
    /// - if it's the native token, it should use `NativeUnderlying`
    /// - otherwise it should use `fToken`
    /// - could be more types available, check `fTokenTypes()`
    /// @param  isNativeUnderlying_ flag to signal fToken type that uses native underlying at Liquidity
    /// @return token_              address of the created token
    function createToken(
        address asset_,
        string calldata fTokenType_,
        bool isNativeUnderlying_
    ) external returns (address token_);
}

interface IFluidLendingFactory is IFluidLendingFactoryAdmin {
    /// @notice list of all created tokens
    function allTokens() external view returns (address[] memory);

    /// @notice list of all fToken types that can be deployed
    function fTokenTypes() external view returns (string[] memory);

    /// @notice returns the creation code for a certain `fTokenType_`
    function fTokenCreationCode(string memory fTokenType_) external view returns (bytes memory);

    /// @notice address of the Liquidity contract.
    function LIQUIDITY() external view returns (IFluidLiquidity);

    /// @notice computes deterministic token address for `asset_` for a lending protocol
    /// @param  asset_      address of the asset
    /// @param  fTokenType_         type of fToken:
    /// - if it's the native token, it should use `NativeUnderlying`
    /// - otherwise it should use `fToken`
    /// - could be more types available, check `fTokenTypes()`
    /// @return token_      detemrinistic address of the computed token
    function computeToken(address asset_, string calldata fTokenType_) external view returns (address token_);
}

File 29 of 31 : iLendingRewardsRateModel.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IFluidLendingRewardsRateModel {
    /// @notice Calculates the current rewards rate (APR)
    /// @param totalAssets_ amount of assets in the lending
    /// @return rate_ rewards rate percentage per year with 1e12 RATE_PRECISION, e.g. 1e12 = 1%, 1e14 = 100%
    /// @return ended_ flag to signal that rewards have ended (always 0 going forward)
    /// @return startTime_ start time of rewards to compare against last update timestamp
    function getRate(uint256 totalAssets_) external view returns (uint256 rate_, bool ended_, uint256 startTime_);

    /// @notice Returns config constants for rewards rate model
    function getConfig()
        external
        view
        returns (
            uint256 duration_,
            uint256 startTime_,
            uint256 endTime_,
            uint256 startTvl_,
            uint256 maxRate_,
            uint256 rewardAmount_,
            address initiator_
        );
}

File 30 of 31 : iAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
/// from https://github.com/Uniswap/permit2/blob/main/src/interfaces/ISignatureTransfer.sol.
/// Copyright (c) 2022 Uniswap Labs
interface IAllowanceTransfer {
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Thrown when an allowance on a token has expired.
    /// @param deadline The timestamp at which the allowed amount is no longer valid
    error AllowanceExpired(uint256 deadline);

    /// @notice Thrown when an allowance on a token has been depleted.
    /// @param amount The maximum amount allowed
    error InsufficientAllowance(uint256 amount);

    /// @notice Thrown when too many nonces are invalidated.
    error ExcessiveInvalidation();

    /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
    event NonceInvalidation(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint48 newNonce,
        uint48 oldNonce
    );

    /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
    event Approval(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint160 amount,
        uint48 expiration
    );

    /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
    event Permit(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint160 amount,
        uint48 expiration,
        uint48 nonce
    );

    /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
    event Lockdown(address indexed owner, address token, address spender);

    /// @notice The permit data for a token
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice The permit message signed for a single token allownce
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The permit message signed for multiple token allowances
    struct PermitBatch {
        // the permit data for multiple token allowances
        PermitDetails[] details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The saved permissions
    /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice A token spender pair.
    struct TokenSpenderPair {
        // the token the spender is approved
        address token;
        // the spender address
        address spender;
    }

    /// @notice Details for a token transfer.
    struct AllowanceTransferDetails {
        // the owner of the token
        address from;
        // the recipient of the token
        address to;
        // the amount of the token
        uint160 amount;
        // the token to be transferred
        address token;
    }

    /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
    /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
    /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
    function allowance(
        address user,
        address token,
        address spender
    ) external view returns (uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Approves the spender to use up to amount of the specified token up until the expiration
    /// @param token The token to approve
    /// @param spender The spender address to approve
    /// @param amount The approved amount of the token
    /// @param expiration The timestamp at which the approval is no longer valid
    /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitSingle Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitBatch Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;

    /// @notice Transfer approved tokens from one address to another
    /// @param from The address to transfer from
    /// @param to The address of the recipient
    /// @param amount The amount of the token to transfer
    /// @param token The token address to transfer
    /// @dev Requires the from address to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(address from, address to, uint160 amount, address token) external;

    /// @notice Transfer approved tokens in a batch
    /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
    /// @dev Requires the from addresses to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;

    /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
    /// by batch revoking approvals
    /// @param approvals Array of approvals to revoke.
    function lockdown(TokenSpenderPair[] calldata approvals) external;

    /// @notice Invalidate nonces for a given (token, spender) pair
    /// @param token The token to invalidate nonces for
    /// @param spender The spender to invalidate nonces for
    /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
    /// @dev Can't invalidate more than 2**16 nonces per transaction.
    function invalidateNonces(address token, address spender, uint48 newNonce) external;
}

File 31 of 31 : FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

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

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

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

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

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            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.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, 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(y, 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
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

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

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IFluidLiquidity","name":"liquidity_","type":"address"},{"internalType":"contract IFluidLendingFactory","name":"lendingFactory_","type":"address"},{"internalType":"contract IERC20","name":"asset_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidLendingError","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidLiquidityCalcsError","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorId_","type":"uint256"}],"name":"FluidSafeTransferError","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"LogRebalance","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"LogRescueFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenExchangePrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"liquidityExchangePrice","type":"uint256"}],"name":"LogUpdateRates","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rebalancer","type":"address"}],"name":"LogUpdateRebalancer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IFluidLendingRewardsRateModel","name":"rewardsRateModel","type":"address"}],"name":"LogUpdateRewards","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":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"components":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint160","name":"amount","type":"uint160"},{"internalType":"uint48","name":"expiration","type":"uint48"},{"internalType":"uint48","name":"nonce","type":"uint48"}],"internalType":"struct IAllowanceTransfer.PermitDetails","name":"details","type":"tuple"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"sigDeadline","type":"uint256"}],"internalType":"struct IAllowanceTransfer.PermitSingle","name":"permit_","type":"tuple"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"depositWithSignature","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"depositWithSignatureEIP2612","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getData","outputs":[{"internalType":"contract IFluidLiquidity","name":"liquidity_","type":"address"},{"internalType":"contract IFluidLendingFactory","name":"lendingFactory_","type":"address"},{"internalType":"contract IFluidLendingRewardsRateModel","name":"lendingRewardsRateModel_","type":"address"},{"internalType":"contract IAllowanceTransfer","name":"permit2_","type":"address"},{"internalType":"address","name":"rebalancer_","type":"address"},{"internalType":"bool","name":"rewardsActive_","type":"bool"},{"internalType":"uint256","name":"liquidityBalance_","type":"uint256"},{"internalType":"uint256","name":"liquidityExchangePrice_","type":"uint256"},{"internalType":"uint256","name":"tokenExchangePrice_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"},{"internalType":"bytes","name":"data_","type":"bytes"}],"name":"liquidityCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner_","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner_","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"},{"components":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint160","name":"amount","type":"uint160"},{"internalType":"uint48","name":"expiration","type":"uint48"},{"internalType":"uint48","name":"nonce","type":"uint48"}],"internalType":"struct IAllowanceTransfer.PermitDetails","name":"details","type":"tuple"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"sigDeadline","type":"uint256"}],"internalType":"struct IAllowanceTransfer.PermitSingle","name":"permit_","type":"tuple"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"mintWithSignature","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"uint256","name":"maxAssets_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"mintWithSignatureEIP2612","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","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":"","type":"uint256"}],"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":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rebalance","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"minAmountOut_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"redeemWithSignature","outputs":[{"internalType":"uint256","name":"assets_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"}],"name":"rescueFunds","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":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"updateRates","outputs":[{"internalType":"uint256","name":"tokenExchangePrice_","type":"uint256"},{"internalType":"uint256","name":"liquidityExchangePrice_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newRebalancer_","type":"address"}],"name":"updateRebalancer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IFluidLendingRewardsRateModel","name":"rewardsRateModel_","type":"address"}],"name":"updateRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"sharesToPermit_","type":"uint256"},{"internalType":"uint256","name":"assets_","type":"uint256"},{"internalType":"address","name":"receiver_","type":"address"},{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"maxSharesBurn_","type":"uint256"},{"internalType":"uint256","name":"deadline_","type":"uint256"},{"internalType":"bytes","name":"signature_","type":"bytes"}],"name":"withdrawWithSignature","outputs":[{"internalType":"uint256","name":"shares_","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

6102206040523480156200001257600080fd5b5060405162005905380380620059058339810160408190526200003591620007ec565b82828282828260405180604001604052806006815260200165023363ab4b2160d51b815250846001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa15801562000099573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052620000c391908101906200087c565b604051602001620000d692919062000934565b60405160208183030381529060405280604051806040016040528060018152602001603160f81b81525060405180604001604052806006815260200165023363ab4b2160d51b815250876001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156200015e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200018891908101906200087c565b6040516020016200019b92919062000934565b604051602081830303815290604052604051806040016040528060018152602001603360f91b815250886001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801562000203573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200022d91908101906200087c565b6040516020016200024092919062000934565b60408051601f1981840301815291905260036200025e8382620009f0565b5060046200026d8282620009f0565b5050825160208085019190912083518483012060e08290526101008190524660a0818152604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81880181905281830187905260608201869052608082019490945230818401528151808203909301835260c0019052805194019390932091935091906080523060c0526101205250506040805163313ce56760e01b815290516001600160a01b038616945063313ce5679350600480830193506020928290030181865afa15801562000346573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200036c919062000abc565b60ff166101a0526001600160a01b038082166101805283811661014052821661016052620003dd6005620003a06101805190565b604080516001600160a01b038316602082015290810183905260009060600160405160208183030381529060405280519060200120905092915050565b6101c052620003f26007620003a06101805190565b6101e05262000468600830620004086101805190565b604080516001600160a01b039384166020808301919091528183019590955281518082038301815260608201835280519086012092909316608084015260a0808401929092528051808403909201825260c0909201909152805191012090565b61020052508491506200047d9050816200050f565b8262000489816200050f565b8262000495816200050f565b50506008805460ff60a81b1916600160a81b17905550620004ba925050620005439050565b600880546001600160401b03929092166001600160801b0319909216919091176ce8d4a5100000000000000000001764ffffffffff60801b1916600160801b4264ffffffffff16021790555062000b18915050565b6001600160a01b038116620005405760405163694bda1d60e01b8152614e2460048201526024015b60405180910390fd5b50565b6000620005c8610140516001600160a01b031663b5c736e46101c0516040518263ffffffff1660e01b81526004016200057e91815260200190565b602060405180830381865afa1580156200059c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620005c2919062000ae8565b620005ce565b50919050565b6001600160401b03605b82901c811690609b83901c16811580620005f0575080155b156200061557604051636a86ba8960e11b815262011171600482015260240162000537565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff1691148062000640575082155b806200064c5750806001145b156200065a57505050915091565b64496cebb80084840283020484019350617fff60db87901c169250826001036200068657505050915091565b82600116600103620006e05760019290921c91826c7e37be2022c0914b268000000081620006b857620006b862000b02565b049250612710601e87901c613fff166b033b2e3c9fd0803ce80000008501020492506200070d565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b80600116600103620007495760011c61271081016b033b2e3c9fd0803ce800000082028162000740576200074062000b02565b04905062000782565b60011c61271081016b033b2e3c9fd0803ce800000082028162000770576200077062000b02565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b6001600160a01b03811681146200054057600080fd5b6000806000606084860312156200080257600080fd5b83516200080f81620007d6565b60208501519093506200082281620007d6565b60408501519092506200083581620007d6565b809150509250925092565b634e487b7160e01b600052604160045260246000fd5b60005b838110156200087357818101518382015260200162000859565b50506000910152565b6000602082840312156200088f57600080fd5b81516001600160401b0380821115620008a757600080fd5b818401915084601f830112620008bc57600080fd5b815181811115620008d157620008d162000840565b604051601f8201601f19908116603f01168101908382118183101715620008fc57620008fc62000840565b816040528281528760208487010111156200091657600080fd5b6200092983602083016020880162000856565b979650505050505050565b600083516200094881846020880162000856565b8351908301906200095e81836020880162000856565b01949350505050565b600181811c908216806200097c57607f821691505b602082108103620005c857634e487b7160e01b600052602260045260246000fd5b601f821115620009eb57600081815260208120601f850160051c81016020861015620009c65750805b601f850160051c820191505b81811015620009e757828155600101620009d2565b5050505b505050565b81516001600160401b0381111562000a0c5762000a0c62000840565b62000a248162000a1d845462000967565b846200099d565b602080601f83116001811462000a5c576000841562000a435750858301515b600019600386901b1c1916600185901b178555620009e7565b600085815260208120601f198616915b8281101562000a8d5788860151825594840194600190910190840162000a6c565b508582101562000aac5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60006020828403121562000acf57600080fd5b815160ff8116811462000ae157600080fd5b9392505050565b60006020828403121562000afb57600080fd5b5051919050565b634e487b7160e01b600052601260045260246000fd5b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e05161020051614ca162000c6460003960008181612de8015261365a015260008181610e290152610f6d0152600061245a0152600061041b01526000818161048101528181610d82015281816113690152818161184701528181611aa301528181611b7501528181611c85015281816122660152818161347e01528181613d000152614025015260008181610c07015261325d015260008181610be501528181610e7301528181610fb001528181611a7901528181611b9701528181611c550152818161231c0152818161249c01528181612dac015281816134420152818161369a01528181613cc40152613ffa01526000612cfc01526000612d4b01526000612d2601526000612c7f01526000612ca901526000612cd30152614ca16000f3fe6080604052600436106103135760003560e01c80637ecebe001161019a578063b460af94116100e1578063d505accf1161008a578063e083be2211610064578063e083be221461099e578063e53b2017146109be578063ef8b30f7146109de57600080fd5b8063d505accf1461090b578063d905777e1461092b578063dd62ed3e1461094b57600080fd5b8063c63d75b6116100bb578063c63d75b6146108ab578063c6e6f592146108cb578063ce96cb77146108eb57600080fd5b8063b460af941461084b578063ba0876521461086b578063bc157ac11461088b57600080fd5b8063a318c1a411610143578063ad2075011161011d578063ad207501146107eb578063b046a4491461080b578063b3d7f6b91461082b57600080fd5b8063a318c1a41461078b578063a457c2d7146107ab578063a9059cbb146107cb57600080fd5b806394bf804d1161017457806394bf804d1461073657806395d89b41146107565780639f40a7b31461076b57600080fd5b80637ecebe00146106d6578063836a1040146106f65780638c87483a1461071657600080fd5b80633c3821f41161025e5780635fd619651161020757806370a08231116101e157806370a082311461066b578063740c955e146106ae5780637d7c2a1c146106ce57600080fd5b80635fd6196514610609578063635c31c21461062b5780636e553f651461064b57600080fd5b806341b3d1851161023857806341b3d185146105b45780634cdad506146105c957806350cc0f8f146105e957600080fd5b80633c3821f41461054a5780633f4c093014610574578063402d267d1461059457600080fd5b806323b872dd116102c057806338d52e0f1161029a57806338d52e0f1461045a57806339509351146104ab5780633bc5de30146104cb57600080fd5b806323b872dd146103e7578063313ce567146104075780633644e5151461044557600080fd5b8063095ea7b3116102f1578063095ea7b3146103825780630a28a477146103b257806318160ddd146103d257600080fd5b806301e1d1141461031857806306fdde031461034057806307a2d13a14610362575b600080fd5b34801561032457600080fd5b5061032d6109fe565b6040519081526020015b60405180910390f35b34801561034c57600080fd5b50610355610a3d565b6040516103379190614398565b34801561036e57600080fd5b5061032d61037d3660046143ab565b610acf565b34801561038e57600080fd5b506103a261039d3660046143e6565b610af7565b6040519015158152602001610337565b3480156103be57600080fd5b5061032d6103cd3660046143ab565b610b11565b3480156103de57600080fd5b5060025461032d565b3480156103f357600080fd5b506103a2610402366004614412565b610b32565b34801561041357600080fd5b5060405160ff7f0000000000000000000000000000000000000000000000000000000000000000168152602001610337565b34801561045157600080fd5b5061032d610b56565b34801561046657600080fd5b5060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152602001610337565b3480156104b757600080fd5b506103a26104c63660046143e6565b610b65565b3480156104d757600080fd5b506104e0610bb1565b6040805173ffffffffffffffffffffffffffffffffffffffff9a8b168152988a1660208a0152968916968801969096529387166060870152959091166080850152151560a084015260c083019390935260e082019290925261010081019190915261012001610337565b34801561055657600080fd5b5061055f610c9d565b60408051928352602083019190915201610337565b34801561058057600080fd5b5061032d61058f36600461449c565b610cbb565b3480156105a057600080fd5b5061032d6105af36600461450f565b610e01565b3480156105c057600080fd5b5061032d610f45565b3480156105d557600080fd5b5061032d6105e43660046143ab565b611046565b3480156105f557600080fd5b5061032d61060436600461452c565b611051565b34801561061557600080fd5b5061062961062436600461450f565b61112e565b005b34801561063757600080fd5b5061032d6106463660046145bb565b6111f4565b34801561065757600080fd5b5061032d610666366004614643565b61130a565b34801561067757600080fd5b5061032d61068636600461450f565b73ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b3480156106ba57600080fd5b5061032d6106c9366004614673565b61144b565b61032d611530565b3480156106e257600080fd5b5061032d6106f136600461450f565b611695565b34801561070257600080fd5b5061032d6107113660046146f9565b6116c0565b34801561072257600080fd5b5061032d6107313660046145bb565b6116d8565b34801561074257600080fd5b5061032d610751366004614643565b6117e8565b34801561076257600080fd5b50610355611939565b34801561077757600080fd5b5061032d610786366004614720565b611948565b34801561079757600080fd5b5061032d6107a6366004614720565b611969565b3480156107b757600080fd5b506103a26107c63660046143e6565b611982565b3480156107d757600080fd5b506103a26107e63660046143e6565b611a53565b3480156107f757600080fd5b50610629610806366004614768565b611a61565b34801561081757600080fd5b5061062961082636600461450f565b611cff565b34801561083757600080fd5b5061032d6108463660046143ab565b611d81565b34801561085757600080fd5b5061032d6108663660046147c4565b611da2565b34801561087757600080fd5b5061032d6108863660046147c4565b611e3a565b34801561089757600080fd5b5061032d6108a63660046146f9565b611f1e565b3480156108b757600080fd5b5061032d6108c636600461450f565b611f36565b3480156108d757600080fd5b5061032d6108e63660046143ab565b611f45565b3480156108f757600080fd5b5061032d61090636600461450f565b611f66565b34801561091757600080fd5b50610629610926366004614806565b611fba565b34801561093757600080fd5b5061032d61094636600461450f565b61216d565b34801561095757600080fd5b5061032d61096636600461487d565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260016020908152604080832093909416825291909152205490565b3480156109aa57600080fd5b5061032d6109b936600461449c565b6121ab565b3480156109ca57600080fd5b506106296109d936600461450f565b6122d8565b3480156109ea57600080fd5b5061032d6109f93660046143ab565b612427565b600080610a11610a0c612432565b612512565b50905064e8d4a51000610a2360025490565b610a2d90836148da565b610a379190614920565b91505090565b606060038054610a4c9061495b565b80601f0160208091040260200160405190810160405280929190818152602001828054610a789061495b565b8015610ac55780601f10610a9a57610100808354040283529160200191610ac5565b820191906000526020600020905b815481529060010190602001808311610aa857829003601f168201915b5050505050905090565b600080610add610a0c612432565b509050610af0838264e8d4a510006126f2565b9392505050565b600033610b0581858561272e565b60019150505b92915050565b600080610b1f610a0c612432565b509050610af08364e8d4a51000836128e1565b600033610b40858285612925565b610b4b8585856129f6565b506001949350505050565b6000610b60612c65565b905090565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168452909152812054909190610b059082908690610bac9087906149a8565b61272e565b6000806000806000806000806000610bc7612432565b91506000610bd483612512565b6007546009546008549395509193507f0000000000000000000000000000000000000000000000000000000000000000927f00000000000000000000000000000000000000000000000000000000000000009273ffffffffffffffffffffffffffffffffffffffff928316926e22d473030f116ddee9f6b43ac78ba392911690760100000000000000000000000000000000000000000000900460ff168015610c7b575085155b610c83612d99565b995099509950995099509950995050909192939495969798565b600080610ca8612432565b9050610cb5816001612e9d565b91509091565b6000610cc687611d81565b90506000806000610d0c86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b6040517fd505accf00000000000000000000000000000000000000000000000000000000815233600482015230602482015260448101889052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063d505accf9060e401600060405180830381600087803b158015610dc657600080fd5b505af1158015610dda573d6000803e3d6000fd5b50505050610de88a8a6117e8565b9350610df48489613046565b5050509695505050505050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819067ffffffffffffffff9073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa158015610eba573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ede91906149bb565b16600881901c60ff9091161b905064e8d4a51000610efa612432565b820281610f0957610f096148f1565b0490506f7fffffffffffff7fffffffffffffffff811115610f2d5750600092915050565b6f7fffffffffffffffffffffffffffffff0392915050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819060ff9073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa158015610ff7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101b91906149bb565b166001901b9050600061102e6001611d81565b905080821161103d578061103f565b815b9250505090565b6000610b0b82610acf565b600061105b613088565b73ffffffffffffffffffffffffffffffffffffffff861633036110b3576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2660048201526024015b60405180910390fd5b6110c0868a868686613126565b6110cb888888613189565b90506110d78186613046565b6110e2863383612925565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905598975050505050505050565b61113661322f565b61113e610c9d565b5050600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8316908117909155600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff16821515760100000000000000000000000000000000000000000000021790556040517fd14b198a72267efb36b8bbc193eb6d52a00d1f61799029250f6a520ad47be82d90600090a250565b60006111fe613088565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b5709061124f903390889088908890600401614a38565b600060405180830381600087803b15801561126957600080fd5b505af115801561127d573d6000803e3d6000fd5b5050604080516001602082015233918101919091526112b4925089915088906060015b604051602081830303815290604052613319565b90506112c08186613400565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b6000611314613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036113ec576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa1580156113c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e991906149bb565b92505b604080513360208201526114049185918591016112a0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b6000611455613088565b73ffffffffffffffffffffffffffffffffffffffff861633036114a8576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2660048201526024016110aa565b6114b188611046565b90506114bd8186613400565b6114ca8689868686613126565b60006114d7828989613189565b90506114e4873383612925565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055979650505050505050565b600061153a613088565b60095473ffffffffffffffffffffffffffffffffffffffff16331461158f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2960048201526024016110aa565b34156115cb576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2a60048201526024016110aa565b6115d3612d99565b6115db6109fe565b6115e59190614af2565b604080513360208201529192506000916116109184910160405160208183030381529060405261343e565b905061161d816001612e9d565b506040518281527fe97ad8b810ae9d9e29aa69dc04d4ac2e3e71d65307830ccb97c8f876dfc439319060200160405180910390a150600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905590565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040812054610b0b565b60006116cc84846117e8565b9050610af08183613046565b60006116e2613088565b6116eb87611d81565b90506116f78186613046565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b57090611748903390889088908890600401614a38565b600060405180830381600087803b15801561176257600080fd5b505af1158015611776573d6000803e3d6000fd5b50506040805160016020820152339181019190915261179d925083915088906060016112a0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b60006117f2613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036118ce576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa1580156118a3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c791906149bb565b90506118da565b6118d783611d81565b90505b604080513360208201526118f29183918591016112a0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b606060048054610a4c9061495b565b6000611955858585611e3a565b90506119618183613400565b949350505050565b6000611976858585611da2565b90506119618183613046565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8716845290915281205490919083811015611a46576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f00000000000000000000000000000000000000000000000000000060648201526084016110aa565b610b4b828686840361272e565b600033610b058185856129f6565b3373ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016141580611af257507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b80611b1c57506008547501000000000000000000000000000000000000000000900460ff16600214155b15611b57576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2560048201526024016110aa565b6020819003611bc2576000611b6e8284018461450f565b9050611bbc7f0000000000000000000000000000000000000000000000000000000000000000827f000000000000000000000000000000000000000000000000000000000000000087613517565b50611cf9565b600080611bd183850185614b13565b9150915081611c10576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2460048201526024016110aa565b6040517f36c7851600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff80831660048301527f00000000000000000000000000000000000000000000000000000000000000008116602483015280871660448301527f00000000000000000000000000000000000000000000000000000000000000001660648201526e22d473030f116ddee9f6b43ac78ba3906336c7851690608401600060405180830381600087803b158015611cde57600080fd5b505af1158015611cf2573d6000803e3d6000fd5b5050505050505b50505050565b80611d09816135de565b611d1161322f565b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091556040517fdb94ee7fd8b5bbf8f6d59e76731ff4b4f5a02ab3af1d3e0c774862cf96ff613b90600090a25050565b600080611d8f610a0c612432565b509050610af0838264e8d4a510006128e1565b6000611dac613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611e0557611e026105e48373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b93505b611e10848484613189565b90503373ffffffffffffffffffffffffffffffffffffffff83161461140457611404823383612925565b6000611e44613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611e945773ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205493505b611e9d84611046565b90506000611eac828585613189565b90503373ffffffffffffffffffffffffffffffffffffffff841614611ed657611ed6833383612925565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b6000611f2a848461130a565b9050610af08183613400565b6000610b0b6108e66000610e01565b600080611f53610a0c612432565b509050610af08364e8d4a51000836126f2565b600080611f71613632565b90506000611fa461037d8573ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b9050808210611fb35780611961565b5092915050565b83421115612024576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e6500000060448201526064016110aa565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886120538c613786565b60408051602081019690965273ffffffffffffffffffffffffffffffffffffffff94851690860152929091166060840152608083015260a082015260c0810186905260e00160405160208183030381529060405280519060200120905060006120bb826137b9565b905060006120cb82878787613822565b90508973ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614612162576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e6174757265000060448201526064016110aa565b611cf28a8a8a61272e565b60008061217b6108e6613632565b90506000611fa48473ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b6000806000806121f086868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b6040517fd505accf000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018e9052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063d505accf9060e401600060405180830381600087803b1580156122aa57600080fd5b505af11580156122be573d6000803e3d6000fd5b505050506122cc8a8a61130a565b9350610df48489613400565b6122e0613088565b6122e861322f565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526123a39082907f00000000000000000000000000000000000000000000000000000000000000009073ffffffffffffffffffffffffffffffffffffffff8316906370a0823190602401602060405180830381865afa15801561237a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061239e91906149bb565b61384a565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fdff2a3947bcf9fc0807b142e7c8497066db9183428b7bdbfb1fcd0f55c27a3df90600090a250600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055565b6000610b0b82611f45565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f0000000000000000000000000000000000000000000000000000000000000000600482015260009061250c9073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa1580156124e3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061250791906149bb565b6138ee565b50919050565b600854600090819067ffffffffffffffff6801000000000000000082048116911680851015612571576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2b60048201526024016110aa565b600854600090760100000000000000000000000000000000000000000000900460ff16156126a857600754600090819073ffffffffffffffffffffffffffffffffffffffff16635776409464e8d4a510006125cb60025490565b6125d590896148da565b6125df9190614920565b6040518263ffffffff1660e01b81526004016125fd91815260200190565b606060405180830381865afa15801561261a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061263e9190614b31565b9097509092509050652d79883d20008211806126575750855b1561266157600091505b600854700100000000000000000000000000000000900464ffffffffff168181101561268a5750805b6301e133808142038402816126a1576126a16148f1565b0493505050505b81828703655af3107a400002816126c1576126c16148f1565b0401655af3107a40006126d482856148da565b6126de9190614920565b6126e890846149a8565b9450505050915091565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048411830215820261272757600080fd5b5091020490565b73ffffffffffffffffffffffffffffffffffffffff83166127d0576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f726573730000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff8216612873576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f737300000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048411830215820261291657600080fd5b50910281810615159190040190565b73ffffffffffffffffffffffffffffffffffffffff8381166000908152600160209081526040808320938616835292905220547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114611cf957818110156129e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016110aa565b611cf9848484840361272e565b73ffffffffffffffffffffffffffffffffffffffff8316612a99576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f647265737300000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff8216612b3c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f657373000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604090205481811015612bf2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e6365000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3611cf9565b60003073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016148015612ccb57507f000000000000000000000000000000000000000000000000000000000000000046145b15612cf557507f000000000000000000000000000000000000000000000000000000000000000090565b50604080517f00000000000000000000000000000000000000000000000000000000000000006020808301919091527f0000000000000000000000000000000000000000000000000000000000000000828401527f000000000000000000000000000000000000000000000000000000000000000060608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b600080612e7767ffffffffffffffff60017f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b5c736e47f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b8152600401612e2591815260200190565b602060405180830381865afa158015612e42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6691906149bb565b901c16600860ff9082901c91161b90565b905064e8d4a51000612e87612432565b820281612e9657612e966148f1565b0491505090565b600080612ea984612512565b6008549193509150760100000000000000000000000000000000000000000000900460ff1680612ed65750825b15612fe25767ffffffffffffffff821115612f21576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2860048201526024016110aa565b6008805467ffffffffffffffff8681167fffffffffffffffffffffff00000000000000000000000000000000000000000090921668010000000000000000918616919091027fffffffffffffffffffffff0000000000ffffffffffffffff00000000000000001617177001000000000000000000000000000000004264ffffffffff160217905560408051838152602081018690527f9dd85e9767d796973b86c6ccf3a294429cfd5e3e93fa23ac388b9277bb8283fd910160405180910390a15b8015611fb357600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff1690555092915050565b6000806000835160411461302a57600080fd5b5050506020810151604082015160609092015160001a92909190565b80821115613084576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2360048201526024016110aa565b5050565b6008547501000000000000000000000000000000000000000000900460ff166001146130e4576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2760048201526024016110aa565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167502000000000000000000000000000000000000000000179055565b600080600061316a85858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b92509250925061317f88338989878787611fba565b5050505050505050565b600082613195816135de565b6131b864e8d4a510006131b06131a9612432565b6000612e9d565b8791906128e1565b91506131c48383613afc565b6131ce8585613cc0565b50604080518681526020810184905273ffffffffffffffffffffffffffffffffffffffff808616929087169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4509392505050565b6040517f2520e7ff0000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1690632520e7ff90602401602060405180830381865afa1580156132b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132dd9190614b6a565b613317576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2560048201526024016110aa565b565b600082613325816135de565b6000613331868561343e565b905061333e816000612e9d565b90508061335064e8d4a51000886148da565b61335a9190614920565b92508260000361339a576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2160048201526024016110aa565b6133a48584613d80565b604080518781526020810185905273ffffffffffffffffffffffffffffffffffffffff87169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a350509392505050565b80821015613084576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2260048201526024016110aa565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ad967e157f00000000000000000000000000000000000000000000000000000000000000006134a686613e73565b6000806000886040518763ffffffff1660e01b81526004016134cd96959493929190614b87565b60408051808303816000875af11580156134eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061350f9190614be0565b509392505050565b60006040517f23b872dd00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015273ffffffffffffffffffffffffffffffffffffffff841660248201528260448201526020600060648360008a5af13d15601f3d11600160005114161716915050806135d7576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155960048201526024016110aa565b5050505050565b73ffffffffffffffffffffffffffffffffffffffff811661362f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2460048201526024016110aa565b50565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f00000000000000000000000000000000000000000000000000000000000000006004820152600090819073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000169063b5c736e490602401602060405180830381865afa1580156136e1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061370591906149bb565b9050600981901c66ffffffffffffff16600182901c60ff161b6137288282613f29565b92506000613734612432565b64e8d4a51000948102859004949202919091049050828111613757576000613761565b6137618382614af2565b9250600061376d613fbd565b905083811161377c578061377e565b835b935050505090565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040902080546001810182559061250c565b6000610b0b6137c6612c65565b836040517f19010000000000000000000000000000000000000000000000000000000000006020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b600080600061383387878787614092565b9150915061384081614181565b5095945050505050565b60006040517fa9059cbb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff84166004820152826024820152602060006044836000895af13d15601f3d1160016000511416171691505080611cf9576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155a60048201526024016110aa565b67ffffffffffffffff605b82901c811690609b83901c16811580613910575080155b1561394c576040517fd50d75120000000000000000000000000000000000000000000000000000000081526201117160048201526024016110aa565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff16911480613976575082155b806139815750806001145b1561398e57505050915091565b64496cebb80084840283020484019350617fff60db87901c169250826001036139b957505050915091565b82600116600103613a0e5760019290921c91826c7e37be2022c0914b2680000000816139e7576139e76148f1565b049250612710601e87901c613fff166b033b2e3c9fd0803ce8000000850102049250613a3b565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b80600116600103613a725760011c61271081016b033b2e3c9fd0803ce8000000820281613a6a57613a6a6148f1565b049050613aa8565b60011c61271081016b033b2e3c9fd0803ce8000000820281613a9657613a966148f1565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b73ffffffffffffffffffffffffffffffffffffffff8216613b9f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f730000000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205481811015613c55576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f636500000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff83166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ad967e157f0000000000000000000000000000000000000000000000000000000000000000613d2886613e73565b613d3190614c04565b60408051600080825260208201928390527fffffffff0000000000000000000000000000000000000000000000000000000060e087901b169092526134cd939291908890829060248101614b87565b73ffffffffffffffffffffffffffffffffffffffff8216613dfd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016110aa565b8060026000828254613e0f91906149a8565b909155505073ffffffffffffffffffffffffffffffffffffffff8216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115613f25576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160448201527f6e20696e7432353600000000000000000000000000000000000000000000000060648201526084016110aa565b5090565b600066ffffffffffffff604984901c1660ff604185901c161b808203613f53576000915050610b0b565b612710613fff60a286901c168402046401ffffffff608186901c16420362ffffff60b087901c16613f8482846148da565b613f8e9190614920565b9050808311613f9e576000613fa2565b8083035b93505080840383811115613fb4578093505b50505092915050565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000811660048301526000917f0000000000000000000000000000000000000000000000000000000000000000909116906370a0823190602401602060405180830381865afa15801561406e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b6091906149bb565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156140c95750600090506003614178565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561411d573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811661417157600060019250925050614178565b9150600090505b94509492505050565b600081600481111561419557614195614c3c565b0361419d5750565b60018160048111156141b1576141b1614c3c565b03614218576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f45434453413a20696e76616c6964207369676e6174757265000000000000000060448201526064016110aa565b600281600481111561422c5761422c614c3c565b03614293576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e6774680060448201526064016110aa565b60038160048111156142a7576142a7614c3c565b0361362f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f756500000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b6000815180845260005b8181101561435a5760208185018101518683018201520161433e565b5060006020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b602081526000610af06020830184614334565b6000602082840312156143bd57600080fd5b5035919050565b73ffffffffffffffffffffffffffffffffffffffff8116811461362f57600080fd5b600080604083850312156143f957600080fd5b8235614404816143c4565b946020939093013593505050565b60008060006060848603121561442757600080fd5b8335614432816143c4565b92506020840135614442816143c4565b929592945050506040919091013590565b60008083601f84011261446557600080fd5b50813567ffffffffffffffff81111561447d57600080fd5b60208301915083602082850101111561449557600080fd5b9250929050565b60008060008060008060a087890312156144b557600080fd5b8635955060208701356144c7816143c4565b94506040870135935060608701359250608087013567ffffffffffffffff8111156144f157600080fd5b6144fd89828a01614453565b979a9699509497509295939492505050565b60006020828403121561452157600080fd5b8135610af0816143c4565b60008060008060008060008060e0898b03121561454857600080fd5b88359750602089013596506040890135614561816143c4565b95506060890135614571816143c4565b94506080890135935060a0890135925060c089013567ffffffffffffffff81111561459b57600080fd5b6145a78b828c01614453565b999c989b5096995094979396929594505050565b6000806000806000808688036101408112156145d657600080fd5b8735965060208801356145e8816143c4565b95506040880135945060c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa08201121561462157600080fd5b5060608701925061012087013567ffffffffffffffff8111156144f157600080fd5b6000806040838503121561465657600080fd5b823591506020830135614668816143c4565b809150509250929050565b600080600080600080600060c0888a03121561468e57600080fd5b8735965060208801356146a0816143c4565b955060408801356146b0816143c4565b9450606088013593506080880135925060a088013567ffffffffffffffff8111156146da57600080fd5b6146e68a828b01614453565b989b979a50959850939692959293505050565b60008060006060848603121561470e57600080fd5b833592506020840135614442816143c4565b6000806000806080858703121561473657600080fd5b843593506020850135614748816143c4565b92506040850135614758816143c4565b9396929550929360600135925050565b6000806000806060858703121561477e57600080fd5b8435614789816143c4565b935060208501359250604085013567ffffffffffffffff8111156147ac57600080fd5b6147b887828801614453565b95989497509550505050565b6000806000606084860312156147d957600080fd5b8335925060208401356147eb816143c4565b915060408401356147fb816143c4565b809150509250925092565b600080600080600080600060e0888a03121561482157600080fd5b873561482c816143c4565b9650602088013561483c816143c4565b95506040880135945060608801359350608088013560ff8116811461486057600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561489057600080fd5b823561489b816143c4565b91506020830135614668816143c4565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082028115828204841417610b0b57610b0b6148ab565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082614956577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b600181811c9082168061496f57607f821691505b60208210810361250c577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b80820180821115610b0b57610b0b6148ab565b6000602082840312156149cd57600080fd5b5051919050565b803565ffffffffffff811681146149ea57600080fd5b919050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b600061010073ffffffffffffffffffffffffffffffffffffffff80881684528635614a62816143c4565b8181166020860152506020870135614a79816143c4565b818116604086015250614a8e604088016149d4565b65ffffffffffff808216606087015280614aaa60608b016149d4565b16608087015250506080870135614ac0816143c4565b81811660a0860152505060a086013560c08401528060e0840152614ae781840185876149ef565b979650505050505050565b81810381811115610b0b57610b0b6148ab565b801515811461362f57600080fd5b60008060408385031215614b2657600080fd5b823561489b81614b05565b600080600060608486031215614b4657600080fd5b835192506020840151614b5881614b05565b80925050604084015190509250925092565b600060208284031215614b7c57600080fd5b8151610af081614b05565b600073ffffffffffffffffffffffffffffffffffffffff8089168352876020840152866040840152808616606084015280851660808401525060c060a0830152614bd460c0830184614334565b98975050505050505050565b60008060408385031215614bf357600080fd5b505080516020909101519092909150565b60007f80000000000000000000000000000000000000000000000000000000000000008203614c3557614c356148ab565b5060000390565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fdfea2646970667358221220dc2bfae06ad921069351d56bdcb5f130055a166516a80e2117e6d9b030e689d064736f6c6343000815003300000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49700000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48

Deployed Bytecode

0x6080604052600436106103135760003560e01c80637ecebe001161019a578063b460af94116100e1578063d505accf1161008a578063e083be2211610064578063e083be221461099e578063e53b2017146109be578063ef8b30f7146109de57600080fd5b8063d505accf1461090b578063d905777e1461092b578063dd62ed3e1461094b57600080fd5b8063c63d75b6116100bb578063c63d75b6146108ab578063c6e6f592146108cb578063ce96cb77146108eb57600080fd5b8063b460af941461084b578063ba0876521461086b578063bc157ac11461088b57600080fd5b8063a318c1a411610143578063ad2075011161011d578063ad207501146107eb578063b046a4491461080b578063b3d7f6b91461082b57600080fd5b8063a318c1a41461078b578063a457c2d7146107ab578063a9059cbb146107cb57600080fd5b806394bf804d1161017457806394bf804d1461073657806395d89b41146107565780639f40a7b31461076b57600080fd5b80637ecebe00146106d6578063836a1040146106f65780638c87483a1461071657600080fd5b80633c3821f41161025e5780635fd619651161020757806370a08231116101e157806370a082311461066b578063740c955e146106ae5780637d7c2a1c146106ce57600080fd5b80635fd6196514610609578063635c31c21461062b5780636e553f651461064b57600080fd5b806341b3d1851161023857806341b3d185146105b45780634cdad506146105c957806350cc0f8f146105e957600080fd5b80633c3821f41461054a5780633f4c093014610574578063402d267d1461059457600080fd5b806323b872dd116102c057806338d52e0f1161029a57806338d52e0f1461045a57806339509351146104ab5780633bc5de30146104cb57600080fd5b806323b872dd146103e7578063313ce567146104075780633644e5151461044557600080fd5b8063095ea7b3116102f1578063095ea7b3146103825780630a28a477146103b257806318160ddd146103d257600080fd5b806301e1d1141461031857806306fdde031461034057806307a2d13a14610362575b600080fd5b34801561032457600080fd5b5061032d6109fe565b6040519081526020015b60405180910390f35b34801561034c57600080fd5b50610355610a3d565b6040516103379190614398565b34801561036e57600080fd5b5061032d61037d3660046143ab565b610acf565b34801561038e57600080fd5b506103a261039d3660046143e6565b610af7565b6040519015158152602001610337565b3480156103be57600080fd5b5061032d6103cd3660046143ab565b610b11565b3480156103de57600080fd5b5060025461032d565b3480156103f357600080fd5b506103a2610402366004614412565b610b32565b34801561041357600080fd5b5060405160ff7f0000000000000000000000000000000000000000000000000000000000000006168152602001610337565b34801561045157600080fd5b5061032d610b56565b34801561046657600080fd5b5060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48168152602001610337565b3480156104b757600080fd5b506103a26104c63660046143e6565b610b65565b3480156104d757600080fd5b506104e0610bb1565b6040805173ffffffffffffffffffffffffffffffffffffffff9a8b168152988a1660208a0152968916968801969096529387166060870152959091166080850152151560a084015260c083019390935260e082019290925261010081019190915261012001610337565b34801561055657600080fd5b5061055f610c9d565b60408051928352602083019190915201610337565b34801561058057600080fd5b5061032d61058f36600461449c565b610cbb565b3480156105a057600080fd5b5061032d6105af36600461450f565b610e01565b3480156105c057600080fd5b5061032d610f45565b3480156105d557600080fd5b5061032d6105e43660046143ab565b611046565b3480156105f557600080fd5b5061032d61060436600461452c565b611051565b34801561061557600080fd5b5061062961062436600461450f565b61112e565b005b34801561063757600080fd5b5061032d6106463660046145bb565b6111f4565b34801561065757600080fd5b5061032d610666366004614643565b61130a565b34801561067757600080fd5b5061032d61068636600461450f565b73ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b3480156106ba57600080fd5b5061032d6106c9366004614673565b61144b565b61032d611530565b3480156106e257600080fd5b5061032d6106f136600461450f565b611695565b34801561070257600080fd5b5061032d6107113660046146f9565b6116c0565b34801561072257600080fd5b5061032d6107313660046145bb565b6116d8565b34801561074257600080fd5b5061032d610751366004614643565b6117e8565b34801561076257600080fd5b50610355611939565b34801561077757600080fd5b5061032d610786366004614720565b611948565b34801561079757600080fd5b5061032d6107a6366004614720565b611969565b3480156107b757600080fd5b506103a26107c63660046143e6565b611982565b3480156107d757600080fd5b506103a26107e63660046143e6565b611a53565b3480156107f757600080fd5b50610629610806366004614768565b611a61565b34801561081757600080fd5b5061062961082636600461450f565b611cff565b34801561083757600080fd5b5061032d6108463660046143ab565b611d81565b34801561085757600080fd5b5061032d6108663660046147c4565b611da2565b34801561087757600080fd5b5061032d6108863660046147c4565b611e3a565b34801561089757600080fd5b5061032d6108a63660046146f9565b611f1e565b3480156108b757600080fd5b5061032d6108c636600461450f565b611f36565b3480156108d757600080fd5b5061032d6108e63660046143ab565b611f45565b3480156108f757600080fd5b5061032d61090636600461450f565b611f66565b34801561091757600080fd5b50610629610926366004614806565b611fba565b34801561093757600080fd5b5061032d61094636600461450f565b61216d565b34801561095757600080fd5b5061032d61096636600461487d565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260016020908152604080832093909416825291909152205490565b3480156109aa57600080fd5b5061032d6109b936600461449c565b6121ab565b3480156109ca57600080fd5b506106296109d936600461450f565b6122d8565b3480156109ea57600080fd5b5061032d6109f93660046143ab565b612427565b600080610a11610a0c612432565b612512565b50905064e8d4a51000610a2360025490565b610a2d90836148da565b610a379190614920565b91505090565b606060038054610a4c9061495b565b80601f0160208091040260200160405190810160405280929190818152602001828054610a789061495b565b8015610ac55780601f10610a9a57610100808354040283529160200191610ac5565b820191906000526020600020905b815481529060010190602001808311610aa857829003601f168201915b5050505050905090565b600080610add610a0c612432565b509050610af0838264e8d4a510006126f2565b9392505050565b600033610b0581858561272e565b60019150505b92915050565b600080610b1f610a0c612432565b509050610af08364e8d4a51000836128e1565b600033610b40858285612925565b610b4b8585856129f6565b506001949350505050565b6000610b60612c65565b905090565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168452909152812054909190610b059082908690610bac9087906149a8565b61272e565b6000806000806000806000806000610bc7612432565b91506000610bd483612512565b6007546009546008549395509193507f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497927f00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d039273ffffffffffffffffffffffffffffffffffffffff928316926e22d473030f116ddee9f6b43ac78ba392911690760100000000000000000000000000000000000000000000900460ff168015610c7b575085155b610c83612d99565b995099509950995099509950995050909192939495969798565b600080610ca8612432565b9050610cb5816001612e9d565b91509091565b6000610cc687611d81565b90506000806000610d0c86868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b6040517fd505accf00000000000000000000000000000000000000000000000000000000815233600482015230602482015260448101889052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48169063d505accf9060e401600060405180830381600087803b158015610dc657600080fd5b505af1158015610dda573d6000803e3d6000fd5b50505050610de88a8a6117e8565b9350610df48489613046565b5050509695505050505050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527ff942f4688cdba65adc8aa59da583acae93fa87351143ebc775559218bfa5f8326004820152600090819067ffffffffffffffff9073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa158015610eba573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ede91906149bb565b16600881901c60ff9091161b905064e8d4a51000610efa612432565b820281610f0957610f096148f1565b0490506f7fffffffffffff7fffffffffffffffff811115610f2d5750600092915050565b6f7fffffffffffffffffffffffffffffff0392915050565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527ff942f4688cdba65adc8aa59da583acae93fa87351143ebc775559218bfa5f8326004820152600090819060ff9073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa158015610ff7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101b91906149bb565b166001901b9050600061102e6001611d81565b905080821161103d578061103f565b815b9250505090565b6000610b0b82610acf565b600061105b613088565b73ffffffffffffffffffffffffffffffffffffffff861633036110b3576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2660048201526024015b60405180910390fd5b6110c0868a868686613126565b6110cb888888613189565b90506110d78186613046565b6110e2863383612925565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905598975050505050505050565b61113661322f565b61113e610c9d565b5050600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8316908117909155600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff16821515760100000000000000000000000000000000000000000000021790556040517fd14b198a72267efb36b8bbc193eb6d52a00d1f61799029250f6a520ad47be82d90600090a250565b60006111fe613088565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b5709061124f903390889088908890600401614a38565b600060405180830381600087803b15801561126957600080fd5b505af115801561127d573d6000803e3d6000fd5b5050604080516001602082015233918101919091526112b4925089915088906060015b604051602081830303815290604052613319565b90506112c08186613400565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b6000611314613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036113ec576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4873ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa1580156113c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e991906149bb565b92505b604080513360208201526114049185918591016112a0565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b6000611455613088565b73ffffffffffffffffffffffffffffffffffffffff861633036114a8576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2660048201526024016110aa565b6114b188611046565b90506114bd8186613400565b6114ca8689868686613126565b60006114d7828989613189565b90506114e4873383612925565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055979650505050505050565b600061153a613088565b60095473ffffffffffffffffffffffffffffffffffffffff16331461158f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2960048201526024016110aa565b34156115cb576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2a60048201526024016110aa565b6115d3612d99565b6115db6109fe565b6115e59190614af2565b604080513360208201529192506000916116109184910160405160208183030381529060405261343e565b905061161d816001612e9d565b506040518281527fe97ad8b810ae9d9e29aa69dc04d4ac2e3e71d65307830ccb97c8f876dfc439319060200160405180910390a150600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905590565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040812054610b0b565b60006116cc84846117e8565b9050610af08183613046565b60006116e2613088565b6116eb87611d81565b90506116f78186613046565b6040517f2b67b5700000000000000000000000000000000000000000000000000000000081526e22d473030f116ddee9f6b43ac78ba390632b67b57090611748903390889088908890600401614a38565b600060405180830381600087803b15801561176257600080fd5b505af1158015611776573d6000803e3d6000fd5b50506040805160016020820152339181019190915261179d925083915088906060016112a0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559695505050505050565b60006117f2613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83036118ce576040517f70a082310000000000000000000000000000000000000000000000000000000081523360048201527f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4873ffffffffffffffffffffffffffffffffffffffff16906370a0823190602401602060405180830381865afa1580156118a3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c791906149bb565b90506118da565b6118d783611d81565b90505b604080513360208201526118f29183918591016112a0565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905592915050565b606060048054610a4c9061495b565b6000611955858585611e3a565b90506119618183613400565b949350505050565b6000611976858585611da2565b90506119618183613046565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8716845290915281205490919083811015611a46576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f00000000000000000000000000000000000000000000000000000060648201526084016110aa565b610b4b828686840361272e565b600033610b058185856129f6565b3373ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49716141580611af257507f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4873ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b80611b1c57506008547501000000000000000000000000000000000000000000900460ff16600214155b15611b57576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2560048201526024016110aa565b6020819003611bc2576000611b6e8284018461450f565b9050611bbc7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48827f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49787613517565b50611cf9565b600080611bd183850185614b13565b9150915081611c10576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2460048201526024016110aa565b6040517f36c7851600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff80831660048301527f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e4978116602483015280871660448301527f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb481660648201526e22d473030f116ddee9f6b43ac78ba3906336c7851690608401600060405180830381600087803b158015611cde57600080fd5b505af1158015611cf2573d6000803e3d6000fd5b5050505050505b50505050565b80611d09816135de565b611d1161322f565b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091556040517fdb94ee7fd8b5bbf8f6d59e76731ff4b4f5a02ab3af1d3e0c774862cf96ff613b90600090a25050565b600080611d8f610a0c612432565b509050610af0838264e8d4a510006128e1565b6000611dac613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611e0557611e026105e48373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b93505b611e10848484613189565b90503373ffffffffffffffffffffffffffffffffffffffff83161461140457611404823383612925565b6000611e44613088565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8403611e945773ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205493505b611e9d84611046565b90506000611eac828585613189565b90503373ffffffffffffffffffffffffffffffffffffffff841614611ed657611ed6833383612925565b50600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff1675010000000000000000000000000000000000000000001790559392505050565b6000611f2a848461130a565b9050610af08183613400565b6000610b0b6108e66000610e01565b600080611f53610a0c612432565b509050610af08364e8d4a51000836126f2565b600080611f71613632565b90506000611fa461037d8573ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b9050808210611fb35780611961565b5092915050565b83421115612024576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e6500000060448201526064016110aa565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886120538c613786565b60408051602081019690965273ffffffffffffffffffffffffffffffffffffffff94851690860152929091166060840152608083015260a082015260c0810186905260e00160405160208183030381529060405280519060200120905060006120bb826137b9565b905060006120cb82878787613822565b90508973ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614612162576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e6174757265000060448201526064016110aa565b611cf28a8a8a61272e565b60008061217b6108e6613632565b90506000611fa48473ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b6000806000806121f086868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b6040517fd505accf000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018e9052606481018b905260ff8416608482015260a4810183905260c48101829052929550909350915073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48169063d505accf9060e401600060405180830381600087803b1580156122aa57600080fd5b505af11580156122be573d6000803e3d6000fd5b505050506122cc8a8a61130a565b9350610df48489613400565b6122e0613088565b6122e861322f565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526123a39082907f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e4979073ffffffffffffffffffffffffffffffffffffffff8316906370a0823190602401602060405180830381865afa15801561237a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061239e91906149bb565b61384a565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fdff2a3947bcf9fc0807b142e7c8497066db9183428b7bdbfb1fcd0f55c27a3df90600090a250600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167501000000000000000000000000000000000000000000179055565b6000610b0b82611f45565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527fa8e1248eddf82e10c0adc6c737b6d8da17674abf51801ea5a4549f41c2dfdf21600482015260009061250c9073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa1580156124e3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061250791906149bb565b6138ee565b50919050565b600854600090819067ffffffffffffffff6801000000000000000082048116911680851015612571576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2b60048201526024016110aa565b600854600090760100000000000000000000000000000000000000000000900460ff16156126a857600754600090819073ffffffffffffffffffffffffffffffffffffffff16635776409464e8d4a510006125cb60025490565b6125d590896148da565b6125df9190614920565b6040518263ffffffff1660e01b81526004016125fd91815260200190565b606060405180830381865afa15801561261a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061263e9190614b31565b9097509092509050652d79883d20008211806126575750855b1561266157600091505b600854700100000000000000000000000000000000900464ffffffffff168181101561268a5750805b6301e133808142038402816126a1576126a16148f1565b0493505050505b81828703655af3107a400002816126c1576126c16148f1565b0401655af3107a40006126d482856148da565b6126de9190614920565b6126e890846149a8565b9450505050915091565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048411830215820261272757600080fd5b5091020490565b73ffffffffffffffffffffffffffffffffffffffff83166127d0576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f726573730000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff8216612873576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f737300000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048411830215820261291657600080fd5b50910281810615159190040190565b73ffffffffffffffffffffffffffffffffffffffff8381166000908152600160209081526040808320938616835292905220547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114611cf957818110156129e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016110aa565b611cf9848484840361272e565b73ffffffffffffffffffffffffffffffffffffffff8316612a99576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f647265737300000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff8216612b3c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f657373000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604090205481811015612bf2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e6365000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3611cf9565b60003073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009fb7b4477576fe5b32be4c1843afb1e55f251b3316148015612ccb57507f000000000000000000000000000000000000000000000000000000000000000146145b15612cf557507f11202510c510f7160179c5f667b194559b0cafbb047d222ea6ef69968f4be99e90565b50604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6020808301919091527fd68646cd6b6934a55a1dd29476ac37e8a1b774300c251a7ab0215fa717a73efb828401527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608301524660808301523060a0808401919091528351808403909101815260c0909201909252805191012090565b600080612e7767ffffffffffffffff60017f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663b5c736e47f9d4def7286a4ebc4ac55f8b0df348c30c2a6689e31f26c88ed2ca9f32314dc9e6040518263ffffffff1660e01b8152600401612e2591815260200190565b602060405180830381865afa158015612e42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6691906149bb565b901c16600860ff9082901c91161b90565b905064e8d4a51000612e87612432565b820281612e9657612e966148f1565b0491505090565b600080612ea984612512565b6008549193509150760100000000000000000000000000000000000000000000900460ff1680612ed65750825b15612fe25767ffffffffffffffff821115612f21576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2860048201526024016110aa565b6008805467ffffffffffffffff8681167fffffffffffffffffffffff00000000000000000000000000000000000000000090921668010000000000000000918616919091027fffffffffffffffffffffff0000000000ffffffffffffffff00000000000000001617177001000000000000000000000000000000004264ffffffffff160217905560408051838152602081018690527f9dd85e9767d796973b86c6ccf3a294429cfd5e3e93fa23ac388b9277bb8283fd910160405180910390a15b8015611fb357600880547fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff1690555092915050565b6000806000835160411461302a57600080fd5b5050506020810151604082015160609092015160001a92909190565b80821115613084576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2360048201526024016110aa565b5050565b6008547501000000000000000000000000000000000000000000900460ff166001146130e4576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2760048201526024016110aa565b600880547fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff167502000000000000000000000000000000000000000000179055565b600080600061316a85858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061301792505050565b92509250925061317f88338989878787611fba565b5050505050505050565b600082613195816135de565b6131b864e8d4a510006131b06131a9612432565b6000612e9d565b8791906128e1565b91506131c48383613afc565b6131ce8585613cc0565b50604080518681526020810184905273ffffffffffffffffffffffffffffffffffffffff808616929087169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4509392505050565b6040517f2520e7ff0000000000000000000000000000000000000000000000000000000081523360048201527f00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d0373ffffffffffffffffffffffffffffffffffffffff1690632520e7ff90602401602060405180830381865afa1580156132b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132dd9190614b6a565b613317576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2560048201526024016110aa565b565b600082613325816135de565b6000613331868561343e565b905061333e816000612e9d565b90508061335064e8d4a51000886148da565b61335a9190614920565b92508260000361339a576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2160048201526024016110aa565b6133a48584613d80565b604080518781526020810185905273ffffffffffffffffffffffffffffffffffffffff87169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a350509392505050565b80821015613084576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2260048201526024016110aa565b60007f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663ad967e157f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486134a686613e73565b6000806000886040518763ffffffff1660e01b81526004016134cd96959493929190614b87565b60408051808303816000875af11580156134eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061350f9190614be0565b509392505050565b60006040517f23b872dd00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015273ffffffffffffffffffffffffffffffffffffffff841660248201528260448201526020600060648360008a5af13d15601f3d11600160005114161716915050806135d7576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155960048201526024016110aa565b5050505050565b73ffffffffffffffffffffffffffffffffffffffff811661362f576040517f694bda1d000000000000000000000000000000000000000000000000000000008152614e2460048201526024016110aa565b50565b6040517fb5c736e40000000000000000000000000000000000000000000000000000000081527f9d4def7286a4ebc4ac55f8b0df348c30c2a6689e31f26c88ed2ca9f32314dc9e6004820152600090819073ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497169063b5c736e490602401602060405180830381865afa1580156136e1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061370591906149bb565b9050600981901c66ffffffffffffff16600182901c60ff161b6137288282613f29565b92506000613734612432565b64e8d4a51000948102859004949202919091049050828111613757576000613761565b6137618382614af2565b9250600061376d613fbd565b905083811161377c578061377e565b835b935050505090565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260056020526040902080546001810182559061250c565b6000610b0b6137c6612c65565b836040517f19010000000000000000000000000000000000000000000000000000000000006020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b600080600061383387878787614092565b9150915061384081614181565b5095945050505050565b60006040517fa9059cbb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff84166004820152826024820152602060006044836000895af13d15601f3d1160016000511416171691505080611cf9576040517fdee51a8a0000000000000000000000000000000000000000000000000000000081526201155a60048201526024016110aa565b67ffffffffffffffff605b82901c811690609b83901c16811580613910575080155b1561394c576040517fd50d75120000000000000000000000000000000000000000000000000000000081526201117160048201526024016110aa565b61ffff8316603a84901c6401ffffffff16428181039160ea87901c617fff16911480613976575082155b806139815750806001145b1561398e57505050915091565b64496cebb80084840283020484019350617fff60db87901c169250826001036139b957505050915091565b82600116600103613a0e5760019290921c91826c7e37be2022c0914b2680000000816139e7576139e76148f1565b049250612710601e87901c613fff166b033b2e3c9fd0803ce8000000850102049250613a3b565b60019290921c916305f5e100601e87901c613fff166127108501026b033b2e3c9fd0803ce8000000020492505b80600116600103613a725760011c61271081016b033b2e3c9fd0803ce8000000820281613a6a57613a6a6148f1565b049050613aa8565b60011c61271081016b033b2e3c9fd0803ce8000000820281613a9657613a966148f1565b046b033b2e3c9fd0803ce80000000390505b760a70c3c40a64e6c51999090b65f67d92400000000000008382026127100261ffff881691900402601087901c613fff16612710030292506801b5a660ea44b8000085840283020485019450505050915091565b73ffffffffffffffffffffffffffffffffffffffff8216613b9f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f730000000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205481811015613c55576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f636500000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b73ffffffffffffffffffffffffffffffffffffffff83166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b60007f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49773ffffffffffffffffffffffffffffffffffffffff1663ad967e157f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48613d2886613e73565b613d3190614c04565b60408051600080825260208201928390527fffffffff0000000000000000000000000000000000000000000000000000000060e087901b169092526134cd939291908890829060248101614b87565b73ffffffffffffffffffffffffffffffffffffffff8216613dfd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016110aa565b8060026000828254613e0f91906149a8565b909155505073ffffffffffffffffffffffffffffffffffffffff8216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115613f25576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f53616665436173743a2076616c756520646f65736e27742066697420696e206160448201527f6e20696e7432353600000000000000000000000000000000000000000000000060648201526084016110aa565b5090565b600066ffffffffffffff604984901c1660ff604185901c161b808203613f53576000915050610b0b565b612710613fff60a286901c168402046401ffffffff608186901c16420362ffffff60b087901c16613f8482846148da565b613f8e9190614920565b9050808311613f9e576000613fa2565b8083035b93505080840383811115613fb4578093505b50505092915050565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497811660048301526000917f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48909116906370a0823190602401602060405180830381865afa15801561406e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b6091906149bb565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156140c95750600090506003614178565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa15801561411d573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811661417157600060019250925050614178565b9150600090505b94509492505050565b600081600481111561419557614195614c3c565b0361419d5750565b60018160048111156141b1576141b1614c3c565b03614218576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f45434453413a20696e76616c6964207369676e6174757265000000000000000060448201526064016110aa565b600281600481111561422c5761422c614c3c565b03614293576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e6774680060448201526064016110aa565b60038160048111156142a7576142a7614c3c565b0361362f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f756500000000000000000000000000000000000000000000000000000000000060648201526084016110aa565b6000815180845260005b8181101561435a5760208185018101518683018201520161433e565b5060006020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b602081526000610af06020830184614334565b6000602082840312156143bd57600080fd5b5035919050565b73ffffffffffffffffffffffffffffffffffffffff8116811461362f57600080fd5b600080604083850312156143f957600080fd5b8235614404816143c4565b946020939093013593505050565b60008060006060848603121561442757600080fd5b8335614432816143c4565b92506020840135614442816143c4565b929592945050506040919091013590565b60008083601f84011261446557600080fd5b50813567ffffffffffffffff81111561447d57600080fd5b60208301915083602082850101111561449557600080fd5b9250929050565b60008060008060008060a087890312156144b557600080fd5b8635955060208701356144c7816143c4565b94506040870135935060608701359250608087013567ffffffffffffffff8111156144f157600080fd5b6144fd89828a01614453565b979a9699509497509295939492505050565b60006020828403121561452157600080fd5b8135610af0816143c4565b60008060008060008060008060e0898b03121561454857600080fd5b88359750602089013596506040890135614561816143c4565b95506060890135614571816143c4565b94506080890135935060a0890135925060c089013567ffffffffffffffff81111561459b57600080fd5b6145a78b828c01614453565b999c989b5096995094979396929594505050565b6000806000806000808688036101408112156145d657600080fd5b8735965060208801356145e8816143c4565b95506040880135945060c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa08201121561462157600080fd5b5060608701925061012087013567ffffffffffffffff8111156144f157600080fd5b6000806040838503121561465657600080fd5b823591506020830135614668816143c4565b809150509250929050565b600080600080600080600060c0888a03121561468e57600080fd5b8735965060208801356146a0816143c4565b955060408801356146b0816143c4565b9450606088013593506080880135925060a088013567ffffffffffffffff8111156146da57600080fd5b6146e68a828b01614453565b989b979a50959850939692959293505050565b60008060006060848603121561470e57600080fd5b833592506020840135614442816143c4565b6000806000806080858703121561473657600080fd5b843593506020850135614748816143c4565b92506040850135614758816143c4565b9396929550929360600135925050565b6000806000806060858703121561477e57600080fd5b8435614789816143c4565b935060208501359250604085013567ffffffffffffffff8111156147ac57600080fd5b6147b887828801614453565b95989497509550505050565b6000806000606084860312156147d957600080fd5b8335925060208401356147eb816143c4565b915060408401356147fb816143c4565b809150509250925092565b600080600080600080600060e0888a03121561482157600080fd5b873561482c816143c4565b9650602088013561483c816143c4565b95506040880135945060608801359350608088013560ff8116811461486057600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561489057600080fd5b823561489b816143c4565b91506020830135614668816143c4565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082028115828204841417610b0b57610b0b6148ab565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082614956577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b600181811c9082168061496f57607f821691505b60208210810361250c577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b80820180821115610b0b57610b0b6148ab565b6000602082840312156149cd57600080fd5b5051919050565b803565ffffffffffff811681146149ea57600080fd5b919050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b600061010073ffffffffffffffffffffffffffffffffffffffff80881684528635614a62816143c4565b8181166020860152506020870135614a79816143c4565b818116604086015250614a8e604088016149d4565b65ffffffffffff808216606087015280614aaa60608b016149d4565b16608087015250506080870135614ac0816143c4565b81811660a0860152505060a086013560c08401528060e0840152614ae781840185876149ef565b979650505050505050565b81810381811115610b0b57610b0b6148ab565b801515811461362f57600080fd5b60008060408385031215614b2657600080fd5b823561489b81614b05565b600080600060608486031215614b4657600080fd5b835192506020840151614b5881614b05565b80925050604084015190509250925092565b600060208284031215614b7c57600080fd5b8151610af081614b05565b600073ffffffffffffffffffffffffffffffffffffffff8089168352876020840152866040840152808616606084015280851660808401525060c060a0830152614bd460c0830184614334565b98975050505050505050565b60008060408385031215614bf357600080fd5b505080516020909101519092909150565b60007f80000000000000000000000000000000000000000000000000000000000000008203614c3557614c356148ab565b5060000390565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fdfea2646970667358221220dc2bfae06ad921069351d56bdcb5f130055a166516a80e2117e6d9b030e689d064736f6c63430008150033

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

00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e49700000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48

-----Decoded View---------------
Arg [0] : liquidity_ (address): 0x52Aa899454998Be5b000Ad077a46Bbe360F4e497
Arg [1] : lendingFactory_ (address): 0x54B91A0D94cb471F37f949c60F7Fa7935b551D03
Arg [2] : asset_ (address): 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 00000000000000000000000052aa899454998be5b000ad077a46bbe360f4e497
Arg [1] : 00000000000000000000000054b91a0d94cb471f37f949c60f7fa7935b551d03
Arg [2] : 000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.