// File: ConvexDepositToken.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import "IERC20Metadata.sol";
import "ICurveProxy.sol";
import "IVault.sol";
import "PrismaOwnable.sol";

interface IBooster {
    function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns (bool);

    function poolInfo(
        uint256 _pid
    )
        external
        view
        returns (address lpToken, address token, address gauge, address crvRewards, address stash, bool shutdown);
}

interface IBaseRewardPool {
    function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);

    function getReward(address _account, bool _claimExtras) external returns (bool);

    function getReward() external;
}

interface IConvexStash {
    function tokenInfo(address _token) external view returns (address token, address rewards);
}

/**
    @title Prisma Convex Deposit Wrapper
    @notice Standard ERC20 interface around a deposit of a Curve LP token into Convex.
            Tokens are minted by depositing Curve LP tokens, and burned to receive the LP
            tokens back. Holders may claim PRISMA emissions on top of the earned CRV and CVX.
 */
contract ConvexDepositToken is PrismaOwnable {
    IERC20 public immutable PRISMA;
    IERC20 public immutable CRV;
    IERC20 public immutable CVX;

    IBooster public immutable booster;
    ICurveProxy public immutable curveProxy;
    IPrismaVault public immutable vault;

    IERC20 public lpToken;
    uint256 public depositPid;
    IBaseRewardPool public crvRewards;
    IBaseRewardPool public cvxRewards;

    uint256 public emissionId;

    string public symbol;
    string public name;
    uint256 public constant decimals = 18;
    uint256 public totalSupply;

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

    // each array relates to [PRISMA, CRV, CVX]
    uint256[3] public rewardIntegral;
    uint128[3] public rewardRate;

    // last known balances for CRV, CVX
    // must track because anyone can trigger a claim for any address
    uint128 public lastCrvBalance;
    uint128 public lastCvxBalance;

    uint32 public lastUpdate;
    uint32 public periodFinish;

    // maximum percent of weekly emissions that can be directed to this receiver,
    // as a whole number out of 10000. emissions greater than this amount are stored
    // until `Vault.lockWeeks() == 0` and then returned to the unallocated supply.
    uint16 public maxWeeklyEmissionPct;
    uint128 public storedExcessEmissions;

    mapping(address => uint256[3]) public rewardIntegralFor;
    mapping(address => uint128[3]) private storedPendingReward;

    uint256 constant REWARD_DURATION = 1 weeks;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event LPTokenDeposited(address indexed lpToken, address indexed receiver, uint256 amount);
    event LPTokenWithdrawn(address indexed lpToken, address indexed receiver, uint256 amount);
    event RewardClaimed(address indexed receiver, uint256 prismaAmount, uint256 crvAmount, uint256 cvxAmount);
    event MaxWeeklyEmissionPctSet(uint256 pct);
    event MaxWeeklyEmissionsExceeded(uint256 allocated, uint256 maxAllowed);

    constructor(
        IERC20 _prisma,
        IERC20 _CRV,
        IERC20 _CVX,
        IBooster _booster,
        ICurveProxy _proxy,
        IPrismaVault _vault,
        address prismaCore
    ) PrismaOwnable(prismaCore) {
        PRISMA = _prisma;
        CRV = _CRV;
        CVX = _CVX;
        booster = _booster;
        curveProxy = _proxy;
        vault = _vault;
    }

    function initialize(uint256 pid) external {
        require(address(lpToken) == address(0), "Already initialized");
        (address _lpToken, , , address _crvRewards, address _stash, ) = booster.poolInfo(pid);

        depositPid = pid;
        lpToken = IERC20(_lpToken);
        crvRewards = IBaseRewardPool(_crvRewards);

        (, address _rewards) = IConvexStash(_stash).tokenInfo(address(CVX));
        require(_rewards != address(0), "Pool has no CVX rewards");
        cvxRewards = IBaseRewardPool(_rewards);

        IERC20(_lpToken).approve(address(booster), type(uint256).max);
        PRISMA.approve(address(vault), type(uint256).max);

        string memory _symbol = IERC20Metadata(_lpToken).symbol();
        name = string.concat("Prisma ", _symbol, " Convex Deposit");
        symbol = string.concat("prisma-", _symbol);

        periodFinish = uint32(block.timestamp - 1);
        maxWeeklyEmissionPct = 10000;
        emit MaxWeeklyEmissionPctSet(10000);
    }

    function setMaxWeeklyEmissionPct(uint16 _maxWeeklyEmissionPct) external onlyOwner returns (bool) {
        require(_maxWeeklyEmissionPct < 10001, "Invalid maxWeeklyEmissionPct");
        maxWeeklyEmissionPct = _maxWeeklyEmissionPct;

        emit MaxWeeklyEmissionPctSet(_maxWeeklyEmissionPct);
        return true;
    }

    function notifyRegisteredId(uint256[] memory assignedIds) external returns (bool) {
        require(msg.sender == address(vault));
        require(emissionId == 0, "Already registered");
        require(assignedIds.length == 1, "Incorrect ID count");
        emissionId = assignedIds[0];

        return true;
    }

    function deposit(address receiver, uint256 amount) external returns (bool) {
        require(amount > 0, "Cannot deposit zero");
        lpToken.transferFrom(msg.sender, address(this), amount);
        booster.deposit(depositPid, amount, true);
        uint256 balance = balanceOf[receiver];
        uint256 supply = totalSupply;
        balanceOf[receiver] = balance + amount;
        totalSupply = supply + amount;

        _updateIntegrals(receiver, balance, supply);
        if (block.timestamp / 1 weeks >= periodFinish / 1 weeks) _fetchRewards();

        emit Transfer(address(0), receiver, amount);
        emit LPTokenDeposited(address(lpToken), receiver, amount);

        return true;
    }

    function withdraw(address receiver, uint256 amount) external returns (bool) {
        require(amount > 0, "Cannot withdraw zero");
        uint256 balance = balanceOf[msg.sender];
        uint256 supply = totalSupply;
        balanceOf[msg.sender] = balance - amount;
        totalSupply = supply - amount;

        crvRewards.withdrawAndUnwrap(amount, false);
        lpToken.transfer(receiver, amount);

        _updateIntegrals(msg.sender, balance, supply);
        if (block.timestamp / 1 weeks >= periodFinish / 1 weeks) _fetchRewards();

        emit Transfer(msg.sender, address(0), amount);
        emit LPTokenWithdrawn(address(lpToken), receiver, amount);

        return true;
    }

    function _claimReward(address claimant, address receiver) internal returns (uint128[3] memory amounts) {
        _updateIntegrals(claimant, balanceOf[claimant], totalSupply);
        amounts = storedPendingReward[claimant];
        delete storedPendingReward[claimant];
        lastCrvBalance -= amounts[1];
        lastCvxBalance -= amounts[2];

        CRV.transfer(receiver, amounts[1]);
        CVX.transfer(receiver, amounts[2]);

        return amounts;
    }

    function claimReward(
        address receiver
    ) external returns (uint256 prismaAmount, uint256 crvAmount, uint256 cvxAmount) {
        uint128[3] memory amounts = _claimReward(msg.sender, receiver);
        vault.transferAllocatedTokens(msg.sender, receiver, amounts[0]);

        emit RewardClaimed(receiver, amounts[0], amounts[1], amounts[2]);
        return (amounts[0], amounts[1], amounts[2]);
    }

    function vaultClaimReward(address claimant, address receiver) external returns (uint256) {
        require(msg.sender == address(vault));
        uint128[3] memory amounts = _claimReward(claimant, receiver);

        emit RewardClaimed(claimant, 0, amounts[1], amounts[2]);
        return amounts[0];
    }

    function claimableReward(
        address account
    ) external view returns (uint256 prismaAmount, uint256 crvAmount, uint256 cvxAmount) {
        uint256 updated = periodFinish;
        if (updated > block.timestamp) updated = block.timestamp;
        uint256 duration = updated - lastUpdate;
        uint256 balance = balanceOf[account];
        uint256 supply = totalSupply;
        uint256[3] memory amounts;

        for (uint256 i = 0; i < 3; i++) {
            uint256 integral = rewardIntegral[i];
            if (supply > 0) {
                integral += (duration * rewardRate[i] * 1e18) / supply;
            }
            uint256 integralFor = rewardIntegralFor[account][i];
            amounts[i] = storedPendingReward[account][i] + ((balance * (integral - integralFor)) / 1e18);
        }
        return (amounts[0], amounts[1], amounts[2]);
    }

    function approve(address _spender, uint256 _value) public returns (bool) {
        allowance[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
        return true;
    }

    function _transfer(address _from, address _to, uint256 _value) internal {
        uint256 supply = totalSupply;

        uint256 balance = balanceOf[_from];
        balanceOf[_from] = balance - _value;
        _updateIntegrals(_from, balance, supply);

        balance = balanceOf[_to];
        balanceOf[_to] = balance + _value;
        _updateIntegrals(_to, balance, supply);

        emit Transfer(_from, _to, _value);
    }

    function transfer(address _to, uint256 _value) public returns (bool) {
        _transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        uint256 allowed = allowance[_from][msg.sender];
        if (allowed != type(uint256).max) {
            allowance[_from][msg.sender] = allowed - _value;
        }
        _transfer(_from, _to, _value);
        return true;
    }

    function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {
        uint256 updated = periodFinish;
        if (updated > block.timestamp) updated = block.timestamp;
        uint256 duration = updated - lastUpdate;
        if (duration > 0) lastUpdate = uint32(updated);

        for (uint256 i = 0; i < 3; i++) {
            uint256 integral = rewardIntegral[i];
            if (duration > 0 && supply > 0) {
                integral += (duration * rewardRate[i] * 1e18) / supply;
                rewardIntegral[i] = integral;
            }
            if (account != address(0)) {
                uint256 integralFor = rewardIntegralFor[account][i];
                if (integral > integralFor) {
                    storedPendingReward[account][i] += uint128((balance * (integral - integralFor)) / 1e18);
                    rewardIntegralFor[account][i] = integral;
                }
            }
        }
    }

    function pushExcessEmissions() external {
        _pushExcessEmissions(0);
    }

    function _pushExcessEmissions(uint256 newAmount) internal {
        if (vault.lockWeeks() > 0) storedExcessEmissions = uint128(storedExcessEmissions + newAmount);
        else {
            uint256 excess = storedExcessEmissions + newAmount;
            storedExcessEmissions = 0;
            vault.transferAllocatedTokens(address(this), address(this), excess);
            vault.increaseUnallocatedSupply(PRISMA.balanceOf(address(this)));
        }
    }

    function fetchRewards() external {
        require(block.timestamp / 1 weeks >= periodFinish / 1 weeks, "Can only fetch once per week");
        _updateIntegrals(address(0), 0, totalSupply);
        _fetchRewards();
    }

    function _fetchRewards() internal {
        uint256 prismaAmount;
        uint256 id = emissionId;
        if (id > 0) prismaAmount = vault.allocateNewEmissions(id);
        crvRewards.getReward(address(this), false);
        cvxRewards.getReward();

        // apply max weekly emission limit
        uint256 maxWeekly = maxWeeklyEmissionPct;
        if (maxWeekly < 10000) {
            maxWeekly = (vault.weeklyEmissions(vault.getWeek()) * maxWeekly) / 10000;
            if (prismaAmount > maxWeekly) {
                emit MaxWeeklyEmissionsExceeded(prismaAmount, maxWeekly);
                _pushExcessEmissions(prismaAmount - maxWeekly);
                prismaAmount = maxWeekly;
            }
        }

        uint256 last = lastCrvBalance;
        uint256 crvAmount = CRV.balanceOf(address(this)) - last;
        // apply CRV fee and send fee tokens to curveProxy
        uint256 fee = (crvAmount * curveProxy.crvFeePct()) / 10000;
        if (fee > 0) {
            crvAmount -= fee;
            CRV.transfer(address(curveProxy), fee);
        }
        lastCrvBalance = uint128(last + crvAmount);

        last = lastCvxBalance;
        uint256 cvxAmount = CVX.balanceOf(address(this)) - last;
        lastCvxBalance = uint128(cvxAmount + last);

        uint256 _periodFinish = periodFinish;
        if (block.timestamp < _periodFinish) {
            uint256 remaining = _periodFinish - block.timestamp;
            prismaAmount += remaining * rewardRate[0];
            crvAmount += remaining * rewardRate[1];
            cvxAmount += remaining * rewardRate[2];
        }

        rewardRate[0] = uint128(prismaAmount / REWARD_DURATION);
        rewardRate[1] = uint128(crvAmount / REWARD_DURATION);
        rewardRate[2] = uint128(cvxAmount / REWARD_DURATION);

        lastUpdate = uint32(block.timestamp);
        periodFinish = uint32(block.timestamp + REWARD_DURATION);
    }
}

// File: IERC20Metadata.sol



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

pragma solidity ^0.8.0;

import "IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: 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: ICurveProxy.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ICurveProxy {
    struct GaugeWeightVote {
        address gauge;
        uint256 weight;
    }

    struct TokenBalance {
        address token;
        uint256 amount;
    }

    event CrvFeePctSet(uint256 feePct);

    function approveGaugeDeposit(address gauge, address depositor) external returns (bool);

    function claimFees() external returns (uint256);

    function execute(address target, bytes calldata data) external returns (bytes memory);

    function lockCRV() external returns (bool);

    function mintCRV(address gauge, address receiver) external returns (uint256);

    function setCrvFeePct(uint64 _feePct) external returns (bool);

    function setDepositManager(address _depositManager) external returns (bool);

    function setExecutePermissions(
        address caller,
        address target,
        bytes4[] calldata selectors,
        bool permitted
    ) external returns (bool);

    function setGaugeRewardsReceiver(address gauge, address receiver) external returns (bool);

    function setPerGaugeApproval(address caller, address gauge) external returns (bool);

    function setVoteManager(address _voteManager) external returns (bool);

    function transferTokens(address receiver, TokenBalance[] calldata balances) external returns (bool);

    function voteForGaugeWeights(GaugeWeightVote[] calldata votes) external returns (bool);

    function voteInCurveDao(address aragon, uint256 id, bool support) external returns (bool);

    function withdrawFromGauge(
        address gauge,
        address lpToken,
        uint256 amount,
        address receiver
    ) external returns (bool);

    function CRV() external view returns (address);

    function PRISMA_CORE() external view returns (address);

    function crvFeePct() external view returns (uint64);

    function depositManager() external view returns (address);

    function feeDistributor() external view returns (address);

    function feeToken() external view returns (address);

    function gaugeController() external view returns (address);

    function guardian() external view returns (address);

    function minter() external view returns (address);

    function owner() external view returns (address);

    function perGaugeApproval(address caller) external view returns (address gauge);

    function unlockTime() external view returns (uint64);

    function voteManager() external view returns (address);

    function votingEscrow() external view returns (address);
}

