// File: contracts/WardenPledge.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;

import "./oz/interfaces/IERC20.sol";
import "./oz/libraries/SafeERC20.sol";
import "./utils/Owner.sol";
import "./oz/utils/Pausable.sol";
import "./oz/utils/ReentrancyGuard.sol";
import "./interfaces/IVotingEscrow.sol";
import "./interfaces/IBoostV2.sol";
import "./utils/Errors.sol";

/** @title Warden Pledge contract */
/// @author Paladin
/*
    Delegation market (Pledge version) based on Curve Boost V2 contract
*/
contract WardenPledge is Owner, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Constants :
    uint256 public constant UNIT = 1e18;
    uint256 public constant MAX_PCT = 10000;
    uint256 public constant WEEK = 604800;

    /** @notice Minimum Pledge duration */
    uint256 public constant MIN_PLEDGE_DURATION = 1 weeks;
    /** @notice Minimum delegation time when pledging */
    uint256 public constant MIN_DELEGATION_DURATION = 2 days;

    // Storage :

    struct Pledge{
        // Target amount of veCRV (balance scaled by Boost v2, fetched as adjusted_balance)
        uint256 targetVotes;
        // Price per vote per week, set by the owner
        uint256 rewardPerVotePerWeek;
        // Address to receive the Boosts
        address receiver;
        // Address of the token given as rewards to Boosters
        address rewardToken;
        // Timestamp of end of the Pledge
        uint64 endTimestamp;
        // Set to true if the Pledge is cancelled, or when closed after the endTimestamp
        bool closed;
    }

    /** @notice List of all Pledges */
    Pledge[] public pledges;

    /** @notice Owner of each Pledge (ordered by index in the pledges list) */
    mapping(uint256 => address) public pledgeOwner;
    /** @notice List of all Pledges for each owner */
    mapping(address => uint256[]) public ownerPledges;

    /** @notice Amount of rewards available for each Pledge */
    // sorted by Pledge index
    mapping(uint256 => uint256) public pledgeAvailableRewardAmounts;

    /** @notice Address of the votingToken to delegate */
    IVotingEscrow public immutable votingEscrow;
    /** @notice Address of the Delegation Boost contract */
    IBoostV2 public immutable delegationBoost;


    /** @notice Minimum amount of reward per vote for each reward token */
    // Also used to whitelist the tokens for rewards
    mapping(address => uint256) public minAmountRewardToken;
    /** @notice Total amount held in Pledge for the reward amount */
    mapping(address => uint256) public rewardTokenTotalAmount;


    /** @notice ratio of fees to pay the protocol (in BPS) */
    uint256 public protocolFeeRatio = 500; // 5%
    /** @notice Address to receive protocol fees */
    address public chestAddress;

    /** @notice Minimum vote difference for a Pledge */
    uint256 public minVoteDiff;


    // Events

    /** @notice Event emitted when a new Pledge is created */
    event NewPledge(
        address indexed creator,
        address indexed receiver,
        address indexed rewardToken,
        uint256 id,
        uint256 targetVotes,
        uint256 rewardPerVotePerWeek,
        uint256 endTimestamp
    );
    /** @notice Event emitted when a Pledge duration is extended */
    event ExtendPledgeDuration(uint256 indexed pledgeId, uint256 oldEndTimestamp, uint256 newEndTimestamp);
    /** @notice Event emitted when a Pledge reward per vote is increased */
    event IncreasePledgeRewardPerVote(uint256 indexed pledgeId, uint256 oldrewardPerVotePerWeek, uint256 newrewardPerVotePerWeek);
    /** @notice Event emitted when a Pledge is closed */
    event ClosePledge(uint256 indexed pledgeId);
    /** @notice Event emitted when rewards are retrieved from a closed Pledge */
    event RetrievedPledgeRewards(uint256 indexed pledgeId, address receiver, uint256 amount);

    /** @notice Event emitted when an user delegate to a Pledge */
    event Pledged(uint256 indexed pledgeId, address indexed user, uint256 amount, uint256 endTimestamp);

    /** @notice Event emitted when a new reward token is added to the list */
    event NewRewardToken(address indexed token, uint256 minRewardPerWeek);
    /** @notice Event emitted when a reward token parameter is updated */
    event UpdateRewardToken(address indexed token, uint256 minRewardPerWeek);
    /** @notice Event emitted when a reward token is removed from the list */
    event RemoveRewardToken(address indexed token);

    /** @notice Event emitted when the address for the Chest is updated */
    event ChestUpdated(address oldChest, address newChest);
    /** @notice Event emitted when the platform fee is updated */
    event PlatformFeeUpdated(uint256 oldFee, uint256 newFee);
    /** @notice Event emitted when the minimum vote difference value is updated */
    event MinVoteDiffUpdated(uint256 oldMinVoteDiff, uint256 newMinVoteDiff);



    // Constructor

    /**
    * @dev Creates the contract, set the given base parameters
    * @param _votingEscrow address of the voting token to delegate
    * @param _delegationBoost address of the contract handling delegation
    * @param _chestAddress address of the contract receiving the fees
    * @param _minVoteDiff min amount of veToken to target in a Pledge
    */
    constructor(
        address _votingEscrow,
        address _delegationBoost,
        address _chestAddress,
        uint256 _minVoteDiff
    ) {
        // We want that value to be at minimum 1e18, to avoid any rounding issues
        if(_minVoteDiff < UNIT) revert Errors.InvalidValue();
        if(_votingEscrow == address(0) || _delegationBoost == address(0) || _chestAddress == address(0)) revert Errors.ZeroAddress();

        votingEscrow = IVotingEscrow(_votingEscrow);
        delegationBoost = IBoostV2(_delegationBoost);

        chestAddress = _chestAddress;

        minVoteDiff = _minVoteDiff;
    }

    
    // View Methods

    /**
    * @notice Amount of Pledges listed in this contract
    * @dev Amount of Pledges listed in this contract
    * @return uint256: Amount of Pledges listed in this contract
    */
    function nextPledgeIndex() public view returns(uint256){
        return pledges.length;
    }

    /**
    * @notice Get all Pledges created by the user
    * @dev Get all Pledges created by the user
    * @param user Address of the user
    * @return uint256[]: List of Pledges IDs
    */
    function getUserPledges(address user) external view returns(uint256[] memory){
        return ownerPledges[user];
    }

    /**
    * @notice Get all the Pledges
    * @dev Get all the Pledges
    * @return Pledge[]: List of Pledge structs
    */
    function getAllPledges() external view returns(Pledge[] memory){
        return pledges;
    }

    /**
    * @dev Rounds down given timestamp to weekly periods
    * @param timestamp timestamp to round down
    * @return uint256: rounded down timestamp
    */
    function _getRoundedTimestamp(uint256 timestamp) internal pure returns(uint256) {
        return (timestamp / WEEK) * WEEK;
    }


    // Pledgers Methods

    /**
    * @notice Delegates boost to a given Pledge & receive rewards
    * @dev Delegates boost to a given Pledge & receive rewards
    * @param pledgeId Pledge to delegate to
    * @param amount Amount to delegate
    * @param endTimestamp End of delegation
    */
    function pledge(uint256 pledgeId, uint256 amount, uint256 endTimestamp) external nonReentrant whenNotPaused {
        _pledge(pledgeId, msg.sender, amount, endTimestamp);
    }

    /**
    * @notice Delegates boost (using a percentage of the balance) to a given Pledge & receive rewards
    * @dev Delegates boost (using a percentage of the balance) to a given Pledge & receive rewards
    * @param pledgeId Pledge to delegate to
    * @param percent Percent of balance to delegate
    * @param endTimestamp End of delegation
    */
    function pledgePercent(uint256 pledgeId, uint256 percent, uint256 endTimestamp) external nonReentrant whenNotPaused {
        if(percent > MAX_PCT) revert Errors.PercentOverMax();
        uint256 amount = (delegationBoost.delegable_balance(msg.sender) * percent) / MAX_PCT;

        _pledge(pledgeId, msg.sender, amount, endTimestamp);
        
    }

    /**
    * @dev Delegates the boost to the Pledge receiver & sends rewards to the delegator
    * @param pledgeId Pledge to delegate to
    * @param user Address of the delegator
    * @param amount Amount to delegate
    * @param endTimestamp End of delegation
    */
    function _pledge(uint256 pledgeId, address user, uint256 amount, uint256 endTimestamp) internal {
        if(amount == 0) revert Errors.NullValue();
        if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();

        // Load Pledge parameters & check the Pledge is still active
        Pledge storage pledgeParams = pledges[pledgeId];
        if(pledgeParams.closed) revert Errors.PledgeClosed();
        if(pledgeParams.endTimestamp <= block.timestamp) revert Errors.ExpiredPledge();

        // To join until the end of the pledge, user can input 0 as endTimestamp
        // so it's overridden by the Pledge's endTimestamp
        if(endTimestamp == 0) endTimestamp = pledgeParams.endTimestamp;
        if(endTimestamp > pledgeParams.endTimestamp || endTimestamp != _getRoundedTimestamp(endTimestamp)) revert Errors.InvalidEndTimestamp();

        // Calculated the effective Pledge duration
        uint256 boostDuration = endTimestamp - block.timestamp;
        if(boostDuration < MIN_DELEGATION_DURATION) revert Errors.DurationTooShort();

        // Check that the user has enough boost delegation available & set the correct allowance to this contract
        IBoostV2 _delegationBoost = delegationBoost;
        _delegationBoost.checkpoint_user(user);
        if(_delegationBoost.allowance(user, address(this)) < amount) revert Errors.InsufficientAllowance();
        if(_delegationBoost.delegable_balance(user) < amount) revert Errors.CannotDelegate();

        // Check that this will not go over the Pledge target of votes
        if(_delegationBoost.adjusted_balance_of(pledgeParams.receiver) + amount > pledgeParams.targetVotes) revert Errors.TargetVotesOverflow();

        // Creates the DelegationBoost
        _delegationBoost.boost(
            pledgeParams.receiver,
            amount,
            endTimestamp,
            user
        );

        // Re-calculate the new Boost bias & slope (using BoostV2 logic)
        uint256 slope = amount / boostDuration;
        uint256 bias = slope * boostDuration;

        if(bias == 0) revert Errors.EmptyBoost();

        // Rewards are set in the Pledge as reward/veToken/sec
        // To find the total amount of veToken delegated through the whole Boost duration
        // based on the Boost bias & the Boost duration, to take in account that the delegated amount decreases
        // each second of the Boost duration
        uint256 totalDelegatedAmount = ((bias * boostDuration) + bias) / 2;
        // Then we can calculate the total amount of rewards for this Boost
        // And scale it back to reward/vote/second
        uint256 rewardAmount = ((totalDelegatedAmount * pledgeParams.rewardPerVotePerWeek) / WEEK) / UNIT;

        if(rewardAmount == 0) revert Errors.NoRewards();

        address _rewardToken = pledgeParams.rewardToken;
        if(rewardAmount > pledgeAvailableRewardAmounts[pledgeId]) revert Errors.RewardsBalanceTooLow();
        pledgeAvailableRewardAmounts[pledgeId] -= rewardAmount;
        rewardTokenTotalAmount[_rewardToken] -= rewardAmount;

        uint256 feeAmount = (rewardAmount * protocolFeeRatio) / MAX_PCT;
        rewardAmount = rewardAmount - feeAmount;

        // Take fees, transfer them to the Chest contract
        // And transfer the fees from the Pledge creator to the Chest contract
        IERC20(_rewardToken).safeTransfer(chestAddress, feeAmount);

        // Send the rewards to the user
        IERC20(_rewardToken).safeTransfer(user, rewardAmount);

        emit Pledged(pledgeId, user, bias, endTimestamp);
    }


    // Pledge Creators Methods

    struct CreatePledgeVars {
        uint256 totalVotes;
        uint256 totalRewardAmount;
        uint256 newPledgeID;
    }

    /**
    * @notice Creates a new Pledge
    * @dev Creates a new Pledge
    * @param receiver Address to receive the boost delegation
    * @param rewardToken Address of the token distributed as reward
    * @param targetVotes Maximum target of votes to have (own balance + delegation) for the receiver
    * @param rewardPerVotePerWeek Amount of reward given for each vote delegation (per week)
    * @param endTimestamp End of the Pledge
    * @param maxTotalRewardAmount Maximum total reward amount allowed to be pulled by this contract
    * @return uint256: Newly created Pledge ID
    */ 
    function createPledge(
        address receiver,
        address rewardToken,
        uint256 targetVotes,
        uint256 rewardPerVotePerWeek, // reward/veToken/week
        uint256 endTimestamp,
        uint256 maxTotalRewardAmount
    ) external nonReentrant whenNotPaused returns(uint256){
        address creator = msg.sender;

        if(receiver == address(0) || rewardToken == address(0)) revert Errors.ZeroAddress();
        uint256 _minAmountRewardToken = minAmountRewardToken[rewardToken];
        if(_minAmountRewardToken == 0) revert Errors.TokenNotWhitelisted();
        if(rewardPerVotePerWeek < _minAmountRewardToken) revert Errors.RewardPerVoteTooLow();

        if(endTimestamp == 0) revert Errors.NullEndTimestamp();
        if(endTimestamp != _getRoundedTimestamp(endTimestamp) || endTimestamp < block.timestamp) revert Errors.InvalidEndTimestamp();

        CreatePledgeVars memory vars;
        
        vars.totalVotes = _getTotalVotesForDuration(receiver, targetVotes, endTimestamp);

        // We receive rewards rate weekly, and calculate the totalVotes based on the full duration in
        // seconds, so we scale back the reward/vote to seconds here
        vars.totalRewardAmount = ((rewardPerVotePerWeek * vars.totalVotes) / WEEK) / UNIT;
        if(vars.totalRewardAmount == 0) revert Errors.NullAmount();
        if(vars.totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();

        // Pull all the rewards in this contract
        IERC20(rewardToken).safeTransferFrom(creator, address(this), vars.totalRewardAmount);

        vars.newPledgeID = pledges.length;

        // Add the total rewards as available for the Pledge & write Pledge parameters in storage
        pledgeAvailableRewardAmounts[vars.newPledgeID] = vars.totalRewardAmount;
        rewardTokenTotalAmount[rewardToken] += vars.totalRewardAmount;

        pledges.push(Pledge(
            targetVotes,
            rewardPerVotePerWeek,
            receiver,
            rewardToken,
            safe64(endTimestamp),
            false
        ));

        pledgeOwner[vars.newPledgeID] = creator;
        ownerPledges[creator].push(vars.newPledgeID);

        emit NewPledge(creator, receiver, rewardToken, vars.newPledgeID, targetVotes, rewardPerVotePerWeek, endTimestamp);

        return vars.newPledgeID;
    }

    /**
    * @notice Extends the Pledge duration
    * @dev Extends the Pledge duration & add rewards for that new duration
    * @param pledgeId ID of the Pledge
    * @param newEndTimestamp New end of the Pledge
    * @param maxTotalRewardAmount Maximum added total reward amount allowed to be pulled by this contract
    */
    function extendPledge(
        uint256 pledgeId,
        uint256 newEndTimestamp,
        uint256 maxTotalRewardAmount
    ) external nonReentrant whenNotPaused {
        if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();
        address creator = pledgeOwner[pledgeId];
        if(msg.sender != creator) revert Errors.NotPledgeCreator();

        Pledge storage pledgeParams = pledges[pledgeId];
        uint256 oldEndTimestamp = pledgeParams.endTimestamp;
        if(pledgeParams.closed) revert Errors.PledgeClosed();
        if(oldEndTimestamp <= block.timestamp) revert Errors.ExpiredPledge();
        address _rewardToken = pledgeParams.rewardToken;
        if(minAmountRewardToken[_rewardToken] == 0) revert Errors.TokenNotWhitelisted();
        if(pledgeParams.rewardPerVotePerWeek < minAmountRewardToken[_rewardToken]) revert Errors.RewardPerVoteTooLow();

        if(newEndTimestamp == 0) revert Errors.NullEndTimestamp();
        if(newEndTimestamp != _getRoundedTimestamp(newEndTimestamp) || newEndTimestamp < oldEndTimestamp) revert Errors.InvalidEndTimestamp();

        if((newEndTimestamp - oldEndTimestamp) < MIN_PLEDGE_DURATION) revert Errors.DurationTooShort();

        // To find the Total Votes for the added duration, we fetch the Total Votes
        // for the current endTimestamp (from now to oldEndTimestamp), and the Total Votes
        // for the new endTimestamp (from now to newEndTimestamp).
        // And the Total Votes for the added duration is simply the Total Votes for the new
        // endTimestamp minus the Total Votes for the current endTimestamp.
        // (the subsctraction removes the Total Votes for the common duration between the 2 endTimestamps)
        uint256 oldEndTotalRemaingVotes = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, oldEndTimestamp);
        uint256 totalVotesAddedDuration = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, newEndTimestamp) - oldEndTotalRemaingVotes;
        uint256 totalRewardAmount = ((pledgeParams.rewardPerVotePerWeek * totalVotesAddedDuration) / WEEK) / UNIT;
        if(totalRewardAmount == 0) revert Errors.NullAmount();
        if(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();


        // Pull all the rewards in this contract
        IERC20(_rewardToken).safeTransferFrom(creator, address(this), totalRewardAmount);

        // Update the Pledge parameters in storage
        pledgeParams.endTimestamp = safe64(newEndTimestamp);

        pledgeAvailableRewardAmounts[pledgeId] += totalRewardAmount;
        rewardTokenTotalAmount[_rewardToken] += totalRewardAmount;

        emit ExtendPledgeDuration(pledgeId, oldEndTimestamp, newEndTimestamp);
    }

    /**
    * @notice Increases the Pledge reward per vote delegated
    * @dev Increases the Pledge reward per vote delegated & add rewards for that new duration
    * @param pledgeId ID of the Pledge
    * @param newRewardPerVotePerWeek New amount of reward given for each vote delegation (per week)
    * @param maxTotalRewardAmount Maximum added total reward amount allowed to be pulled by this contract
    */
    function increasePledgeRewardPerVote(
        uint256 pledgeId,
        uint256 newRewardPerVotePerWeek,
        uint256 maxTotalRewardAmount
    ) external nonReentrant whenNotPaused {
        if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();
        address creator = pledgeOwner[pledgeId];
        if(msg.sender != creator) revert Errors.NotPledgeCreator();

        Pledge storage pledgeParams = pledges[pledgeId];
        if(pledgeParams.closed) revert Errors.PledgeClosed();
        uint256 _endTimestamp = pledgeParams.endTimestamp;
        if(_endTimestamp <= block.timestamp) revert Errors.ExpiredPledge();
        address _rewardToken = pledgeParams.rewardToken;
        if(minAmountRewardToken[_rewardToken] == 0) revert Errors.TokenNotWhitelisted();
        if(pledgeParams.rewardPerVotePerWeek < minAmountRewardToken[_rewardToken]) revert Errors.RewardPerVoteTooLow();

        uint256 oldRewardPerVotePerWeek = pledgeParams.rewardPerVotePerWeek;
        if(newRewardPerVotePerWeek <= oldRewardPerVotePerWeek) revert Errors.RewardsPerVotesTooLow();
        uint256 rewardPerVoteDiff = newRewardPerVotePerWeek - oldRewardPerVotePerWeek;

        uint256 totalVotes = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, _endTimestamp);
        
        uint256 totalRewardAmount = ((rewardPerVoteDiff * totalVotes) / WEEK) / UNIT;
        if(totalRewardAmount == 0) revert Errors.NullAmount();
        if(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();

        // Pull all the rewards in this contract
        IERC20(_rewardToken).safeTransferFrom(creator, address(this), totalRewardAmount);

        // Update the Pledge parameters in storage
        pledgeParams.rewardPerVotePerWeek = newRewardPerVotePerWeek;

        pledgeAvailableRewardAmounts[pledgeId] += totalRewardAmount;
        rewardTokenTotalAmount[_rewardToken] += totalRewardAmount;

        emit IncreasePledgeRewardPerVote(pledgeId, oldRewardPerVotePerWeek, newRewardPerVotePerWeek);
    }

    /**
    * @notice Closes a Pledge and retrieves all non-distributed rewards from a Pledge
    * @dev Closes a Pledge and retrieves all non-distributed rewards from a Pledge & send them to the given receiver
    * @param pledgeId ID of the Pledge to close
    * @param receiver Address to receive the remaining rewards
    */
    function closePledge(uint256 pledgeId, address receiver) external nonReentrant {
        if(receiver == address(0) || receiver == address(this)) revert Errors.InvalidValue();
        if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();
        address creator = pledgeOwner[pledgeId];
        if(msg.sender != creator) revert Errors.NotPledgeCreator();

        Pledge storage pledgeParams = pledges[pledgeId];
        if(pledgeParams.closed) revert Errors.PledgeAlreadyClosed();

        // Set the Pledge as Closed
        pledgeParams.closed = true;

        // Get the current remaining amount of rewards not distributed for the Pledge
        uint256 remainingAmount = pledgeAvailableRewardAmounts[pledgeId];

        if(remainingAmount != 0) {
            // Transfer the non-used rewards and reset storage
            pledgeAvailableRewardAmounts[pledgeId] = 0;
            address _rewardToken = pledgeParams.rewardToken;
            rewardTokenTotalAmount[_rewardToken] -= remainingAmount;

            IERC20(_rewardToken).safeTransfer(receiver, remainingAmount);

            emit RetrievedPledgeRewards(pledgeId, receiver, remainingAmount);

        }

        emit ClosePledge(pledgeId);
    }

    /**
    * @dev Get the missing votes for the given receiver to reach the target votes
    * We ignore any delegated boost here because they might expire during the Pledge duration
    * (we can have a future version of this contract using adjusted_balance)
    * @param receiver Address to receive the boost delegation
    * @param targetVotes Maximum target of votes to have (own balance + delegation) for the receiver
    * @param endTimestamp End of the Pledge
    */
    function _getTotalVotesForDuration(
        address receiver,
        uint256 targetVotes,
        uint256 endTimestamp
    ) internal view returns(uint256) {
        IVotingEscrow _votingEscrow = votingEscrow;
        uint256 duration = endTimestamp - block.timestamp;
        if(duration < MIN_PLEDGE_DURATION) revert Errors.DurationTooShort();

        // Total votes needed to reach the TargetVotes for each second of the Pledge duration
        uint256 neededTotalVotes = targetVotes * duration;
        // Total votes the receiver already has (from the veCRV balance) for each second of the Pledge duration
        uint256 totalReceiverVotes;
        
        // Current receiver bias (calculated by veCRV contract)
        uint256 receiverBalance = _votingEscrow.balanceOf(receiver);

        if((targetVotes - receiverBalance) < minVoteDiff) revert Errors.TargetVoteUnderMin();

        if(receiverBalance != 0){
            // If receiver has a veCRV lock
            uint256 receiverLockEnd = _votingEscrow.locked__end(receiver);

            if(receiverLockEnd < endTimestamp) {
                // If the receiver veCRV lock ends after the Pledge endTimestamp
                uint256 lockRemainingDuration = receiverLockEnd - block.timestamp;

                // We calculate the total amount of vote the receiver will have for each second until the end of the lock
                totalReceiverVotes = ((receiverBalance * lockRemainingDuration) + receiverBalance) / 2;
            } else {
                // If the receiver veCRV lock ends before the end of the Pledge
                uint256 receiverSlope = _votingEscrow.get_last_user_slope(receiver);
                uint256 receiverEndTsBias = receiverBalance - (duration * receiverSlope);

                // We calculate the receiver bias at the end of the duration, and account
                // for the veCRV balance decrease, and sum up to get the total amount of votes the receiver
                // will have through the duration of the Pledge
                totalReceiverVotes = ((duration * (receiverBalance + receiverEndTsBias + receiverSlope)) / 2);
            }
        }

        return neededTotalVotes - totalReceiverVotes;
    }


    // Admin Methods

    /**
    * @dev Adds a given reward token to the whitelist
    * @param token Address of the token
    * @param minRewardPerWeek Minimum amount of reward per vote per week for the token
    */
    function _addRewardToken(address token, uint256 minRewardPerWeek) internal {
        if(token == address(0)) revert Errors.ZeroAddress();
        if(minRewardPerWeek == 0) revert Errors.NullValue();
        if(minAmountRewardToken[token] != 0) revert Errors.AlreadyAllowedToken();
        
        minAmountRewardToken[token] = minRewardPerWeek;

        emit NewRewardToken(token, minRewardPerWeek);
    }

    /**
    * @notice Adds a given reward token to the whitelist
    * @dev Adds a given reward token to the whitelist
    * @param tokens List of token addresses to add
    * @param minRewardsPerWeek Minimum amount of reward per vote per week for each token in the list
    */
    function addMultipleRewardToken(address[] calldata tokens, uint256[] calldata minRewardsPerWeek) external onlyOwner {
        uint256 length = tokens.length;

        if(length == 0) revert Errors.EmptyArray();
        if(length != minRewardsPerWeek.length) revert Errors.UnequalArraySizes();

        for(uint256 i; i < length;){
            _addRewardToken(tokens[i], minRewardsPerWeek[i]);

            unchecked{ ++i; }
        }
    }

    /**
    * @notice Adds a given reward token to the whitelist
    * @dev Adds a given reward token to the whitelist
    * @param token Address of the token
    * @param minRewardPerWeek Minimum amount of reward per vote per week for the token
    */
    function addRewardToken(address token, uint256 minRewardPerWeek) external onlyOwner {
        _addRewardToken(token, minRewardPerWeek);
    }

    /**
    * @notice Updates a reward token
    * @dev Updates a reward token
    * @param token Address of the token
    * @param minRewardPerWeek Minimum amount of reward per vote per week for the token
    */
    function updateRewardToken(address token, uint256 minRewardPerWeek) external onlyOwner {
        if(token == address(0)) revert Errors.ZeroAddress();
        if(minAmountRewardToken[token] == 0) revert Errors.NotAllowedToken();
        if(minRewardPerWeek == 0) revert Errors.InvalidValue();

        minAmountRewardToken[token] = minRewardPerWeek;

        emit UpdateRewardToken(token, minRewardPerWeek);
    }

    /**
    * @notice Removes a reward token from the whitelist
    * @dev Removes a reward token from the whitelist
    * @param token Address of the token
    */
    function removeRewardToken(address token) external onlyOwner {
        if(token == address(0)) revert Errors.ZeroAddress();
        if(minAmountRewardToken[token] == 0) revert Errors.NotAllowedToken();
        
        minAmountRewardToken[token] = 0;
        
        emit RemoveRewardToken(token);
    }
    
    /**
    * @notice Updates the Chest address
    * @dev Updates the Chest address
    * @param chest Address of the new Chest
    */
    function updateChest(address chest) external onlyOwner {
        if(chest == address(0) || chest == address(this)) revert Errors.InvalidAddress();
        address oldChest = chestAddress;
        chestAddress = chest;

        emit ChestUpdated(oldChest, chest);
    }

    /**
    * @notice Updates the new min difference of votes for Pledges
    * @dev Updates the new min difference of votes for Pledges
    * @param newMinVoteDiff New minimum difference of votes
    */
    function updateMinVoteDiff(uint256 newMinVoteDiff) external onlyOwner {
        // We want that value to be at minimum 1e18, to avoid any rounding issues
        if(newMinVoteDiff < UNIT) revert Errors.InvalidValue();
        uint256 oldMinTarget = minVoteDiff;
        minVoteDiff = newMinVoteDiff;

        emit MinVoteDiffUpdated(oldMinTarget, newMinVoteDiff);
    }

    /**
    * @notice Updates the platform fees BPS ratio
    * @dev Updates the platform fees BPS ratio
    * @param newFee New fee ratio
    */
    function updatePlatformFee(uint256 newFee) external onlyOwner {
        if(newFee > 500 || newFee == 0) revert Errors.InvalidValue();
        uint256 oldFee = protocolFeeRatio;
        protocolFeeRatio = newFee;

        emit PlatformFeeUpdated(oldFee, newFee);
    }

    /**
     * @notice Pauses the contract
     */
    function pause() external onlyOwner {
        _pause();
    }

    /**
     * @notice Unpauses the contract
     */
    function unpause() external onlyOwner {
        _unpause();
    }

    /**
    * @notice Recovers ERC2O tokens sent by mistake to the contract
    * @dev Recovers ERC2O tokens sent by mistake to the contract
    * @param token Address of the ERC2O token
    * @return bool: success
    */
    function recoverERC20(address token) external nonReentrant onlyOwner returns(bool) {
        uint256 currentBalance = IERC20(token).balanceOf(address(this));
        if(currentBalance == 0) revert Errors.NullValue();
        uint256 amount;

        // Total amount of the token owned by the Pledges
        uint256 pledgesBalance = rewardTokenTotalAmount[token];

        if(pledgesBalance >= currentBalance) revert Errors.CannotRecoverToken();
        amount = currentBalance - pledgesBalance;

        if(amount != 0) {
            IERC20(token).safeTransfer(owner(), amount);
        }
        
        return true;
    }

    // Utils 

    function safe64(uint256 n) internal pure returns (uint64) {
        if(n > type(uint64).max) revert Errors.NumberExceed64Bits();
        return uint64(n);
    }


}
// File: contracts/oz/interfaces/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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/oz/libraries/SafeERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../interfaces/IERC20.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;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

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

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    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");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @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");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
// File: contracts/utils/Owner.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;

