Skip to content
Verified contractExactBUSL-1.1

TokenVestingManager

Address0xd2f6832d2bcd8de796d1764ce8bb103a9425f19d
Balance

0.028324 ETH

 

Transactions

67

 

Compiler

solc 0.8.28

 

Same code

22 more contracts

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 2,000 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,427,159
Creation transaction
0x97d4dab483…0d95265c58

contracts/TokenVestingManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { AccessProtected } from "contracts/libraries/AccessProtected.sol";
import { TokenVestingLib } from "contracts/libraries/TokenVestingLib.sol";
import { Errors } from "contracts/libraries/Errors.sol";
import { ITokenVestingManager } from "contracts/interfaces/ITokenVestingManager.sol";
import { ITypes } from "contracts/interfaces/ITypes.sol";

/**
 * @title Token Vesting Manager
 * @notice Contract to manage token vesting
 */
contract TokenVestingManager is AccessProtected, ITokenVestingManager {
	using TokenVestingLib for TokenVestingLib.Vesting;
	using SafeERC20 for IERC20;

	/// Basis points for fee calculation
	uint256 public constant BASIS_POINTS = 10000;

	/// Address of the token to be vested
	address public immutable TOKEN_ADDRESS;
	/// Fee type for this contract
	ITypes.FeeType public immutable FEE_TYPE;
	/// Funding type for this contract
	ITypes.FundingType public immutable FUNDING_TYPE;
	/// Block number when this contract was deployed
	uint256 public immutable DEPLOYMENT_BLOCK_NUMBER;
	/// Fee amount for this contract
	uint256 public immutable FEE;

	/// Total number of tokens reserved for vesting
	uint256 public numTokensReservedForVesting;
	/// Number of tokens reserved for fees
	uint256 public numTokensReservedForFee;
	/// Nonce to generate vesting IDs
	uint256 private vestingIdNonce;
	/// Address of the fee collector
	address public feeCollector;
	/// List of all recipients

	address[] public recipients;
	/// Mapping: recipient address => index+1 in recipients array (0 means not in array)
	mapping(address => uint256) private recipientToIndex;

	// Mappings for vesting data
	/// Mapping: vestingId => funding amount
	mapping(bytes32 => uint256) public vestingFunding;
	/// Mapping: recipient => vestingIds
	/// Holds the vesting ids for each recipient
	mapping(address => bytes32[]) public recipientVestings;
	/// Mapping: recipient => vestingId => index+1 in recipientVestings array (0 means not in array)
	mapping(address => mapping(bytes32 => uint256))
		private vestingToRecipientIndex;
	/// Mapping: vestingId => vesting
	/// Holds the vesting information for each vesting id
	mapping(bytes32 => TokenVestingLib.Vesting) public vestingById;
	/// Mapping: vestingId => newOwner
	/// Tracks pending ownership transfers for each vesting ID
	mapping(bytes32 => address) public pendingVestingTransfers;

	/**
	 * @dev Reverts if the vesting is not active
	 */
	modifier isVestingActive(bytes32 _vestingId) {
		if (vestingById[_vestingId].deactivationTimestamp != 0) {
			revert Errors.VestingNotActive();
		}
		_;
	}

	/**
	 * @dev Reverts if caller is not the recipient of the vesting
	 */
	modifier onlyVestingRecipient(bytes32 _vestingId) {
		if (msg.sender != vestingById[_vestingId].recipient) {
			revert Errors.NotVestingOwner();
		}
		_;
	}

	// This checks if the msg.sender is the fee collector
	modifier onlyFeeCollector() {
		if (msg.sender != feeCollector) revert Errors.NotFeeCollector();
		_;
	}

	/**
	 * @notice Sets the token address to be vested
	 * @param tokenAddress_ - Address of the token to be vested
	 * @param feeType_ - Fee type for this contract
	 * @param fee_ - Fee amount for this contract
	 * @param feeCollector_ - Address of the fee collector
	 * @param fundingType_ - Type of funding for this contract (Full or Partial)
	 */
	constructor(
		address tokenAddress_,
		ITypes.FeeType feeType_,
		uint256 fee_,
		address feeCollector_,
		ITypes.FundingType fundingType_
	) {
		if (tokenAddress_ == address(0) || feeCollector_ == address(0))
			revert Errors.InvalidAddress();
		if (feeType_ == ITypes.FeeType.DistributionToken && fee_ > BASIS_POINTS)
			revert Errors.FeeTooHigh();

		TOKEN_ADDRESS = tokenAddress_;
		FEE_TYPE = feeType_;
		FEE = fee_;
		feeCollector = feeCollector_;
		FUNDING_TYPE = fundingType_;
		DEPLOYMENT_BLOCK_NUMBER = block.number;
	}

	// EXTERNAL WRITE FUNCTIONS

	/**
	 * @notice Create a new vesting
	 * @param _recipient - Address of the recipient
	 * @param _startTimestamp - Start timestamp of the vesting
	 * @param _endTimestamp - End timestamp of the vesting
	 * @param _timelock - Timelock for the vesting
	 * @param _initialUnlock - Initial unlock amount
	 * @param _cliffReleaseTimestamp - Cliff release timestamp
	 * @param _cliffAmount - Cliff amount
	 * @param _releaseIntervalSecs - Release interval in seconds
	 * @param _linearVestAmount - Linear vest amount
	 * @param _isRevocable - Whether the vesting is revocable
	 */
	function createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount,
		bool _isRevocable
	) external onlyAdmin {
		uint256 totalExpectedAmount = _initialUnlock +
			_cliffAmount +
			_linearVestAmount;

		bytes32 vestingId = bytes32(vestingIdNonce++);

		// Create the vesting
		_createVesting(
			TokenVestingLib.VestingParams({
				_vestingId: vestingId,
				_recipient: _recipient,
				_startTimestamp: _startTimestamp,
				_endTimestamp: _endTimestamp,
				_timelock: _timelock,
				_initialUnlock: _initialUnlock,
				_cliffReleaseTimestamp: _cliffReleaseTimestamp,
				_cliffAmount: _cliffAmount,
				_releaseIntervalSecs: _releaseIntervalSecs,
				_linearVestAmount: _linearVestAmount,
				_isRevocable: _isRevocable
			})
		);

		// For partial funding, the vesting is created first then funded separately
		if (FUNDING_TYPE == ITypes.FundingType.Full) {
			numTokensReservedForVesting += totalExpectedAmount;

			IERC20(TOKEN_ADDRESS).safeTransferFrom(
				msg.sender,
				address(this),
				totalExpectedAmount
			);
		}
	}

	/**
	 * @notice Create a batch of vestings
	 * @param params - Parameters for creating the vesting batch
	 */
	function createVestingBatch(
		CreateVestingBatchParams calldata params
	) external onlyAdmin {
		uint256 length = params._recipients.length;

		uint256 totalExpectedAmount;
		bytes32[] memory newVestingIds = new bytes32[](length);

		// Check array lengths match
		_checkArrayLengthMismatch(params, length);

		for (uint256 i; i < length; ++i) {
			bytes32 vestingId = bytes32(vestingIdNonce++);
			newVestingIds[i] = vestingId;
			_createVesting(
				TokenVestingLib.VestingParams({
					_vestingId: newVestingIds[i],
					_recipient: params._recipients[i],
					_startTimestamp: params._startTimestamps[i],
					_endTimestamp: params._endTimestamps[i],
					_timelock: params._timelocks[i],
					_initialUnlock: params._initialUnlocks[i],
					_cliffReleaseTimestamp: params._cliffReleaseTimestamps[i],
					_cliffAmount: params._cliffAmounts[i],
					_releaseIntervalSecs: params._releaseIntervalSecs[i],
					_linearVestAmount: params._linearVestAmounts[i],
					_isRevocable: params._isRevocables[i]
				})
			);

			uint256 vestingAmount = params._initialUnlocks[i] +
				params._cliffAmounts[i] +
				params._linearVestAmounts[i];

			totalExpectedAmount += vestingAmount;
		}

		// In full funding mode, we require the full amount to be transferred
		// Avoid using the vestingFunding mapping for full funding mode
		if (FUNDING_TYPE == ITypes.FundingType.Full) {
			numTokensReservedForVesting += totalExpectedAmount;

			IERC20(TOKEN_ADDRESS).safeTransferFrom(
				msg.sender,
				address(this),
				totalExpectedAmount
			);
		}
	}

	/**
	 * @notice Fund an existing vesting schedule
	 * @param _vestingId - Identifier of the vesting to fund
	 * @param _fundingAmount - Amount of tokens to add as funding
	 */
	function fundVesting(
		bytes32 _vestingId,
		uint256 _fundingAmount
	) external isVestingActive(_vestingId) onlyAdmin {
		if (FUNDING_TYPE == ITypes.FundingType.Full)
			revert Errors.VestingFullyFunded();
		if (_fundingAmount == 0) revert Errors.InvalidFundingAmount();

		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		if (vesting.recipient == address(0)) revert Errors.EmptyVesting();

		// Calculate total tokens needed for the vesting
		uint256 totalRequired = vesting.initialUnlock +
			vesting.cliffAmount +
			vesting.linearVestAmount;
		uint256 currentFunding = vestingFunding[_vestingId];

		if (currentFunding >= totalRequired) revert Errors.VestingFullyFunded();

		// Calculate how much more funding is allowed
		uint256 remainingFunding = totalRequired - currentFunding;
		if (_fundingAmount > remainingFunding)
			revert Errors.FundingLimitExceeded();

		// Update funding records
		vestingFunding[_vestingId] += _fundingAmount;
		numTokensReservedForVesting += _fundingAmount;

		emit VestingFunded(
			_vestingId,
			msg.sender,
			_fundingAmount,
			vestingFunding[_vestingId],
			totalRequired
		);

		// Transfer tokens from sender to contract
		IERC20(TOKEN_ADDRESS).safeTransferFrom(
			msg.sender,
			address(this),
			_fundingAmount
		);
	}

	/**
	 * @notice Fund multiple vestings in batch
	 * @param _vestingIds - Array of vesting identifiers to fund
	 * @param _fundingAmounts - Array of funding amounts for each vesting
	 */
	function fundVestingBatch(
		bytes32[] calldata _vestingIds,
		uint256[] calldata _fundingAmounts
	) external onlyAdmin {
		if (FUNDING_TYPE == ITypes.FundingType.Full)
			revert Errors.VestingFullyFunded();
		uint256 length = _vestingIds.length;
		if (length == 0) revert Errors.EmptyArray();
		if (length != _fundingAmounts.length)
			revert Errors.ArrayLengthMismatch();

		uint256 totalFundingAmount;

		// validate, update state, and calculate total
		for (uint256 i; i < length; ++i) {
			bytes32 vestingId = _vestingIds[i];
			uint256 fundingAmount = _fundingAmounts[i];

			// Skip entries with zero funding amount
			if (fundingAmount == 0) continue;

			TokenVestingLib.Vesting storage vesting = vestingById[vestingId];
			if (vesting.recipient == address(0)) revert Errors.EmptyVesting();
			if (vesting.deactivationTimestamp != 0)
				revert Errors.VestingNotActive();

			// Calculate total tokens needed for the vesting
			uint256 totalRequired = vesting.initialUnlock +
				vesting.cliffAmount +
				vesting.linearVestAmount;
			uint256 currentFunding = vestingFunding[vestingId];

			// Ensure we don't overfund
			if (currentFunding >= totalRequired)
				revert Errors.VestingFullyFunded();

			// Calculate how much more funding is allowed
			uint256 remainingFunding = totalRequired - currentFunding;
			if (fundingAmount > remainingFunding)
				revert Errors.FundingLimitExceeded();

			// Update funding records
			vestingFunding[vestingId] += fundingAmount;
			numTokensReservedForVesting += fundingAmount;

			// Track total for the transfer
			totalFundingAmount += fundingAmount;

			// Emit event for this funding
			emit VestingFunded(
				vestingId,
				msg.sender,
				fundingAmount,
				vestingFunding[vestingId],
				totalRequired
			);
		}

		// If no actual funding happened, revert to avoid empty transactions
		if (totalFundingAmount == 0) {
			revert Errors.InvalidFundingAmount();
		}

		// Transfer total tokens from sender to contract after all state updates
		IERC20(TOKEN_ADDRESS).safeTransferFrom(
			msg.sender,
			address(this),
			totalFundingAmount
		);
	}

	/**
	 * @notice Claim vested tokens
	 * @param _vestingId - Identifier of the vesting
	 */
	function claim(
		bytes32 _vestingId
	) external payable onlyVestingRecipient(_vestingId) {
		if (FEE_TYPE == ITypes.FeeType.Gas && msg.value != FEE)
			revert Errors.InsufficientFee();
		_claim(_vestingId);
	}

	/**
	 * @notice Admin claims vested tokens on behalf of a recipient (gas sponsoring)
	 * @param _vestingId - Identifier of the vesting
	 */
	function adminClaim(bytes32 _vestingId) external payable onlyAdmin {
		if (FEE_TYPE == ITypes.FeeType.Gas && msg.value != FEE)
			revert Errors.InsufficientFee();

		_claim(_vestingId);
	}

	/**
	 * @notice Admin claims vested tokens for multiple recipients (batch gas sponsoring)
	 * @param _vestingIds - Array of vesting identifiers to claim
	 */
	function batchAdminClaim(
		bytes32[] calldata _vestingIds
	) external payable onlyAdmin {
		uint256 length = _vestingIds.length;
		if (length == 0) revert Errors.EmptyArray();

		// Validate the total fee for all claims upfront
		if (FEE_TYPE == ITypes.FeeType.Gas && msg.value != FEE * length)
			revert Errors.InsufficientFee();

		for (uint256 i; i < length; ++i) {
			_claim(_vestingIds[i]);
		}
	}

	/**
	 * @notice Revoke active Vesting
	 * @param _vestingId - Vesting Identifier
	 */
	function revokeVesting(bytes32 _vestingId) external onlyAdmin {
		_revokeVesting(_vestingId);
	}

	/**
	 * @notice Revoke multiple vestings in batch
	 * @param _vestingIds - Array of vesting identifiers to revoke
	 * @dev More gas efficient than calling revokeVesting multiple times
	 */
	function batchRevokeVestings(
		bytes32[] calldata _vestingIds
	) external onlyAdmin {
		uint256 length = _vestingIds.length;
		if (length == 0) revert Errors.EmptyArray();
		for (uint256 i; i < length; ++i) _revokeVesting(_vestingIds[i]);
	}

	/**
	 * @notice Allow the owner to withdraw any balance not currently tied up in Vestings
	 * @param _amountRequested - Amount to withdraw
	 */
	function withdrawAdmin(uint256 _amountRequested) external onlyAdmin {
		uint256 amountRemaining = amountAvailableToWithdrawByAdmin();
		if (amountRemaining < _amountRequested)
			revert Errors.InsufficientBalance();

		emit AdminWithdrawn(msg.sender, _amountRequested);
		IERC20(TOKEN_ADDRESS).safeTransfer(msg.sender, _amountRequested);
	}

	/**
	 * @notice Withdraw a token which isn't controlled by the vesting contract. Useful when someone accidentally sends tokens to the contract
	 * @param _otherTokenAddress - the token which we want to withdraw
	 */
	function withdrawOtherToken(address _otherTokenAddress) external onlyAdmin {
		if (_otherTokenAddress == address(0)) revert Errors.InvalidAddress();
		if (_otherTokenAddress == TOKEN_ADDRESS) revert Errors.InvalidToken();

		uint256 balance = IERC20(_otherTokenAddress).balanceOf(address(this));
		IERC20(_otherTokenAddress).safeTransfer(msg.sender, balance);
	}

	/**
	 * @notice Initiate the transfer of vesting ownership to a new address
	 * @param _vestingId The ID of the vesting to transfer
	 * @param _newOwner The address of the new owner
	 */
	function initiateVestingTransfer(
		bytes32 _vestingId,
		address _newOwner
	) external onlyVestingRecipient(_vestingId) isVestingActive(_vestingId) {
		if (_newOwner == address(0)) revert Errors.InvalidAddress();
		if (pendingVestingTransfers[_vestingId] != address(0))
			revert Errors.PendingTransferExists();

		pendingVestingTransfers[_vestingId] = _newOwner;
		emit VestingTransferInitiated(msg.sender, _newOwner, _vestingId);
	}

	/**
	 * @notice Cancel a pending vesting transfer
	 * @param _vestingId The ID of the vesting with a pending transfer
	 */
	function cancelVestingTransfer(
		bytes32 _vestingId
	) external onlyVestingRecipient(_vestingId) {
		if (pendingVestingTransfers[_vestingId] == address(0))
			revert Errors.NoPendingTransfer();

		delete pendingVestingTransfers[_vestingId];
		emit VestingTransferCancelled(msg.sender, _vestingId);
	}

	/**
	 * @notice Accept a vesting transfer as the new owner
	 * @param _vestingId The ID of the vesting to accept
	 */
	function acceptVestingTransfer(
		bytes32 _vestingId
	) external isVestingActive(_vestingId) {
		address pendingOwner = pendingVestingTransfers[_vestingId];

		if (pendingOwner != msg.sender)
			revert Errors.NotAuthorizedForTransfer();

		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		address previousOwner = vesting.recipient;

		// Remove vesting ID from previous owner's mapping
		_removeVestingFromRecipient(previousOwner, _vestingId);

		// Update vesting recipient to new owner
		vesting.recipient = pendingOwner;

		// Add new owner to recipients list if they're not already in it
		if (!_isRecipient(pendingOwner)) {
			recipients.push(pendingOwner);
			recipientToIndex[pendingOwner] = recipients.length;
		}

		// Add vesting ID to new owner's mapping
		recipientVestings[pendingOwner].push(_vestingId);

		// Update the vesting index mapping for the new owner
		vestingToRecipientIndex[pendingOwner][_vestingId] = recipientVestings[
			pendingOwner
		].length;

		// Clear the pending transfer
		delete pendingVestingTransfers[_vestingId];

		// Emit transfer event
		emit VestingTransferred(previousOwner, pendingOwner, _vestingId);
	}

	/**
	 * @notice Direct transfer of vesting ownership by admin (for contract compatibility)
	 * @param _vestingId The ID of the vesting to transfer
	 * @param _newOwner The address of the new owner
	 * @dev This is specifically for compatibility with contracts that cannot call acceptVestingTransfer
	 */
	function directVestingTransfer(
		bytes32 _vestingId,
		address _newOwner
	) external onlyVestingRecipient(_vestingId) isVestingActive(_vestingId) {
		if (_newOwner == address(0)) revert Errors.InvalidAddress();

		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		address previousOwner = vesting.recipient;

		// Remove vesting ID from previous owner's mapping
		_removeVestingFromRecipient(previousOwner, _vestingId);

		// Update vesting recipient to new owner
		vesting.recipient = _newOwner;

		// Add new owner to recipients list if they're not already in it
		if (!_isRecipient(_newOwner)) {
			recipients.push(_newOwner);
			recipientToIndex[_newOwner] = recipients.length; // Store index+1 to distinguish from 0 (not in array)
		}

		// Add vesting ID to new owner's mapping
		recipientVestings[_newOwner].push(_vestingId);

		// Update the vesting index mapping for the new owner
		vestingToRecipientIndex[_newOwner][_vestingId] = recipientVestings[
			_newOwner
		].length;

		// Clear any pending transfer if it exists
		if (pendingVestingTransfers[_vestingId] != address(0)) {
			delete pendingVestingTransfers[_vestingId];
		}

		// Emit transfer event
		emit VestingTransferred(previousOwner, _newOwner, _vestingId);
	}

	/**
	 * @notice Allows only fee collector to withdraw collected token fees
	 * @dev This function is completely separate from distributor admin controls
	 * @param recipient Address to receive the fee
	 * @param amount Amount to withdraw, if 0 withdraws all available fees
	 */
	function withdrawTokenFee(
		address recipient,
		uint256 amount
	) external onlyFeeCollector {
		if (recipient == address(0)) revert Errors.InvalidAddress();
		if (numTokensReservedForFee == 0) revert Errors.InsufficientBalance();

		uint256 withdrawAmount = amount;
		// If amount is 0, withdraw all fees
		if (withdrawAmount == 0 || withdrawAmount > numTokensReservedForFee) {
			withdrawAmount = numTokensReservedForFee;
		}

		// Update the reserved fee amount
		numTokensReservedForFee -= withdrawAmount;

		emit TokenFeeWithdrawn(recipient, TOKEN_ADDRESS, withdrawAmount);

		IERC20(TOKEN_ADDRESS).safeTransfer(recipient, withdrawAmount);
	}

	/**
	 * @notice Allows only fee collector to withdraw collected gas fees
	 * @dev This function is completely separate from distributor admin controls
	 * @param recipient Address to receive the fee
	 * @param amount Amount to withdraw, if 0 withdraws all available fees
	 */
	function withdrawGasFee(
		address recipient,
		uint256 amount
	) external onlyFeeCollector {
		if (recipient == address(0)) revert Errors.InvalidAddress();

		uint256 balance = address(this).balance;
		if (balance == 0) revert Errors.InsufficientBalance();

		uint256 withdrawAmount = amount;
		// If amount is 0, withdraw all fees
		if (withdrawAmount == 0) withdrawAmount = balance;
		if (withdrawAmount > balance) revert Errors.FeeTooLow();

		emit GasFeeWithdrawn(recipient, withdrawAmount);

		// Using low-level call with re-entrancy protection
		(bool success, ) = recipient.call{ value: withdrawAmount }("");
		if (!success) revert Errors.TransferFailed();
	}

	/**
	 * @notice Updates the fee collector address
	 * @param newFeeCollector Address of the new fee collector
	 * @dev Can only be called by the fee collector
	 */
	function transferFeeCollectorRole(
		address newFeeCollector
	) external onlyFeeCollector {
		if (newFeeCollector == address(0)) revert Errors.InvalidAddress();

		address oldFeeCollector = feeCollector;
		feeCollector = newFeeCollector;

		emit FeeCollectorUpdated(oldFeeCollector, newFeeCollector);
	}

	// EXTERNAL VIEW FUNCTIONS

	/**
	 * @notice Get funding information for a vesting
	 * @param _vestingId - Identifier of the vesting
	 * @return fundingType - Type of funding (Full or Partial)
	 * @return totalFunded - Total amount of tokens funded so far
	 * @return totalRequired - Total amount of tokens required for full funding
	 */
	function getVestingFundingInfo(
		bytes32 _vestingId
	)
		external
		view
		returns (uint8 fundingType, uint256 totalFunded, uint256 totalRequired)
	{
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		if (vesting.recipient == address(0)) revert Errors.EmptyVesting();

		fundingType = uint8(FUNDING_TYPE);

		totalRequired =
			vesting.initialUnlock +
			vesting.cliffAmount +
			vesting.linearVestAmount;

		totalFunded = FUNDING_TYPE == ITypes.FundingType.Full
			? totalRequired
			: vestingFunding[_vestingId];

		return (fundingType, totalFunded, totalRequired);
	}

	/**
	 * @notice Check if a vesting is fully funded
	 * @param _vestingId - Identifier of the vesting
	 * @return isFullyFunded - True if the vesting is fully funded
	 */
	function isVestingFullyFunded(
		bytes32 _vestingId
	) external view returns (bool) {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		if (vesting.recipient == address(0)) revert Errors.EmptyVesting();
		if (FUNDING_TYPE == ITypes.FundingType.Full) return true;

		uint256 totalRequired = vesting.initialUnlock +
			vesting.cliffAmount +
			vesting.linearVestAmount;
		uint256 totalFunded = vestingFunding[_vestingId];

		return totalFunded >= totalRequired;
	}

	/**
	 * @notice Get the vesting information
	 * @param _vestingId - Identifier of the vesting
	 * @return vesting - Vesting information
	 */
	function getVestingInfo(
		bytes32 _vestingId
	) external view returns (TokenVestingLib.Vesting memory) {
		return vestingById[_vestingId];
	}

	/**
	 * @notice Get the vested amount for a Vesting, at a given timestamp.
	 * @param _referenceTimestamp Timestamp for which we're calculating
	 */
	function getVestedAmount(
		bytes32 _vestingId,
		uint32 _referenceTimestamp
	) external view returns (uint256) {
		TokenVestingLib.Vesting memory vesting = vestingById[_vestingId];
		return vesting.calculateVestedAmount(_referenceTimestamp);
	}

	/**
	 * @notice Get the claimable amount for a vesting
	 * @param _vestingId - Identifier of the vesting
	 * @return claimable - The amount of tokens that can be claimed at the current time
	 */
	function getClaimableAmount(
		bytes32 _vestingId
	) external view returns (uint256 claimable) {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		if (vesting.recipient == address(0)) revert Errors.EmptyVesting();

		// If timelock is active, nothing can be claimed
		if (vesting.timelock > uint32(block.timestamp)) return 0;

		// Calculate vested amount as of now
		uint256 vestedAmount = vesting.calculateVestedAmount(
			uint32(block.timestamp)
		);

		// Calculate claimable amount (vested - already claimed)
		claimable = vestedAmount > vesting.claimedAmount
			? vestedAmount - vesting.claimedAmount
			: 0;

		// For partial funding, ensure we don't return more than what's funded
		if (FUNDING_TYPE == ITypes.FundingType.Partial) {
			uint256 currentFunding = vestingFunding[_vestingId];

			// If funding is less than what's vested, adjust claimable
			if (currentFunding < vestedAmount) {
				claimable = currentFunding > vesting.claimedAmount
					? currentFunding - vesting.claimedAmount
					: 0;
			}
		}

		return claimable;
	}

	/**
	 * @notice Get all recipients
	 * @return recipients - The list of recipients
	 */
	function getAllRecipients() external view returns (address[] memory) {
		return recipients;
	}

	/**
	 * @notice Get the length of all recipients
	 * @return length - The length of all recipients
	 */
	function getAllRecipientsLength() external view returns (uint256) {
		return recipients.length;
	}

	/**
	 * @notice Get all recipients in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return recipientsSliced - The list of recipients in the range
	 */
	function getAllRecipientsSliced(
		uint256 _from,
		uint256 _to
	) external view returns (address[] memory) {
		if (_from >= _to || _to > recipients.length)
			revert Errors.InvalidRange();

		address[] memory recipientsSliced = new address[](_to - _from);
		for (uint256 i = _from; i < _to; ++i)
			recipientsSliced[i - _from] = recipients[i];
		return recipientsSliced;
	}

	/**
	 * @notice Get all vestings for a recipient
	 * @param _recipient - The recipient address
	 * @return recipientVestings - The list of vestings for the recipient
	 */
	function getAllRecipientVestings(
		address _recipient
	) external view returns (bytes32[] memory) {
		return recipientVestings[_recipient];
	}

	/**
	 * @notice Get all vestings for a recipient in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @param _recipient - The recipient address
	 * @return recipientVestingsSliced - The list of vestings for the recipient in the range
	 */
	function getAllRecipientVestingsSliced(
		uint256 _from,
		uint256 _to,
		address _recipient
	) external view returns (bytes32[] memory) {
		if (_recipient == address(0)) revert Errors.InvalidAddress();
		if (_from >= _to || _to > recipientVestings[_recipient].length)
			revert Errors.InvalidRange();

		bytes32[] memory recipientVestingsSliced = new bytes32[](_to - _from);
		for (uint256 i = _from; i < _to; ++i)
			recipientVestingsSliced[i - _from] = recipientVestings[_recipient][
				i
			];
		return recipientVestingsSliced;
	}

	/**
	 * @notice Get the length of all vestings for a recipient
	 * @param _recipient - The recipient address
	 * @return length - The length of all vestings for the recipient
	 */
	function getAllRecipientVestingsLength(
		address _recipient
	) external view returns (uint256) {
		if (_recipient == address(0)) revert Errors.InvalidAddress();
		return recipientVestings[_recipient].length;
	}

	/**
	 * @notice Get the pending owner for a vesting transfer
	 * @param _vestingId The ID of the vesting
	 * @return The address of the pending owner if there is one, or zero address
	 */
	function getPendingVestingTransfer(
		bytes32 _vestingId
	) external view returns (address) {
		return pendingVestingTransfers[_vestingId];
	}

	// PUBLIC VIEW/PURE FUNCTIONS

	/**
	 * @notice Amount of tokens available to withdraw by the admin
	 * @return The amount of tokens available to withdraw
	 */
	function amountAvailableToWithdrawByAdmin() public view returns (uint256) {
		return
			IERC20(TOKEN_ADDRESS).balanceOf(address(this)) -
			numTokensReservedForVesting -
			numTokensReservedForFee;
	}

	/**
	 * @notice Check if a recipient has vestings
	 * @param recipient - The recipient address
	 * @return isRecipient - True if the recipient has vestings
	 */
	function isRecipient(address recipient) external view returns (bool) {
		return _isRecipient(recipient);
	}

	// INTERNAL WRITE FUNCTIONS

	/**
	 * @dev Internal function to create a new vesting
	 * @param params - Vesting parameters
	 */
	function _createVesting(
		TokenVestingLib.VestingParams memory params
	) internal {
		if (params._recipient == address(0)) revert Errors.InvalidAddress();
		if (
			params._linearVestAmount +
				params._initialUnlock +
				params._cliffAmount ==
			0
		) revert Errors.InvalidVestedAmount();
		if (params._startTimestamp == 0) revert Errors.InvalidStartTimestamp();
		if (params._startTimestamp > params._endTimestamp)
			revert Errors.InvalidEndTimestamp();
		if (
			params._startTimestamp == params._endTimestamp &&
			params._linearVestAmount > 0
		) revert Errors.InvalidEndTimestamp();
		if (params._releaseIntervalSecs == 0)
			revert Errors.InvalidReleaseInterval();
		if (params._cliffReleaseTimestamp == 0) {
			if (params._cliffAmount != 0) revert Errors.InvalidCliffAmount();
			if (
				(params._endTimestamp - params._startTimestamp) %
					params._releaseIntervalSecs !=
				0
			) revert Errors.InvalidIntervalLength();
		} else {
			// Cliff release is set but amount can be zero
			if (
				((params._startTimestamp > params._cliffReleaseTimestamp) ||
					(params._cliffReleaseTimestamp >= params._endTimestamp))
			) revert Errors.InvalidCliffRelease();
			if (
				(params._endTimestamp - params._cliffReleaseTimestamp) %
					params._releaseIntervalSecs !=
				0
			) revert Errors.InvalidIntervalLength();
		}

		TokenVestingLib.Vesting memory vesting = TokenVestingLib.Vesting({
			recipient: params._recipient,
			startTimestamp: params._startTimestamp,
			endTimestamp: params._endTimestamp,
			deactivationTimestamp: 0,
			timelock: params._timelock,
			initialUnlock: params._initialUnlock,
			cliffReleaseTimestamp: params._cliffReleaseTimestamp,
			cliffAmount: params._cliffAmount,
			releaseIntervalSecs: params._releaseIntervalSecs,
			linearVestAmount: params._linearVestAmount,
			claimedAmount: 0,
			isRevocable: params._isRevocable
		});

		if (!_isRecipient(params._recipient)) {
			// Add the recipient to the array and update the index mapping
			recipients.push(params._recipient);
			recipientToIndex[params._recipient] = recipients.length; // Store index+1
		}

		vestingById[params._vestingId] = vesting;
		recipientVestings[params._recipient].push(params._vestingId);

		// Update the vesting index mapping for efficient removal (store index+1 to distinguish from 0)
		vestingToRecipientIndex[params._recipient][
			params._vestingId
		] = recipientVestings[params._recipient].length;

		emit VestingCreated(params._vestingId, params._recipient, vesting);
	}

	/**
	 * @dev Internal function to claim vested tokens
	 * @param _vestingId - Identifier of the vesting
	 */
	function _claim(bytes32 _vestingId) internal {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];

		if (vesting.recipient == address(0)) revert Errors.EmptyVesting();
		if (vesting.timelock > uint32(block.timestamp))
			revert Errors.TimelockEnabled();

		uint256 vested = vesting.calculateVestedAmount(uint32(block.timestamp));
		uint256 claimable = vested - vesting.claimedAmount;

		if (claimable == 0) revert Errors.InsufficientBalance();

		// If partial funding is enabled, check if there's enough funding
		if (FUNDING_TYPE == ITypes.FundingType.Partial) {
			uint256 currentFunding = vestingFunding[_vestingId];

			// Check if there's enough funding for the claim
			if (currentFunding < vested) {
				claimable = currentFunding > vesting.claimedAmount
					? currentFunding - vesting.claimedAmount
					: 0;

				if (claimable == 0) revert Errors.InsufficientFunding();
			}
		}

		vesting.claimedAmount += claimable;
		numTokensReservedForVesting -= claimable;

		uint256 transferAmount = claimable;

		if (FEE_TYPE == ITypes.FeeType.DistributionToken && FEE > 0) {
			uint256 feeAmount = (claimable * FEE) / BASIS_POINTS;
			if (feeAmount > claimable) revert Errors.FeeTooHigh();
			transferAmount = claimable - feeAmount;
			numTokensReservedForFee += feeAmount;
		}

		emit Claimed(_vestingId, vesting.recipient, transferAmount);

		IERC20(TOKEN_ADDRESS).safeTransfer(vesting.recipient, transferAmount);
	}

	/**
	 * @dev Internal function to revoke a vesting
	 * @param _vestingId - Vesting Identifier
	 */
	function _revokeVesting(
		bytes32 _vestingId
	) internal isVestingActive(_vestingId) {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];

		if (block.timestamp >= vesting.endTimestamp)
			revert Errors.FullyVested();
		if (!vesting.isRevocable) revert Errors.VestingNotRevocable();

		uint256 vestedAmountNow = vesting.calculateVestedAmount(
			uint32(block.timestamp)
		);
		uint256 finalVestAmount = vesting.calculateVestedAmount(
			vesting.endTimestamp
		);
		uint256 amountRemaining = finalVestAmount - vestedAmountNow;

		// In partial funding mode, we need to adjust the amount based on what was actually funded
		if (FUNDING_TYPE == ITypes.FundingType.Partial) {
			uint256 totalFunded = vestingFunding[_vestingId];

			// If there's not enough funding to cover what's already vested, we need to adjust
			if (totalFunded <= vestedAmountNow) {
				// All funded tokens are already vested, nothing to release
				amountRemaining = 0;
			} else {
				// Only release what's actually funded and not yet vested
				amountRemaining = totalFunded - vestedAmountNow;
			}
		}

		vesting.deactivationTimestamp = uint32(block.timestamp);
		numTokensReservedForVesting -= amountRemaining;

		emit VestingRevoked(_vestingId, amountRemaining, vesting);
	}

	/**
	 * @dev Helper function to remove a vesting ID from a recipient's array
	 * @param _recipient The address of the recipient
	 * @param _vestingId The ID of the vesting to remove
	 */
	function _removeVestingFromRecipient(
		address _recipient,
		bytes32 _vestingId
	) internal {
		bytes32[] storage vestingIds = recipientVestings[_recipient];
		uint256 indexPlusOne = vestingToRecipientIndex[_recipient][_vestingId];

		if (indexPlusOne == 0) return; // Vesting not found

		uint256 index = indexPlusOne - 1;
		uint256 lastIndex = vestingIds.length - 1;

		// If this is not the last element, move the last element to this position
		if (index != lastIndex) {
			bytes32 lastVestingId = vestingIds[lastIndex];
			vestingIds[index] = lastVestingId;
			// Update the index mapping for the moved element
			vestingToRecipientIndex[_recipient][lastVestingId] = index + 1;
		}

		// Remove the last element and clear the mapping
		vestingIds.pop();
		delete vestingToRecipientIndex[_recipient][_vestingId];

		// If recipient has no more vestings, remove from recipients array
		if (vestingIds.length == 0) _removeRecipient(_recipient);
	}

	/**
	 * @dev Helper function to remove a recipient from the recipients array
	 * @param _recipient The address of the recipient to remove
	 */
	function _removeRecipient(address _recipient) internal {
		uint256 indexPlusOne = recipientToIndex[_recipient];
		if (indexPlusOne == 0) return;

		uint256 index = indexPlusOne - 1; // Convert from index+1 to zero-based index
		uint256 lastIndex = recipients.length - 1;

		// If this is not the last element, move the last element to this position
		if (index != lastIndex) {
			address lastRecipient = recipients[lastIndex];
			recipients[index] = lastRecipient;
			recipientToIndex[lastRecipient] = index + 1; // Update index+1 for the moved element
		}

		// Remove the last element and clear the mapping
		recipients.pop();
		delete recipientToIndex[_recipient];
	}

	// INTERNAL VIEW/PURE FUNCTIONS

	/// @dev Internal function to check if an address is a recipient
	/// @param recipient The address to check
	/// @return True if the address is a recipient, false otherwise
	function _isRecipient(address recipient) internal view returns (bool) {
		if (recipient == address(0)) revert Errors.InvalidAddress();
		return recipientToIndex[recipient] != 0;
	}

	/**
	 * @dev Internal function to check if all array lengths in batch params match the expected length
	 * @param params - Batch parameters to validate
	 * @param expectedLength - The expected length all arrays should match
	 */
	function _checkArrayLengthMismatch(
		CreateVestingBatchParams calldata params,
		uint256 expectedLength
	) internal pure {
		if (
			params._startTimestamps.length != expectedLength ||
			params._endTimestamps.length != expectedLength ||
			params._timelocks.length != expectedLength ||
			params._initialUnlocks.length != expectedLength ||
			params._cliffAmounts.length != expectedLength ||
			params._cliffReleaseTimestamps.length != expectedLength ||
			params._releaseIntervalSecs.length != expectedLength ||
			params._linearVestAmounts.length != expectedLength ||
			params._isRevocables.length != expectedLength
		) {
			revert Errors.ArrayLengthMismatch();
		}
	}
}