// File: IVault.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPrismaVault {
    struct InitialAllowance {
        address receiver;
        uint256 amount;
    }

    event BoostCalculatorSet(address boostCalculator);
    event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);
    event EmissionScheduleSet(address emissionScheduler);
    event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);
    event NewReceiverRegistered(address receiver, uint256 id);
    event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);
    event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);
    event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);

    function allocateNewEmissions(uint256 id) external returns (uint256);

    function batchClaimRewards(
        address receiver,
        address boostDelegate,
        address[] calldata rewardContracts,
        uint256 maxFeePct
    ) external returns (bool);

    function increaseUnallocatedSupply(uint256 amount) external returns (bool);

    function registerReceiver(address receiver, uint256 count) external returns (bool);

    function setBoostCalculator(address _boostCalculator) external returns (bool);

    function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);

    function setEmissionSchedule(address _emissionSchedule) external returns (bool);

    function setInitialParameters(
        address _emissionSchedule,
        address _boostCalculator,
        uint256 totalSupply,
        uint64 initialLockWeeks,
        uint128[] calldata _fixedInitialAmounts,
        InitialAllowance[] calldata initialAllowances
    ) external;

    function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);

    function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);

    function transferTokens(address token, address receiver, uint256 amount) external returns (bool);

    function PRISMA_CORE() external view returns (address);

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

    function boostCalculator() external view returns (address);

    function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);

    function claimableRewardAfterBoost(
        address account,
        address receiver,
        address boostDelegate,
        address rewardContract
    ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);

    function emissionSchedule() external view returns (address);

    function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);

    function getWeek() external view returns (uint256 week);

    function guardian() external view returns (address);

    function idToReceiver(uint256) external view returns (address account, bool isActive);

    function lockWeeks() external view returns (uint64);

    function locker() external view returns (address);

    function owner() external view returns (address);

    function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);

    function prismaToken() external view returns (address);

    function receiverUpdatedWeek(uint256) external view returns (uint16);

    function totalUpdateWeek() external view returns (uint64);

    function unallocatedTotal() external view returns (uint128);

    function voter() external view returns (address);

    function weeklyEmissions(uint256) external view returns (uint128);
}

