// File: src/PartyVaultRouter.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

import {IERC20} from "points-periphery_@openzeppelin-contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "points-periphery_@openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721Receiver} from "points-periphery_@openzeppelin-contracts/token/ERC721/IERC721Receiver.sol";
import {IPointsVaultExtension} from "points-periphery_points/interfaces/IPointsVaultExtension.sol";
import {IVaultFactory} from "./external/IVaultFactory.sol";
import {IUniversalVault} from "./external/IUniversalVault.sol";
import {IGeyser} from "./external/IGeyser.sol";
import {IPartyVaultRouter} from "./interfaces/IPartyVaultRouter.sol";

contract PartyVaultRouter is IPartyVaultRouter, IERC721Receiver {
    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    uint256 private chainId;

    constructor() {
        uint256 chainId_;
        assembly {
            chainId_ := chainid()
        }
        chainId = chainId_;
    }

    /**
     * @inheritdoc IERC721Receiver
     */
    function onERC721Received(address, /*operator*/ address from, uint256 tokenId, bytes calldata data)
        external
        view
        returns (bytes4)
    {
        return bytes4(
            abi.encodeWithSelector(
                IERC721Receiver(address(this)).onERC721Received.selector, msg.sender, from, tokenId, data
            )
        );
    }

    /**
     * @inheritdoc IPartyVaultRouter
     */
    function createAndDeposit(
        address vaultFactory,
        bytes32 salt,
        address token,
        uint128 amount,
        LockRequest[] calldata requests
    ) external returns (address vault) {
        vault = IVaultFactory(vaultFactory).create2(salt);
        IVaultFactory(vaultFactory).safeTransferFrom(
            address(this), msg.sender, IVaultFactory(vaultFactory).addressToUint(vault)
        );
        deposit(vault, token, amount, requests);
    }

    /**
     * @inheritdoc IPartyVaultRouter
     */
    function deposit(address vault, address token, uint128 amount, LockRequest[] calldata requests) public {
        SafeERC20.safeTransferFrom(IERC20(token), msg.sender, vault, amount);
        for (uint256 index = 0; index < requests.length; index++) {
            LockRequest calldata request = requests[index];
            if (request.rewardProgramType == RewardProgram.Points) {
                IPointsVaultExtension(request.rewardProgram).stakeToken(
                    vault, token, request.amount, request.permission
                );
            } else {
                IGeyser(request.rewardProgram).stake(vault, request.amount, request.permission);
            }
        }
    }

    /**
     * @inheritdoc IPartyVaultRouter
     */
    function unlock(address vault, address token, UnlockRequest[] calldata requests) external {
        for (uint256 index = 0; index < requests.length; index++) {
            UnlockRequest calldata request = requests[index];
            if (request.rewardProgramType == RewardProgram.Points) {
                IPointsVaultExtension(request.rewardProgram).unstakeToken(
                    vault, token, request.amount, request.permission
                );
            } else {
                IGeyser(request.rewardProgram).unstakeAndClaim(vault, request.amount, request.permission);
            }
        }
    }

    function generateNewVaultLockPermissionDigest(
        address delegate,
        address vaultFactory,
        address token,
        uint256 amount,
        bytes32 salt
    ) external view returns (bytes32 digest) {
        address vaultAddress = IVaultFactory(vaultFactory).predictCreate2Address(salt);
        return generateLockPermissionDigest(vaultAddress, delegate, token, amount, 0);
    }

    function generateExistingVaultLockPermissionDigest(
        address vaultAddress,
        address delegate,
        address token,
        uint256 amount
    ) external view returns (bytes32 digest) {
        return generateLockPermissionDigest(
            vaultAddress, delegate, token, amount, IUniversalVault(vaultAddress).getNonce()
        );
    }

    function generateLockPermissionDigest(
        address vaultAddress,
        address delegate,
        address token,
        uint256 amount,
        uint256 nonce
    ) public view returns (bytes32 digest) {
        return generatePermissionDigest(
            keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)"),
            token,
            amount,
            nonce,
            vaultAddress,
            delegate
        );
    }

    function generateUnlockPermissionDigest(
        address vaultAddress,
        address delegate,
        address token,
        uint256 amount,
        uint256 nonce
    ) public view returns (bytes32 digest) {
        return generatePermissionDigest(
            keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)"),
            token,
            amount,
            nonce,
            vaultAddress,
            delegate
        );
    }

    function generatePermissionDigest(
        bytes32 eip712TypeHash,
        address token,
        uint256 amount,
        uint256 nonce,
        address vaultAddress,
        address delegate
    ) public view returns (bytes32 digest) {
        digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                keccak256(
                    abi.encode(
                        _TYPE_HASH, keccak256(bytes("UniversalVault")), keccak256(bytes("1.0.0")), chainId, vaultAddress
                    )
                ),
                keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
            )
        );
    }
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