contracts/interfaces/ITokenVestingManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import "contracts/libraries/TokenVestingLib.sol";
import "contracts/interfaces/ITypes.sol";

/// @title Interface for the TokenVestingManager contract
/// @notice Provides the external functions of the TokenVestingManager contract for managing token vesting schedules
interface ITokenVestingManager {
	/**
	 * @notice Parameters for vesting creation with a predefined ID
	 */
	struct VestingCreationParams {
		bytes32 vestingId;
		address recipient;
		uint32 startTimestamp;
		uint32 endTimestamp;
		uint32 timelock;
		uint256 initialUnlock;
		uint32 cliffReleaseTimestamp;
		uint256 cliffAmount;
		uint32 releaseIntervalSecs;
		uint256 linearVestAmount;
		bool isRevocable;
	}

	/// @notice Parameters for batch creation of vesting schedules
	/// @dev Arrays must be of equal length
	struct CreateVestingBatchParams {
		address[] _recipients;
		uint32[] _startTimestamps;
		uint32[] _endTimestamps;
		uint32[] _timelocks;
		uint256[] _initialUnlocks;
		uint32[] _cliffReleaseTimestamps;
		uint256[] _cliffAmounts;
		uint32[] _releaseIntervalSecs;
		uint256[] _linearVestAmounts;
		bool[] _isRevocables;
	}

