// File: contracts/erc20/ERC20.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

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

    constructor(string memory _name, string memory _symbol, uint8 _decimals) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return
            block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256(
                        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                    ),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

// File: contracts/erc20/SafeERC20.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import "./ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeERC20 {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

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

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(ERC20 token, address from, address to, uint256 amount) internal {
        bool success;

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

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(
                freeMemoryPointer,
                0x23b872dd00000000000000000000000000000000000000000000000000000000
            )
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

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

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(ERC20 token, address to, uint256 amount) internal {
        bool success;

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

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(
                freeMemoryPointer,
                0xa9059cbb00000000000000000000000000000000000000000000000000000000
            )
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

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

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(ERC20 token, address to, uint256 amount) internal {
        bool success;

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

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(
                freeMemoryPointer,
                0x095ea7b300000000000000000000000000000000000000000000000000000000
            )
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

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

        require(success, "APPROVE_FAILED");
    }
}

// File: contracts/PerpetualBond/interfaces/IPerpetualBondFactory.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Perpetual bond factory interface
 * @author Bonding Finance
 */
interface IPerpetualBondFactory {
    event VaultCreated(address indexed token, address vault);

    struct FeeInfo {
        address feeTo;
        uint256 vaultFee;
        uint256 surplusFee;
    }

    function paused() external view returns (bool);

    function feeInfo() external view returns (address feeTo, uint256 vaultFee, uint256 surplusFee);

    function allVaults(uint256) external view returns (address);

    function getVault(address token) external view returns (address);

    function allVaultsLength() external view returns (uint256);

    //////////////////////////
    /* Restricted Functions */
    //////////////////////////

    function createVault(address token) external returns (address vault);

    function setPaused(bool paused) external;

    function setStaking(address vault, address staking) external;

    function collectVaultFees(address vault) external;

    function collectSurplusFees(address staking) external;

    function setFeeTo(address feeTo) external;

    function setVaultFee(uint256 vaultFee) external;

    function setSurplusFee(uint256 surplusFee) external;
}

// File: contracts/PerpetualBond/interfaces/IPerpetualBondStaking.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Perpetual bond staking interface
 * @author Bonding Finance
 */
interface IPerpetualBondStaking {
    event Stake(address indexed user, address indexed token, uint256 amount);
    event Unstake(address indexed user, address indexed token, uint256 amount);
    event EmergencyWithdraw(address indexed user, address indexed token, uint256 amount);
    event Claim(address indexed user, address indexed token, uint256 amount);
    event Distribute(address indexed pool, uint256 rewardAmount, uint256 amountStaked);
    event CollectSurplus(address indexed feeTo, uint256 amount);

    struct PoolInfo {
        uint256 accRewardsPerShare;
        uint256 accRewards;
        uint256 claimedRewards;
    }

    struct UserInfo {
        uint256 amount;
        uint256 rewardDebt;
    }

    function factory() external view returns (address);

    function vault() external view returns (address);

    function yToken() external view returns (address);

    function lpToken() external view returns (address);

    function rewardToken() external view returns (address);

    function fees() external view returns (uint256);

    function userInfo(
        address token,
        address user
    ) external view returns (uint256 amount, uint256 rewardDebt);

    function poolInfo(
        address token
    )
        external
        view
        returns (uint256 accRewardsPerShare, uint256 accRewards, uint256 claimedRewards);

    function stake(address token, uint256 amount) external returns (uint256 rewards);

    function unstake(address token, uint256 amount) external returns (uint256 rewards);

    function emergencyWithdraw(address token) external;

    function harvest() external;

    function pendingRewards(address token, address user) external view returns (uint256 rewards);

    //////////////////////////
    /* Restricted Functions */
    //////////////////////////

    function collectFees(address feeTo) external;
}

// File: contracts/PerpetualBond/interfaces/IPerpetualBondVault.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

/**
 * @title Perpetual bond vault interface
 * @author Bonding Finance
 */
interface IPerpetualBondVault {
    event Mint(address indexed user, uint256 amount);
    event Redeem(address indexed user, uint256 amount);
    event Harvest(uint256 amount);
    event CollectFees(address indexed feeTo, uint256 amount);

    function factory() external view returns (address);

    function token() external view returns (address);

    function dToken() external view returns (address);

    function yToken() external view returns (address);

    function staking() external view returns (address);

    function totalDeposits() external view returns (uint256);

    function fees() external view returns (uint256);

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

    function redeem(uint256 amount) external returns (uint256 redeemAmount);

    function harvest() external;

    function pendingRewards() external view returns (uint256);

    //////////////////////////
    /* Restricted Functions */
    //////////////////////////

    function setStaking(address staking) external;

    function collectFees(address feeTo) external;
}

// File: contracts/PerpetualBond/PerpetualBondStaking.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "./interfaces/IPerpetualBondStaking.sol";
import "./interfaces/IPerpetualBondVault.sol";
import "./interfaces/IPerpetualBondFactory.sol";
import "../erc20/ERC20.sol";
import "../erc20/SafeERC20.sol";
import "../utils/ReentrancyGuard.sol";

/**
 * @title Perpetual bond staking contract
 * @author Bonding Finance
 */
contract PerpetualBondStaking is IPerpetualBondStaking, ReentrancyGuard {
    using SafeERC20 for ERC20;

    address public immutable override factory;
    address public immutable override vault;
    address public immutable override yToken;
    address public immutable override lpToken;
    address public immutable override rewardToken;
    uint256 public override fees;

    mapping(address => mapping(address => UserInfo)) public override userInfo;
    mapping(address => PoolInfo) public override poolInfo;

    constructor(address _vault, address _lpToken) {
        require(_vault != address(0));
        factory = IPerpetualBondVault(_vault).factory();
        vault = _vault;
        yToken = IPerpetualBondVault(_vault).yToken();
        // Note: If _lpToken is 0, the protocol will earn all surplus yield
        lpToken = _lpToken;
        rewardToken = IPerpetualBondVault(_vault).token();
    }

    /**
     * @notice Stakes `amount` of `token`
     * @dev Harvests and claims rewards
     * @param token Token to stake
     * @param amount Amount of tokens to stake
     * @return rewards Amount of rewards claimed
     */
    function stake(
        address token,
        uint256 amount
    ) external override nonReentrant returns (uint256 rewards) {
        _validateToken(token);
        harvest();
        rewards = _claimRewards(token, msg.sender);

        UserInfo storage user = userInfo[token][msg.sender];
        if (amount != 0) {
            ERC20(token).safeTransferFrom(msg.sender, address(this), amount);
            user.amount += amount;
        }
        user.rewardDebt = (user.amount * poolInfo[token].accRewardsPerShare) / 1e18;

        emit Stake(msg.sender, token, amount);
    }

    /**
     * @notice Unstakes `amount` of `token`
     * @dev Harvests and claims rewards
     * @param token Token to unstake
     * @param amount Amount of tokens to unstake
     * @return rewards Amount of rewards claimed
     */
    function unstake(
        address token,
        uint256 amount
    ) external override nonReentrant returns (uint256 rewards) {
        _validateToken(token);
        harvest();
        rewards = _claimRewards(token, msg.sender);

        UserInfo storage user = userInfo[token][msg.sender];
        user.amount -= amount;
        user.rewardDebt = (user.amount * poolInfo[token].accRewardsPerShare) / 1e18;

        ERC20(token).safeTransfer(msg.sender, amount);

        emit Unstake(msg.sender, token, amount);
    }

    /**
     * @notice Emergency withdraw `token`
     * @dev Does not claim rewards
     * @param token Token to withdraw
     */
    function emergencyWithdraw(address token) external override nonReentrant {
        UserInfo storage user = userInfo[token][msg.sender];

        uint256 amount = user.amount;
        user.amount = 0;
        user.rewardDebt = 0;
        ERC20(token).safeTransfer(msg.sender, amount);

        emit EmergencyWithdraw(msg.sender, token, amount);
    }

    /**
     * @notice Calls `harvest()` on vault contract and then distributes pending rewards
     * @dev Rebase rewards from unclaimed rewards are also distributed
     */
    function harvest() public override {
        if (IPerpetualBondVault(vault).staking() == address(this)) {
            IPerpetualBondVault(vault).harvest();
        }

        // Accounts for rebase from unclaimed rewards
        uint256 balance = ERC20(rewardToken).balanceOf(address(this));
        uint256 rewards = balance + _totalClaimedRewards() - _totalAccRewards() - fees;
        _distribute(rewards);
    }

    /**
     * @notice Calculates `_user` pending rewards
     * @dev Does not include harvested rewards that have not been distributed yet
     * @param _token Address of the staked token
     * @param _user Address of the user
     * @return rewards Amount of pending rewards
     */
    function pendingRewards(
        address _token,
        address _user
    ) public view override returns (uint256 rewards) {
        UserInfo memory user = userInfo[_token][_user];
        rewards = ((user.amount * poolInfo[_token].accRewardsPerShare) / 1e18) - user.rewardDebt;
    }

    /**
     * @notice Claims all pending rewards for `user`
     * @param token Token to claim rewards for
     * @param user User to claim rewards for
     * @return rewards Amount of rewards claimed
     */
    function _claimRewards(address token, address user) internal returns (uint256 rewards) {
        if (userInfo[token][user].amount == 0) return 0;

        rewards = pendingRewards(token, user);
        if (rewards == 0) return 0;

        uint256 balance = ERC20(rewardToken).balanceOf(address(this));
        // In case of rounding error
        if (rewards > balance) rewards = balance;

        ERC20(rewardToken).safeTransfer(user, rewards);
        poolInfo[token].claimedRewards += rewards;

        emit Claim(user, token, rewards);
    }

    /**
     * @notice Distributes rewards to stakers
     * @param rewards Amount of rewards to distribute
     */
    function _distribute(uint256 rewards) internal {
        if (rewards == 0) return;

        uint256 yTokenStaked = ERC20(yToken).balanceOf(address(this));
        uint256 yTokenSupply = ERC20(yToken).totalSupply();

        // Forces yToken yield to match rebase yield, regardless of % staked
        uint256 yTokenRewards = yTokenSupply != 0 ? (rewards * yTokenStaked) / yTokenSupply : 0;
        uint256 miscRewards = rewards - yTokenRewards;

        // Distribute allocated rewards to yToken stakers
        if (yTokenRewards != 0) {
            PoolInfo storage yTokenPool = poolInfo[yToken];
            yTokenPool.accRewardsPerShare += (yTokenRewards * 1e18) / yTokenStaked;
            yTokenPool.accRewards += yTokenRewards;

            emit Distribute(yToken, yTokenRewards, yTokenStaked);
        }

        // Distribute excess rewards to LP token stakers and protocol
        if (miscRewards != 0) {
            uint256 feeAmount = _chargeFee(miscRewards);
            uint256 lpRewards = miscRewards - feeAmount;
            if (lpRewards == 0) return;

            uint256 lpStaked = ERC20(lpToken).balanceOf(address(this));
            PoolInfo storage lpTokenPool = poolInfo[lpToken];
            lpTokenPool.accRewardsPerShare += (lpRewards * 1e18) / lpStaked;
            lpTokenPool.accRewards += lpRewards;

            emit Distribute(lpToken, lpRewards, lpStaked);
        }
    }

    /**
     * @notice Calculates the total amount of rewards accrued
     * @return totalRewards Total rewards accrued
     */
    function _totalAccRewards() internal view returns (uint256 totalRewards) {
        totalRewards = poolInfo[yToken].accRewards + poolInfo[lpToken].accRewards;
    }

    /**
     * @notice Calculates the total amount of claimed rewards
     * @return totalClaimed Total rewards claimed
     */
    function _totalClaimedRewards() internal view returns (uint256 totalClaimed) {
        totalClaimed = poolInfo[yToken].claimedRewards + poolInfo[lpToken].claimedRewards;
    }

    /**
     * @notice Validates `token` is a supported token
     * @param token Token to validate
     */
    function _validateToken(address token) internal view {
        require(token != address(0) && (token == yToken || token == lpToken), "!valid");
    }

    /**
     * @notice Applies surplus fee (if any) to `amount`
     * @dev If LP token or staked amount is 0, all excess is distributed to the protocol
     * @param amount The original amount
     * @return feeAmount The fee amount charged
     */
    function _chargeFee(uint256 amount) internal returns (uint256 feeAmount) {
        if (lpToken == address(0) || ERC20(lpToken).balanceOf(address(this)) == 0) {
            feeAmount = amount;
        } else {
            (, , uint256 fee) = IPerpetualBondFactory(factory).feeInfo();
            if (fee == 0) return 0;

            feeAmount = (amount * fee) / 10000;
        }

        fees += feeAmount;
    }

    //////////////////////////
    /* Restricted Functions */
    //////////////////////////

    function collectFees(address feeTo) external override {
        require(msg.sender == factory, "!factory");

        if (fees == 0) return;

        ERC20(rewardToken).safeTransfer(feeTo, fees);

        emit CollectSurplus(feeTo, fees);

        delete fees;
    }
}

// File: contracts/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}