// File: lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @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);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // 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 cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

// File: lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: lib/points/src/interfaces/IPointsVaultExtension.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

import {IPoints} from "./IPoints.sol";
import {IRageQuit} from "../external/IRageQuit.sol";
import {IPointsVaultExtensionEvents} from "./IPointsVaultExtensionEvents.sol";
import {IPointsVaultExtensionErrors} from "./IPointsVaultExtensionErrors.sol";

/**
 * @title IPointsVaultExtension
 * @notice Interface for the vault-extension of the Points contract.
 * @dev Does not support fee-on-transfer or rebasing tokens (in unwrapped form).
 */
interface IPointsVaultExtension is IPoints, IRageQuit, IPointsVaultExtensionEvents, IPointsVaultExtensionErrors {
    /**
     * @notice Get the length of the registered vaultFactory whitelist
     * @return length The length of the vaultFactory whitelist
     */
    function getVaultFactorySetLength() external view returns (uint256 length);

    /**
     * @notice Get the address of the vaultFactory at the corresponding index on the whitelist
     * @param index The index of the vaultFactory
     * @return factory The address of the vaultFactory at the index on the whitelist
     */
    function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);

    /**
     * @notice Validate whether or not the target vault is from a whitelisted factory
     * @param vault The address of the vault in question
     * @return validity Whether the target vault is from a whitelisted factory or not
     */
    function isValidVault(address vault) external view returns (bool validity);

    /**
     * @notice Register a new vaultFactory onto the whitelist. Only callable by owner.
     * @param factory The address of the factory to add.
     */
    function registerVaultFactory(address factory) external;

    /**
     * @notice Remove a vaultFactory from the whitelist. Only callable by owner.
     * @param factory The address of the factory to remove.
     */
    function removeVaultFactory(address factory) external;

    /**
     * @notice Stake tokens from vault into Points contract.
     * @notice Vault must be from whitelisted vaultFactory.
     * @param vault Address of the vault to stake from.
     * @param token The address of the token.
     * @param amount The amount of tokens to deposit.
     * @param permission Permission signature from vault owner.
     */
    function stakeToken(address vault, address token, uint128 amount, bytes calldata permission) external;

    /**
     * @notice Unstake tokens from Points contract and transfer earned points to the vault.
     * @param vault Address of the vault to unstake from.
     * @param token The address of the token.
     * @param amount The amount of tokens to deposit.
     * @param permission Permission signature from vault owner.
     */
    function unstakeToken(address vault, address token, uint128 amount, bytes calldata permission) external;
}

// File: src/external/IVaultFactory.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;

import {IFactory} from "./IFactory.sol";
import {IInstanceRegistry} from "./IInstanceRegistry.sol";
import {IERC721} from "points-periphery_@openzeppelin-contracts/token/ERC721/IERC721.sol";

interface IVaultFactory is IFactory, IInstanceRegistry, IERC721 {
    function create2(bytes32 salt) external returns (address vault);

