// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



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

// File: contracts/interfaces/IFeeManager.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.17;

import "./IMintableBurnableERC20.sol";

interface IFeeManager {
    function protocolFee(address, uint) external view returns (uint);
    function redemptionFee(address, uint) external view returns (uint);
    function protocolRedemptionFeeShare() external view returns (uint);
    function protocolFeeTo() external view returns (address);
    function redemptionFeeTo() external view returns (address);

    function beforeRedeem(uint) external;
    function afterRedeem(uint) external;
}

// File: contracts/interfaces/IMintableBurnableERC20.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.17;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IMintableBurnableERC20 is IERC20 {
    function mint(address _to, uint256 _amount) external;
    function burn(uint256 _amount) external;
    function transferOwner(address _owner) external;
    function setMinter(address _minter, bool _status) external;
}

// File: contracts/interfaces/IVault.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.17;

import "./IVaultFactory.sol";

interface IVault {
    function initialize(address) external;

    function factory() external view returns (IVaultFactory);
    function owner() external view returns (address);
    function deposited() external view returns (uint);
    function minted() external view returns (uint);
    function availableBalance() external view returns (uint);
    function pendingYield() external view returns (uint);
    function mintRatio() external view returns (uint);
    
    function deposit(uint) external returns (uint);
    function withdraw(uint) external;
    function mint(uint) external;
    function burn(uint) external;
    function redeem(uint) external;
    function claim() external;
}

// File: contracts/interfaces/IVaultFactory.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.17;

import "./IMintableBurnableERC20.sol";

interface IVaultFactory {
    function collateral() external view returns (IERC20);
    function token() external view returns (IMintableBurnableERC20);
    function feeManager() external view returns (address);

    function createVault(address) external returns (address);
    function getVault(address) external view returns (address);
    function allVaults(uint) external view returns (address);
    function isVault(address) external view returns (bool);
    function isVaultManager(address) external view returns (bool);
    function vaultsLength() external view returns (uint);
}

// File: contracts/Vault.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.17;

import "./interfaces/IVault.sol";
import "./interfaces/IFeeManager.sol";

contract Vault is IVault {

    /* ========== STATES ========== */

    IVaultFactory public immutable override factory;
    address public override owner;
    uint public override deposited;
    uint public override minted;
    uint public constant PRECISION = 1e18;

    /* ========== CONSTRUCTOR ========== */

    constructor() {
        factory = IVaultFactory(msg.sender);
    }

    // Called once by the factory on deployment
    function initialize(address _owner) external override {
        require(msg.sender == address(factory), '!factory');
        owner = _owner;
    }

    /* ========== VIEWS ========== */

    function availableBalance() public view override returns (uint) {
        // In extreme unlike scenario of multiple large negative rebases, vault balance can become < than deposited.
        // In this case vault owner need to transfer in stETH and make up for the diff before withdrawing.
        // This ensures collateral > debt at all times.
        return factory.collateral().balanceOf(address(this)) < deposited ? 0 : deposited - minted;
    }

    function pendingYield() public view override returns (uint) {
        uint balance = factory.collateral().balanceOf(address(this));
        return balance <= deposited ? 0 : balance - deposited;
    }

    function mintRatio() external view override returns (uint) {
        return deposited == 0 ? 0 : minted * PRECISION / deposited;
    }

    /* ========== USER FUNCTIONS ========== */

    // Deposit collateral from msg.sender to vault
    function deposit(uint _amount) external override onlyManagerOrOwner() returns (uint) {
        _claim();
        // stETH have known rounding error on transfers by 1-2 wei
        uint before = factory.collateral().balanceOf(address(this));
        factory.collateral().transferFrom(msg.sender, address(this), _amount);
        uint actualAmount = factory.collateral().balanceOf(address(this)) - before;
        deposited += actualAmount;
        emit Deposit(actualAmount);
        return actualAmount;
    }

    // Withdraw available collateral to owner
    function withdraw(uint _amount) external override onlyManagerOrOwner() {
        _claim();
        _withdraw(_amount, owner);
        emit Withdraw(_amount);
    }

    // Mint token to vault owner using available collateral
    function mint(uint _amount) external override onlyManagerOrOwner() {
        require(availableBalance() >= _amount, "!available");
        _claim();
        factory.token().mint(owner, _amount);
        minted += _amount;
        emit Mint(_amount);
    }

    // Burn token from msg.sender for vault
    function burn(uint _amount) external override onlyManagerOrOwner() {
        _claim();
        _burn(_amount);
        emit Burn(_amount);
    }

    // Claim pending yield into deposited, pay protocol fee
    function claim() external override {
        _claim();
    }

    // Redeem collateral from vault by burning token from msg.sender and paying redemption fee
    function redeem(uint _amount) external {
        IFeeManager feeManager = IFeeManager(factory.feeManager());
        feeManager.beforeRedeem(_amount);
        uint fee = feeManager.redemptionFee(address(this), _amount);
        _claim();
        _burn(_amount);
        _withdraw(_amount - fee, msg.sender);
        uint protocolShare = fee * feeManager.protocolRedemptionFeeShare() / PRECISION;
        _withdraw(protocolShare, feeManager.redemptionFeeTo());
        feeManager.afterRedeem(_amount);
        emit Redeem(msg.sender, _amount, protocolShare, fee - protocolShare);
    }

    /* ========== INTERNAL FUNCTIONS ========== */

    function _claim() internal {
        uint yield = pendingYield();
        if (yield == 0) {
            return;
        }
        IFeeManager feeManager = IFeeManager(factory.feeManager());
        uint fee = feeManager.protocolFee(address(this), yield);
        factory.collateral().transfer(feeManager.protocolFeeTo(), fee);
        deposited += yield - fee;
        emit Claim(yield - fee, fee);
    }

    function _burn(uint _amount) internal {
        require(minted >= _amount, "!minted");
        factory.token().transferFrom(msg.sender, address(this), _amount);
        factory.token().burn(_amount);
        minted -= _amount;
    }

    function _withdraw(uint _amount, address _recipient) internal {
        require(availableBalance() >= _amount, "!available");
        deposited -= _amount;
        factory.collateral().transfer(_recipient, _amount);
    }

    /* ========== MODIFIERS ========== */

    modifier onlyManagerOrOwner() {
        require(msg.sender == owner || factory.isVaultManager(msg.sender), "!allowed");
        _;
    }

    /* ========== EVENTS ========== */

    event Deposit(uint amount);
    event Withdraw(uint amount);
    event Mint(uint amount);
    event Burn(uint amount);
    event Claim(uint yieldAfterProtocolFee, uint protocolFee);
    event Redeem(address indexed redeemer, uint amount, uint protocolFee, uint ownerFee);
}