	/// @notice Emitted when an admin withdraws tokens not tied up in vesting
	/// @param recipient Address of the recipient (admin) making the withdrawal
	/// @param amountRequested Amount of tokens withdrawn by the admin
	event AdminWithdrawn(address indexed recipient, uint256 amountRequested);

	/// @notice Emitted when a claim is made by a vesting recipient
	/// @param vestingId Unique identifier of the recipient's vesting arrangement
	/// @param recipient Address of the recipient making the claim
	/// @param withdrawalAmount Amount of tokens withdrawn in the claim
	event Claimed(
		bytes32 indexed vestingId,
		address indexed recipient,
		uint256 withdrawalAmount
	);

	/// @notice Emitted when new fee collector is set
	/// @param oldFeeCollector Address of the previous fee collector
	/// @param newFeeCollector Address of the new fee collector
	event FeeCollectorUpdated(
		address indexed oldFeeCollector,
		address indexed newFeeCollector
	);

	/// @notice Emitted when gas fees (ETH) are withdrawn by the fee collector
	/// @param recipient Address receiving the withdrawn fees
	/// @param amount Amount of ETH withdrawn
	event GasFeeWithdrawn(address indexed recipient, uint256 amount);

	/// @notice Emitted when token fees are withdrawn by the fee collector
	/// @param recipient Address receiving the withdrawn fees
	/// @param token Address of the token being withdrawn
	/// @param amount Amount of tokens withdrawn
	event TokenFeeWithdrawn(
		address indexed recipient,
		address indexed token,
		uint256 amount
	);