    function addressToUint(address vault) external pure returns (uint256 tokenId);

    function predictCreate2Address(bytes32 salt) external view returns (address instance);

    function setTokenURIHandler(address tokenURIHandler) external;

    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// File: src/external/IUniversalVault.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import {IUniversalVaultEvents} from "./IUniversalVaultEvents.sol";

/**
 * @notice IUniversalVault interface
 * @dev Source: https://github.com/ampleforth/token-geyser-v2/blob/c878fd6ba5856d818ff41c54bce59c9413bc93c9/contracts/UniversalVault.sol#L17-L87
 */
interface IUniversalVault is IUniversalVaultEvents {
    /* data types */

    struct LockData {
        address delegate;
        address token;
        uint256 balance;
    }

    /* initialize function */

    function initialize() external;

    /* user functions */

    function lock(address token, uint256 amount, bytes calldata permission) external;

    function unlock(address token, uint256 amount, bytes calldata permission) external;

    function rageQuit(address delegate, address token) external returns (bool notified, string memory error);

    function transferERC20(address token, address to, uint256 amount) external;

    function transferETH(address to, uint256 amount) external payable;

    /* pure functions */

    function calculateLockID(address delegate, address token) external pure returns (bytes32 lockID);

    /* getter functions */

    function getPermissionHash(bytes32 eip712TypeHash, address delegate, address token, uint256 amount, uint256 nonce)
        external
        view
        returns (bytes32 permissionHash);

    function getNonce() external view returns (uint256 nonce);

    function owner() external view returns (address ownerAddress);

    function getLockSetCount() external view returns (uint256 count);

    function getLockAt(uint256 index) external view returns (LockData memory lockData);

    function getBalanceDelegated(address token, address delegate) external view returns (uint256 balance);

    function getBalanceLocked(address token) external view returns (uint256 balance);

    function checkBalances() external view returns (bool validity);
}

// File: src/external/IGeyser.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

interface IGeyser {
    /* admin events */

    event GeyserCreated(address rewardPool, address powerSwitch);
    event GeyserFunded(uint256 amount, uint256 duration);
    event BonusTokenRegistered(address token);
    event VaultFactoryRegistered(address factory);
    event VaultFactoryRemoved(address factory);

    /* user events */

    event Staked(address vault, uint256 amount);
    event Unstaked(address vault, uint256 amount);
    event RewardClaimed(address vault, address token, uint256 amount);

    /* data types */

    struct GeyserData {
        address stakingToken;
        address rewardToken;
        address rewardPool;
        RewardScaling rewardScaling;
        uint256 rewardSharesOutstanding;
        uint256 totalStake;
        uint256 totalStakeUnits;
        uint256 lastUpdate;
        RewardSchedule[] rewardSchedules;
    }

    struct RewardSchedule {
        uint256 duration;
        uint256 start;
        uint256 shares;
    }

    struct VaultData {
        uint256 totalStake;
        StakeData[] stakes;
    }

    struct StakeData {
        uint256 amount;
        uint256 timestamp;
    }

    struct RewardScaling {
        uint256 floor;
        uint256 ceiling;
        uint256 time;
    }

    struct RewardOutput {
        uint256 lastStakeAmount;
        uint256 newStakesCount;
        uint256 reward;
        uint256 newTotalStakeUnits;
    }

    /* user functions */

    function stake(address vault, uint256 amount, bytes calldata permission) external;

    function unstakeAndClaim(address vault, uint256 amount, bytes calldata permission) external;

    /* getter functions */

    function getGeyserData() external view returns (GeyserData memory geyser);

    function getBonusTokenSetLength() external view returns (uint256 length);

    function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);

    function getVaultFactorySetLength() external view returns (uint256 length);

