// File: contracts/Adscendo/AdscendoPool.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./interfaces/IERC20.sol";
import "./interfaces/ILido.sol";
import "./interfaces/IPriceFeed.sol";
import "./utils/Context.sol";
import "./utils/math/SafeMath.sol";
import "./utils/ReentrancyGuard.sol";

/**
 * @title AdscendoPool
 * @author
 * @notice Leveraged staking pool for ETH
 * @dev Implements minting and redeeming of LSTETH tokens
 */
contract AdscendoPool is Context, ReentrancyGuard {
    // Libraries

    using SafeMath for uint256; // Prevent overflows

    // State variables

    uint private _liquidationPrice; // Liquidation price threshold

    uint private _safePrice; // Safe price threshold

    uint private _mintFee;

    uint private _redeemFee;

    uint private immutable MAX_MINT_FEE = 50; // 5% max mint fee

    uint private immutable MAX_REDEEM_FEE = 50; // 5% max redeem fee

    uint256 private _totalFee;

    // Total amount of staked STETH
    uint256 private _stakedAmount;

    // Address to receive insurance fees
    address private _insurance;

    // Address to receive team fees
    address private _team;

    // Admin address
    address private _admin;

    // Factory contract that created this pool
    address private _factory;

    mapping(address => bool) _stakingPool;

    uint private _teamShare = 30;

    uint private _insuranceShare = 70;

    // AUSD stablecoin token contract
    IERC20 private _AUSD;

    // LSTETH token contract
    IERC20 private _lstETH;

    // STETH token contract
    IERC20 private _stETH;

    ILido private _lido;

    // Price feed contract
    IPriceFeed internal _priceFeed;

    // Flag for liquidation state
    bool internal _liquidated = false;

    /**
     * @notice Emitted when STETH is deposited
     * @param user User address
     * @param amount Amount deposited
     */
    event Mint(address user, uint256 amount);

    /**
     * @notice Emitted when LSTETH is redeemed
     * @param user User address
     * @param amount Amount redeemed
     */
    event Redeem(address user, uint256 amount);

    event EmergencyRedeem(address user, uint256 amount);

    event Liquidation(uint price);

    /**
     * @dev Reverts if pool is liquidated
     */
    modifier onlyNotLiquidated() {
        require(_liquidated == false, "Must be not liquidate");
        _;
    }

    // Modifier to check liquidated
    modifier onlyLiquidated() {
        require(_liquidated == true, "Must be liquidated");
        _;
    }

    // Modifier to check caller is admin
    modifier onlyAdmin() {
        require(_admin == _msgSender(), "Only admin");
        _;
    }

    modifier onlyStakingPool() {
        require(_stakingPool[_msgSender()] == true, "Only staking pool");
        _;
    }

    /**
     * @dev Sets initial state variables
     * @param liquidationPrice_ Liquidation price threshold
     * @param safePrice_ Safe price threshold
     * @param ausdAddress_ AUSD token address
     * @param lstethAddress_ LSTETH token address
     * @param stethAddress_ STETH token address
     * @param priceFeedAddress_ Price feed address
     * @param insurance_ Insurance fee address
     * @param team_ Team fee address
     * @param admin_ Admin address
     * @param mintFee_ Initial minting fee percentage
     * @param redeemFee_ Initial redeem fee percentage
     */
    constructor(
        uint liquidationPrice_,
        uint safePrice_,
        address ausdAddress_,
        address lstethAddress_,
        address stethAddress_,
        address priceFeedAddress_,
        address insurance_,
        address team_,
        address admin_,
        uint mintFee_,
        uint redeemFee_
    ) {
        // Set liquidation and safe price thresholds
        // 18-digit precision uint
        _liquidationPrice = liquidationPrice_;
        _safePrice = safePrice_;

        // Set token contract addresses
        _AUSD = IERC20(ausdAddress_);
        _stETH = IERC20(stethAddress_);
        _lstETH = IERC20(lstethAddress_);
        _lido = ILido(stethAddress_);

        // Set price feed and admin addresses
        _priceFeed = IPriceFeed(priceFeedAddress_);
        _insurance = insurance_;
        _team = team_;
        _admin = admin_;

        // Set factory and starting round
        _factory = _msgSender();

        // Set initial fee percentages
        _mintFee = mintFee_;
        _redeemFee = redeemFee_;
    }

    function lstETH() public view returns (address) {
        return address(_lstETH);
    }

    function stETH() public view returns (address) {
        return address(_stETH);
    }

    function AUSD() public view returns (address) {
        return address(_AUSD);
    }

    function admin() public view returns (address) {
        return _admin;
    }

    function factory() public view returns (address) {
        return _factory;
    }

    function team() public view returns (address) {
        return _team;
    }

    function insurance() public view returns (address) {
        return _insurance;
    }

    function mintFee() public view returns (uint) {
        return _mintFee;
    }

    function redeemFee() public view returns (uint) {
        return _redeemFee;
    }

    function liquidationPrice() public view returns (uint) {
        return _liquidationPrice;
    }

    function safePrice() public view returns (uint) {
        return _safePrice;
    }

    function priceFeed() public view returns (address) {
        return address(_priceFeed);
    }

    function stakedAmount() public view returns (uint256) {
        return _stakedAmount;
    }

    function totalFee() public view returns (uint256) {
        return _totalFee;
    }

    function liquidated() public view returns (bool) {
        return _liquidated;
    }

    function isFeeWhitelist(address account) public view returns (bool) {
        return _stakingPool[account];
    }

    /**
     * @notice Deposits STETH and mints LSTETH + AUSD
     * @dev Only allowed if unliquidated
     * @param stAmount Amount of STETH to deposit
     */
    function mint(uint256 stAmount) external onlyNotLiquidated nonReentrant {
        uint _price = _priceFeed.fetchPrice();
        require(_price > _safePrice, "Current price must above threshold");

        _stETH.transferFrom(_msgSender(), address(this), stAmount);
        _mint(stAmount, _mintFee);
    }

    function mintWithETH(
        address _ref
    ) external payable onlyNotLiquidated nonReentrant {
        uint _price = _priceFeed.fetchPrice();
        require(_price > _safePrice, "Current price must above threshold");

        uint256 stAmount = _depositETHForSTETH(_ref);

        _mint(stAmount, _mintFee);
    }

    function mintNoFee(
        uint256 stAmount
    ) external onlyNotLiquidated onlyStakingPool nonReentrant {
        uint _price = _priceFeed.fetchPrice();
        require(_price > _safePrice, "Current price must above threshold");

        _stETH.transferFrom(_msgSender(), address(this), stAmount);
        _mint(stAmount, 0);
    }

    function mintWithETHNoFee(
        address _ref
    )
        external
        payable
        onlyNotLiquidated
        onlyStakingPool
        nonReentrant
        returns (uint256)
    {
        uint _price = _priceFeed.fetchPrice();
        require(_price > _safePrice, "Current price must above threshold");

        uint256 stAmount = _depositETHForSTETH(_ref);

        _mint(stAmount, 0);

        return stAmount;
    }

    function _depositETHForSTETH(address _ref) internal returns (uint256) {
        uint256 _sharesAmount = _lido.submit{value: msg.value}(_ref);
        uint256 stAmount = _lido.getPooledEthByShares(_sharesAmount);

        return stAmount;
    }

    function _mint(uint256 stAmount, uint mintFee_) internal {
        uint256 _fee = stAmount.mul(mintFee_).div(1000);
        uint256 _amount = stAmount.sub(_fee);

        _AUSD.mint(_msgSender(), _amount.mul(_liquidationPrice).div(10 ** 18));
        _lstETH.mint(_msgSender(), _amount);

        _stakedAmount = _stakedAmount.add(_amount);
        // fees
        _totalFee = _totalFee.add(_fee);

        emit Mint(_msgSender(), stAmount);
    }

    /**
     * @notice Redeems LSTETH for STETH and burns AUSD
     * @dev Only allowed if unliquidated
     * @param stAmount Amount of LSTETH to redeem
     */
    function redeem(uint256 stAmount) external onlyNotLiquidated nonReentrant {
        _redeem(stAmount, _redeemFee);
    }

    function redeemNoFee(
        uint256 stAmount
    ) external onlyNotLiquidated onlyStakingPool nonReentrant {
        _redeem(stAmount, 0);
    }

    function _redeem(uint256 stAmount, uint redeemFee_) internal {
        uint _price = _priceFeed.fetchPrice();
        require(
            _price > _liquidationPrice,
            "Current price must above threshold"
        );

        // Calculate fee
        uint256 _fee = stAmount.mul(redeemFee_).div(1000);
        uint256 _amount = stAmount.sub(_fee);

        // Burn AUSD and LSTETH
        _AUSD.burn(_msgSender(), stAmount.mul(_liquidationPrice).div(10 ** 18));
        _lstETH.burn(_msgSender(), stAmount);

        // Transfer STETH minus fee
        _stETH.transfer(_msgSender(), _amount);

        // Update staked amount
        _stakedAmount = _stakedAmount.sub(stAmount);

        // fees
        _totalFee = _totalFee.add(_fee);

        emit Redeem(_msgSender(), stAmount);
    }

    /**
     * @notice Liquidates the pool
     * @dev Changes liquidated state to true
     */
    function liquidation() external {
        uint _price = _priceFeed.fetchPrice();

        require(
            _price < _liquidationPrice,
            "Current price must below threshold"
        );

        // Set liquidated flag
        _liquidated = true;

        emit Liquidation(_price);
    }

    /**
     * @notice Emergency redeem post liquidation
     * @dev Allows redeem if price > safe
     * @param ausdAmount Amount of AUSD to redeem
     * @return stETHAmount Amount of STETH withdrawn
     */
    function emergencyRedeem(
        uint256 ausdAmount
    ) external onlyLiquidated nonReentrant returns (uint256) {
        uint _price = _priceFeed.fetchPrice();

        require(_price > _safePrice, "Current price must above threshold");

        return _emergencyRedeem(ausdAmount, _price, _redeemFee);
    }

    /**
     * @notice Maintenance redeem post liquidation
     * @dev Allows admin to redeem LSTETH if liquidated
     * @param ausdAmount Amount of AUSD to redeem
     * @return stETHAmount Amount of STETH withdrawn
     */
    function mantenceRedeem(
        uint256 ausdAmount
    ) external onlyAdmin onlyLiquidated nonReentrant returns (uint256) {
        uint _price = _priceFeed.fetchPrice();

        return _emergencyRedeem(ausdAmount, _price, _redeemFee);
    }

    function emergencyRedeemNoFee(
        uint ausdAmount
    ) external onlyStakingPool onlyLiquidated nonReentrant returns (uint256) {
        uint _price = _priceFeed.fetchPrice();

        return _emergencyRedeem(ausdAmount, _price, 0);
    }

    /**
     * @dev Internal logic for emergency redeem
     * @param ausdAmount AUSD amount to redeem
     * @param price Current price of ETH
     * @return stETHAmount Amount of STETH withdrawn
     */
    function _emergencyRedeem(
        uint256 ausdAmount,
        uint price,
        uint redeemFee_
    ) internal returns (uint256) {
        require(_stakedAmount > 0, "Nothing left");

        uint256 stAmount = ausdAmount.mul(10 ** 18).div(price);
        uint256 fee = stAmount.mul(redeemFee_).div(1000);
        uint256 redeemAmount = stAmount.sub(fee);

        _AUSD.burn(_msgSender(), ausdAmount);

        if (stAmount > _stakedAmount) {
            _stETH.transfer(_msgSender(), _stakedAmount.sub(fee));
            _stakedAmount = 0;
        } else {
            _stETH.transfer(_msgSender(), redeemAmount);
            _stakedAmount = _stakedAmount.sub(stAmount);
        }

        _totalFee = _totalFee.add(fee);

        emit EmergencyRedeem(_msgSender(), stAmount);

        return redeemAmount;
    }

    /**
     * @notice Set minting fee percentage
     * @dev Only callable by admin
     * @param value_ New minting fee percentage
     */
    function setMintFee(uint value_) external onlyAdmin {
        require(value_ <= MAX_MINT_FEE, "Can not greater than max mint fee");
        _mintFee = value_;
    }

    /**
     * @notice Set redeeming fee percentage
     * @dev Only callable by admin
     * @param value_ New redeeming fee percentage
     */
    function setRedeemFee(uint value_) external onlyAdmin {
        require(
            value_ <= MAX_REDEEM_FEE,
            "Can not greater than max redeem fee"
        );
        _redeemFee = value_;
    }

    function withdrawSTETHReward() external onlyAdmin {
        uint256 _balance = _stETH.balanceOf(address(this));
        uint256 _reward = _balance.sub(_stakedAmount).sub(_totalFee);

        if (_reward <= 0) {
            revert();
        }

        _stETH.transfer(_admin, _reward);
    }

    function distributeCollectedFees() external onlyAdmin {
        require(_totalFee > 0, "No fee collected yet");

        _stETH.transfer(_team, _totalFee.mul(_teamShare).div(100));
        _stETH.transfer(_insurance, _totalFee.mul(_insuranceShare).div(100));

        _totalFee = 0;
    }

    function setTeamShare(uint value) external onlyAdmin {
        require(value < 100, "Value should less than 100");

        _teamShare = value;
        _insuranceShare = 100 - value;
    }

    function setStakingPool(address account, bool value) external onlyAdmin {
        require(account != address(0), "No Zero address");

        _stakingPool[account] = value;
    }
}

// File: contracts/Adscendo/interfaces/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

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

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

    event Mint(address indexed account, uint256 value);

    event Burn(address indexed account, uint256 value);

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

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

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

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

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

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

    function mint(address account, uint256 value) external;

    function burn(address account, uint256 value) external;
}
// File: contracts/Adscendo/interfaces/ILido.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

interface ILido {
    function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);

    function submit(address _referral) external payable returns (uint256);
}

// File: contracts/Adscendo/interfaces/IPriceFeed.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

interface IPriceFeed {

    // --- Events ---
    event LastGoodPriceUpdated(uint _lastGoodPrice);
   
    // --- Function ---
    function fetchPrice() external returns (uint);
}

// File: contracts/Adscendo/utils/Context.sol



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

pragma solidity ^0.8.20;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
// File: contracts/Adscendo/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

/**
 * Based on OpenZeppelin's SafeMath:
 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
 *
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     *
     * _Available since v2.4.0._
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     *
     * _Available since v2.4.0._
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     *
     * _Available since v2.4.0._
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

// File: contracts/Adscendo/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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