	/// @notice Emitted when a new vesting is created
	/// @param vestingId Unique identifier for the vesting
	/// @param recipient Address of the vesting recipient
	/// @param vesting Details of the created vesting
	event VestingCreated(
		bytes32 indexed vestingId,
		address indexed recipient,
		TokenVestingLib.Vesting vesting
	);

	/// @notice Emitted when a vesting is funded or additionally funded
	/// @param vestingId Unique identifier of the vesting
	/// @param funder Address of the account funding the vesting
	/// @param amount Amount of tokens added to the vesting
	/// @param totalFunded Total amount funded for this vesting so far
	/// @param totalRequired Total amount required by the vesting
	event VestingFunded(
		bytes32 indexed vestingId,
		address indexed funder,
		uint256 amount,
		uint256 totalFunded,
		uint256 totalRequired
	);

	/// @notice Emitted when a vesting is revoked
	/// @param vestingId Identifier of the revoked vesting
	/// @param numTokensWithheld Amount of tokens withheld during the revocation
	/// @param vesting Details of the revoked vesting
	event VestingRevoked(
		bytes32 indexed vestingId,
		uint256 numTokensWithheld,
		TokenVestingLib.Vesting vesting
	);

	/// @notice Emitted when a vesting ownership is transferred
	/// @param previousOwner Address of the previous vesting owner
	/// @param newOwner Address of the new vesting owner
	/// @param vestingId Unique identifier of the transferred vesting
	event VestingTransferred(
		address indexed previousOwner,
		address indexed newOwner,
		bytes32 indexed vestingId
	);