    function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);

    function getVaultData(address vault) external view returns (VaultData memory vaultData);

    function isValidAddress(address target) external view returns (bool validity);

    function isValidVault(address target) external view returns (bool validity);

    function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);

    function getFutureUnlockedRewards(uint256 timestamp) external view returns (uint256 unlockedRewards);

    function getCurrentVaultReward(address vault) external view returns (uint256 reward);

    function getCurrentStakeReward(address vault, uint256 stakeAmount) external view returns (uint256 reward);

    function getFutureVaultReward(address vault, uint256 timestamp) external view returns (uint256 reward);

    function getFutureStakeReward(address vault, uint256 stakeAmount, uint256 timestamp)
        external
        view
        returns (uint256 reward);

    function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);

    function getFutureVaultStakeUnits(address vault, uint256 timestamp) external view returns (uint256 stakeUnits);

    function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);

    function getFutureTotalStakeUnits(uint256 timestamp) external view returns (uint256 totalStakeUnits);

    /* pure functions */

    function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
        external
        pure
        returns (uint256 totalStakeUnits);

    function calculateStakeUnits(uint256 amount, uint256 start, uint256 end)
        external
        pure
        returns (uint256 stakeUnits);

    function calculateUnlockedRewards(
        RewardSchedule[] memory rewardSchedules,
        uint256 rewardBalance,
        uint256 sharesOutstanding,
        uint256 timestamp
    ) external pure returns (uint256 unlockedRewards);

    function calculateRewardFromStakes(
        StakeData[] memory stakes,
        uint256 unstakeAmount,
        uint256 unlockedRewards,
        uint256 totalStakeUnits,
        uint256 timestamp,
        RewardScaling memory rewardScaling
    ) external pure returns (RewardOutput memory out);

    function calculateReward(
        uint256 unlockedRewards,
        uint256 stakeAmount,
        uint256 stakeDuration,
        uint256 totalStakeUnits,
        RewardScaling memory rewardScaling
    ) external pure returns (uint256 reward);
}

// File: src/interfaces/IPartyVaultRouter.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

import {IPartyVaultRouterEvents} from "./IPartyVaultRouterEvents.sol";
import {IPartyVaultRouterErrors} from "./IPartyVaultRouterErrors.sol";

/**
 * @title IPartyVaultRouter
 * @notice Interface for the PartyVaultRouter contract
 */
interface IPartyVaultRouter is IPartyVaultRouterEvents, IPartyVaultRouterErrors {
    /**
     * @notice Enum used to determine which interface should be used when interacting with a reward program
     */
    enum RewardProgram {
        Points,
        Geyser
    }

    /**
     * @notice Encodes a request to add a lock to a vault
     * @param rewardProgramType Used to determine what interface to use when interacting with the reward program
     * @param rewardProgram The address of the reward program
     * @param amount The amount of tokens to lock against this reward program
     * @param permission The owner's permission to add the lock to the vault
     */
    struct LockRequest {
        RewardProgram rewardProgramType;
        address rewardProgram;
        uint128 amount;
        bytes permission;
    }

    /**
     * @notice Encodes a request to remove a lock from a vault
     * @param rewardProgramType Used to determine what interface to use when interacting with the reward program
     * @param rewardProgram The address of the reward program
     * @param amount The amount of tokens to unlock from this reward program
     * @param permission The owner's permission to remove the lock from the vault
     */
    struct UnlockRequest {
        RewardProgram rewardProgramType;
        address rewardProgram;
        uint128 amount;
        bytes permission;
    }

    /**
     * @notice Create a new vault for a user, deposit tokens, and lock
     * @param vaultFactory The address of the vault factory to use
     * @param salt The salt to use for the vault creation
     * @param token The address of the token to deposit
     * @param amount The amount of tokens to deposit
     * @param requests Set of requests to lock the deposited tokens against different reward programs
     * @return vault The address of the newly created vault
     */
    function createAndDeposit(
        address vaultFactory,
        bytes32 salt,
        address token,
        uint128 amount,
        LockRequest[] calldata requests
    ) external returns (address vault);