import "../oz/utils/Ownable.sol";

/** @title Extend OZ Ownable contract  */
/// @author Paladin

contract Owner is Ownable {

    address public pendingOwner;

    event NewPendingOwner(address indexed previousPendingOwner, address indexed newPendingOwner);

    error CannotBeOwner();
    error CallerNotPendingOwner();
    error OwnerZeroAddress();

    function transferOwnership(address newOwner) public override virtual onlyOwner {
        if(newOwner == address(0)) revert OwnerZeroAddress();
        if(newOwner == owner()) revert CannotBeOwner();
        address oldPendingOwner = pendingOwner;

        pendingOwner = newOwner;

        emit NewPendingOwner(oldPendingOwner, newOwner);
    }

    function acceptOwnership() public virtual {
        if(msg.sender != pendingOwner) revert CallerNotPendingOwner();
        address newOwner = pendingOwner;
        _transferOwnership(pendingOwner);
        pendingOwner = address(0);

        emit NewPendingOwner(newOwner, address(0));
    }

}
// File: contracts/oz/utils/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "./Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
// File: contracts/oz/utils/ReentrancyGuard.sol



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

pragma solidity ^0.8.0;

/**
 * @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;

    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() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}
// File: contracts/interfaces/IVotingEscrow.sol



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


/** @title Custom Interface for Curve VotingEscrow contract  */
interface IVotingEscrow {