	/// @notice Emitted when a vesting transfer is initiated
	/// @param currentOwner Address of the current vesting owner
	/// @param newOwner Address of the proposed new vesting owner
	/// @param vestingId Unique identifier of the vesting to be transferred
	event VestingTransferInitiated(
		address indexed currentOwner,
		address indexed newOwner,
		bytes32 indexed vestingId
	);

	/// @notice Emitted when a vesting transfer is cancelled
	/// @param currentOwner Address of the current vesting owner
	/// @param vestingId Unique identifier of the vesting transfer that was cancelled
	event VestingTransferCancelled(
		address indexed currentOwner,
		bytes32 indexed vestingId
	);

	/// @notice The basis points denominator for percentage calculations
	function BASIS_POINTS() external view returns (uint256);

	/// @notice The block number when this contract was deployed
	function DEPLOYMENT_BLOCK_NUMBER() external view returns (uint256);

	/// @notice The fee percentage charged for vesting operations
	function FEE() external view returns (uint256);

	/// @notice The type of fee (flat, percentage, etc)
	function FEE_TYPE() external view returns (ITypes.FeeType);

	/// @notice The funding type for vestings (full or partial)
	function FUNDING_TYPE() external view returns (ITypes.FundingType);

	/// @notice The address of the token being vested
	function TOKEN_ADDRESS() external view returns (address);

