ETH Price: $2,115.69 (-3.24%)

Transaction Decoder

Block:
18414209 at Oct-23-2023 04:37:59 PM +UTC
Transaction Fee:
0.0022726916929344 ETH $4.81
Gas Used:
81,460 Gas / 27.89948064 Gwei

Emitted Events:

198 LBR.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0xe042f0f5880224edb66cc34cb2ca52d51322a200, value=337620018241597988880 )
199 ProtocolRewardsPool.WithdrawLBR( user=[Sender] 0xe042f0f5880224edb66cc34cb2ca52d51322a200, amount=337620018241597988880, time=1698079079 )

Account State Difference:

  Address   Before After State Difference Code
1.15722298218875065 Eth1.15723112818875065 Eth0.000008146
0xC2966A73...E972eD89e
0xE042F0f5...51322A200
2.178844472453491433 Eth
Nonce: 89
2.176571780760557033 Eth
Nonce: 90
0.0022726916929344
0xed1167b6...2D0981ebd

Execution Trace

ProtocolRewardsPool.withdraw( user=0xE042F0f5880224EdB66cc34Cb2cA52d51322A200 )
  • LBR.mint( user=0xE042F0f5880224EdB66cc34Cb2cA52d51322A200, amount=337620018241597988880 ) => ( True )
    • LybraProxy.bf21c60c( )
      • LybraConfigurator.tokenMiner( 0xC2966A73Bbc53f3C99268ED84D245dBE972eD89e ) => ( True )
        File 1 of 4: ProtocolRewardsPool
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface AggregatorV3Interface {
          function decimals() external view returns (uint8);
          function description() external view returns (string memory);
          function version() external view returns (uint256);
          function getRoundData(uint80 _roundId)
            external
            view
            returns (
              uint80 roundId,
              int256 answer,
              uint256 startedAt,
              uint256 updatedAt,
              uint80 answeredInRound
            );
          function latestRoundData()
            external
            view
            returns (
              uint80 roundId,
              int256 answer,
              uint256 startedAt,
              uint256 updatedAt,
              uint80 answeredInRound
            );
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/Context.sol";
        /**
         * @dev Contract module which provides a basic access control mechanism, where
         * there is an account (an owner) that can be granted exclusive access to
         * specific functions.
         *
         * By default, the owner account will be the one that deploys the contract. This
         * can later be changed with {transferOwnership}.
         *
         * This module is used through inheritance. It will make available the modifier
         * `onlyOwner`, which can be applied to your functions to restrict their use to
         * the owner.
         */
        abstract contract Ownable is Context {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            constructor() {
                _transferOwnership(_msgSender());
            }
            /**
             * @dev Throws if called by any account other than the owner.
             */
            modifier onlyOwner() {
                _checkOwner();
                _;
            }
            /**
             * @dev Returns the address of the current owner.
             */
            function owner() public view virtual returns (address) {
                return _owner;
            }
            /**
             * @dev Throws if the sender is not the owner.
             */
            function _checkOwner() internal view virtual {
                require(owner() == _msgSender(), "Ownable: caller is not the owner");
            }
            /**
             * @dev Leaves the contract without owner. It will not be possible to call
             * `onlyOwner` functions. Can only be called by the current owner.
             *
             * NOTE: Renouncing ownership will leave the contract without an owner,
             * thereby disabling any functionality that is only available to the owner.
             */
            function renounceOwnership() public virtual onlyOwner {
                _transferOwnership(address(0));
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Can only be called by the current owner.
             */
            function transferOwnership(address newOwner) public virtual onlyOwner {
                require(newOwner != address(0), "Ownable: new owner is the zero address");
                _transferOwnership(newOwner);
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Internal function without access restriction.
             */
            function _transferOwnership(address newOwner) internal virtual {
                address oldOwner = _owner;
                _owner = newOwner;
                emit OwnershipTransferred(oldOwner, newOwner);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.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].
         *
         * The default value of {decimals} is 18. To change this, you should override
         * this function so it returns a different value.
         *
         * 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}.
             *
             * 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 default value returned by this function, unless
             * it's 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 {}
        }
        // 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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
        pragma solidity ^0.8.0;
        import "../IERC20.sol";
        import "../extensions/IERC20Permit.sol";
        import "../../../utils/Address.sol";
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20 {
            using Address for address;
            /**
             * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
            /**
             * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
             * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
             */
            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                require(
                    (value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
            /**
             * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 oldAllowance = token.allowance(address(this), spender);
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
            }
            /**
             * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                unchecked {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                }
            }
            /**
             * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
             * 0 before setting it to a non-zero value.
             */
            function forceApprove(IERC20 token, address spender, uint256 value) internal {
                bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                if (!_callOptionalReturnBool(token, approvalCall)) {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                    _callOptionalReturn(token, approvalCall);
                }
            }
            /**
             * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
             * Revert on invalid signature.
             */
            function safePermit(
                IERC20Permit token,
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) internal {
                uint256 nonceBefore = token.nonces(owner);
                token.permit(owner, spender, value, deadline, v, r, s);
                uint256 nonceAfter = token.nonces(owner);
                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             *
             * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
             */
            function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                // and not revert is the subcall reverts.
                (bool success, bytes memory returndata) = address(token).call(data);
                return
                    success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             *
             * Furthermore, `isContract` will also return true if the target contract within
             * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
             * which only has an effect at the end of a transaction.
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
        // 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;
            }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface Iconfigurator {
            function mintVault(address pool) external view returns(bool);
            function mintVaultMaxSupply(address pool) external view returns(uint256);
            function vaultMintPaused(address pool) external view returns(bool);
            function vaultBurnPaused(address pool) external view returns(bool);
            function tokenMiner(address pool) external view returns(bool);
            function getSafeCollateralRatio(address pool) external view returns(uint256);
            function getBadCollateralRatio(address pool) external view returns(uint256);
            function getVaultWeight(address pool) external view returns (uint256);
            function vaultMintFeeApy(address pool) external view returns(uint256);
            function vaultKeeperRatio(address pool) external view returns(uint256);
            function redemptionFee() external view returns(uint256);
            function getEUSDAddress() external view returns(address);
            function peUSD() external view returns(address);
            function eUSDMiningIncentives() external view returns(address);
            function getProtocolRewardsPool() external view returns(address);
            function flashloanFee() external view returns(uint256);
            function getEUSDMaxLocked() external view returns (uint256);
            function stableToken() external view returns (address);
            function isRedemptionProvider(address user) external view returns (bool);
            function becomeRedemptionProvider(bool _bool) external;
            function refreshMintReward(address user) external;
            function distributeRewards() external;
            function hasRole(bytes32 role, address account) external view returns (bool);
        }// SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface IesLBR {
            function totalSupply() external view returns (uint256);
            function balanceOf(address account) external view returns (uint256);
            function mint(address user, uint256 amount) external returns(bool);
            function burn(address user, uint256 amount) external returns(bool);
            function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
            function getPastTotalSupply(uint256 timepoint) external view returns (uint256);
        }// SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface ILBR {
            function totalSupply() external view returns (uint256);
            function balanceOf(address account) external view returns (uint256);
            function mint(address user, uint256 amount) external returns(bool);
            function burn(address user, uint256 amount) external returns(bool);
        }// SPDX-License-Identifier: GPL-3.0
        pragma solidity ^0.8.17;
        /**
         * @title ProtocolRewardsPool is a derivative version of Synthetix StakingRewards.sol, distributing Protocol revenue to esLBR stakers.
         * Converting esLBR to LBR.
         * Differences from the original contract,
         * - Get `totalStaked` from totalSupply() in contract esLBR.
         * - Get `stakedOf(user)` from balanceOf(user) in contract esLBR.
         * - When an address esLBR balance changes, call the refreshReward method to update rewards to be claimed.
         */
        import "@openzeppelin/contracts/access/Ownable.sol";
        import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
        import "../interfaces/Iconfigurator.sol";
        import "../interfaces/IesLBR.sol";
        import "../interfaces/ILBR.sol";
        import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
        import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
        interface IesLBRBoost {
            function userLockStatus(
                address user
            ) external view returns (uint256, uint256, uint256, uint256);
        }
        contract ProtocolRewardsPool is Ownable {
            using SafeERC20 for ERC20;
            Iconfigurator public immutable configurator;
            IesLBR public esLBR;
            ILBR public LBR;
            IesLBRBoost public esLBRBoost;
            AggregatorV3Interface internal lbrPriceFeed;
            // Sum of (reward ratio * dt * 1e18 / total supply)
            uint public rewardPerTokenStored;
            // User address => rewardPerTokenStored
            mapping(address => uint) public userRewardPerTokenPaid;
            // User address => rewards to be claimed
            mapping(address => uint) public rewards;
            mapping(address => uint) public time2fullRedemption;
            mapping(address => uint) public unstakeRatio;
            mapping(address => uint) public lastWithdrawTime;
            uint256 immutable exitCycle = 90 days;
            uint256 public grabableAmount;
            uint256 public grabFeeRatio = 3000;
            event Restake(address indexed user, uint256 amount, uint256 time);
            event StakeLBR(address indexed user, uint256 amount, uint256 time);
            event UnstakeLBR(address indexed user, uint256 amount, uint256 time);
            event WithdrawLBR(address indexed user, uint256 amount, uint256 time);
            event UnlockPrematurely(address indexed user, uint256 amount, uint256 time);
            event ClaimReward(address indexed user, uint256 eUSDAmount, address indexed token, uint256 tokenAmount, uint256 time);
            event GrabEsLBR(address indexed user, uint256 esLBRAmount, uint256 payAmount, bool useEUSD, uint256 time);
            constructor(address _config) {
                configurator = Iconfigurator(_config);
            }
            function setTokenAddress(address _eslbr, address _lbr, address _boost, address _lbrOracle) external onlyOwner {
                esLBR = IesLBR(_eslbr);
                LBR = ILBR(_lbr);
                esLBRBoost = IesLBRBoost(_boost);
                lbrPriceFeed = AggregatorV3Interface(_lbrOracle);
            }
            function setGrabCost(uint256 _ratio) external onlyOwner {
                require(_ratio <= 8000, "BCE");
                grabFeeRatio = _ratio;
            }
            function setLBROracle(address _lbrOracle) external onlyOwner {
                lbrPriceFeed = AggregatorV3Interface(_lbrOracle);
            }
            // Total staked
            function totalStaked() internal view returns (uint256) {
                return esLBR.totalSupply();
            }
            // User address => esLBR balance
            function stakedOf(address staker) internal view returns (uint256) {
                return esLBR.balanceOf(staker);
            }
            function stake(uint256 amount) external {
                LBR.burn(msg.sender, amount);
                esLBR.mint(msg.sender, amount);
                emit StakeLBR(msg.sender, amount, block.timestamp);
            }
            /**
             * @dev Unlocks esLBR and converts it to LBR.
             * @param amount The amount to convert.
             * Requirements:
             * If the current time is less than the unlock time of the user's lock status in the esLBRBoost contract,
             * the locked portion in the esLBRBoost contract cannot be unlocked.
             * Effects:
             * Resets the user's vesting data, entering a new vesting period, when converting to LBR.
             */
            function unstake(uint256 amount) external {
                (uint256 lockedAmount, uint256 unLockTime,,) = esLBRBoost.userLockStatus(msg.sender);
                if(block.timestamp < unLockTime) {
                    require(esLBR.balanceOf(msg.sender) >= lockedAmount + amount, "UCE");
                }
                esLBR.burn(msg.sender, amount);
                withdraw(msg.sender);
                uint256 total = amount;
                if (time2fullRedemption[msg.sender] > block.timestamp) {
                    total += unstakeRatio[msg.sender] * (time2fullRedemption[msg.sender] - block.timestamp);
                }
                unstakeRatio[msg.sender] = total / exitCycle;
                time2fullRedemption[msg.sender] = block.timestamp + exitCycle;
                emit UnstakeLBR(msg.sender, amount, block.timestamp);
            }
            function withdraw(address user) public {
                uint256 amount = getClaimAbleLBR(user);
                if (amount > 0) {
                    LBR.mint(user, amount);
                }
                lastWithdrawTime[user] = block.timestamp;
                emit WithdrawLBR(user, amount, block.timestamp);
            }
            /**
             * @dev Redeems and converts the ESLBR being claimed in advance,
             * with the lost portion being recorded in the contract and available for others to purchase in LBR at a certain ratio.
             */
            function unlockPrematurely() external {
                require(block.timestamp + exitCycle - 3 days > time2fullRedemption[msg.sender], "ENW");
                uint256 burnAmount = getReservedLBRForVesting(msg.sender) - getPreUnlockableAmount(msg.sender);
                uint256 amount = getPreUnlockableAmount(msg.sender) + getClaimAbleLBR(msg.sender);
                if (amount > 0) {
                    LBR.mint(msg.sender, amount);
                }
                unstakeRatio[msg.sender] = 0;
                time2fullRedemption[msg.sender] = 0;
                grabableAmount += burnAmount;
                emit UnlockPrematurely(msg.sender, amount, block.timestamp);
            }
            /**
             * @dev Purchase the accumulated amount of pre-claimed lost ESLBR in the contract using LBR or eUSD.
             * @param amount The amount of ESLBR to be purchased.
             * Requirements:
             * The amount must be greater than 1e17.
             */
            function grabEsLBR(uint256 amount, bool useEUSD) external {
                require(amount > 1e17, "QMG");
                grabableAmount -= amount;
                uint256 payAmount = amount * grabFeeRatio / 10_000;
                if(useEUSD) {
                    (, int lbrPrice, , , ) = lbrPriceFeed.latestRoundData();
                    payAmount = payAmount * uint256(lbrPrice) / 1e8;
                    bool success = ERC20(configurator.getEUSDAddress()).transferFrom(msg.sender, address(owner()), payAmount);
                    require(success, "TF");
                } else {
                    LBR.burn(msg.sender, payAmount);
                }
                esLBR.mint(msg.sender, amount);
                emit GrabEsLBR(msg.sender, amount, payAmount, useEUSD, block.timestamp);
            }
            /**
             * @dev Convert unredeemed and converting LBR tokens back to esLBR.
             */
            function reStake() external {
                uint256 amount = getReservedLBRForVesting(msg.sender) + getClaimAbleLBR(msg.sender);
                esLBR.mint(msg.sender, amount);
                unstakeRatio[msg.sender] = 0;
                time2fullRedemption[msg.sender] = 0;
                emit Restake(msg.sender, amount, block.timestamp);
            }
            function getPreUnlockableAmount(address user) public view returns (uint256 amount) {
                uint256 a = getReservedLBRForVesting(user);
                if (a == 0) return 0;
                amount = (a * (75e18 - ((time2fullRedemption[user] - block.timestamp) * 70e18) / (exitCycle / 1 days - 3) / 1 days)) / 100e18;
            }
            function getClaimAbleLBR(address user) public view returns (uint256 amount) {
                if (time2fullRedemption[user] > lastWithdrawTime[user]) {
                    amount = block.timestamp > time2fullRedemption[user] ? unstakeRatio[user] * (time2fullRedemption[user] - lastWithdrawTime[user]) : unstakeRatio[user] * (block.timestamp - lastWithdrawTime[user]);
                }
            }
            function getReservedLBRForVesting(address user) public view returns (uint256 amount) {
                if (time2fullRedemption[user] > block.timestamp) {
                    amount = unstakeRatio[user] * (time2fullRedemption[user] - block.timestamp);
                }
            }
            function earned(address _account) public view returns (uint) {
                return ((stakedOf(_account) * (rewardPerTokenStored - userRewardPerTokenPaid[_account])) / 1e18) + rewards[_account];
            }
            /**
             * @dev Call this function when deposit or withdraw ETH on Lybra and update the status of corresponding user.
             */
            modifier updateReward(address account) {
                rewards[account] = earned(account);
                userRewardPerTokenPaid[account] = rewardPerTokenStored;
                _;
            }
            function refreshReward(address _account) external updateReward(_account) {}
            /**
             * @notice When claiming protocol rewards earnings, 
             * peUSD will be prioritized for distribution if there is a sufficient amount of peUSD in the Protocol Rewards Pool. 
             * If the peUSD balance is insufficient, earnings will be distributed in the order of other stablecoins such as USDC.
             */
            function getReward() external updateReward(msg.sender) {
                uint reward = rewards[msg.sender];
                if (reward > 0) {
                    rewards[msg.sender] = 0;
                    ERC20 peUSD = ERC20(configurator.peUSD());
                    uint256 balance = peUSD.balanceOf(address(this));
                    uint256 peUSDAmount = balance >= reward ? reward : balance;
                    peUSD.transfer(msg.sender, peUSDAmount);
                    if(reward > peUSDAmount) {
                        ERC20 token = ERC20(configurator.stableToken());
                        uint256 tokenAmount = (reward - peUSDAmount) * (10 ** token.decimals()) / 1e18;
                        token.safeTransfer(msg.sender, tokenAmount);
                        emit ClaimReward(msg.sender, peUSDAmount, address(token), reward - peUSDAmount, block.timestamp);
                    } else {
                        emit ClaimReward(msg.sender, peUSDAmount, address(0), 0, block.timestamp);
                    }
                   
                }
            }
            /**
             * @notice Notifies the protocol rewards pool about the amount of rewards to be distributed and the token type.
             * @param amount The amount of rewards to be distributed.
             * @param tokenType The type of token (0 for peUSD, 1 for other stablecoins).
             * Requirements:
             * - The caller must be the configurator contract.
             * - There must be staked tokens in the protocol rewards pool.
             * - The amount must not be zero.
             * @dev When receiving stablecoin tokens other than eUSD, the decimals of the token are converted to 18 for consistent calculations.
             */
            function notifyRewardAmount(uint amount, uint tokenType) external {
                require(msg.sender == address(configurator), "NA");
                if (totalStaked() == 0) return;
                require(amount != 0, "amount = 0");
                if(tokenType == 1) {
                    ERC20 token = ERC20(configurator.stableToken());
                    rewardPerTokenStored = rewardPerTokenStored + (amount * 1e36 / (10 ** token.decimals())) / totalStaked();
                } else {
                    rewardPerTokenStored = rewardPerTokenStored + (amount * 1e18) / totalStaked();
                }
            }
        }
        

        File 2 of 4: LBR
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.5.0;
        import "./ILayerZeroUserApplicationConfig.sol";
        interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
            // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
            // @param _dstChainId - the destination chain identifier
            // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
            // @param _payload - a custom bytes payload to send to the destination contract
            // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
            // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
            // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
            function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
            // @notice used by the messaging library to publish verified payload
            // @param _srcChainId - the source chain identifier
            // @param _srcAddress - the source contract (as bytes) at the source chain
            // @param _dstAddress - the address on destination chain
            // @param _nonce - the unbound message ordering nonce
            // @param _gasLimit - the gas limit for external contract execution
            // @param _payload - verified payload to send to the destination contract
            function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
            // @notice get the inboundNonce of a lzApp from a source chain which could be EVM or non-EVM chain
            // @param _srcChainId - the source chain identifier
            // @param _srcAddress - the source chain contract address
            function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
            // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
            // @param _srcAddress - the source chain contract address
            function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
            // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
            // @param _dstChainId - the destination chain identifier
            // @param _userApplication - the user app address on this EVM chain
            // @param _payload - the custom message to send over LayerZero
            // @param _payInZRO - if false, user app pays the protocol fee in native token
            // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
            function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
            // @notice get this Endpoint's immutable source identifier
            function getChainId() external view returns (uint16);
            // @notice the interface to retry failed message on this Endpoint destination
            // @param _srcChainId - the source chain identifier
            // @param _srcAddress - the source chain contract address
            // @param _payload - the payload to be retried
            function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
            // @notice query if any STORED payload (message blocking) at the endpoint.
            // @param _srcChainId - the source chain identifier
            // @param _srcAddress - the source chain contract address
            function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
            // @notice query if the _libraryAddress is valid for sending msgs.
            // @param _userApplication - the user app address on this EVM chain
            function getSendLibraryAddress(address _userApplication) external view returns (address);
            // @notice query if the _libraryAddress is valid for receiving msgs.
            // @param _userApplication - the user app address on this EVM chain
            function getReceiveLibraryAddress(address _userApplication) external view returns (address);
            // @notice query if the non-reentrancy guard for send() is on
            // @return true if the guard is on. false otherwise
            function isSendingPayload() external view returns (bool);
            // @notice query if the non-reentrancy guard for receive() is on
            // @return true if the guard is on. false otherwise
            function isReceivingPayload() external view returns (bool);
            // @notice get the configuration of the LayerZero messaging library of the specified version
            // @param _version - messaging library version
            // @param _chainId - the chainId for the pending config change
            // @param _userApplication - the contract address of the user application
            // @param _configType - type of configuration. every messaging library has its own convention.
            function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
            // @notice get the send() LayerZero messaging library version
            // @param _userApplication - the contract address of the user application
            function getSendVersion(address _userApplication) external view returns (uint16);
            // @notice get the lzReceive() LayerZero messaging library version
            // @param _userApplication - the contract address of the user application
            function getReceiveVersion(address _userApplication) external view returns (uint16);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.5.0;
        interface ILayerZeroReceiver {
            // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
            // @param _srcChainId - the source endpoint identifier
            // @param _srcAddress - the source sending contract address from the source chain
            // @param _nonce - the ordered message nonce
            // @param _payload - the signed payload is the UA bytes has encoded to be sent
            function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.5.0;
        interface ILayerZeroUserApplicationConfig {
            // @notice set the configuration of the LayerZero messaging library of the specified version
            // @param _version - messaging library version
            // @param _chainId - the chainId for the pending config change
            // @param _configType - type of configuration. every messaging library has its own convention.
            // @param _config - configuration in the bytes. can encode arbitrary content.
            function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
            // @notice set the send() LayerZero messaging library version to _version
            // @param _version - new messaging library version
            function setSendVersion(uint16 _version) external;
            // @notice set the lzReceive() LayerZero messaging library version to _version
            // @param _version - new messaging library version
            function setReceiveVersion(uint16 _version) external;
            // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
            // @param _srcChainId - the chainId of the source chain
            // @param _srcAddress - the contract address of the source contract at the source chain
            function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import "@openzeppelin/contracts/access/Ownable.sol";
        import "../interfaces/ILayerZeroReceiver.sol";
        import "../interfaces/ILayerZeroUserApplicationConfig.sol";
        import "../interfaces/ILayerZeroEndpoint.sol";
        import "../util/BytesLib.sol";
        /*
         * a generic LzReceiver implementation
         */
        abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
            using BytesLib for bytes;
            // ua can not send payload larger than this by default, but it can be changed by the ua owner
            uint constant public DEFAULT_PAYLOAD_SIZE_LIMIT = 10000;
            ILayerZeroEndpoint public immutable lzEndpoint;
            mapping(uint16 => bytes) public trustedRemoteLookup;
            mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
            mapping(uint16 => uint) public payloadSizeLimitLookup;
            address public precrime;
            event SetPrecrime(address precrime);
            event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
            event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
            event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
            constructor(address _endpoint) {
                lzEndpoint = ILayerZeroEndpoint(_endpoint);
            }
            function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual override {
                // lzReceive must be called by the endpoint for security
                require(_msgSender() == address(lzEndpoint), "LzApp: invalid endpoint caller");
                bytes memory trustedRemote = trustedRemoteLookup[_srcChainId];
                // if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.
                require(_srcAddress.length == trustedRemote.length && trustedRemote.length > 0 && keccak256(_srcAddress) == keccak256(trustedRemote), "LzApp: invalid source sending contract");
                _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
            }
            // abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging
            function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
            function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint _nativeFee) internal virtual {
                bytes memory trustedRemote = trustedRemoteLookup[_dstChainId];
                require(trustedRemote.length != 0, "LzApp: destination chain is not a trusted source");
                _checkPayloadSize(_dstChainId, _payload.length);
                lzEndpoint.send{value: _nativeFee}(_dstChainId, trustedRemote, _payload, _refundAddress, _zroPaymentAddress, _adapterParams);
            }
            function _checkGasLimit(uint16 _dstChainId, uint16 _type, bytes memory _adapterParams, uint _extraGas) internal view virtual {
                uint providedGasLimit = _getGasLimit(_adapterParams);
                uint minGasLimit = minDstGasLookup[_dstChainId][_type] + _extraGas;
                require(minGasLimit > 0, "LzApp: minGasLimit not set");
                require(providedGasLimit >= minGasLimit, "LzApp: gas limit is too low");
            }
            function _getGasLimit(bytes memory _adapterParams) internal pure virtual returns (uint gasLimit) {
                require(_adapterParams.length >= 34, "LzApp: invalid adapterParams");
                assembly {
                    gasLimit := mload(add(_adapterParams, 34))
                }
            }
            function _checkPayloadSize(uint16 _dstChainId, uint _payloadSize) internal view virtual {
                uint payloadSizeLimit = payloadSizeLimitLookup[_dstChainId];
                if (payloadSizeLimit == 0) { // use default if not set
                    payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT;
                }
                require(_payloadSize <= payloadSizeLimit, "LzApp: payload size is too large");
            }
            //---------------------------UserApplication config----------------------------------------
            function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
                return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
            }
            // generic config for LayerZero user Application
            function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override onlyOwner {
                lzEndpoint.setConfig(_version, _chainId, _configType, _config);
            }
            function setSendVersion(uint16 _version) external override onlyOwner {
                lzEndpoint.setSendVersion(_version);
            }
            function setReceiveVersion(uint16 _version) external override onlyOwner {
                lzEndpoint.setReceiveVersion(_version);
            }
            function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                lzEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
            }
            // _path = abi.encodePacked(remoteAddress, localAddress)
            // this function set the trusted path for the cross-chain communication
            function setTrustedRemote(uint16 _remoteChainId, bytes calldata _path) external onlyOwner {
                trustedRemoteLookup[_remoteChainId] = _path;
                emit SetTrustedRemote(_remoteChainId, _path);
            }
            function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external onlyOwner {
                trustedRemoteLookup[_remoteChainId] = abi.encodePacked(_remoteAddress, address(this));
                emit SetTrustedRemoteAddress(_remoteChainId, _remoteAddress);
            }
            function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory) {
                bytes memory path = trustedRemoteLookup[_remoteChainId];
                require(path.length != 0, "LzApp: no trusted path record");
                return path.slice(0, path.length - 20); // the last 20 bytes should be address(this)
            }
            function setPrecrime(address _precrime) external onlyOwner {
                precrime = _precrime;
                emit SetPrecrime(_precrime);
            }
            function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint _minGas) external onlyOwner {
                require(_minGas > 0, "LzApp: invalid minGas");
                minDstGasLookup[_dstChainId][_packetType] = _minGas;
                emit SetMinDstGas(_dstChainId, _packetType, _minGas);
            }
            // if the size is 0, it means default size limit
            function setPayloadSizeLimit(uint16 _dstChainId, uint _size) external onlyOwner {
                payloadSizeLimitLookup[_dstChainId] = _size;
            }
            //--------------------------- VIEW FUNCTION ----------------------------------------
            function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool) {
                bytes memory trustedSource = trustedRemoteLookup[_srcChainId];
                return keccak256(trustedSource) == keccak256(_srcAddress);
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import "./LzApp.sol";
        import "../util/ExcessivelySafeCall.sol";
        /*
         * the default LayerZero messaging behaviour is blocking, i.e. any failed message will block the channel
         * this abstract class try-catch all fail messages and store locally for future retry. hence, non-blocking
         * NOTE: if the srcAddress is not configured properly, it will still block the message pathway from (srcChainId, srcAddress)
         */
        abstract contract NonblockingLzApp is LzApp {
            using ExcessivelySafeCall for address;
            constructor(address _endpoint) LzApp(_endpoint) {}
            mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages;
            event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);
            event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);
            // overriding the virtual function in LzReceiver
            function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                (bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft(), 150, abi.encodeWithSelector(this.nonblockingLzReceive.selector, _srcChainId, _srcAddress, _nonce, _payload));
                // try-catch all errors/exceptions
                if (!success) {
                    _storeFailedMessage(_srcChainId, _srcAddress, _nonce, _payload, reason);
                }
            }
            function _storeFailedMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload, bytes memory _reason) internal virtual {
                failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
                emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload, _reason);
            }
            function nonblockingLzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual {
                // only internal transaction
                require(_msgSender() == address(this), "NonblockingLzApp: caller must be LzApp");
                _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
            }
            //@notice override this function
            function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
            function retryMessage(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public payable virtual {
                // assert there is message to retry
                bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce];
                require(payloadHash != bytes32(0), "NonblockingLzApp: no stored message");
                require(keccak256(_payload) == payloadHash, "NonblockingLzApp: invalid payload");
                // clear the stored message
                failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0);
                // execute the message. revert if it fails again
                _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                emit RetryMessageSuccess(_srcChainId, _srcAddress, _nonce, payloadHash);
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import "./OFTCoreV2.sol";
        import "./IOFTV2.sol";
        import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
        abstract contract BaseOFTV2 is OFTCoreV2, ERC165, IOFTV2 {
            constructor(uint8 _sharedDecimals, address _lzEndpoint) OFTCoreV2(_sharedDecimals, _lzEndpoint) {
            }
            /************************************************************************
            * public functions
            ************************************************************************/
            function sendFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, LzCallParams calldata _callParams) public payable virtual override {
                _send(_from, _dstChainId, _toAddress, _amount, _callParams.refundAddress, _callParams.zroPaymentAddress, _callParams.adapterParams);
            }
            function sendAndCall(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes calldata _payload, uint64 _dstGasForCall, LzCallParams calldata _callParams) public payable virtual override {
                _sendAndCall(_from, _dstChainId, _toAddress, _amount, _payload, _dstGasForCall, _callParams.refundAddress, _callParams.zroPaymentAddress, _callParams.adapterParams);
            }
            /************************************************************************
            * public view functions
            ************************************************************************/
            function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
                return interfaceId == type(IOFTV2).interfaceId || super.supportsInterface(interfaceId);
            }
            function estimateSendFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) public view virtual override returns (uint nativeFee, uint zroFee) {
                return _estimateSendFee(_dstChainId, _toAddress, _amount, _useZro, _adapterParams);
            }
            function estimateSendAndCallFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes calldata _payload, uint64 _dstGasForCall, bool _useZro, bytes calldata _adapterParams) public view virtual override returns (uint nativeFee, uint zroFee) {
                return _estimateSendAndCallFee(_dstChainId, _toAddress, _amount, _payload, _dstGasForCall, _useZro, _adapterParams);
            }
            function circulatingSupply() public view virtual override returns (uint);
            function token() public view virtual override returns (address);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.5.0;
        import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
        /**
         * @dev Interface of the IOFT core standard
         */
        interface ICommonOFT is IERC165 {
            struct LzCallParams {
                address payable refundAddress;
                address zroPaymentAddress;
                bytes adapterParams;
            }
            /**
             * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
             * _dstChainId - L0 defined chain id to send tokens too
             * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
             * _amount - amount of the tokens to transfer
             * _useZro - indicates to use zro to pay L0 fees
             * _adapterParam - flexible bytes array to indicate messaging adapter services in L0
             */
            function estimateSendFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
            function estimateSendAndCallFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes calldata _payload, uint64 _dstGasForCall, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
            /**
             * @dev returns the circulating amount of tokens on current chain
             */
            function circulatingSupply() external view returns (uint);
            /**
             * @dev returns the address of the ERC20 token
             */
            function token() external view returns (address);
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity >=0.5.0;
        interface IOFTReceiverV2 {
            /**
             * @dev Called by the OFT contract when tokens are received from source chain.
             * @param _srcChainId The chain id of the source chain.
             * @param _srcAddress The address of the OFT token contract on the source chain.
             * @param _nonce The nonce of the transaction on the source chain.
             * @param _from The address of the account who calls the sendAndCall() on the source chain.
             * @param _amount The amount of tokens to transfer.
             * @param _payload Additional data with no specified format.
             */
            function onOFTReceived(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes32 _from, uint _amount, bytes calldata _payload) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.5.0;
        import "./ICommonOFT.sol";
        /**
         * @dev Interface of the IOFT core standard
         */
        interface IOFTV2 is ICommonOFT {
            /**
             * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
             * `_from` the owner of token
             * `_dstChainId` the destination chain identifier
             * `_toAddress` can be any size depending on the `dstChainId`.
             * `_amount` the quantity of tokens in wei
             * `_refundAddress` the address LayerZero refunds if too much message fee is sent
             * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
             * `_adapterParams` is a flexible bytes array to indicate messaging adapter services
             */
            function sendFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, LzCallParams calldata _callParams) external payable;
            function sendAndCall(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes calldata _payload, uint64 _dstGasForCall, LzCallParams calldata _callParams) external payable;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import "../../../lzApp/NonblockingLzApp.sol";
        import "../../../util/ExcessivelySafeCall.sol";
        import "./ICommonOFT.sol";
        import "./IOFTReceiverV2.sol";
        abstract contract OFTCoreV2 is NonblockingLzApp {
            using BytesLib for bytes;
            using ExcessivelySafeCall for address;
            uint public constant NO_EXTRA_GAS = 0;
            // packet type
            uint8 public constant PT_SEND = 0;
            uint8 public constant PT_SEND_AND_CALL = 1;
            uint8 public immutable sharedDecimals;
            bool public useCustomAdapterParams;
            mapping(uint16 => mapping(bytes => mapping(uint64 => bool))) public creditedPackets;
            /**
             * @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`)
             * `_nonce` is the outbound nonce
             */
            event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes32 indexed _toAddress, uint _amount);
            /**
             * @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain.
             * `_nonce` is the inbound nonce.
             */
            event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint _amount);
            event SetUseCustomAdapterParams(bool _useCustomAdapterParams);
            event CallOFTReceivedSuccess(uint16 indexed _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _hash);
            event NonContractAddress(address _address);
            // _sharedDecimals should be the minimum decimals on all chains
            constructor(uint8 _sharedDecimals, address _lzEndpoint) NonblockingLzApp(_lzEndpoint) {
                sharedDecimals = _sharedDecimals;
            }
            /************************************************************************
            * public functions
            ************************************************************************/
            function callOnOFTReceived(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes32 _from, address _to, uint _amount, bytes calldata _payload, uint _gasForCall) public virtual {
                require(_msgSender() == address(this), "OFTCore: caller must be OFTCore");
                // send
                _amount = _transferFrom(address(this), _to, _amount);
                emit ReceiveFromChain(_srcChainId, _to, _amount);
                // call
                IOFTReceiverV2(_to).onOFTReceived{gas: _gasForCall}(_srcChainId, _srcAddress, _nonce, _from, _amount, _payload);
            }
            function setUseCustomAdapterParams(bool _useCustomAdapterParams) public virtual onlyOwner {
                useCustomAdapterParams = _useCustomAdapterParams;
                emit SetUseCustomAdapterParams(_useCustomAdapterParams);
            }
            /************************************************************************
            * internal functions
            ************************************************************************/
            function _estimateSendFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bool _useZro, bytes memory _adapterParams) internal view virtual returns (uint nativeFee, uint zroFee) {
                // mock the payload for sendFrom()
                bytes memory payload = _encodeSendPayload(_toAddress, _ld2sd(_amount));
                return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams);
            }
            function _estimateSendAndCallFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes memory _payload, uint64 _dstGasForCall, bool _useZro, bytes memory _adapterParams) internal view virtual returns (uint nativeFee, uint zroFee) {
                // mock the payload for sendAndCall()
                bytes memory payload = _encodeSendAndCallPayload(msg.sender, _toAddress, _ld2sd(_amount), _payload, _dstGasForCall);
                return lzEndpoint.estimateFees(_dstChainId, address(this), payload, _useZro, _adapterParams);
            }
            function _nonblockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
                uint8 packetType = _payload.toUint8(0);
                if (packetType == PT_SEND) {
                    _sendAck(_srcChainId, _srcAddress, _nonce, _payload);
                } else if (packetType == PT_SEND_AND_CALL) {
                    _sendAndCallAck(_srcChainId, _srcAddress, _nonce, _payload);
                } else {
                    revert("OFTCore: unknown packet type");
                }
            }
            function _send(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams) internal virtual returns (uint amount) {
                _checkAdapterParams(_dstChainId, PT_SEND, _adapterParams, NO_EXTRA_GAS);
                (amount,) = _removeDust(_amount);
                amount = _debitFrom(_from, _dstChainId, _toAddress, amount); // amount returned should not have dust
                require(amount > 0, "OFTCore: amount too small");
                bytes memory lzPayload = _encodeSendPayload(_toAddress, _ld2sd(amount));
                _lzSend(_dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value);
                emit SendToChain(_dstChainId, _from, _toAddress, amount);
            }
            function _sendAck(uint16 _srcChainId, bytes memory, uint64, bytes memory _payload) internal virtual {
                (address to, uint64 amountSD) = _decodeSendPayload(_payload);
                if (to == address(0)) {
                    to = address(0xdead);
                }
                uint amount = _sd2ld(amountSD);
                amount = _creditTo(_srcChainId, to, amount);
                emit ReceiveFromChain(_srcChainId, to, amount);
            }
            function _sendAndCall(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes memory _payload, uint64 _dstGasForCall, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams) internal virtual returns (uint amount) {
                _checkAdapterParams(_dstChainId, PT_SEND_AND_CALL, _adapterParams, _dstGasForCall);
                (amount,) = _removeDust(_amount);
                amount = _debitFrom(_from, _dstChainId, _toAddress, amount);
                require(amount > 0, "OFTCore: amount too small");
                // encode the msg.sender into the payload instead of _from
                bytes memory lzPayload = _encodeSendAndCallPayload(msg.sender, _toAddress, _ld2sd(amount), _payload, _dstGasForCall);
                _lzSend(_dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value);
                emit SendToChain(_dstChainId, _from, _toAddress, amount);
            }
            function _sendAndCallAck(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual {
                (bytes32 from, address to, uint64 amountSD, bytes memory payloadForCall, uint64 gasForCall) = _decodeSendAndCallPayload(_payload);
                bool credited = creditedPackets[_srcChainId][_srcAddress][_nonce];
                uint amount = _sd2ld(amountSD);
                // credit to this contract first, and then transfer to receiver only if callOnOFTReceived() succeeds
                if (!credited) {
                    amount = _creditTo(_srcChainId, address(this), amount);
                    creditedPackets[_srcChainId][_srcAddress][_nonce] = true;
                }
                if (!_isContract(to)) {
                    emit NonContractAddress(to);
                    return;
                }
                // workaround for stack too deep
                uint16 srcChainId = _srcChainId;
                bytes memory srcAddress = _srcAddress;
                uint64 nonce = _nonce;
                bytes memory payload = _payload;
                bytes32 from_ = from;
                address to_ = to;
                uint amount_ = amount;
                bytes memory payloadForCall_ = payloadForCall;
                // no gas limit for the call if retry
                uint gas = credited ? gasleft() : gasForCall;
                (bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft(), 150, abi.encodeWithSelector(this.callOnOFTReceived.selector, srcChainId, srcAddress, nonce, from_, to_, amount_, payloadForCall_, gas));
                if (success) {
                    bytes32 hash = keccak256(payload);
                    emit CallOFTReceivedSuccess(srcChainId, srcAddress, nonce, hash);
                } else {
                    // store the failed message into the nonblockingLzApp
                    _storeFailedMessage(srcChainId, srcAddress, nonce, payload, reason);
                }
            }
            function _isContract(address _account) internal view returns (bool) {
                return _account.code.length > 0;
            }
            function _checkAdapterParams(uint16 _dstChainId, uint16 _pkType, bytes memory _adapterParams, uint _extraGas) internal virtual {
                if (useCustomAdapterParams) {
                    _checkGasLimit(_dstChainId, _pkType, _adapterParams, _extraGas);
                } else {
                    require(_adapterParams.length == 0, "OFTCore: _adapterParams must be empty.");
                }
            }
            function _ld2sd(uint _amount) internal virtual view returns (uint64) {
                uint amountSD = _amount / _ld2sdRate();
                require(amountSD <= type(uint64).max, "OFTCore: amountSD overflow");
                return uint64(amountSD);
            }
            function _sd2ld(uint64 _amountSD) internal virtual view returns (uint) {
                return _amountSD * _ld2sdRate();
            }
            function _removeDust(uint _amount) internal virtual view returns (uint amountAfter, uint dust) {
                dust = _amount % _ld2sdRate();
                amountAfter = _amount - dust;
            }
            function _encodeSendPayload(bytes32 _toAddress, uint64 _amountSD) internal virtual view returns (bytes memory) {
                return abi.encodePacked(PT_SEND, _toAddress, _amountSD);
            }
            function _decodeSendPayload(bytes memory _payload) internal virtual view returns (address to, uint64 amountSD) {
                require(_payload.toUint8(0) == PT_SEND && _payload.length == 41, "OFTCore: invalid payload");
                to = _payload.toAddress(13); // drop the first 12 bytes of bytes32
                amountSD = _payload.toUint64(33);
            }
            function _encodeSendAndCallPayload(address _from, bytes32 _toAddress, uint64 _amountSD, bytes memory _payload, uint64 _dstGasForCall) internal virtual view returns (bytes memory) {
                return abi.encodePacked(
                    PT_SEND_AND_CALL,
                    _toAddress,
                    _amountSD,
                    _addressToBytes32(_from),
                    _dstGasForCall,
                    _payload
                );
            }
            function _decodeSendAndCallPayload(bytes memory _payload) internal virtual view returns (bytes32 from, address to, uint64 amountSD, bytes memory payload, uint64 dstGasForCall) {
                require(_payload.toUint8(0) == PT_SEND_AND_CALL, "OFTCore: invalid payload");
                to = _payload.toAddress(13); // drop the first 12 bytes of bytes32
                amountSD = _payload.toUint64(33);
                from = _payload.toBytes32(41);
                dstGasForCall = _payload.toUint64(73);
                payload = _payload.slice(81, _payload.length - 81);
            }
            function _addressToBytes32(address _address) internal pure virtual returns (bytes32) {
                return bytes32(uint(uint160(_address)));
            }
            function _debitFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount) internal virtual returns (uint);
            function _creditTo(uint16 _srcChainId, address _toAddress, uint _amount) internal virtual returns (uint);
            function _transferFrom(address _from, address _to, uint _amount) internal virtual returns (uint);
            function _ld2sdRate() internal view virtual returns (uint);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
        import "./BaseOFTV2.sol";
        contract OFTV2 is BaseOFTV2, ERC20 {
            uint internal immutable ld2sdRate;
            constructor(string memory _name, string memory _symbol, uint8 _sharedDecimals, address _lzEndpoint) ERC20(_name, _symbol) BaseOFTV2(_sharedDecimals, _lzEndpoint) {
                uint8 decimals = decimals();
                require(_sharedDecimals <= decimals, "OFT: sharedDecimals must be <= decimals");
                ld2sdRate = 10 ** (decimals - _sharedDecimals);
            }
            /************************************************************************
            * public functions
            ************************************************************************/
            function circulatingSupply() public view virtual override returns (uint) {
                return totalSupply();
            }
            function token() public view virtual override returns (address) {
                return address(this);
            }
            /************************************************************************
            * internal functions
            ************************************************************************/
            function _debitFrom(address _from, uint16, bytes32, uint _amount) internal virtual override returns (uint) {
                address spender = _msgSender();
                if (_from != spender) _spendAllowance(_from, spender, _amount);
                _burn(_from, _amount);
                return _amount;
            }
            function _creditTo(uint16, address _toAddress, uint _amount) internal virtual override returns (uint) {
                _mint(_toAddress, _amount);
                return _amount;
            }
            function _transferFrom(address _from, address _to, uint _amount) internal virtual override returns (uint) {
                address spender = _msgSender();
                // if transfer from this contract, no need to check allowance
                if (_from != address(this) && _from != spender) _spendAllowance(_from, spender, _amount);
                _transfer(_from, _to, _amount);
                return _amount;
            }
            function _ld2sdRate() internal view virtual override returns (uint) {
                return ld2sdRate;
            }
        }
        // SPDX-License-Identifier: Unlicense
        /*
         * @title Solidity Bytes Arrays Utils
         * @author Gonçalo Sá <goncalo.sa@consensys.net>
         *
         * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
         *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
         */
        pragma solidity >=0.8.0 <0.9.0;
        library BytesLib {
            function concat(
                bytes memory _preBytes,
                bytes memory _postBytes
            )
            internal
            pure
            returns (bytes memory)
            {
                bytes memory tempBytes;
                assembly {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                    tempBytes := mload(0x40)
                // Store the length of the first bytes array at the beginning of
                // the memory for tempBytes.
                    let length := mload(_preBytes)
                    mstore(tempBytes, length)
                // Maintain a memory counter for the current write location in the
                // temp bytes array by adding the 32 bytes for the array length to
                // the starting location.
                    let mc := add(tempBytes, 0x20)
                // Stop copying when the memory counter reaches the length of the
                // first bytes array.
                    let end := add(mc, length)
                    for {
                    // Initialize a copy counter to the start of the _preBytes data,
                    // 32 bytes into its memory.
                        let cc := add(_preBytes, 0x20)
                    } lt(mc, end) {
                    // Increase both counters by 32 bytes each iteration.
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                    // Write the _preBytes data into the tempBytes memory 32 bytes
                    // at a time.
                        mstore(mc, mload(cc))
                    }
                // Add the length of _postBytes to the current length of tempBytes
                // and store it as the new length in the first 32 bytes of the
                // tempBytes memory.
                    length := mload(_postBytes)
                    mstore(tempBytes, add(length, mload(tempBytes)))
                // Move the memory counter back from a multiple of 0x20 to the
                // actual end of the _preBytes data.
                    mc := end
                // Stop copying when the memory counter reaches the new combined
                // length of the arrays.
                    end := add(mc, length)
                    for {
                        let cc := add(_postBytes, 0x20)
                    } lt(mc, end) {
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                        mstore(mc, mload(cc))
                    }
                // Update the free-memory pointer by padding our last write location
                // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                // next 32 byte block, then round down to the nearest multiple of
                // 32. If the sum of the length of the two arrays is zero then add
                // one before rounding down to leave a blank 32 bytes (the length block with 0).
                    mstore(0x40, and(
                    add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                    not(31) // Round down to the nearest 32 bytes.
                    ))
                }
                return tempBytes;
            }
            function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                assembly {
                // Read the first 32 bytes of _preBytes storage, which is the length
                // of the array. (We don't need to use the offset into the slot
                // because arrays use the entire slot.)
                    let fslot := sload(_preBytes.slot)
                // Arrays of 31 bytes or less have an even value in their slot,
                // while longer arrays have an odd value. The actual length is
                // the slot divided by two for odd values, and the lowest order
                // byte divided by two for even values.
                // If the slot is even, bitwise and the slot with 255 and divide by
                // two to get the length. If the slot is odd, bitwise and the slot
                // with -1 and divide by two.
                    let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                    let mlength := mload(_postBytes)
                    let newlength := add(slength, mlength)
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                    switch add(lt(slength, 32), lt(newlength, 32))
                    case 2 {
                    // Since the new array still fits in the slot, we just need to
                    // update the contents of the slot.
                    // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                        sstore(
                        _preBytes.slot,
                        // all the modifications to the slot are inside this
                        // next block
                        add(
                        // we can just add to the slot contents because the
                        // bytes we want to change are the LSBs
                        fslot,
                        add(
                        mul(
                        div(
                        // load the bytes from memory
                        mload(add(_postBytes, 0x20)),
                        // zero all bytes to the right
                        exp(0x100, sub(32, mlength))
                        ),
                        // and now shift left the number of bytes to
                        // leave space for the length in the slot
                        exp(0x100, sub(32, newlength))
                        ),
                        // increase length by the double of the memory
                        // bytes length
                        mul(mlength, 2)
                        )
                        )
                        )
                    }
                    case 1 {
                    // The stored value fits in the slot, but the combined value
                    // will exceed it.
                    // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                        let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                    // save new length
                        sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                    // The contents of the _postBytes array start 32 bytes into
                    // the structure. Our first read should obtain the `submod`
                    // bytes that can fit into the unused space in the last word
                    // of the stored array. To get this, we read 32 bytes starting
                    // from `submod`, so the data we read overlaps with the array
                    // contents by `submod` bytes. Masking the lowest-order
                    // `submod` bytes allows us to add that value directly to the
                    // stored value.
                        let submod := sub(32, slength)
                        let mc := add(_postBytes, submod)
                        let end := add(_postBytes, mlength)
                        let mask := sub(exp(0x100, submod), 1)
                        sstore(
                        sc,
                        add(
                        and(
                        fslot,
                        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                        ),
                        and(mload(mc), mask)
                        )
                        )
                        for {
                            mc := add(mc, 0x20)
                            sc := add(sc, 1)
                        } lt(mc, end) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            sstore(sc, mload(mc))
                        }
                        mask := exp(0x100, sub(mc, end))
                        sstore(sc, mul(div(mload(mc), mask), mask))
                    }
                    default {
                    // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                    // Start copying to the last used word of the stored array.
                        let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                    // save new length
                        sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                    // Copy over the first `submod` bytes of the new data as in
                    // case 1 above.
                        let slengthmod := mod(slength, 32)
                        let mlengthmod := mod(mlength, 32)
                        let submod := sub(32, slengthmod)
                        let mc := add(_postBytes, submod)
                        let end := add(_postBytes, mlength)
                        let mask := sub(exp(0x100, submod), 1)
                        sstore(sc, add(sload(sc), and(mload(mc), mask)))
                        for {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } lt(mc, end) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            sstore(sc, mload(mc))
                        }
                        mask := exp(0x100, sub(mc, end))
                        sstore(sc, mul(div(mload(mc), mask), mask))
                    }
                }
            }
            function slice(
                bytes memory _bytes,
                uint256 _start,
                uint256 _length
            )
            internal
            pure
            returns (bytes memory)
            {
                require(_length + 31 >= _length, "slice_overflow");
                require(_bytes.length >= _start + _length, "slice_outOfBounds");
                bytes memory tempBytes;
                assembly {
                    switch iszero(_length)
                    case 0 {
                    // Get a location of some free memory and store it in tempBytes as
                    // Solidity does for memory variables.
                        tempBytes := mload(0x40)
                    // The first word of the slice result is potentially a partial
                    // word read from the original array. To read it, we calculate
                    // the length of that partial word and start copying that many
                    // bytes into the array. The first word we copy will start with
                    // data we don't care about, but the last `lengthmod` bytes will
                    // land at the beginning of the contents of the new array. When
                    // we're done copying, we overwrite the full first word with
                    // the actual length of the slice.
                        let lengthmod := and(_length, 31)
                    // The multiplication in the next line is necessary
                    // because when slicing multiples of 32 bytes (lengthmod == 0)
                    // the following copy loop was copying the origin's length
                    // and then ending prematurely not copying everything it should.
                        let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                        let end := add(mc, _length)
                        for {
                        // The multiplication in the next line has the same exact purpose
                        // as the one above.
                            let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                        } lt(mc, end) {
                            mc := add(mc, 0x20)
                            cc := add(cc, 0x20)
                        } {
                            mstore(mc, mload(cc))
                        }
                        mstore(tempBytes, _length)
                    //update free-memory pointer
                    //allocating the array padded to 32 bytes like the compiler does now
                        mstore(0x40, and(add(mc, 31), not(31)))
                    }
                    //if we want a zero-length slice let's just return a zero-length array
                    default {
                        tempBytes := mload(0x40)
                    //zero out the 32 bytes slice we are about to return
                    //we need to do it because Solidity does not garbage collect
                        mstore(tempBytes, 0)
                        mstore(0x40, add(tempBytes, 0x20))
                    }
                }
                return tempBytes;
            }
            function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
                require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
                address tempAddress;
                assembly {
                    tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                }
                return tempAddress;
            }
            function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
                uint8 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x1), _start))
                }
                return tempUint;
            }
            function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
                uint16 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x2), _start))
                }
                return tempUint;
            }
            function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
                uint32 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x4), _start))
                }
                return tempUint;
            }
            function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
                uint64 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x8), _start))
                }
                return tempUint;
            }
            function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
                uint96 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0xc), _start))
                }
                return tempUint;
            }
            function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
                uint128 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x10), _start))
                }
                return tempUint;
            }
            function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
                uint256 tempUint;
                assembly {
                    tempUint := mload(add(add(_bytes, 0x20), _start))
                }
                return tempUint;
            }
            function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
                bytes32 tempBytes32;
                assembly {
                    tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                }
                return tempBytes32;
            }
            function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                bool success = true;
                assembly {
                    let length := mload(_preBytes)
                // if lengths don't match the arrays are not equal
                    switch eq(length, mload(_postBytes))
                    case 1 {
                    // cb is a circuit breaker in the for loop since there's
                    //  no said feature for inline assembly loops
                    // cb = 1 - don't breaker
                    // cb = 0 - break
                        let cb := 1
                        let mc := add(_preBytes, 0x20)
                        let end := add(mc, length)
                        for {
                            let cc := add(_postBytes, 0x20)
                        // the next line is the loop condition:
                        // while(uint256(mc < end) + cb == 2)
                        } eq(add(lt(mc, end), cb), 2) {
                            mc := add(mc, 0x20)
                            cc := add(cc, 0x20)
                        } {
                        // if any of these checks fails then arrays are not equal
                            if iszero(eq(mload(mc), mload(cc))) {
                            // unsuccess:
                                success := 0
                                cb := 0
                            }
                        }
                    }
                    default {
                    // unsuccess:
                        success := 0
                    }
                }
                return success;
            }
            function equalStorage(
                bytes storage _preBytes,
                bytes memory _postBytes
            )
            internal
            view
            returns (bool)
            {
                bool success = true;
                assembly {
                // we know _preBytes_offset is 0
                    let fslot := sload(_preBytes.slot)
                // Decode the length of the stored array like in concatStorage().
                    let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                    let mlength := mload(_postBytes)
                // if lengths don't match the arrays are not equal
                    switch eq(slength, mlength)
                    case 1 {
                    // slength can contain both the length and contents of the array
                    // if length < 32 bytes so let's prepare for that
                    // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                        if iszero(iszero(slength)) {
                            switch lt(slength, 32)
                            case 1 {
                            // blank the last byte which is the length
                                fslot := mul(div(fslot, 0x100), 0x100)
                                if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                // unsuccess:
                                    success := 0
                                }
                            }
                            default {
                            // cb is a circuit breaker in the for loop since there's
                            //  no said feature for inline assembly loops
                            // cb = 1 - don't breaker
                            // cb = 0 - break
                                let cb := 1
                            // get the keccak hash to get the contents of the array
                                mstore(0x0, _preBytes.slot)
                                let sc := keccak256(0x0, 0x20)
                                let mc := add(_postBytes, 0x20)
                                let end := add(mc, mlength)
                            // the next line is the loop condition:
                            // while(uint256(mc < end) + cb == 2)
                                for {} eq(add(lt(mc, end), cb), 2) {
                                    sc := add(sc, 1)
                                    mc := add(mc, 0x20)
                                } {
                                    if iszero(eq(sload(sc), mload(mc))) {
                                    // unsuccess:
                                        success := 0
                                        cb := 0
                                    }
                                }
                            }
                        }
                    }
                    default {
                    // unsuccess:
                        success := 0
                    }
                }
                return success;
            }
        }
        // SPDX-License-Identifier: MIT OR Apache-2.0
        pragma solidity >=0.7.6;
        library ExcessivelySafeCall {
            uint256 constant LOW_28_MASK =
            0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
            /// @notice Use when you _really_ really _really_ don't trust the called
            /// contract. This prevents the called contract from causing reversion of
            /// the caller in as many ways as we can.
            /// @dev The main difference between this and a solidity low-level call is
            /// that we limit the number of bytes that the callee can cause to be
            /// copied to caller memory. This prevents stupid things like malicious
            /// contracts returning 10,000,000 bytes causing a local OOG when copying
            /// to memory.
            /// @param _target The address to call
            /// @param _gas The amount of gas to forward to the remote contract
            /// @param _maxCopy The maximum number of bytes of returndata to copy
            /// to memory.
            /// @param _calldata The data to send to the remote contract
            /// @return success and returndata, as `.call()`. Returndata is capped to
            /// `_maxCopy` bytes.
            function excessivelySafeCall(
                address _target,
                uint256 _gas,
                uint16 _maxCopy,
                bytes memory _calldata
            ) internal returns (bool, bytes memory) {
                // set up for assembly call
                uint256 _toCopy;
                bool _success;
                bytes memory _returnData = new bytes(_maxCopy);
                // dispatch message to recipient
                // by assembly calling "handle" function
                // we call via assembly to avoid memcopying a very large returndata
                // returned by a malicious contract
                assembly {
                    _success := call(
                    _gas, // gas
                    _target, // recipient
                    0, // ether value
                    add(_calldata, 0x20), // inloc
                    mload(_calldata), // inlen
                    0, // outloc
                    0 // outlen
                    )
                // limit our copy to 256 bytes
                    _toCopy := returndatasize()
                    if gt(_toCopy, _maxCopy) {
                        _toCopy := _maxCopy
                    }
                // Store the length of the copied bytes
                    mstore(_returnData, _toCopy)
                // copy the bytes from returndata[0:_toCopy]
                    returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                }
                return (_success, _returnData);
            }
            /// @notice Use when you _really_ really _really_ don't trust the called
            /// contract. This prevents the called contract from causing reversion of
            /// the caller in as many ways as we can.
            /// @dev The main difference between this and a solidity low-level call is
            /// that we limit the number of bytes that the callee can cause to be
            /// copied to caller memory. This prevents stupid things like malicious
            /// contracts returning 10,000,000 bytes causing a local OOG when copying
            /// to memory.
            /// @param _target The address to call
            /// @param _gas The amount of gas to forward to the remote contract
            /// @param _maxCopy The maximum number of bytes of returndata to copy
            /// to memory.
            /// @param _calldata The data to send to the remote contract
            /// @return success and returndata, as `.call()`. Returndata is capped to
            /// `_maxCopy` bytes.
            function excessivelySafeStaticCall(
                address _target,
                uint256 _gas,
                uint16 _maxCopy,
                bytes memory _calldata
            ) internal view returns (bool, bytes memory) {
                // set up for assembly call
                uint256 _toCopy;
                bool _success;
                bytes memory _returnData = new bytes(_maxCopy);
                // dispatch message to recipient
                // by assembly calling "handle" function
                // we call via assembly to avoid memcopying a very large returndata
                // returned by a malicious contract
                assembly {
                    _success := staticcall(
                    _gas, // gas
                    _target, // recipient
                    add(_calldata, 0x20), // inloc
                    mload(_calldata), // inlen
                    0, // outloc
                    0 // outlen
                    )
                // limit our copy to 256 bytes
                    _toCopy := returndatasize()
                    if gt(_toCopy, _maxCopy) {
                        _toCopy := _maxCopy
                    }
                // Store the length of the copied bytes
                    mstore(_returnData, _toCopy)
                // copy the bytes from returndata[0:_toCopy]
                    returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                }
                return (_success, _returnData);
            }
            /**
             * @notice Swaps function selectors in encoded contract calls
             * @dev Allows reuse of encoded calldata for functions with identical
             * argument types but different names. It simply swaps out the first 4 bytes
             * for the new selector. This function modifies memory in place, and should
             * only be used with caution.
             * @param _newSelector The new 4-byte selector
             * @param _buf The encoded contract args
             */
            function swapSelector(bytes4 _newSelector, bytes memory _buf)
            internal
            pure
            {
                require(_buf.length >= 4);
                uint256 _mask = LOW_28_MASK;
                assembly {
                // load the first word of
                    let _word := mload(add(_buf, 0x20))
                // mask out the top 4 bytes
                // /x
                    _word := and(_word, _mask)
                    _word := or(_newSelector, _word)
                    mstore(add(_buf, 0x20), _word)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/Context.sol";
        /**
         * @dev Contract module which provides a basic access control mechanism, where
         * there is an account (an owner) that can be granted exclusive access to
         * specific functions.
         *
         * By default, the owner account will be the one that deploys the contract. This
         * can later be changed with {transferOwnership}.
         *
         * This module is used through inheritance. It will make available the modifier
         * `onlyOwner`, which can be applied to your functions to restrict their use to
         * the owner.
         */
        abstract contract Ownable is Context {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            constructor() {
                _transferOwnership(_msgSender());
            }
            /**
             * @dev Throws if called by any account other than the owner.
             */
            modifier onlyOwner() {
                _checkOwner();
                _;
            }
            /**
             * @dev Returns the address of the current owner.
             */
            function owner() public view virtual returns (address) {
                return _owner;
            }
            /**
             * @dev Throws if the sender is not the owner.
             */
            function _checkOwner() internal view virtual {
                require(owner() == _msgSender(), "Ownable: caller is not the owner");
            }
            /**
             * @dev Leaves the contract without owner. It will not be possible to call
             * `onlyOwner` functions. Can only be called by the current owner.
             *
             * NOTE: Renouncing ownership will leave the contract without an owner,
             * thereby disabling any functionality that is only available to the owner.
             */
            function renounceOwnership() public virtual onlyOwner {
                _transferOwnership(address(0));
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Can only be called by the current owner.
             */
            function transferOwnership(address newOwner) public virtual onlyOwner {
                require(newOwner != address(0), "Ownable: new owner is the zero address");
                _transferOwnership(newOwner);
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Internal function without access restriction.
             */
            function _transferOwnership(address newOwner) internal virtual {
                address oldOwner = _owner;
                _owner = newOwner;
                emit OwnershipTransferred(oldOwner, newOwner);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.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].
         *
         * The default value of {decimals} is 18. To change this, you should override
         * this function so it returns a different value.
         *
         * 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}.
             *
             * 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 default value returned by this function, unless
             * it's 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 {}
        }
        // 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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.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);
        }
        // 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;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
        pragma solidity ^0.8.0;
        import "./IERC165.sol";
        /**
         * @dev Implementation of the {IERC165} interface.
         *
         * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
         * for the additional interface id that will be supported. For example:
         *
         * ```solidity
         * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
         *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
         * }
         * ```
         *
         * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
         */
        abstract contract ERC165 is IERC165 {
            /**
             * @dev See {IERC165-supportsInterface}.
             */
            function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                return interfaceId == type(IERC165).interfaceId;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Interface of the ERC165 standard, as defined in the
         * https://eips.ethereum.org/EIPS/eip-165[EIP].
         *
         * Implementers can declare support of contract interfaces, which can then be
         * queried by others ({ERC165Checker}).
         *
         * For an implementation, see {ERC165}.
         */
        interface IERC165 {
            /**
             * @dev Returns true if this contract implements the interface defined by
             * `interfaceId`. See the corresponding
             * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
             * to learn more about how these ids are created.
             *
             * This function call must use less than 30 000 gas.
             */
            function supportsInterface(bytes4 interfaceId) external view returns (bool);
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface Iconfigurator {
            function mintVault(address pool) external view returns(bool);
            function mintVaultMaxSupply(address pool) external view returns(uint256);
            function vaultMintPaused(address pool) external view returns(bool);
            function vaultBurnPaused(address pool) external view returns(bool);
            function tokenMiner(address pool) external view returns(bool);
            function getSafeCollateralRatio(address pool) external view returns(uint256);
            function getBadCollateralRatio(address pool) external view returns(uint256);
            function getVaultWeight(address pool) external view returns (uint256);
            function vaultMintFeeApy(address pool) external view returns(uint256);
            function vaultKeeperRatio(address pool) external view returns(uint256);
            function redemptionFee() external view returns(uint256);
            function getEUSDAddress() external view returns(address);
            function peUSD() external view returns(address);
            function eUSDMiningIncentives() external view returns(address);
            function getProtocolRewardsPool() external view returns(address);
            function flashloanFee() external view returns(uint256);
            function getEUSDMaxLocked() external view returns (uint256);
            function stableToken() external view returns (address);
            function isRedemptionProvider(address user) external view returns (bool);
            function becomeRedemptionProvider(bool _bool) external;
            function refreshMintReward(address user) external;
            function distributeRewards() external;
            function hasRole(bytes32 role, address account) external view returns (bool);
        }// SPDX-License-Identifier: GPL-3.0
        pragma solidity ^0.8.17;
        /**
         * @title LBR is an ERC20-compliant token.
         * - LBR can only be exchanged to esLBR in the lybraFund contract.
         * - Apart from the initial production, LBR can only be produced by destroying esLBR in the fund contract.
         */
        import "../interfaces/Iconfigurator.sol";
        import "@layerzerolabs/solidity-examples/contracts/token/oft/v2/OFTV2.sol";
        contract LBR is OFTV2 {
            Iconfigurator public immutable configurator;
            uint256 constant maxSupply = 100_000_000 * 1e18;
            constructor(address _config, uint8 _sharedDecimals, address _lzEndpoint) OFTV2("Lybra", "LBR", _sharedDecimals, _lzEndpoint) {
                configurator = Iconfigurator(_config);
            }
            function mint(address user, uint256 amount) external returns (bool) {
                require(amount != 0, "ZA");
                require(configurator.tokenMiner(msg.sender), "NA");
                require(totalSupply() + amount <= maxSupply, "exceeding the maximum supply quantity.");
                _mint(user, amount);
                return true;
            }
            function burn(address user, uint256 amount) external returns (bool) {
                require(amount != 0, "ZA");
                require(configurator.tokenMiner(msg.sender), "NA");
                _burn(user, amount);
                return true;
            }
        }
        

        File 3 of 4: LybraProxy
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
         * proxy whose upgrades are fully controlled by the current implementation.
         */
        interface IERC1822Proxiable {
            /**
             * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
             * address.
             *
             * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
             * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
             * function revert if invoked through a proxy.
             */
            function proxiableUUID() external view returns (bytes32);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
         *
         * _Available since v4.8.3._
         */
        interface IERC1967 {
            /**
             * @dev Emitted when the implementation is upgraded.
             */
            event Upgraded(address indexed implementation);
            /**
             * @dev Emitted when the admin account has changed.
             */
            event AdminChanged(address previousAdmin, address newAdmin);
            /**
             * @dev Emitted when the beacon is changed.
             */
            event BeaconUpgraded(address indexed beacon);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev This is the interface that {BeaconProxy} expects of its beacon.
         */
        interface IBeacon {
            /**
             * @dev Must return an address that can be used as a delegate call target.
             *
             * {BeaconProxy} will check that this address is a contract.
             */
            function implementation() external view returns (address);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
        pragma solidity ^0.8.0;
        import "../Proxy.sol";
        import "./ERC1967Upgrade.sol";
        /**
         * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
         * implementation address that can be changed. This address is stored in storage in the location specified by
         * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
         * implementation behind the proxy.
         */
        contract ERC1967Proxy is Proxy, ERC1967Upgrade {
            /**
             * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
             *
             * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
             * function call, and allows initializing the storage of the proxy like a Solidity constructor.
             */
            constructor(address _logic, bytes memory _data) payable {
                _upgradeToAndCall(_logic, _data, false);
            }
            /**
             * @dev Returns the current implementation address.
             */
            function _implementation() internal view virtual override returns (address impl) {
                return ERC1967Upgrade._getImplementation();
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
        pragma solidity ^0.8.2;
        import "../beacon/IBeacon.sol";
        import "../../interfaces/IERC1967.sol";
        import "../../interfaces/draft-IERC1822.sol";
        import "../../utils/Address.sol";
        import "../../utils/StorageSlot.sol";
        /**
         * @dev This abstract contract provides getters and event emitting update functions for
         * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
         *
         * _Available since v4.1._
         */
        abstract contract ERC1967Upgrade is IERC1967 {
            // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
            bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
            /**
             * @dev Storage slot with the address of the current implementation.
             * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
             * validated in the constructor.
             */
            bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
            /**
             * @dev Returns the current implementation address.
             */
            function _getImplementation() internal view returns (address) {
                return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
            }
            /**
             * @dev Stores a new address in the EIP1967 implementation slot.
             */
            function _setImplementation(address newImplementation) private {
                require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
            }
            /**
             * @dev Perform implementation upgrade
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeTo(address newImplementation) internal {
                _setImplementation(newImplementation);
                emit Upgraded(newImplementation);
            }
            /**
             * @dev Perform implementation upgrade with additional setup call.
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                _upgradeTo(newImplementation);
                if (data.length > 0 || forceCall) {
                    Address.functionDelegateCall(newImplementation, data);
                }
            }
            /**
             * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
             *
             * Emits an {Upgraded} event.
             */
            function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
                // Upgrades from old implementations will perform a rollback test. This test requires the new
                // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                // this special case will break upgrade paths from old UUPS implementation to new ones.
                if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                    _setImplementation(newImplementation);
                } else {
                    try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                        require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                    } catch {
                        revert("ERC1967Upgrade: new implementation is not UUPS");
                    }
                    _upgradeToAndCall(newImplementation, data, forceCall);
                }
            }
            /**
             * @dev Storage slot with the admin of the contract.
             * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
             * validated in the constructor.
             */
            bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
            /**
             * @dev Returns the current admin.
             */
            function _getAdmin() internal view returns (address) {
                return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
            }
            /**
             * @dev Stores a new address in the EIP1967 admin slot.
             */
            function _setAdmin(address newAdmin) private {
                require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
            }
            /**
             * @dev Changes the admin of the proxy.
             *
             * Emits an {AdminChanged} event.
             */
            function _changeAdmin(address newAdmin) internal {
                emit AdminChanged(_getAdmin(), newAdmin);
                _setAdmin(newAdmin);
            }
            /**
             * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
             * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
             */
            bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
            /**
             * @dev Returns the current beacon.
             */
            function _getBeacon() internal view returns (address) {
                return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
            }
            /**
             * @dev Stores a new beacon in the EIP1967 beacon slot.
             */
            function _setBeacon(address newBeacon) private {
                require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                require(
                    Address.isContract(IBeacon(newBeacon).implementation()),
                    "ERC1967: beacon implementation is not a contract"
                );
                StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
            }
            /**
             * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
             * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
             *
             * Emits a {BeaconUpgraded} event.
             */
            function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                _setBeacon(newBeacon);
                emit BeaconUpgraded(newBeacon);
                if (data.length > 0 || forceCall) {
                    Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
         * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
         * be specified by overriding the virtual {_implementation} function.
         *
         * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
         * different contract through the {_delegate} function.
         *
         * The success and return data of the delegated call will be returned back to the caller of the proxy.
         */
        abstract contract Proxy {
            /**
             * @dev Delegates the current call to `implementation`.
             *
             * This function does not return to its internal call site, it will return directly to the external caller.
             */
            function _delegate(address implementation) internal virtual {
                assembly {
                    // Copy msg.data. We take full control of memory in this inline assembly
                    // block because it will not return to Solidity code. We overwrite the
                    // Solidity scratch pad at memory position 0.
                    calldatacopy(0, 0, calldatasize())
                    // Call the implementation.
                    // out and outsize are 0 because we don't know the size yet.
                    let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                    // Copy the returned data.
                    returndatacopy(0, 0, returndatasize())
                    switch result
                    // delegatecall returns 0 on error.
                    case 0 {
                        revert(0, returndatasize())
                    }
                    default {
                        return(0, returndatasize())
                    }
                }
            }
            /**
             * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
             * and {_fallback} should delegate.
             */
            function _implementation() internal view virtual returns (address);
            /**
             * @dev Delegates the current call to the address returned by `_implementation()`.
             *
             * This function does not return to its internal call site, it will return directly to the external caller.
             */
            function _fallback() internal virtual {
                _beforeFallback();
                _delegate(_implementation());
            }
            /**
             * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
             * function in the contract matches the call data.
             */
            fallback() external payable virtual {
                _fallback();
            }
            /**
             * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
             * is empty.
             */
            receive() external payable virtual {
                _fallback();
            }
            /**
             * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
             * call, or as part of the Solidity `fallback` or `receive` functions.
             *
             * If overridden should call `super._beforeFallback()`.
             */
            function _beforeFallback() internal virtual {}
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
        pragma solidity ^0.8.0;
        import "../ERC1967/ERC1967Proxy.sol";
        /**
         * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
         * does not implement this interface directly, and some of its functions are implemented by an internal dispatch
         * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
         * include them in the ABI so this interface must be used to interact with it.
         */
        interface ITransparentUpgradeableProxy is IERC1967 {
            function admin() external view returns (address);
            function implementation() external view returns (address);
            function changeAdmin(address) external;
            function upgradeTo(address) external;
            function upgradeToAndCall(address, bytes memory) external payable;
        }
        /**
         * @dev This contract implements a proxy that is upgradeable by an admin.
         *
         * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
         * clashing], which can potentially be used in an attack, this contract uses the
         * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
         * things that go hand in hand:
         *
         * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
         * that call matches one of the admin functions exposed by the proxy itself.
         * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
         * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
         * "admin cannot fallback to proxy target".
         *
         * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
         * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
         * to sudden errors when trying to call a function from the proxy implementation.
         *
         * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
         * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
         *
         * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
         * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch
         * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
         * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
         * implementation.
         *
         * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler
         * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function
         * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could
         * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
         */
        contract TransparentUpgradeableProxy is ERC1967Proxy {
            /**
             * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
             * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
             */
            constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
                _changeAdmin(admin_);
            }
            /**
             * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
             *
             * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
             * implementation provides a function with the same selector.
             */
            modifier ifAdmin() {
                if (msg.sender == _getAdmin()) {
                    _;
                } else {
                    _fallback();
                }
            }
            /**
             * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
             */
            function _fallback() internal virtual override {
                if (msg.sender == _getAdmin()) {
                    bytes memory ret;
                    bytes4 selector = msg.sig;
                    if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                        ret = _dispatchUpgradeTo();
                    } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                        ret = _dispatchUpgradeToAndCall();
                    } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                        ret = _dispatchChangeAdmin();
                    } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                        ret = _dispatchAdmin();
                    } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                        ret = _dispatchImplementation();
                    } else {
                        revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                    }
                    assembly {
                        return(add(ret, 0x20), mload(ret))
                    }
                } else {
                    super._fallback();
                }
            }
            /**
             * @dev Returns the current admin.
             *
             * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
             * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
             * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
             */
            function _dispatchAdmin() private returns (bytes memory) {
                _requireZeroValue();
                address admin = _getAdmin();
                return abi.encode(admin);
            }
            /**
             * @dev Returns the current implementation.
             *
             * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
             * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
             * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
             */
            function _dispatchImplementation() private returns (bytes memory) {
                _requireZeroValue();
                address implementation = _implementation();
                return abi.encode(implementation);
            }
            /**
             * @dev Changes the admin of the proxy.
             *
             * Emits an {AdminChanged} event.
             */
            function _dispatchChangeAdmin() private returns (bytes memory) {
                _requireZeroValue();
                address newAdmin = abi.decode(msg.data[4:], (address));
                _changeAdmin(newAdmin);
                return "";
            }
            /**
             * @dev Upgrade the implementation of the proxy.
             */
            function _dispatchUpgradeTo() private returns (bytes memory) {
                _requireZeroValue();
                address newImplementation = abi.decode(msg.data[4:], (address));
                _upgradeToAndCall(newImplementation, bytes(""), false);
                return "";
            }
            /**
             * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
             * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
             * proxied contract.
             */
            function _dispatchUpgradeToAndCall() private returns (bytes memory) {
                (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
                _upgradeToAndCall(newImplementation, data, true);
                return "";
            }
            /**
             * @dev Returns the current admin.
             *
             * CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.
             */
            function _admin() internal view virtual returns (address) {
                return _getAdmin();
            }
            /**
             * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
             * emulate some proxy functions being non-payable while still allowing value to pass through.
             */
            function _requireZeroValue() private {
                require(msg.value == 0);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             *
             * Furthermore, `isContract` will also return true if the target contract within
             * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
             * which only has an effect at the end of a transaction.
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
        // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
        pragma solidity ^0.8.0;
        /**
         * @dev Library for reading and writing primitive types to specific storage slots.
         *
         * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
         * This library helps with reading and writing to such slots without the need for inline assembly.
         *
         * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
         *
         * Example usage to set ERC1967 implementation slot:
         * ```solidity
         * contract ERC1967 {
         *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
         *
         *     function _getImplementation() internal view returns (address) {
         *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
         *     }
         *
         *     function _setImplementation(address newImplementation) internal {
         *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
         *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
         *     }
         * }
         * ```
         *
         * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
         * _Available since v4.9 for `string`, `bytes`._
         */
        library StorageSlot {
            struct AddressSlot {
                address value;
            }
            struct BooleanSlot {
                bool value;
            }
            struct Bytes32Slot {
                bytes32 value;
            }
            struct Uint256Slot {
                uint256 value;
            }
            struct StringSlot {
                string value;
            }
            struct BytesSlot {
                bytes value;
            }
            /**
             * @dev Returns an `AddressSlot` with member `value` located at `slot`.
             */
            function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
             */
            function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
             */
            function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
             */
            function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `StringSlot` with member `value` located at `slot`.
             */
            function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
             */
            function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := store.slot
                }
            }
            /**
             * @dev Returns an `BytesSlot` with member `value` located at `slot`.
             */
            function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := slot
                }
            }
            /**
             * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
             */
            function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r.slot := store.slot
                }
            }
        }
        // SPDX-License-Identifier: GPL-3.0
        pragma solidity ^0.8.17;
        import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
        contract LybraProxy is TransparentUpgradeableProxy {
            constructor(address _logic,address _admin,bytes memory _data) TransparentUpgradeableProxy(_logic, _admin, _data) {}
        }
        

        File 4 of 4: LybraConfigurator
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface AggregatorV3Interface {
          function decimals() external view returns (uint8);
          function description() external view returns (string memory);
          function version() external view returns (uint256);
          function getRoundData(uint80 _roundId)
            external
            view
            returns (
              uint80 roundId,
              int256 answer,
              uint256 startedAt,
              uint256 updatedAt,
              uint80 answeredInRound
            );
          function latestRoundData()
            external
            view
            returns (
              uint80 roundId,
              int256 answer,
              uint256 startedAt,
              uint256 updatedAt,
              uint80 answeredInRound
            );
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/Address.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```solidity
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         *
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts.
             *
             * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
             * constructor.
             *
             * Emits an {Initialized} event.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * A reinitializer may be used after the original initialization step. This is essential to configure modules that
             * are added through upgrades and that require initialization.
             *
             * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
             * cannot be nested. If one is invoked in the context of another, execution will revert.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             *
             * WARNING: setting the version to 255 will prevent any future reinitialization.
             *
             * Emits an {Initialized} event.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             *
             * Emits an {Initialized} event the first time it is successfully executed.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized != type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
            /**
             * @dev Returns the highest version that has been initialized. See {reinitializer}.
             */
            function _getInitializedVersion() internal view returns (uint8) {
                return _initialized;
            }
            /**
             * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
             */
            function _isInitializing() internal view returns (bool) {
                return _initializing;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.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);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
        pragma solidity ^0.8.0;
        import "../IERC20.sol";
        import "../extensions/IERC20Permit.sol";
        import "../../../utils/Address.sol";
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20 {
            using Address for address;
            /**
             * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
            /**
             * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
             * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
             */
            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                require(
                    (value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
            /**
             * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 oldAllowance = token.allowance(address(this), spender);
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
            }
            /**
             * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful.
             */
            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                unchecked {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                }
            }
            /**
             * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
             * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
             * 0 before setting it to a non-zero value.
             */
            function forceApprove(IERC20 token, address spender, uint256 value) internal {
                bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                if (!_callOptionalReturnBool(token, approvalCall)) {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                    _callOptionalReturn(token, approvalCall);
                }
            }
            /**
             * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
             * Revert on invalid signature.
             */
            function safePermit(
                IERC20Permit token,
                address owner,
                address spender,
                uint256 value,
                uint256 deadline,
                uint8 v,
                bytes32 r,
                bytes32 s
            ) internal {
                uint256 nonceBefore = token.nonces(owner);
                token.permit(owner, spender, value, deadline, v, r, s);
                uint256 nonceAfter = token.nonces(owner);
                require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
            }
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             *
             * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
             */
            function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                // and not revert is the subcall reverts.
                (bool success, bytes memory returndata) = address(token).call(data);
                return
                    success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             *
             * Furthermore, `isContract` will also return true if the target contract within
             * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
             * which only has an effect at the end of a transaction.
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResultFromTarget(target, success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
             * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
             *
             * _Available since v4.8._
             */
            function verifyCallResultFromTarget(
                address target,
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                if (success) {
                    if (returndata.length == 0) {
                        // only check isContract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        require(isContract(target), "Address: call to non-contract");
                    }
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            /**
             * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason or using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    _revert(returndata, errorMessage);
                }
            }
            function _revert(bytes memory returndata, string memory errorMessage) private pure {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
        // SPDX-License-Identifier: BUSL-1.1
        /**
         * @title Lybra Protocol V2 Configurator Contract
         * @dev The Configurator contract is used to set various parameters and control functionalities of the Lybra Protocol. It is based on OpenZeppelin's Proxy and AccessControl libraries, allowing the DAO to control contract upgrades. There are three types of governance roles:
         * * DAO: A time-locked contract initiated by esLBR voting, with a minimum effective period of 14 days. After the vote is passed, only the developer can execute the action.
         * * TIMELOCK: A time-locked contract controlled by the developer, with a minimum effective period of 2 days.
         * * ADMIN: A multisignature account controlled by the developer.
         * All setting functions have three levels of calling permissions:
         * * onlyRole(DAO): Only callable by the DAO for governance purposes.
         * * checkRole(TIMELOCK): Callable by both the DAO and the TIMELOCK contract.
         * * checkRole(ADMIN): Callable by all governance roles.
         */
        pragma solidity ^0.8.17;
        import "../interfaces/IGovernanceTimelock.sol";
        import "../interfaces/IPeUSD.sol";
        import "../interfaces/IEUSD.sol";
        import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
        import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
        import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
        import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
        interface IProtocolRewardsPool {
            function notifyRewardAmount(uint256 amount, uint256 tokenType) external;
        }
        interface IeUSDMiningIncentives {
            function refreshReward(address user) external;
        }
        interface IVault {
            function getVaultType() external view returns (uint8);
        }
        interface ICurvePool{
            function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns(uint256);
        }
        contract LybraConfigurator is Initializable {
            using SafeERC20 for IERC20;
            mapping(address => bool) public mintVault;
            mapping(address => uint256) public mintVaultMaxSupply;
            mapping(address => bool) public vaultMintPaused;
            mapping(address => bool) public vaultBurnPaused;
            mapping(address => uint256) vaultSafeCollateralRatio;
            mapping(address => uint256) vaultBadCollateralRatio;
            mapping(address => uint256) public vaultMintFeeApy;
            mapping(address => uint256) public vaultKeeperRatio;
            mapping(address => bool) redemptionProvider;
            mapping(address => bool) public tokenMiner;
            mapping(address => uint256) vaultWeight;
            AggregatorV3Interface public eUSDPriceFeed;
            uint256 public redemptionFee;
            IGovernanceTimelock public GovernanceTimelock;
            IeUSDMiningIncentives public eUSDMiningIncentives;
            IProtocolRewardsPool public lybraProtocolRewardsPool;
            IEUSD public EUSD;
            IPeUSD public peUSD;
            uint256 public flashloanFee;
            // Limiting the maximum percentage of eUSD that can be cross-chain transferred to L2 in relation to the total supply.
            uint256 maxStableRatio;
            address public stableToken;
            ICurvePool public curvePool;
            bool public premiumTradingEnabled;
            bytes32 public constant DAO = keccak256("DAO");
            bytes32 public constant TIMELOCK = keccak256("TIMELOCK");
            bytes32 public constant ADMIN = keccak256("ADMIN");
            event RedemptionFeeChanged(uint256 newSlippage);
            event SafeCollateralRatioChanged(address indexed pool, uint256 newRatio);
            event BadCollateralRatioChanged(address indexed pool, uint256 newRatio);
            event RedemptionProvider(address indexed user, bool status);
            event ProtocolRewardsPoolChanged(address indexed pool, uint256 timestamp);
            event EUSDMiningIncentivesChanged(address indexed pool, uint256 timestamp);
            event BorrowApyChanged(address indexed pool, uint256 newApy);
            event KeeperRatioChanged(address indexed pool, uint256 newSlippage);
            event TokenMinerChanges(address indexed pool, bool status);
            event VaultWeightChanged(address indexed pool, uint256 weight, uint256 timestamp);
            event SendProtocolRewards(address indexed token, uint256 amount, uint256 timestamp);
            event EUSDOracleChanged(address oldAddr, address newAddr, uint256 timestamp);
            event CurvePoolChanged(address oldAddr, address newAddr, uint256 timestamp);
            event GovernanceTimelockChanged(address newAddr, uint256 timestamp);
            /// @notice Emitted when the fees for flash loaning a token have been updated
            /// @param fee The new fee for this token as a percentage and multiplied by 100 to avoid decimals (for example, 10% is 10_00)
            event FlashloanFeeUpdated(uint256 fee);
            constructor() {
                _disableInitializers();
            }
            //stableToken = USDC
            function initialize(address _dao, address _stableToken) public initializer {
                redemptionFee = 50;
                flashloanFee = 500;
                maxStableRatio = 5_000;
                GovernanceTimelock = IGovernanceTimelock(_dao);
                stableToken = _stableToken;
            }
            modifier onlyRole(bytes32 role) {
                require(GovernanceTimelock.checkOnlyRole(role, msg.sender), "NA");
                _;
            }
            modifier checkRole(bytes32 role) {
                require(GovernanceTimelock.checkRole(role, msg.sender), "NA");
                _;
            }
            function setGovernanceTimelock(address _governance) external onlyRole(DAO) {
                GovernanceTimelock = IGovernanceTimelock(_governance);
                emit GovernanceTimelockChanged(_governance, block.timestamp);
            }
            /**
             * @notice Initializes the eUSD and peUSD address. This function can only be executed once.
             */
            function initToken(address _eusd, address _peusd) external onlyRole(DAO) {
                if (address(EUSD) == address(0)) EUSD = IEUSD(_eusd);
                if (address(peUSD) == address(0)) peUSD = IPeUSD(_peusd);
                EUSD.approve(_peusd, type(uint256).max);
            }
            /**
             * @notice Controls the activation of a specific eUSD vault.
             * @param pool The address of the asset pool.
             * @param isActive A boolean indicating whether to activate or deactivate the vault.
             * @dev This function can only be called by the DAO.
             */
            function setMintVault(address pool, bool isActive) external onlyRole(DAO) {
                mintVault[pool] = isActive;
            }
            /**
             * @notice Controls the minting limit of eUSD for an asset pool.
             * @param pool The address of the asset pool.
             * @param maxSupply The maximum amount of eUSD that can be minted for the asset pool.
             * @dev This function can only be called by the DAO.
             */
            function setMintVaultMaxSupply(address pool, uint256 maxSupply) external onlyRole(DAO) {
                mintVaultMaxSupply[pool] = maxSupply;
            }
            /**
             * @notice  badCollateralRatio can be decided by DAO,starts at 130%
             */
            function setBadCollateralRatio(address pool, uint256 newRatio) external onlyRole(DAO) {
                require(newRatio >= 130 * 1e18 && newRatio <= 150 * 1e18 && newRatio <= vaultSafeCollateralRatio[pool] - 1e19, "LNA");
                vaultBadCollateralRatio[pool] = newRatio;
                emit BadCollateralRatioChanged(pool, newRatio);
            }
            /**
             * @notice Sets the address of the protocol rewards pool.
             * @param addr The new address of the protocol rewards pool.
             * @dev This function can only be called by accounts with TIMELOCK or higher privilege.
             */
            function setProtocolRewardsPool(address addr) external checkRole(TIMELOCK) {
                lybraProtocolRewardsPool = IProtocolRewardsPool(addr);
                emit ProtocolRewardsPoolChanged(addr, block.timestamp);
            }
            /**
             * @notice Sets the address of the eUSDMiningIncentives pool.
             * @param addr The new address of the eUSDMiningIncentives pool.
             * @dev This function can only be called by accounts with TIMELOCK or higher privilege.
             */
            function setEUSDMiningIncentives(address addr) external checkRole(TIMELOCK) {
                eUSDMiningIncentives = IeUSDMiningIncentives(addr);
                emit EUSDMiningIncentivesChanged(addr, block.timestamp);
            }
            function setVaultWeight(address vault, uint256 weight) external checkRole(TIMELOCK) {
                require(mintVault[vault], "NV");
                require(weight <= 2e20, "EL");
                vaultWeight[vault] = weight;
                emit VaultWeightChanged(vault, weight, block.timestamp);
            }
            function setEUSDOracle(address _eUSDOracle) external checkRole(TIMELOCK) {
                emit EUSDOracleChanged(address(eUSDPriceFeed), _eUSDOracle, block.timestamp);
                eUSDPriceFeed = AggregatorV3Interface(_eUSDOracle);
            }
            function setCurvePool(address _curvePool) external checkRole(TIMELOCK) {
                emit CurvePoolChanged(address(curvePool), _curvePool, block.timestamp);
                curvePool = ICurvePool(_curvePool);
            }
            /**
             * @notice Sets the status of premium trading.
             * @param isActive Boolean value indicating whether premium trading is enabled or disabled.
             * @dev This function can only be called by accounts with TIMELOCK or higher privilege.
             */
            function setPremiumTradingEnabled(bool isActive) external checkRole(TIMELOCK) {
                premiumTradingEnabled = isActive;
            }
            /**
             * @notice Enables or disables the repayment functionality for a asset pool.
             * @param pool The address of the pool.
             * @param isActive Boolean value indicating whether repayment is active or paused.
             * @dev This function can only be called by accounts with TIMELOCK or higher privilege.
             */
            function setVaultBurnPaused(address pool, bool isActive) external checkRole(TIMELOCK) {
                vaultBurnPaused[pool] = isActive;
            }
            /**
             * @notice Enables or disables the mint functionality for a asset pool.
             * @param pool The address of the pool.
             * @param isActive Boolean value indicating whether minting is active or paused.
             * @dev This function can only be called by accounts with ADMIN or DAO.
             */
            function setVaultMintPaused(address pool, bool isActive) external checkRole(ADMIN) {
                vaultMintPaused[pool] = isActive;
            }
            /**
             * @notice Sets the redemption fee.
             * @param newFee The new fee to be set.
             * @notice The fee cannot exceed 5%.
             */
            function setRedemptionFee(uint256 newFee) external checkRole(TIMELOCK) {
                require(newFee <= 500, "Max Redemption Fee is 5%");
                redemptionFee = newFee;
                emit RedemptionFeeChanged(newFee);
            }
            /**
             * @notice  safeCollateralRatio can be decided by TIMELOCK.
             * The eUSD vault requires a minimum safe collateral rate of 160%,
             * On the other hand, the peUSD vault requires a safe collateral rate at least 10% higher
             * than the liquidation collateral rate, providing an additional buffer to protect against liquidation risks.
             */
            function setSafeCollateralRatio(address pool, uint256 newRatio) external checkRole(TIMELOCK) {
                if(IVault(pool).getVaultType() == 0) {
                    require(newRatio >= 160 * 1e18, "eUSD vault safe collateralRatio should more than 160%");
                } else {
                    require(newRatio >= vaultBadCollateralRatio[pool] + 1e19, "peUSD vault safe collateralRatio should more than bad collateralRatio");
                }
                vaultSafeCollateralRatio[pool] = newRatio;
                emit SafeCollateralRatioChanged(pool, newRatio);
            }
            /**
             * @notice  Set the borrowing annual percentage yield (APY) for a asset pool.
             * @param pool The address of the pool to set the borrowing APY for.
             * @param newApy The new borrowing APY to set, limited to a maximum of 2%.
             */
            function setBorrowApy(address pool, uint256 newApy) external checkRole(TIMELOCK) {
                require(newApy <= 200, "Borrow APY cannot exceed 2%");
                vaultMintFeeApy[pool] = newApy;
                emit BorrowApyChanged(pool, newApy);
            }
            /**
             * @notice Set the reward ratio for the liquidator after liquidation.
             * @param pool The address of the pool to set the reward ratio for.
             * @param newRatio The new reward ratio to set, limited to a maximum of 5%.
             */
            function setKeeperRatio(address pool,uint256 newRatio) external checkRole(TIMELOCK) {
                require(newRatio <= 5, "Max Keeper reward is 5%");
                vaultKeeperRatio[pool] = newRatio;
                emit KeeperRatioChanged(pool, newRatio);
            }
            /**
             * @notice Sets the mining permission for the esLBR&LBR mining pool.
             * @param _contracts An array of addresses representing the contracts.
             * @param _bools An array of booleans indicating whether mining is allowed for each contract.
             */
            function setTokenMiner(address[] calldata _contracts, bool[] calldata _bools) external checkRole(TIMELOCK) {
                for (uint256 i = 0; i < _contracts.length; i++) {
                    tokenMiner[_contracts[i]] = _bools[i];
                    emit TokenMinerChanges(_contracts[i], _bools[i]);
                }
            }
            /**
             * dev Sets the maximum percentage share for peUSD.
             * @param _ratio The ratio in basis points (1/10_000). The maximum value is 10_000.
             */
            function setMaxStableRatio(uint256 _ratio) external checkRole(TIMELOCK) {
                require(_ratio <= 10_000, "The maximum value is 10_000");
                maxStableRatio = _ratio;
            }
            /// @notice Update the flashloan fee percentage, only available to the manager of the contract
            /// @param fee The fee percentage for eUSD, multiplied by 100 (for example, 10% is 1000)
            function setFlashloanFee(uint256 fee) external checkRole(TIMELOCK) {
                if (fee > 10_000) revert('EL');
                emit FlashloanFeeUpdated(fee);
                flashloanFee = fee;
            }
            /**
             * @notice User chooses to become a Redemption Provider
             */
            function becomeRedemptionProvider(bool _bool) external {
                eUSDMiningIncentives.refreshReward(msg.sender);
                redemptionProvider[msg.sender] = _bool;
                emit RedemptionProvider(msg.sender, _bool);
            }
            /**
             * @dev Updates the mining data for the user's eUSD mining incentives.
             */
            function refreshMintReward(address user) external {
                eUSDMiningIncentives.refreshReward(user);
            }
            
            /**
             * @notice Distributes rewards to the LybraProtocolRewardsPool based on the available balance of peUSD and eUSD. 
             * If the balance is greater than 1e21, the distribution process is triggered.
             * 
             * First, if the eUSD balance is greater than 1,000 and the premiumTradingEnabled flag is set to true, 
             * and the eUSD/USDC premium exceeds 0.5%, eUSD will be exchanged for USDC and added to the LybraProtocolRewardsPool. 
             * Otherwise, eUSD will be directly converted to peUSD, and the entire peUSD balance will be transferred to the LybraProtocolRewardsPool.
             * @dev The protocol rewards amount is notified to the LybraProtocolRewardsPool for proper reward allocation.
             */
            function distributeRewards() external {
                uint256 balance = EUSD.balanceOf(address(this));
                if (balance >= 1e21) {
                    if(premiumTradingEnabled){
                        (, int price, , , ) = eUSDPriceFeed.latestRoundData();
                        if(price >= 100_500_000){
                            EUSD.approve(address(curvePool), balance);
                            uint256 amount = curvePool.exchange_underlying(0, 2, balance, balance * uint(price) * 995 / 1e23);
                            IERC20(stableToken).safeTransfer(address(lybraProtocolRewardsPool), amount);
                            lybraProtocolRewardsPool.notifyRewardAmount(amount, 1);
                            emit SendProtocolRewards(stableToken, amount, block.timestamp);
                        }
                    } else {
                        peUSD.convertToPeUSD(address(this), balance);
                    }
                }
                uint256 peUSDBalance = peUSD.balanceOf(address(this));
                if(peUSDBalance >= 1e21) {
                    peUSD.transfer(address(lybraProtocolRewardsPool), peUSDBalance);
                    lybraProtocolRewardsPool.notifyRewardAmount(peUSDBalance, 0);
                    emit SendProtocolRewards(address(peUSD), peUSDBalance, block.timestamp);
                }
            }
            /**
             * @dev Returns the address of the eUSD token.
             * @return The address of the eUSD token.
             */
            function getEUSDAddress() external view returns (address) {
                return address(EUSD);
            }
            /**
             * @dev Returns the address of the Lybra protocol rewards pool.
             * @return The address of the Lybra protocol rewards pool.
             */
            function getProtocolRewardsPool() external view returns (address) {
                return address(lybraProtocolRewardsPool);
            }
            /**
             * @dev Returns the safe collateral ratio for a asset pool.
             * @param pool The address of the pool to check.
             * @return The safe collateral ratio for the specified pool.
             */
            function getSafeCollateralRatio(
                address pool
            ) public view returns (uint256) {
                if (vaultSafeCollateralRatio[pool] == 0) return 160 * 1e18;
                return vaultSafeCollateralRatio[pool];
            }
            function getBadCollateralRatio(address pool) external view returns(uint256) {
                if(vaultBadCollateralRatio[pool] == 0) return getSafeCollateralRatio(pool) - 1e19;
                return vaultBadCollateralRatio[pool];
            }
            function getVaultWeight(
                address pool
            ) external view returns (uint256) {
                if(!mintVault[pool]) return 0;
                if (vaultWeight[pool] == 0) return 100 * 1e18;
                return vaultWeight[pool];
            }
            /**
             * @dev Checks if a user is a redemption provider.
             * @param user The address of the user to check.
             * @return True if the user is a redemption provider, false otherwise.
             */
            function isRedemptionProvider(address user) external view returns (bool) {
                return redemptionProvider[user];
            }
            /**
             * @dev Return the maximum quantity of peUSD that can be minted by using eUSD.
             * @return The maximum quantity of peUSD that can be minted through eUSD.
             */
            function getEUSDMaxLocked() external view returns (uint256) {
                return (EUSD.totalSupply() * maxStableRatio) / 10_000;
            }
            function hasRole(bytes32 role, address caller) external view returns (bool) {
                return GovernanceTimelock.checkRole(role, caller);
            }
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface IEUSD {
            function totalSupply() external view returns (uint256);
            function getTotalShares() external view returns (uint256);
            function balanceOf(address account) external view returns (uint256);
            function sharesOf(address _account) external view returns (uint256);
            function allowance(
                address owner,
                address spender
            ) external view returns (uint256);
            function approve(address _spender, uint256 _amount) external returns (bool);
            function transferFrom(
                address from,
                address to,
                uint256 amount
            ) external returns (bool);
            function transferShares(
                address _recipient,
                uint256 _sharesAmount
            ) external returns (uint256);
            function getSharesByMintedEUSD(
                uint256 _EUSDAmount
            ) external view returns (uint256);
            function getMintedEUSDByShares(
                uint256 _sharesAmount
            ) external view returns (uint256);
            function mint(
                address _recipient,
                uint256 _mintAmount
            ) external returns (uint256 newTotalShares);
            function burnShares(
                address _account,
                uint256 burnAmount
            ) external returns (uint256 newTotalShares);
            function burn(
                address _account,
                uint256 burnAmount
            ) external returns (uint256 newTotalShares);
            function transfer(address to, uint256 amount) external returns (bool);
        }
        // SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface IGovernanceTimelock {
           function checkRole(bytes32 role, address sender) external view returns(bool);
           function checkOnlyRole(bytes32 role, address sender) external view returns(bool);
        }// SPDX-License-Identifier: BUSL-1.1
        pragma solidity ^0.8.17;
        interface IPeUSD {
            function totalSupply() external view returns (uint256);
            function balanceOf(address account) external view returns (uint256);
            function transfer(address to, uint256 amount) external returns (bool);
            function allowance(address owner, address spender) external view returns (uint256);
            function approve(address spender, uint256 amount) external returns (bool);
            function transferFrom(address from, address to, uint256 amount) external returns (bool);
            function convertToPeUSD(address user, uint256 eusdAmount) external;
            function mint(
                address to,
                uint256 amount
            ) external returns (bool);
            function burn(
                address account,
                uint256 amount
            ) external returns (bool);
        }