// File: PrismaOwnable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import "IPrismaCore.sol";

/**
    @title Prisma Ownable
    @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.
            The ownership cannot be independently modified or renounced.
 */
contract PrismaOwnable {
    IPrismaCore public immutable PRISMA_CORE;

    constructor(address _prismaCore) {
        PRISMA_CORE = IPrismaCore(_prismaCore);
    }

    modifier onlyOwner() {
        require(msg.sender == PRISMA_CORE.owner(), "Only owner");
        _;
    }

    function owner() public view returns (address) {
        return PRISMA_CORE.owner();
    }

    function guardian() public view returns (address) {
        return PRISMA_CORE.guardian();
    }
}

// File: IPrismaCore.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPrismaCore {
    event FeeReceiverSet(address feeReceiver);
    event GuardianSet(address guardian);
    event NewOwnerAccepted(address oldOwner, address owner);
    event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);
    event NewOwnerRevoked(address owner, address revokedOwner);
    event Paused();
    event PriceFeedSet(address priceFeed);
    event Unpaused();

    function acceptTransferOwnership() external;

    function commitTransferOwnership(address newOwner) external;

    function revokeTransferOwnership() external;

    function setFeeReceiver(address _feeReceiver) external;

    function setGuardian(address _guardian) external;

    function setPaused(bool _paused) external;

    function setPriceFeed(address _priceFeed) external;

    function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);

    function feeReceiver() external view returns (address);

    function guardian() external view returns (address);

    function owner() external view returns (address);

    function ownershipTransferDeadline() external view returns (uint256);

    function paused() external view returns (bool);

    function pendingOwner() external view returns (address);

    function priceFeed() external view returns (address);

    function startTime() external view returns (uint256);
}