	/// @notice Complete a vesting transfer by accepting it as the new owner
	/// @param _vestingId The ID of the vesting to accept
	function acceptVestingTransfer(bytes32 _vestingId) external;

	/// @notice Allows an admin to claim vested tokens on behalf of a recipient
	/// @param _vestingId Unique identifier of the vesting arrangement
	function adminClaim(bytes32 _vestingId) external payable;

	/// @notice Allows an admin to claim vested tokens for multiple vesting arrangements
	/// @param _vestingIds Array of vesting identifiers to claim
	function batchAdminClaim(bytes32[] memory _vestingIds) external payable;

	/// @notice Revokes multiple vesting arrangements in batch
	/// @param _vestingIds Array of vesting identifiers to revoke
	function batchRevokeVestings(bytes32[] memory _vestingIds) external;

	/// @notice Cancels a pending vesting transfer
	/// @param _vestingId The ID of the vesting with a pending transfer
	function cancelVestingTransfer(bytes32 _vestingId) external;

	/// @notice Allows a recipient to claim their vested tokens
	/// @param _vestingId Unique identifier of the recipient's vesting arrangement
	function claim(bytes32 _vestingId) external payable;

	/// @notice Create a vesting schedule for a recipient
	/// @param _recipient Address of the recipient for whom vesting is being created
	/// @param _startTimestamp Start time of the vesting period as a timestamp
	/// @param _endTimestamp End time of the vesting period as a timestamp
	/// @param _timelock Period during which the tokens are locked and cannot be claimed
	/// @param _initialUnlock Amount of tokens that are initially unlocked and claimable at the start time
	/// @param _cliffReleaseTimestamp Timestamp after which the cliff amount can be released
	/// @param _cliffAmount Amount of tokens that are released at once after the cliff period is reached
	/// @param _releaseIntervalSecs Interval in seconds between subsequent releases
	/// @param _linearVestAmount Total amount of tokens that will be vested linearly after the cliff
	/// @param _isRevocable Whether the vesting can be revoked by the admin
	function createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount,
		bool _isRevocable
	) external;

	/// @notice Create vesting schedules in batch for multiple recipients
	/// @param params Struct containing arrays of parameters for each vesting schedule
	function createVestingBatch(
		CreateVestingBatchParams memory params
	) external;

	/// @notice Direct transfer of vesting ownership
	/// @param _vestingId The ID of the vesting to transfer
	/// @param _newOwner The address of the new owner
	/// @dev This is specifically for compatibility with contracts that cannot call acceptVestingTransfer
	function directVestingTransfer(
		bytes32 _vestingId,
		address _newOwner
	) external;

	/// @notice Returns the address of the current fee collector
	/// @return Address of the fee collector
	function feeCollector() external view returns (address);

	/// @notice Adds additional funding to an existing vesting schedule
	/// @param _vestingId The identifier of the vesting to fund
	/// @param _fundingAmount Amount of tokens to add as funding
	function fundVesting(bytes32 _vestingId, uint256 _fundingAmount) external;

	/// @notice Adds funding to multiple vesting schedules in batch
	/// @param _vestingIds Array of vesting identifiers to fund
	/// @param _fundingAmounts Array of funding amounts for each vesting
	function fundVestingBatch(
		bytes32[] memory _vestingIds,
		uint256[] memory _fundingAmounts
	) external;

	/// @notice Get all vesting IDs for a specific recipient
	/// @param _recipient Address of the recipient
	/// @return Array of vesting IDs belonging to the recipient
	function getAllRecipientVestings(
		address _recipient
	) external view returns (bytes32[] memory);

	/// @notice Get the number of vestings for a specific recipient
	/// @param _recipient Address of the recipient
	/// @return Number of vestings for the recipient
	function getAllRecipientVestingsLength(
		address _recipient
	) external view returns (uint256);

	/// @notice Get a slice of vesting IDs for a specific recipient
	/// @param _from Start index (inclusive)
	/// @param _to End index (exclusive)
	/// @param _recipient Address of the recipient
	/// @return Array of vesting IDs in the specified range
	function getAllRecipientVestingsSliced(
		uint256 _from,
		uint256 _to,
		address _recipient
	) external view returns (bytes32[] memory);

	/// @notice Fetches a list of all recipient addresses who have at least one vesting schedule
	/// @return An array of addresses, each representing a recipient with an active or historical vesting schedule
	function getAllRecipients() external view returns (address[] memory);

	/// @notice Get the total number of recipients
	/// @return Number of recipients
	function getAllRecipientsLength() external view returns (uint256);

	/// @notice Get a slice of recipient addresses
	/// @param _from Start index (inclusive)
	/// @param _to End index (exclusive)
	/// @return Array of recipient addresses in the specified range
	function getAllRecipientsSliced(
		uint256 _from,
		uint256 _to
	) external view returns (address[] memory);

	/// @notice Get the amount of tokens that can be claimed from a vesting
	/// @param _vestingId The identifier of the vesting
	/// @return claimable The amount of tokens that can be claimed
	function getClaimableAmount(
		bytes32 _vestingId
	) external view returns (uint256 claimable);

	/// @notice Checks if a vesting has a pending transfer
	/// @param _vestingId The ID of the vesting to check
	/// @return The address of the pending owner if there is one, or zero address if none
	function getPendingVestingTransfer(
		bytes32 _vestingId
	) external view returns (address);

	/// @notice Get the amount of tokens that have vested by a specific timestamp
	/// @param _vestingId The identifier of the vesting
	/// @param _referenceTimestamp The timestamp to check vesting status at
	/// @return The amount of tokens vested at the reference timestamp
	function getVestedAmount(
		bytes32 _vestingId,
		uint32 _referenceTimestamp
	) external view returns (uint256);

	/// @notice Get funding information for a vesting schedule
	/// @param _vestingId The identifier of the vesting
	/// @return fundingType The type of funding (Full or Partial)
	/// @return totalFunded Total amount of tokens funded so far
	/// @return totalRequired Total amount of tokens required for full funding
	function getVestingFundingInfo(
		bytes32 _vestingId
	)
		external
		view
		returns (uint8 fundingType, uint256 totalFunded, uint256 totalRequired);

	/// @notice Retrieves information about a specific vesting arrangement
	/// @param _vestingId Unique identifier of the vesting
	/// @return Details of the specified vesting
	function getVestingInfo(
		bytes32 _vestingId
	) external view returns (TokenVestingLib.Vesting memory);

	/// @notice Initiates the transfer of vesting ownership
	/// @param _vestingId The ID of the vesting to transfer
	/// @param _newOwner The address of the new owner
	function initiateVestingTransfer(
		bytes32 _vestingId,
		address _newOwner
	) external;

	/// @notice Determine if a vesting is fully funded
	/// @param _vestingId The identifier of the vesting
	/// @return True if the vesting is fully funded
	function isVestingFullyFunded(
		bytes32 _vestingId
	) external view returns (bool);

	/// @notice Returns the total amount of tokens reserved for fees
	/// @return Amount of tokens reserved for fees
	function numTokensReservedForFee() external view returns (uint256);

	/// @notice Returns the total amount of tokens reserved for vesting
	/// @return Amount of tokens reserved for vesting
	function numTokensReservedForVesting() external view returns (uint256);

	/// @notice Returns the pending transfer address for a vesting ID
	/// @param vestingId The vesting ID to check
	/// @return Address of the pending transfer, if any
	function pendingVestingTransfers(
		bytes32 vestingId
	) external view returns (address);

	/// @notice Returns a vesting ID for a specific recipient at a specific index
	/// @param recipient The recipient address
	/// @param index The index in the recipient's vestings array
	/// @return The vesting ID
	function recipientVestings(
		address recipient,
		uint256 index
	) external view returns (bytes32);

	/// @notice Revokes a vesting arrangement before it has been fully claimed
	/// @param _vestingId Unique identifier of the vesting to be revoked
	function revokeVesting(bytes32 _vestingId) external;

	/// @notice Updates the fee collector address
	/// @param newFeeCollector The new fee collector address
	function transferFeeCollectorRole(address newFeeCollector) external;

	/// @notice Returns the amount of funding for a specific vesting ID
	/// @param vestingId The vesting ID to check
	/// @return Amount of funding for the vesting
	function vestingFunding(bytes32 vestingId) external view returns (uint256);

	/// @notice Allows the admin to withdraw ERC20 tokens not locked in vesting
	/// @param _amountRequested Amount of tokens the admin wishes to withdraw
	function withdrawAdmin(uint256 _amountRequested) external;

	/// @notice Withdraws gas fees (ETH) collected by the contract
	/// @param recipient Address to receive the fees
	/// @param amount Amount of ETH to withdraw
	function withdrawGasFee(address recipient, uint256 amount) external;

	/// @notice Withdraws ERC20 tokens accidentally sent to the contract's address
	/// @param _otherTokenAddress Address of the token to be withdrawn
	function withdrawOtherToken(address _otherTokenAddress) external;

	/// @notice Withdraws token fees collected by the contract
	/// @param recipient Address to receive the fees
	/// @param amount Amount of tokens to withdraw
	function withdrawTokenFee(address recipient, uint256 amount) external;
}