    /**
     * @notice Deposit tokens into a pre-existing vault and lock
     * @param vault The address of the vault to deposit into
     * @param token The address of the token to deposit
     * @param amount The amount of tokens to deposit
     * @param requests Set of requests to lock the deposited tokens against different reward programs
     */
    function deposit(address vault, address token, uint128 amount, LockRequest[] calldata requests) external;

    /**
     * @notice Unlocks tokens from a set of reward programs
     * @dev Due to the current vault implementation, token withdrawal cannot be bundled into this operation.
     * @param vault The address of the vault to unlock
     * @param token The address of the token to unlock
     * @param requests Set of requests to unlock the deposited tokens from different reward programs
     */
    function unlock(address vault, address token, UnlockRequest[] calldata requests) external;
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// File: lib/openzeppelin-contracts/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // 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 FailedInnerCall();
        }
    }
}

// File: lib/points/src/interfaces/IPoints.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

import {IERC20} from "points_@openzeppelin-contracts/token/ERC20/IERC20.sol";
import {IPointsEvents} from "./IPointsEvents.sol";
import {IPointsErrors} from "./IPointsErrors.sol";

/**
 * @title IPoints
 * @notice Interface for the Points contract.
 * @dev Does not support fee-on-transfer or rebasing tokens (in unwrapped form).
 */
interface IPoints is IERC20, IPointsEvents, IPointsErrors {
    /**
     * @notice Returns true if transfers are paused.
     * @return paused_ True if transfers are paused. False otherwise.
     */
    function paused() external view returns (bool paused_);

    /**
     * @notice Sets the paused status of the transfers.
     * @param paused_ The new paused status.
     */
    function setPaused(bool paused_) external;

    /**
     * @notice Returns true if the account is whitelisted.
     * @param account The address to check.
     * @return whitelisted True if the account is whitelisted. False otherwise.
     */
    function isWhitelisted(address account) external view returns (bool whitelisted);

    /**
     * @notice Updates the whitelist status of the account.
     * @param account The address to update.
     * @param status The new whitelist status.
     */
    function setAddressWhitelist(address account, bool status) external;

    /**
     * @notice Returns the token at the given index in the token list
     * @dev Tokens that have rates set to 0 are still included in the list.
     * @param index The index of the token in the list.
     * @return token The token
     */
    function tokenAt(uint256 index) external view returns (address token);

    /**
     * @notice Returns the number of tokens in the token list.
     * @dev Tokens that have rates set to 0 are still included in the list.
     * @return count The number of tokens in the list.
     */
    function tokenCount() external view returns (uint256 count);

    /**
     * @notice Sets the rates of the tokens. New tokens will be added if they do not already exist.
     * @dev Token addresses and rates are matched by corresponding index in their respective arrays
     * @dev Passing in the same token address multiple times results in only the final value being used.
     * @param tokens The addresses of the tokens.
     * @param rates The rates of the tokens.
     */
    function setRates(address[] calldata tokens, uint96[] calldata rates) external;

    /**
     * @notice Returns the rate of the token and the timestamp of the last update.
     * @param token The address of the token.
     * @return rate The rate of the token.
     * @return timestamp The timestamp of the last rate update or transfer of the token.
     * @return cumulativeRate The cumulative rate snapshot at the timestamp.
     */
    function getRateInfo(address token) external view returns (uint96 rate, uint32 timestamp, uint128 cumulativeRate);

    /**
     * @notice Returns the multiplier thresholds and scalars for the token.
     * @param token The address of the token.
     * @return thresholds The absolute thresholds for the multipliers.
     * @return scalars The absolute scalars for the multipliers.
     */
    function getMultipliers(address token)
        external
        view
        returns (uint128[] memory thresholds, uint128[] memory scalars);