    struct LockedBalance {
        int128 amount;
        uint256 end;
    }
    
    function balanceOf(address _account) external view returns (uint256);

    function locked(address _account) external view returns (LockedBalance memory);

    function create_lock(uint256 _value, uint256 _unlock_time) external returns (uint256);

    function increase_amount(uint256 _value) external;

    function increase_unlock_time(uint256 _unlock_time) external;

    function locked__end(address _addr) external view returns (uint256);

    function get_last_user_slope(address _addr) external view returns (uint256);

}
// File: contracts/interfaces/IBoostV2.sol



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


/** @title Custom Interface for Curve BoostV2 contract  */
interface IBoostV2 {

    event Boost(
        address indexed _from,
        address indexed _to,
        uint256 _bias,
        uint256 _slope,
        uint256 _start
    );

    function balanceOf(address _user) external view returns(uint256);
    function allowance(address _user, address _spender) external view returns(uint256);

    function adjusted_balance_of(address _user) external view returns(uint256);
    function delegated_balance(address _user) external view returns(uint256);
    function received_balance(address _user) external view returns(uint256);
    function delegable_balance(address _user) external view returns(uint256);

    function checkpoint_user(address _user) external;
    function approve(address _spender, uint256 _value) external;
    function boost(address _to, uint256 _amount, uint256 _endtime, address _from) external;
}
// File: contracts/utils/Errors.sol



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