contracts/interfaces/ITypes.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface ITypes {
	enum FeeType {
		Gas,
		DistributionToken
	}

	enum FundingType {
		Full,
		Partial
	}
}

contracts/libraries/AccessProtected.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "contracts/libraries/Errors.sol";

/**
@title Access Limiter to multiple owner-specified accounts.
@dev Exposes the onlyAdmin modifier, which will revert (AdminAccessRequired) if the caller is not the owner nor the admin.
@notice An address with the role admin can grant that role to or revoke that role from any address via the function setAdmin().
*/
abstract contract AccessProtected is Context {
	mapping(address => bool) private _admins; // user address => admin? mapping
	uint256 public adminCount;

	event AdminAccessSet(address indexed _admin, bool _enabled);

	constructor() {
		_admins[_msgSender()] = true;
		adminCount = 1;
		emit AdminAccessSet(_msgSender(), true);
	}

	/**
	 * Throws if called by any account that isn't an admin or an owner.
	 */
	modifier onlyAdmin() {
		if (!_admins[_msgSender()]) revert Errors.AdminAccessRequired();
		_;
	}

	function isAdmin(address _addressToCheck) external view returns (bool) {
		return _admins[_addressToCheck];
	}

	/**
	 * @notice Set/unset Admin Access for a given address.
	 *
	 * @param admin - Address of the new admin (or the one to be removed)
	 * @param isEnabled - Enable/Disable Admin Access
	 */
	function setAdmin(address admin, bool isEnabled) public onlyAdmin {
		if (admin == address(0)) revert Errors.InvalidAddress();
		if (_admins[admin] == isEnabled)
			revert Errors.AdminStatusAlreadyActive();

		if (isEnabled) {
			adminCount++;
		} else {
			if (adminCount <= 1) revert Errors.CannotRemoveLastAdmin();
			adminCount--;
		}

		_admins[admin] = isEnabled;
		emit AdminAccessSet(admin, isEnabled);
	}
}

contracts/libraries/Errors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title Errors
 * @notice Central library for all custom errors used across the TokenOps vesting contracts
 */