    /**
     * @notice Sets the multiplier thresholds and scalars for the token.
     * @dev To generate the stored absolute thresholds, each iterative threshold is added to the previous one, starting from 0
     * @dev To generate the stored absolute scalars, each iterative scalar is added by the previous one, starting from RATE_DENOMINATOR
     * @param token The address of the token.
     * @param iterativeThresholds The iterative thresholds for the multipliers. Base threshold is 0
     * @param iterativeScalars The iterative scalars for the multipliers. Base multiplier is RATE_DENOMINATOR.
     */
    function setMultipliers(address token, uint128[] calldata iterativeThresholds, uint128[] calldata iterativeScalars)
        external;

    /**
     * @notice Deposits tokens into the contract.
     * @param token The address of the token.
     * @param amount The amount of tokens to deposit.
     */
    function depositToken(address token, uint128 amount) external;

    /**
     * @notice Withdraws tokens from the contract.
     * @param token The address of the token.
     * @param amount The amount of tokens to withdraw.
     */
    function withdrawToken(address token, uint128 amount) external;

    /**
     * @notice Returns the pending balance of the account (points that have yet to be converted)
     * @param account The address of the account.
     * @return pendingBalance The pending balance of the account.
     */
    function pendingBalanceOf(address account) external view returns (uint256 pendingBalance);

    /**
     * @notice Returns the staked amount for a given account and token
     * @param account The address of the account.
     * @param token The address of the token.
     * @return amount The staked amount for the account and token.
     */
    function getTokenStake(address account, address token) external view returns (uint128 amount);

    /**
     * @notice Returns the current multiplier scalar for a given account and token
     * @param account The address of the account.
     * @param token The address of the token.
     * @return rateScalar The current multiplier scalar for the account and token.
     */
    function getTokenMultiplier(address account, address token) external view returns (uint256 rateScalar);
}

// File: lib/points/src/external/IRageQuit.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

/**
 * @notice IRageQuit interface
 * @dev Source: https://github.com/ampleforth/token-geyser-v2/blob/c878fd6ba5856d818ff41c54bce59c9413bc93c9/contracts/Geyser.sol#L17-L19
 */
interface IRageQuit {
    /**
     * @notice Exit without claiming reward
     * @dev Should only be callable by the vault directly
     */
    function rageQuit() external;
}

// File: lib/points/src/interfaces/IPointsVaultExtensionEvents.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPointsVaultExtensionEvents
 * @notice Interface for the Events emitted by the PointsVaultExtension contract.
 */
interface IPointsVaultExtensionEvents {
    /**
     * @notice Emitted when tokens are locked in a vault
     */
    event TokenVaultLocked(address indexed vault, address indexed token, uint256 amount);
    /**
     * @notice Emitted when tokens are unlocked from a vault
     */
    event TokenVaultUnlocked(address indexed vault, address indexed token, uint256 amount);
    /**
     * @notice Emitted when a vaultFactory is registered on the whitelist
     */
    event VaultFactoryRegistered(address indexed vaultFactory);
    /**
     * @notice Emitted when a vaultFactory is removed from the whitelist
     */
    event VaultFactoryRemoved(address indexed vaultFactory);
}

// File: lib/points/src/interfaces/IPointsVaultExtensionErrors.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPointsVaultExtensionErrors
 * @notice Interface for the Errors emitted by the PointsVaultExtension contract.
 */
interface IPointsVaultExtensionErrors {
    /**
     * @notice Thrown when attempting to register a vaultFactory that has already been registered
     */
    error VaultFactoryAlreadyRegistered(address vaultFactory);
    /**
     * @notice Thrown when attempting to remove a vaultFactory that has not been registered
     */
    error VaultFactoryNotRegistered(address vaultFactory);
    /**
     * @notice Thrown when attempting to stake with a vault that is not from a registered vaultFactory;
     */
    error InvalidVault(address vault);
}

// File: src/external/IFactory.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

interface IFactory {
    function create(bytes calldata args) external returns (address instance);

    function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}

// File: src/external/IInstanceRegistry.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;