library Errors {

    // Access Errors
    error CallerNotAllowed();
    error CallerNotManager();

    // Common Errors
    error ZeroAddress();
    error NullValue();
    error InvalidValue();
    error UnequalArraySizes();
    error InvalidAddress();
    error NullAmount();

    // Update Errors
    error FailRewardUpdate();

    // Offers Errors
    error AlreadyRegistered();
    error WardenNotOperator();
    error NotRegistered();
    error NotOfferOwner();

    // Registration Errors
    error NullPrice();
    error NullMaxDuration();
    error IncorrectExpiry();
    error MaxPercTooHigh();
    error MinPercOverMaxPerc();
    error MinPercTooLow();

    // Purchase Errors
    error PercentUnderMinRequired();
    error PercentOverMax();
    error DurationOverOfferMaxDuration();
    error OfferExpired();
    error DurationTooShort();
    error PercentOutOfferBonds();
    error LockEndTooShort();
    error CannotDelegate();
    error NullFees();
    error FeesTooLow();
    error FailDelegationBoost();

    // Cancel Errors
    error CannotCancelBoost();

    // Claim Fees Errors
    error NullClaimAmount();
    error AmountTooHigh();
    error ClaimBlocked();
    error ClaimNotBlocked();
    error InsufficientCash();

    // Rewards Errors
    error InvalidBoostId();
    error RewardsNotStarted();
    error RewardsAlreadyStarted();
    error BoostRewardsNull();
    error RewardsNotUpdated();
    error NotBoostBuyer();
    error AlreadyClaimed();
    error CannotClaim();
    error InsufficientRewardCash();

    // Admin Errors
    error CannotWithdrawFeeToken();
    error ReserveTooLow();
    error BaseDropTooLow();
    error MinDropTooHigh();
    error AlreadyAllowedToken();
    error NotAllowedToken();
    error CannotRecoverToken();

    // MultiBuy Errors
    error NotEnoughFees();
    error FailBoostPurchase();
    error CannotMatchOrder();
    error EmptyArray();
    error InvalidBoostOffer();

    //PledgeErrors
    error TokenNotWhitelisted();
    error RewardPerVoteTooLow();
    error TargetVoteUnderMin();
    error IncorrectMaxTotalRewardAmount();
    error IncorrectMaxFeeAmount();
    error InvalidEndTimestamp();
    error NullEndTimestamp();
    error NotPledgeCreator();
    error ExpiredPledge();
    error PledgeNotExpired();
    error PledgeClosed();
    error PledgeAlreadyClosed();
    error TargetVotesTooLoow();
    error RewardsPerVotesTooLow();
    error InvalidPledgeID();
    error TargetVotesOverflow();
    error RewardsBalanceTooLow();
    error InsufficientAllowance();
    error EmptyBoost();
    error NoRewards();

    // Math Errors
    error NumberExceed64Bits();

}
// File: contracts/oz/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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
     * ====
     *
     * [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://diligence.consensys.net/posts/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.5.11/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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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);
            }
        }
    }
}
// File: contracts/oz/utils/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "./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 anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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);
    }
}
// File: contracts/oz/utils/Context.sol



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