library Errors {
	// ============== Access Control Errors ==============
	/// @notice Thrown when an operation requires admin access but caller is not an admin
	error AdminAccessRequired();
	/// @notice Thrown when an operation requires fee collector access but caller is not the fee collector
	error NotFeeCollector();
	/// @notice Thrown when an operation requires vesting ownership but caller is not the owner
	error NotVestingOwner();
	/// @notice Thrown when an operation requires milestone ownership but caller is not the owner
	error NotMilestoneOwner();
	/// @notice Thrown when an operation requires transfer authorization but caller is not authorized
	error NotAuthorizedForTransfer();
	/// @notice Thrown when a vault operation is attempted by an unauthorized address
	error VaultUnauthorized();
	/// @notice Thrown when an operation requires at least one admin but would leave none
	error CannotRemoveLastAdmin();

	// ============== Input Validation Errors ==============
	/// @notice Thrown when an invalid address (typically zero address) is provided
	error InvalidAddress();
	/// @notice Thrown when a range of values is invalid
	error InvalidRange();
	/// @notice Thrown when arrays in a function call don't have the same length
	error ArrayLengthMismatch();
	/// @notice Thrown when an empty array is provided but non-empty is required
	error EmptyArray();
	/// @notice Thrown when a flag is already set with the same value for an address
	error AdminStatusAlreadyActive();
	/// @notice Thrown when an invalid token address is provided
	error InvalidToken();
	/// @notice Thrown when an invalid step index is provided
	error InvalidStepIndex();

	// ============== Fee-Related Errors ==============
	/// @notice Thrown when a fee is below the minimum required
	error FeeTooLow();
	/// @notice Thrown when a fee exceeds the maximum allowed
	error FeeTooHigh();
	/// @notice Thrown when insufficient fees are provided
	error InsufficientFee();
	/// @notice Thrown when a custom fee is not set for an address
	error CustomFeeNotSet();

	// ============== Token Operation Errors ==============
	/// @notice Thrown when a transfer operation fails
	error TransferFailed();
	/// @notice Thrown when there's insufficient balance for an operation
	error InsufficientBalance();
	/// @notice Thrown when an invalid funding amount is provided
	error InvalidFundingAmount();
	/// @notice Thrown when trying to exceed a funding limit
	error FundingLimitExceeded();
	/// @notice Thrown when a vesting is fully funded and additional funding is attempted
	error VestingFullyFunded();
	/// @notice Thrown when insufficient funding is provided
	error InsufficientFunding();
	/// @notice Thrown when an operation would delegate to a zero address
	error VaultZeroAddressDelegate();

	// ============== Vault-Related Errors ==============
	/// @notice Thrown when a vault is already initialized
	error VaultAlreadyInitialized();
	/// @notice Thrown when vault deployment fails
	error VaultDeploymentFailed();
	/// @notice Thrown when vault initialization fails
	error VaultInitializationFailed();

	// ============== Vesting State Errors ==============
	/// @notice Thrown when a vesting is empty (not initialized)
	error EmptyVesting();
	/// @notice Thrown when a vesting is not active
	error VestingNotActive();
	/// @notice Thrown when a vesting is fully vested
	error FullyVested();
	/// @notice Thrown when a vesting is not revocable but revocation is attempted
	error VestingNotRevocable();
	/// @notice Thrown when a timelock is enabled but an operation would violate it
	error TimelockEnabled();

	// ============== Vesting Parameter Errors ==============
	/// @notice Thrown when an invalid vested amount is provided
	error InvalidVestedAmount();
	/// @notice Thrown when an invalid start timestamp is provided
	error InvalidStartTimestamp();
	/// @notice Thrown when an invalid end timestamp is provided
	error InvalidEndTimestamp();
	/// @notice Thrown when an invalid release interval is provided
	error InvalidReleaseInterval();
	/// @notice Thrown when an invalid interval length is provided
	error InvalidIntervalLength();
	/// @notice Thrown when an invalid cliff release timestamp is provided
	error InvalidCliffRelease();
	/// @notice Thrown when an invalid cliff release timestamp is provided
	error InvalidCliffReleaseTimestamp();
	/// @notice Thrown when an invalid cliff amount is provided
	error InvalidCliffAmount();
	/// @notice Thrown when an invalid unlock timestamp is provided
	error InvalidUnlockTimestamp();

	// ============== Transfer Ownership Errors ==============
	/// @notice Thrown when no pending transfer exists but one is expected
	error NoPendingTransfer();
	/// @notice Thrown when a pending transfer exists but none is expected
	error PendingTransferExists();

	// ============== Milestone State Errors ==============
	/// @notice Thrown when a milestone with the same ID already exists
	error MilestoneAlreadyExists(bytes32 milestoneId);
	/// @notice Thrown when a milestone doesn't exist
	error MilestoneNotExists();
	/// @notice Thrown when a milestone is not active
	error MilestoneNotActive();
	/// @notice Thrown when a milestone is already revoked
	error MilestoneAlreadyRevoked();
	/// @notice Thrown when a milestone is revoked but operation assumes it's active
	error MilestoneIsRevoked();
	/// @notice Thrown when a step is already approved but approval is attempted again
	error StepAlreadyApproved();
	/// @notice Thrown when a step is already revoked but revocation is attempted again
	error StepAlreadyRevoked();
	/// @notice Thrown when a step needs to be approved but isn't
	error StepNotApproved();
	/// @notice Thrown when a milestone is fully funded but additional funding is attempted
	error MilestoneFullyFunded();
	/// @notice Thrown when a milestone step is fully funded but additional funding is attempted
	error StepFullyFunded();
	/// @notice Thrown when a start timestamp is not reached but operation requires it
	error StartTimestampNotReached();
	/// @notice Thrown when a vesting has already ended but operation assumes it's active
	error VestingAlreadyEnded();
}

contracts/libraries/TokenVestingLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import { Errors } from "contracts/libraries/Errors.sol";

library TokenVestingLib {
	/**
	 * @notice A structure representing a Vesting - supporting linear and cliff vesting.
	 * @param releaseIntervalSecs used for calculating the vested amount
	 * @param linearVestAmount vesting allocation, excluding cliff
	 * @param claimedAmount claimed so far, excluding cliff
	 */
	struct Vesting {
		address recipient; // 160 bits 160/256 slot space - 1st slot
		uint32 startTimestamp; // 32 bits 192/256 slot space - 1st slot
		uint32 endTimestamp; // 32 bits  224/256 slot space - 1st slot
		uint32 deactivationTimestamp; // 32 bits 256/256 slot space - 1st slot
		uint32 timelock; // 32 bits 32/256 slot space - 2nd slot
		uint32 releaseIntervalSecs; // 32 bits 64/256 slot space - 2nd slot
		uint32 cliffReleaseTimestamp; // 32 bits 96/256 slot space - 2nd slot
		uint256 initialUnlock; // 256 bits 256/256 slot space - 3nd slot
		uint256 cliffAmount; // 256 bits 256/256 slot space - 4nd slots
		uint256 linearVestAmount; // 256 bits 256/256 slot space - 5th slot
		uint256 claimedAmount; // 256 bits 256/256 slot space - 6th slot
		bool isRevocable; // Flag to determine if vesting can be revoked
	}

	/**
	 * @notice A structure representing a Vesting - supporting linear and cliff vesting.
	 * @param _vestingId The ID of the vesting
	 * @param _recipient The recipient of the vesting
	 * @param _startTimestamp The start timestamp of the vesting
	 * @param _endTimestamp The end timestamp of the vesting
	 * @param _timelock The timelock period for the vesting
	 * @param _initialUnlock The initial unlock amount for the vesting
	 * @param _cliffReleaseTimestamp The cliff release timestamp for the vesting
	 * @param _cliffAmount The cliff amount for the vesting
	 * @param _releaseIntervalSecs The release interval in seconds for the vesting
	 * @param _linearVestAmount The linear vest amount for the vesting
	 * @param _isRevocable Flag to determine if vesting can be revoked
	 */
	struct VestingParams {
		bytes32 _vestingId;
		address _recipient;
		uint32 _startTimestamp;
		uint32 _endTimestamp;
		uint32 _timelock;
		uint256 _initialUnlock;
		uint32 _cliffReleaseTimestamp;
		uint256 _cliffAmount;
		uint32 _releaseIntervalSecs;
		uint256 _linearVestAmount;
		bool _isRevocable;
	}

	/**
	 * @notice Calculate the vested amount for a given Vesting, at a given timestamp.
	 * @param _vesting The vesting in question
	 * @param _referenceTimestamp Timestamp for which we're calculating
	 */
	function calculateVestedAmount(
		Vesting memory _vesting,
		uint32 _referenceTimestamp
	) internal pure returns (uint256) {
		// Does the Vesting exist?
		if (_vesting.deactivationTimestamp != 0) {
			if (_referenceTimestamp > _vesting.deactivationTimestamp) {
				_referenceTimestamp = _vesting.deactivationTimestamp;
			}
		}

		uint256 vestingAmount;

		// Has the Vesting ended?
		if (_referenceTimestamp > _vesting.endTimestamp) {
			_referenceTimestamp = _vesting.endTimestamp;
		}

		// Has the start passed?
		if (_referenceTimestamp >= _vesting.startTimestamp) {
			vestingAmount += _vesting.initialUnlock;
		}

		// Has the cliff passed?
		if (_referenceTimestamp >= _vesting.cliffReleaseTimestamp) {
			vestingAmount += _vesting.cliffAmount;
		}

		// Has the vesting started? If so, calculate the vested amount linearly
		uint256 startTimestamp;
		if (_vesting.cliffReleaseTimestamp != 0) {
			startTimestamp = _vesting.cliffReleaseTimestamp;
		} else {
			startTimestamp = _vesting.startTimestamp;
		}
		if (_referenceTimestamp > startTimestamp) {
			uint256 currentVestingDurationSecs = _referenceTimestamp -
				startTimestamp;

			// Round to releaseIntervalSecs
			uint256 truncatedCurrentVestingDurationSecs = (currentVestingDurationSecs /
					_vesting.releaseIntervalSecs) *
					_vesting.releaseIntervalSecs;

			uint256 finalVestingDurationSecs = _vesting.endTimestamp -
				startTimestamp;

			// Calculate vested amount
			uint256 linearVestAmount = (_vesting.linearVestAmount *
				truncatedCurrentVestingDurationSecs) / finalVestingDurationSecs;

			vestingAmount += linearVestAmount;
		}
		return vestingAmount;
	}
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.0;

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

pragma solidity ^0.8.0;

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

    /**
     * @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.encodeWithSelector(token.transfer.selector, 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.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));
    }

    /**
     * @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);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @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.encodeWithSelector(token.approve.selector, spender, value);

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @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.isContract(address(token));
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://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.0/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");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or 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 {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 2000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@ensdomains/=node_modules/@ensdomains/",
    "eth-gas-reporter/=node_modules/eth-gas-reporter/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "hardhat/=node_modules/hardhat/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.