/**
 * @notice IInstanceRegistry interface
 * @dev Source: https://github.com/ampleforth/token-geyser-v2/blob/c878fd6ba5856d818ff41c54bce59c9413bc93c9/contracts/Factory/InstanceRegistry.sol#L6-L19
 */
interface IInstanceRegistry {
    /* events */

    event InstanceAdded(address instance);
    event InstanceRemoved(address instance);

    /* view functions */

    function isInstance(address instance) external view returns (bool validity);

    function instanceCount() external view returns (uint256 count);

    function instanceAt(uint256 index) external view returns (address instance);
}

// File: lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: src/external/IUniversalVaultEvents.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

/**
 * @notice IUniversalVaultEvents interface
 * @dev Source: https://github.com/ampleforth/token-geyser-v2/blob/c878fd6ba5856d818ff41c54bce59c9413bc93c9/contracts/UniversalVault.sol#L20-L22
 */
interface IUniversalVaultEvents {
    /* user events */
    event Locked(address delegate, address token, uint256 amount);
    event Unlocked(address delegate, address token, uint256 amount);
    event RageQuit(address delegate, address token, bool notified, string reason);
}

// File: src/interfaces/IPartyVaultRouterEvents.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPartyVaultRouterEvents
 * @notice Interface for the Events emitted by the PartyVaultRouter contract.
 */
interface IPartyVaultRouterEvents {}

// File: src/interfaces/IPartyVaultRouterErrors.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPartyVaultRouterErrors
 * @notice Interface for the errors thrown by the PartyVaultRouter contract.
 */
interface IPartyVaultRouterErrors {}

// File: lib/points/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// File: lib/points/src/interfaces/IPointsEvents.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPointsEvents
 * @notice Interface for the Events emitted by the Points contract.
 */
interface IPointsEvents {
    /**
     * @notice Emitted when the paused status of the transfers is updated.
     */
    event IsPaused(bool paused);
    /**
     * @notice Emitted when the whitelist status of an account is updated.
     */
    event WhitelistUpdated(address indexed account, bool whitelisted);
    /**
     * @notice Emitted when the rate of a token is updated.
     */
    event RateUpdated(address indexed token, uint96 rate, uint32 timestamp);
    /**
     * @notice Emitted when points are converted to pending points.
     */
    event PendingPointsConverted(address indexed account, address indexed token, uint256 amount);
    /**
     * @notice Emitted when tokens are deposited.
     */
    event TokenDeposited(address indexed account, address indexed token, uint256 amount);
    /**
     * @notice Emitted when tokens are withdrawn.
     */
    event TokenWithdrawn(address indexed account, address indexed token, uint256 amount);
    /**
     * @notice Emitted when multipliers are updated
     */
    event MultipliersUpdated(address indexed token, uint128[] thresholds, uint128[] scalars);
}

// File: lib/points/src/interfaces/IPointsErrors.sol



// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.21;

/**
 * @title IPointsErrors
 * @notice Interface for the errors thrown by the Points contract.
 */
interface IPointsErrors {
    /**
     * @notice Thrown when attempting to set rates while rates parameter and tokens parameter have different lengths.
     */
    error TokenRatesLengthsMismatched(uint256 tokensLength, uint256 ratesLength);
    /**
     * @notice Thrown when attempting to withdraw more of the token than has been deposited.
     */
    error InsufficientTokenBalance(uint256 tokenBalance, uint256 amount);
    /**
     * @notice Thrown when attempting to transfer when paused and not whitelisted.
     */
    error TransfersPaused();
    /**
     * @notice Thrown when attempting to deposit an unsupported token.
     */
    error TokenNotSupported(address token);
    /**
     * @notice Thrown when attempting to set multipliers with threshold and additionalRate arrays of different lengths.
     */
    error MultiplierLengthsMismatched(uint256 thresholdsLength, uint256 additionalRatesLength);
}

// File: lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}